Last active
April 27, 2022 19:24
-
-
Save gretel/8e65ef8e349df7b5a12c4404f72ddc16 to your computer and use it in GitHub Desktop.
Euclidean rhythms: Björklund's algorithm in Python 3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Copyright (c) 2011 Brian House | |
# https://github.com/brianhouse/bjorklund | |
# Copyright (c) 2017 Tom Hensel | |
# | |
import argparse | |
import sys | |
parser = argparse.ArgumentParser(description='Euclidean rhythms: Björklund''s algorithm in Python 3') | |
parser.add_argument('-p', '--pulses', dest='pulses', type=int, default=5, help='pulse count') | |
parser.add_argument('-s', '--steps', dest='steps', type=int, default=13, help='step count') | |
args = parser.parse_args() | |
class Bjorklund(): | |
def __init__(self, steps : int, pulses : int): | |
if pulses > steps: | |
raise ValueError | |
self.pattern = [] | |
level = 0 | |
counts = [] | |
remainders = [] | |
divisor = steps - pulses | |
remainders.append(pulses) | |
while True: | |
counts.append(divisor / remainders[level]) | |
remainders.append(divisor % remainders[level]) | |
divisor = remainders[level] | |
level += 1 | |
if remainders[level] < 2: | |
break | |
counts.append(divisor) | |
def build(level : int): | |
if level == -1: | |
self.pattern.append(0) | |
elif level == -2: | |
self.pattern.append(1) | |
else: | |
# recursion | |
for i in range(0, int(counts[level])): | |
build(level - 1) | |
if remainders[level] != 0: | |
build(level - 2) | |
build(level) | |
i = self.pattern.index(1) | |
self.pattern = self.pattern[i:] + self.pattern[0:i] | |
if __name__ == "__main__": | |
try: | |
b = Bjorklund(args.steps, args.pulses) | |
print(b.pattern) | |
except ValueError: | |
print('equal or more steps than pulses required!', file=sys.stderr) | |
sys.exit(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment