├── .github
├── FUNDING.yml
└── workflows
│ ├── ci.yml
│ └── test.yml
├── .gitignore
├── .pre-commit-config.yaml
├── LICENSE
├── README.md
├── doc
├── Documentation_Part_1.ipynb
└── doc-requirements.txt
├── poetry.lock
├── pyproject.toml
├── pytest.ini
├── test
├── test_mini_interpreter.py
├── test_mini_parser.py
├── test_pattern.py
└── test_py_vortex.py
└── vortex
├── __init__.py
├── boot.py
├── cli.py
├── control.py
├── euclid.py
├── gui.py
├── mini
├── __init__.py
├── grammar.py
└── interpreter.py
├── pattern.py
├── repl.py
├── res
└── fonts
│ ├── FiraCode-Bold.ttf
│ ├── FiraCode-Light.ttf
│ ├── FiraCode-Medium.ttf
│ ├── FiraCode-Regular.ttf
│ ├── FiraCode-Retina.ttf
│ ├── FiraCode-SemiBold.ttf
│ └── iosevka-term-regular.ttf
├── stream.py
├── utils.py
└── vortex.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | open_collective: tidalcycles
2 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies and run tests with a variety of Python versions
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: CI
5 |
6 | on:
7 | push:
8 | branches: [ "main" ]
9 | pull_request:
10 | branches: [ "main" ]
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 | strategy:
17 | fail-fast: false
18 | matrix:
19 | python-version: ["3.8", "3.9", "3.10"]
20 |
21 | steps:
22 | - uses: actions/checkout@v3
23 | - name: Set up Python ${{ matrix.python-version }}
24 | uses: actions/setup-python@v3
25 | with:
26 | python-version: ${{ matrix.python-version }}
27 | - name: Install system dependencies
28 | run: |
29 | sudo apt install liblo-dev
30 | - name: Install Poetry
31 | run: |
32 | python -m pip install --upgrade poetry==1.3.2
33 | - name: Install all dependencies
34 | run: |
35 | poetry install
36 | - name: Run tests
37 | run: |
38 | poetry run pytest
39 |
--------------------------------------------------------------------------------
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies and run tests except on branch 'main' where CI action is used
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: Vortex Tests
5 |
6 | on:
7 | push:
8 | branches:
9 | - '**' # matches every branch
10 | - '!main' # excludes main
11 |
12 | jobs:
13 | build:
14 |
15 | runs-on: ubuntu-latest
16 | strategy:
17 | fail-fast: false
18 | matrix:
19 | python-version: ["3.10"]
20 |
21 | steps:
22 | - uses: actions/checkout@v3
23 | - name: Set up Python ${{ matrix.python-version }}
24 | uses: actions/setup-python@v3
25 | with:
26 | python-version: ${{ matrix.python-version }}
27 | - name: Install system dependencies
28 | run: |
29 | sudo apt install liblo-dev
30 | - name: Install Poetry
31 | run: |
32 | python -m pip install --upgrade poetry==1.3.2
33 | - name: Install all dependencies
34 | run: |
35 | poetry install
36 | - name: Run tests
37 | run: |
38 | poetry run pytest
39 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
131 | #Pycharm
132 | .idea
133 |
134 | # text editor temp files
135 | *~
136 | \#*\#
137 | .\#*
138 |
--------------------------------------------------------------------------------
/.pre-commit-config.yaml:
--------------------------------------------------------------------------------
1 | # See https://pre-commit.com for more information
2 | # See https://pre-commit.com/hooks.html for more hooks
3 | repos:
4 | - repo: https://github.com/pre-commit/pre-commit-hooks
5 | rev: v3.2.0
6 | hooks:
7 | - id: trailing-whitespace
8 | - id: end-of-file-fixer
9 | - id: check-yaml
10 | - id: check-added-large-files
11 | - repo: https://github.com/psf/black
12 | rev: 22.6.0
13 | hooks:
14 | - id: black
15 | - repo: https://github.com/pycqa/isort
16 | rev: 5.10.1
17 | hooks:
18 | - id: isort
19 | args: ["--profile", "black"]
20 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Vortex: Algorithmic pattern experiments in Python
2 |
3 | Moved to https://codeberg.org/uzu/vortex/
4 |
--------------------------------------------------------------------------------
/doc/Documentation_Part_1.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "markdown",
5 | "id": "51e519ce-1ba5-4ea1-b3f5-76b35fa057ba",
6 | "metadata": {},
7 | "source": [
8 | "# Step-by-Step documentation\n",
9 | "## Part I: Time, TimeSpan, Event\n",
10 | "\n",
11 | "This notebook is meant for anyone to better understand the underlying structures which are used in vortex, and to a larger extent in Tidal.
\n",
12 | "Beware that there may be some differences, but at least, this aims to cover the current `vortex`implementation in Python hoping to explain it a bit more at low-level
\n",
13 | "There are a couple crucial class in vortex, namely Time, TimeSpan, and Event, we will go through in details about how they work.
\n",
14 | "Part II will focus on Pattern only"
15 | ]
16 | },
17 | {
18 | "cell_type": "code",
19 | "execution_count": 1,
20 | "id": "f3ca40fc-1e9f-4db7-9a1d-0465d71bde7b",
21 | "metadata": {},
22 | "outputs": [],
23 | "source": [
24 | "from vortex import *"
25 | ]
26 | },
27 | {
28 | "cell_type": "markdown",
29 | "id": "4f18ae15-562d-42d6-b03c-7a64b328765a",
30 | "metadata": {},
31 | "source": [
32 | "# Time\n",
33 | "Time class is a subclass of fraction. While instanciating a Time object, you can specify it by either one or two floats.
\n",
34 | "If you do so with two numbers, then the fraction is simply the ratio of them
\n",
35 | "If you create it with only one number, it translates it into a fraction
\n",
36 | "Apparently, irrationals does work too (probably rounded)"
37 | ]
38 | },
39 | {
40 | "cell_type": "code",
41 | "execution_count": 2,
42 | "id": "9959c6b5-9d78-4766-b7dc-f49af92a46ee",
43 | "metadata": {},
44 | "outputs": [
45 | {
46 | "data": {
47 | "text/plain": [
48 | "Time(1, 2)"
49 | ]
50 | },
51 | "execution_count": 2,
52 | "metadata": {},
53 | "output_type": "execute_result"
54 | }
55 | ],
56 | "source": [
57 | "Time(1,2)"
58 | ]
59 | },
60 | {
61 | "cell_type": "code",
62 | "execution_count": 3,
63 | "id": "0b8cf0f6-b523-4329-8733-33430352f797",
64 | "metadata": {},
65 | "outputs": [
66 | {
67 | "data": {
68 | "text/plain": [
69 | "Time(1, 2)"
70 | ]
71 | },
72 | "execution_count": 3,
73 | "metadata": {},
74 | "output_type": "execute_result"
75 | }
76 | ],
77 | "source": [
78 | "Time(0.5)"
79 | ]
80 | },
81 | {
82 | "cell_type": "code",
83 | "execution_count": 4,
84 | "id": "12fee21f-7f08-4dfc-b246-424aad575ee8",
85 | "metadata": {},
86 | "outputs": [
87 | {
88 | "data": {
89 | "text/plain": [
90 | "Time(8893444981951847, 72057594037927936)"
91 | ]
92 | },
93 | "execution_count": 4,
94 | "metadata": {},
95 | "output_type": "execute_result"
96 | }
97 | ],
98 | "source": [
99 | "Time(0.12342134234)"
100 | ]
101 | },
102 | {
103 | "cell_type": "code",
104 | "execution_count": 5,
105 | "id": "fafc9372-6c4d-4bf4-9c24-65c451413a68",
106 | "metadata": {},
107 | "outputs": [
108 | {
109 | "data": {
110 | "text/plain": [
111 | "Time(884279719003555, 281474976710656)"
112 | ]
113 | },
114 | "execution_count": 5,
115 | "metadata": {},
116 | "output_type": "execute_result"
117 | }
118 | ],
119 | "source": [
120 | "from math import pi\n",
121 | "Time(pi)"
122 | ]
123 | },
124 | {
125 | "cell_type": "markdown",
126 | "id": "e1b73273-c268-46e6-a877-e3a3f598dfc8",
127 | "metadata": {},
128 | "source": [
129 | "## Methods\n",
130 | "\n",
131 | "Time Class has currently 3 methods, `sam`, `next_sam` and `whole_cycle`.
\n",
132 | "Sam refers to indian music, where *sam* is the denomination of the first beat of the cycle.
\n",
133 | "Trivially, `next_sam` is the first beat of the next cycle
\n",
134 | "And whole_duration is a TimeSpan (see below) of a whole cycle
"
135 | ]
136 | },
137 | {
138 | "cell_type": "markdown",
139 | "id": "2113a7d4-b1d8-43ad-943c-be2781689ff9",
140 | "metadata": {},
141 | "source": [
142 | "### sam"
143 | ]
144 | },
145 | {
146 | "cell_type": "code",
147 | "execution_count": 6,
148 | "id": "3f15d486-d86e-4ad9-83ca-303205ec4d75",
149 | "metadata": {},
150 | "outputs": [
151 | {
152 | "data": {
153 | "text/plain": [
154 | "Time(0, 1)"
155 | ]
156 | },
157 | "execution_count": 6,
158 | "metadata": {},
159 | "output_type": "execute_result"
160 | }
161 | ],
162 | "source": [
163 | "Time(0.43).sam()"
164 | ]
165 | },
166 | {
167 | "cell_type": "markdown",
168 | "id": "a441bbc2-81b2-42e5-bca7-d7f70a534d6d",
169 | "metadata": {},
170 | "source": [
171 | "### next_sam"
172 | ]
173 | },
174 | {
175 | "cell_type": "code",
176 | "execution_count": 7,
177 | "id": "74a1c64a-8ad8-49aa-b1be-8c46c1003399",
178 | "metadata": {},
179 | "outputs": [
180 | {
181 | "data": {
182 | "text/plain": [
183 | "Fraction(1, 1)"
184 | ]
185 | },
186 | "execution_count": 7,
187 | "metadata": {},
188 | "output_type": "execute_result"
189 | }
190 | ],
191 | "source": [
192 | "Time(0.43).next_sam()"
193 | ]
194 | },
195 | {
196 | "cell_type": "markdown",
197 | "id": "82599445-e8cf-42c4-b7dd-b3a07236b17e",
198 | "metadata": {},
199 | "source": [
200 | "### whole_cycle"
201 | ]
202 | },
203 | {
204 | "cell_type": "code",
205 | "execution_count": 8,
206 | "id": "13e3175e-9508-4459-af80-e1f5ef60f263",
207 | "metadata": {},
208 | "outputs": [
209 | {
210 | "data": {
211 | "text/plain": [
212 | "TimeSpan(Time(0, 1), Time(1, 1))"
213 | ]
214 | },
215 | "execution_count": 8,
216 | "metadata": {},
217 | "output_type": "execute_result"
218 | }
219 | ],
220 | "source": [
221 | "Time(0.42).whole_cycle()"
222 | ]
223 | },
224 | {
225 | "cell_type": "code",
226 | "execution_count": 9,
227 | "id": "ab2f7876-03c7-4497-a93d-d73170afba7f",
228 | "metadata": {},
229 | "outputs": [
230 | {
231 | "data": {
232 | "text/plain": [
233 | "TimeSpan(Time(-3, 1), Time(-2, 1))"
234 | ]
235 | },
236 | "execution_count": 9,
237 | "metadata": {},
238 | "output_type": "execute_result"
239 | }
240 | ],
241 | "source": [
242 | "Time(-2.3).whole_cycle()"
243 | ]
244 | },
245 | {
246 | "cell_type": "markdown",
247 | "id": "c808cd9a-6666-4420-8dc6-c7ccb33926df",
248 | "metadata": {},
249 | "source": [
250 | "# TimeSpan\n",
251 | "As introduced right above, TimeSpan represents a structure that has a certain duration
\n",
252 | "It is commonly used in Event, as will be talked about later.\n",
253 | "It has 2 attributes: `begin` and `end` and 3 methods `spanCycles`, `withTime` and `sect`
\n",
254 | "We will not count `maybeSect` here since it is just a method for dealing with sect corner cases.
\n",
255 | "TimeSpan `begin` and `end` attributes are themselves `Time` objects.
\n",
256 | "In theory, nothing restricts them to be such like $begin > end$ but in practive it is not the case.
"
257 | ]
258 | },
259 | {
260 | "cell_type": "code",
261 | "execution_count": 10,
262 | "id": "75a6878f-b010-4152-afea-07d53c47618e",
263 | "metadata": {},
264 | "outputs": [
265 | {
266 | "data": {
267 | "text/plain": [
268 | "TimeSpan(Time(-3602879701896397, 36028797018963968), Time(3602879701896397, 4503599627370496))"
269 | ]
270 | },
271 | "execution_count": 10,
272 | "metadata": {},
273 | "output_type": "execute_result"
274 | }
275 | ],
276 | "source": [
277 | "TimeSpan(-0.1, 0.8)"
278 | ]
279 | },
280 | {
281 | "cell_type": "code",
282 | "execution_count": 11,
283 | "id": "bff9f883-af09-41f0-a2dc-962abbcb96bd",
284 | "metadata": {},
285 | "outputs": [
286 | {
287 | "data": {
288 | "text/plain": [
289 | "TimeSpan(Time(1, 8), Time(1, 4))"
290 | ]
291 | },
292 | "execution_count": 11,
293 | "metadata": {},
294 | "output_type": "execute_result"
295 | }
296 | ],
297 | "source": [
298 | "TimeSpan(1/8, 1/4)"
299 | ]
300 | },
301 | {
302 | "cell_type": "markdown",
303 | "id": "e8877ab1-e4c0-4604-9be5-09afb03b4b5a",
304 | "metadata": {},
305 | "source": [
306 | "## Methods\n",
307 | "\n",
308 | "TimeSpan has some critical methods relevant to how Patterns are working, and are used extensively in vortex.
\n",
309 | "`spanCycles` allows for a TimeSpan to extend its values to its nearest sam and next_sam.
\n",
310 | "`withtime` allows to apply a function to the begining and the end values of a TimeSpan, basically it allows for a Pattern to modify the duration of an Event (for example) or to the moment it is queried.
\n",
311 | "`sect` is also really useful when querying a pattern, to determine the duration of event within a given cycle.
\n",
312 | "These are just examples of how they can be used, to have a better understanding but they are no such strict rules and everything is possible."
313 | ]
314 | },
315 | {
316 | "cell_type": "markdown",
317 | "id": "f08491cd-be4c-4146-99a4-0485e0af5a24",
318 | "metadata": {},
319 | "source": [
320 | "### span_cycles"
321 | ]
322 | },
323 | {
324 | "cell_type": "code",
325 | "execution_count": 12,
326 | "id": "eaddaccd-62ef-46c1-b271-0da6442d981b",
327 | "metadata": {},
328 | "outputs": [
329 | {
330 | "data": {
331 | "text/plain": [
332 | "[TimeSpan(Time(0, 1), Time(1, 1))]"
333 | ]
334 | },
335 | "execution_count": 12,
336 | "metadata": {},
337 | "output_type": "execute_result"
338 | }
339 | ],
340 | "source": [
341 | "TimeSpan(0,1).span_cycles()"
342 | ]
343 | },
344 | {
345 | "cell_type": "code",
346 | "execution_count": 13,
347 | "id": "0e62d20e-44fc-4670-8d33-dbf4f394e3ef",
348 | "metadata": {},
349 | "outputs": [
350 | {
351 | "data": {
352 | "text/plain": [
353 | "[TimeSpan(Time(-1, 4), Time(0, 1)), TimeSpan(Time(0, 1), Time(3, 4))]"
354 | ]
355 | },
356 | "execution_count": 13,
357 | "metadata": {},
358 | "output_type": "execute_result"
359 | }
360 | ],
361 | "source": [
362 | "TimeSpan(-0.25, 0.75).span_cycles()"
363 | ]
364 | },
365 | {
366 | "cell_type": "code",
367 | "execution_count": 14,
368 | "id": "ec850b9f-afb4-4189-b858-696b4da37971",
369 | "metadata": {},
370 | "outputs": [
371 | {
372 | "data": {
373 | "text/plain": [
374 | "[TimeSpan(Time(-9, 4), Time(-2, 1)),\n",
375 | " TimeSpan(Time(-2, 1), Time(-1, 1)),\n",
376 | " TimeSpan(Time(-1, 1), Time(0, 1)),\n",
377 | " TimeSpan(Time(0, 1), Time(1, 1)),\n",
378 | " TimeSpan(Time(1, 1), Time(2, 1)),\n",
379 | " TimeSpan(Time(2, 1), Time(3, 1)),\n",
380 | " TimeSpan(Time(3, 1), Time(3884354678607053, 1125899906842624))]"
381 | ]
382 | },
383 | "execution_count": 14,
384 | "metadata": {},
385 | "output_type": "execute_result"
386 | }
387 | ],
388 | "source": [
389 | "TimeSpan(-2.25, 3.45).span_cycles()"
390 | ]
391 | },
392 | {
393 | "cell_type": "markdown",
394 | "id": "7df256cf-50ac-4acc-8bd2-633495b0bd5d",
395 | "metadata": {},
396 | "source": [
397 | "### with_time"
398 | ]
399 | },
400 | {
401 | "cell_type": "code",
402 | "execution_count": 15,
403 | "id": "0a86122f-816c-440b-8c2b-4407bba2df5e",
404 | "metadata": {},
405 | "outputs": [
406 | {
407 | "data": {
408 | "text/plain": [
409 | "TimeSpan(Time(1, 2), Time(5, 2))"
410 | ]
411 | },
412 | "execution_count": 15,
413 | "metadata": {},
414 | "output_type": "execute_result"
415 | }
416 | ],
417 | "source": [
418 | "TimeSpan(0.25, 1.25).with_time(lambda x: x*2)"
419 | ]
420 | },
421 | {
422 | "cell_type": "markdown",
423 | "id": "62ba47d1-1dd5-450e-ada7-f044db9d1cf3",
424 | "metadata": {},
425 | "source": [
426 | "Ok, let's stop a bit here and understand what's happening.
\n",
427 | "We are defining a lambda function that apply the operation multiply by 2 on each element of the TimeSpan, such that 0.25 and 1.25 become 0.5 and 2.5
\n",
428 | "If you are not comfortable with `lambda` syntax, you can simply declare you function the standard way and pass it to `withTime` in such way:"
429 | ]
430 | },
431 | {
432 | "cell_type": "code",
433 | "execution_count": 16,
434 | "id": "2bb5c359-08d5-4030-b6e0-0a6c5c3df96a",
435 | "metadata": {},
436 | "outputs": [
437 | {
438 | "data": {
439 | "text/plain": [
440 | "TimeSpan(Time(1, 2), Time(5, 2))"
441 | ]
442 | },
443 | "execution_count": 16,
444 | "metadata": {},
445 | "output_type": "execute_result"
446 | }
447 | ],
448 | "source": [
449 | "def multiply_by_2(x):\n",
450 | " return x * 2\n",
451 | "\n",
452 | "TimeSpan(0.25, 1.25).with_time(multiply_by_2)"
453 | ]
454 | },
455 | {
456 | "cell_type": "markdown",
457 | "id": "d7ed2a8f-5322-4d93-98f0-dd856fc0ae6d",
458 | "metadata": {},
459 | "source": [
460 | "And the result is exactly the same."
461 | ]
462 | },
463 | {
464 | "cell_type": "markdown",
465 | "id": "1fa63336-6149-4847-ba86-35466fcda273",
466 | "metadata": {},
467 | "source": [
468 | "### sect"
469 | ]
470 | },
471 | {
472 | "cell_type": "markdown",
473 | "id": "b1465450-8c18-433c-bbde-77ecb7c12ff0",
474 | "metadata": {},
475 | "source": [
476 | "If you need to know what is the TimeSpan common to 2 different TimeSpans, you can just use `sect` "
477 | ]
478 | },
479 | {
480 | "cell_type": "code",
481 | "execution_count": 17,
482 | "id": "9bcc93cd-8426-40a4-9c2a-e6bd16d6d87b",
483 | "metadata": {},
484 | "outputs": [
485 | {
486 | "data": {
487 | "text/plain": [
488 | "TimeSpan(Time(1, 2), Time(3, 4))"
489 | ]
490 | },
491 | "execution_count": 17,
492 | "metadata": {},
493 | "output_type": "execute_result"
494 | }
495 | ],
496 | "source": [
497 | "TimeSpan(0, 0.75).sect(TimeSpan(0.5, 1.5))"
498 | ]
499 | },
500 | {
501 | "cell_type": "code",
502 | "execution_count": 18,
503 | "id": "dbf422a5-3541-4976-bb5f-d09a3cbb73b6",
504 | "metadata": {},
505 | "outputs": [
506 | {
507 | "data": {
508 | "text/plain": [
509 | "TimeSpan(Time(1, 2), Time(3, 4))"
510 | ]
511 | },
512 | "execution_count": 18,
513 | "metadata": {},
514 | "output_type": "execute_result"
515 | }
516 | ],
517 | "source": [
518 | "TimeSpan(0.5, 1.75).sect(TimeSpan(0, 0.75))"
519 | ]
520 | },
521 | {
522 | "cell_type": "markdown",
523 | "id": "fff4e695-b00c-4523-92fb-23a7cd49ddea",
524 | "metadata": {},
525 | "source": [
526 | "If they do not overlap, then the result is None"
527 | ]
528 | },
529 | {
530 | "cell_type": "code",
531 | "execution_count": 19,
532 | "id": "f8bd340b-28c7-473b-a981-9a214bfacf12",
533 | "metadata": {},
534 | "outputs": [
535 | {
536 | "data": {
537 | "text/plain": [
538 | "True"
539 | ]
540 | },
541 | "execution_count": 19,
542 | "metadata": {},
543 | "output_type": "execute_result"
544 | }
545 | ],
546 | "source": [
547 | "no_overlap = TimeSpan(0, 0.75).sect(TimeSpan(1.5, 2))\n",
548 | "no_overlap is None"
549 | ]
550 | },
551 | {
552 | "cell_type": "markdown",
553 | "id": "44479ab3-3984-45ea-8629-15e55a5fefcc",
554 | "metadata": {},
555 | "source": [
556 | "# Event"
557 | ]
558 | },
559 | {
560 | "cell_type": "markdown",
561 | "id": "71e6cc37-be2e-4a70-a9be-c75701ceaeb1",
562 | "metadata": {},
563 | "source": [
564 | "Everythin in TIdal is an event, and Pattern (don't worry will get to it) modifies them.
\n",
565 | "Then, the scheduler who is responsible to making happen event with regards to Time, queries then and make them alive,
\n",
566 | "An event is composed of three different constituents: \n",
567 | "- a whole (a TimeSpan instance) which represents the duration an event is active, regardless of the query \n",
568 | "- a part (a TimeSpan instance) which represents the duration an event is active, during the TimeSpan of the cycle it is queried\n",
569 | "- a value (a string, a number, etc... ) which identifies it. Think of it as a key.\n",
570 | "\n",
571 | "Event possesses methods `withSpan`, `withValue` and `hasOnset`. These methods modifies with functions the differents constituents of an Event"
572 | ]
573 | },
574 | {
575 | "cell_type": "code",
576 | "execution_count": 20,
577 | "id": "463d6026-b0db-46cd-8920-82de5ec89dc1",
578 | "metadata": {},
579 | "outputs": [
580 | {
581 | "data": {
582 | "text/plain": [
583 | "Event(TimeSpan(Time(1, 4), Time(5, 4)), TimeSpan(Time(1, 2), Time(3, 4)), 'hello')"
584 | ]
585 | },
586 | "execution_count": 20,
587 | "metadata": {},
588 | "output_type": "execute_result"
589 | }
590 | ],
591 | "source": [
592 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\")"
593 | ]
594 | },
595 | {
596 | "cell_type": "code",
597 | "execution_count": 21,
598 | "id": "4f6fae5e-04d6-4834-9a72-c135d504f05c",
599 | "metadata": {},
600 | "outputs": [
601 | {
602 | "data": {
603 | "text/plain": [
604 | "Event(TimeSpan(Time(1, 4), Time(5, 4)), TimeSpan(Time(1, 2), Time(3, 4)), 2)"
605 | ]
606 | },
607 | "execution_count": 21,
608 | "metadata": {},
609 | "output_type": "execute_result"
610 | }
611 | ],
612 | "source": [
613 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), 2)"
614 | ]
615 | },
616 | {
617 | "cell_type": "markdown",
618 | "id": "fdf932fb-9f81-4f3b-a3a5-ca0375482ab1",
619 | "metadata": {},
620 | "source": [
621 | "### with_span"
622 | ]
623 | },
624 | {
625 | "cell_type": "code",
626 | "execution_count": 22,
627 | "id": "533ef3e1-a1fa-4702-9713-0b3c89938a5f",
628 | "metadata": {},
629 | "outputs": [
630 | {
631 | "data": {
632 | "text/plain": [
633 | "Event(TimeSpan(Time(9, 4), Time(13, 4)), TimeSpan(Time(5, 2), Time(11, 4)), 'hello')"
634 | ]
635 | },
636 | "execution_count": 22,
637 | "metadata": {},
638 | "output_type": "execute_result"
639 | }
640 | ],
641 | "source": [
642 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").with_span(lambda span: span.with_time(lambda x: x+2))"
643 | ]
644 | },
645 | {
646 | "cell_type": "markdown",
647 | "id": "e567c52b-ce11-41fd-a466-99566c41f2b8",
648 | "metadata": {},
649 | "source": [
650 | "Ok, just a moment of relfexion here. Even though `withSpan` takes a function as a parameter, it cannot take *any* function.
\n",
651 | "For this to be working, this function has to be a method *known* to TimeSpan (i.e. spanCycles, withTime or sect).
\n",
652 | "For example, this does not work (unless the + operator is overloaded for class TimeSpan - which is not the case atm)."
653 | ]
654 | },
655 | {
656 | "cell_type": "code",
657 | "execution_count": 23,
658 | "id": "9ef427c1-933f-4946-b68c-e962a72d0b0e",
659 | "metadata": {},
660 | "outputs": [],
661 | "source": [
662 | "# This does not work !!!\n",
663 | "# Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").withSpan(lambda x: x+2)"
664 | ]
665 | },
666 | {
667 | "cell_type": "markdown",
668 | "id": "69387157-bd17-4cc2-b6b0-f9de5a021f22",
669 | "metadata": {},
670 | "source": [
671 | "Also, be aware that any var pass to lambda will work, we use `span` here for convenience but it could be *anything*
"
672 | ]
673 | },
674 | {
675 | "cell_type": "code",
676 | "execution_count": 24,
677 | "id": "5af94bd6-273f-4665-8da5-0ee3f36f2110",
678 | "metadata": {},
679 | "outputs": [
680 | {
681 | "data": {
682 | "text/plain": [
683 | "Event(TimeSpan(Time(9, 4), Time(13, 4)), TimeSpan(Time(5, 2), Time(11, 4)), 'hello')"
684 | ]
685 | },
686 | "execution_count": 24,
687 | "metadata": {},
688 | "output_type": "execute_result"
689 | }
690 | ],
691 | "source": [
692 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").with_span(lambda x: x.with_time(lambda x: x+2))"
693 | ]
694 | },
695 | {
696 | "cell_type": "code",
697 | "execution_count": 25,
698 | "id": "cea79855-4aeb-402c-b067-d981dfcd6687",
699 | "metadata": {},
700 | "outputs": [
701 | {
702 | "data": {
703 | "text/plain": [
704 | "Event([TimeSpan(Time(1, 4), Time(1, 1)), TimeSpan(Time(1, 1), Time(5, 4))], [TimeSpan(Time(1, 2), Time(3, 4))], 'hello')"
705 | ]
706 | },
707 | "execution_count": 25,
708 | "metadata": {},
709 | "output_type": "execute_result"
710 | }
711 | ],
712 | "source": [
713 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").with_span(lambda span: span.span_cycles())"
714 | ]
715 | },
716 | {
717 | "cell_type": "code",
718 | "execution_count": 26,
719 | "id": "1872bdc0-e618-4b47-aa40-a04759b99e01",
720 | "metadata": {},
721 | "outputs": [
722 | {
723 | "data": {
724 | "text/plain": [
725 | "Event(TimeSpan(Time(1, 4), Time(5, 4)), TimeSpan(Time(1, 2), Time(3, 4)), 'hello')"
726 | ]
727 | },
728 | "execution_count": 26,
729 | "metadata": {},
730 | "output_type": "execute_result"
731 | }
732 | ],
733 | "source": [
734 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").with_span(lambda span: span.sect(TimeSpan(0,2)))"
735 | ]
736 | },
737 | {
738 | "cell_type": "markdown",
739 | "id": "e4773602-6627-43b7-9ae2-b7476b191df9",
740 | "metadata": {},
741 | "source": [
742 | "### with_value"
743 | ]
744 | },
745 | {
746 | "cell_type": "code",
747 | "execution_count": 27,
748 | "id": "35b886fb-a89a-4445-bde1-8278b74b38d2",
749 | "metadata": {},
750 | "outputs": [
751 | {
752 | "data": {
753 | "text/plain": [
754 | "Event(TimeSpan(Time(1, 4), Time(5, 4)), TimeSpan(Time(1, 2), Time(3, 4)), 'HELLO')"
755 | ]
756 | },
757 | "execution_count": 27,
758 | "metadata": {},
759 | "output_type": "execute_result"
760 | }
761 | ],
762 | "source": [
763 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").with_value(lambda x: x.upper())"
764 | ]
765 | },
766 | {
767 | "cell_type": "code",
768 | "execution_count": 28,
769 | "id": "5cf01a11-7f62-4e9e-91e2-40963a0c98e3",
770 | "metadata": {},
771 | "outputs": [
772 | {
773 | "data": {
774 | "text/plain": [
775 | "Event(TimeSpan(Time(1, 4), Time(5, 4)), TimeSpan(Time(1, 2), Time(3, 4)), 12)"
776 | ]
777 | },
778 | "execution_count": 28,
779 | "metadata": {},
780 | "output_type": "execute_result"
781 | }
782 | ],
783 | "source": [
784 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), 10).with_value(lambda x: x + 2)"
785 | ]
786 | },
787 | {
788 | "cell_type": "markdown",
789 | "id": "594b9c31-901f-415d-8aba-2f0b85470c86",
790 | "metadata": {},
791 | "source": [
792 | "### has_onset"
793 | ]
794 | },
795 | {
796 | "cell_type": "code",
797 | "execution_count": 29,
798 | "id": "aa068a49-4711-45fd-a4e1-338d5f1a6295",
799 | "metadata": {},
800 | "outputs": [
801 | {
802 | "data": {
803 | "text/plain": [
804 | "False"
805 | ]
806 | },
807 | "execution_count": 29,
808 | "metadata": {},
809 | "output_type": "execute_result"
810 | }
811 | ],
812 | "source": [
813 | "Event(TimeSpan(0.25, 1.25), TimeSpan(0.5, 0.75), \"hello\").has_onset()"
814 | ]
815 | },
816 | {
817 | "cell_type": "code",
818 | "execution_count": 30,
819 | "id": "fdfe3c9a-e8aa-4f9c-9efb-ee3654f5c154",
820 | "metadata": {},
821 | "outputs": [
822 | {
823 | "data": {
824 | "text/plain": [
825 | "True"
826 | ]
827 | },
828 | "execution_count": 30,
829 | "metadata": {},
830 | "output_type": "execute_result"
831 | }
832 | ],
833 | "source": [
834 | "Event(TimeSpan(0.5, 1.25), TimeSpan(0.5, 0.75), \"hello\").has_onset()"
835 | ]
836 | }
837 | ],
838 | "metadata": {
839 | "kernelspec": {
840 | "display_name": "Python 3 (ipykernel)",
841 | "language": "python",
842 | "name": "python3"
843 | },
844 | "language_info": {
845 | "codemirror_mode": {
846 | "name": "ipython",
847 | "version": 3
848 | },
849 | "file_extension": ".py",
850 | "mimetype": "text/x-python",
851 | "name": "python",
852 | "nbconvert_exporter": "python",
853 | "pygments_lexer": "ipython3",
854 | "version": "3.9.7"
855 | }
856 | },
857 | "nbformat": 4,
858 | "nbformat_minor": 5
859 | }
860 |
--------------------------------------------------------------------------------
/doc/doc-requirements.txt:
--------------------------------------------------------------------------------
1 | jupyterlab==3.2.4
2 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.poetry]
2 | name = "tidalvortex"
3 | version = "0.1.0-alpha.0"
4 | description = "Python port of TidalCycles"
5 | authors = ["Tidal Cyclists "]
6 | repository = "https://github.com/tidalcycles/vortex"
7 | license = "GPL-3.0-or-later"
8 | packages = [
9 | { include = "vortex" }
10 | ]
11 |
12 | [tool.poetry.dependencies]
13 | python = ">=3.8,<3.11"
14 | parsy = "^1.4.0"
15 | LinkPython = "^0.1.1"
16 | pyliblo3 = "^0.13.0"
17 | ipython = "^8.4.0"
18 | parsimonious = "^0.9.0"
19 | pyqt6 = "^6.4.2"
20 | pyqt6-qscintilla = "^2.13.4"
21 |
22 | [tool.poetry.dev-dependencies]
23 | pytest = "^7.1.2"
24 | pytest-cov = "^3.0.0"
25 | pytest-reorder = "^0.1.1"
26 | pre-commit = "^2.20.0"
27 | black = "22.6.0"
28 | isort = "5.10.1"
29 | pytest-watch = "^4.2.0"
30 | pytest-benchmark = "^3.4.1"
31 |
32 | [tool.poetry.scripts]
33 | vortex = 'vortex.cli:run'
34 |
35 | [build-system]
36 | requires = ["poetry-core>=1.0.0"]
37 | build-backend = "poetry.core.masonry.api"
38 |
--------------------------------------------------------------------------------
/pytest.ini:
--------------------------------------------------------------------------------
1 | [pytest]
2 | addopts = --benchmark-disable
3 |
--------------------------------------------------------------------------------
/test/test_mini_interpreter.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from vortex.mini import mini
4 | from vortex.pattern import (
5 | Pattern,
6 | TimeSpan,
7 | cat,
8 | choose_cycles,
9 | degrade,
10 | fast,
11 | polyrhythm,
12 | pure,
13 | silence,
14 | slow,
15 | slowcat,
16 | stack,
17 | timecat,
18 | )
19 |
20 |
21 | @pytest.mark.parametrize(
22 | "input_code,query_span,expected_pat",
23 | [
24 | # numbers
25 | ("45", None, pure(45)),
26 | ("-2.", None, pure(-2.0)),
27 | ("4.64", None, pure(4.64)),
28 | ("-3", None, pure(-3)),
29 | # words
30 | ("foo", None, pure("foo")),
31 | ("Bar", None, pure("Bar")),
32 | # rest
33 | ("~", None, silence()),
34 | # modifiers
35 | ("bd*2", None, fast(2, "bd")),
36 | ("bd/3", None, slow(3, "bd")),
37 | ("hh?", None, degrade("hh")),
38 | ("hh??", None, degrade(degrade("hh"))),
39 | (
40 | "hh!!??",
41 | None,
42 | degrade(degrade(cat("hh", "hh", "hh"))),
43 | ),
44 | # sequences
45 | ("bd sd", None, cat("bd", "sd")),
46 | ("bd hh sd", None, cat("bd", "hh", "sd")),
47 | ("hh@2", None, pure("hh")),
48 | ("bd hh@2", None, timecat((1, "bd"), (2, "hh"))),
49 | ("bd hh@3 sd@2", None, timecat((1, "bd"), (3, "hh"), (2, "sd"))),
50 | ("hh!", None, cat("hh", "hh")),
51 | ("hh!!", None, cat("hh", "hh", "hh")),
52 | ("bd! cp", None, cat("bd", "bd", "cp")),
53 | (
54 | "bd! hh? ~ sd/2 cp*3",
55 | None,
56 | timecat(
57 | (1, "bd"),
58 | (1, "bd"),
59 | (1, degrade("hh")),
60 | (1, silence()),
61 | (1, slow(2, "sd")),
62 | (1, fast(3, "cp")),
63 | ),
64 | ),
65 | ("bd | sd", TimeSpan(0, 10), choose_cycles("bd", "sd")),
66 | (
67 | "[bd [~ sd]] cp",
68 | None,
69 | cat(polyrhythm(["bd", polyrhythm([silence(), "sd"])]), "cp"),
70 | ),
71 | (
72 | "{a b c, D E}%2",
73 | TimeSpan(0, 3),
74 | slowcat(
75 | stack(cat("a", "b"), cat("D", "E")),
76 | stack(cat("c", "a"), cat("D", "E")),
77 | stack(cat("b", "c"), cat("D", "E")),
78 | ),
79 | ),
80 | ("", TimeSpan(0, 3), mini("{a b, c d e}%1")),
81 | ("bd(3,8)", None, pure("bd").euclid(3, 8)),
82 | ("bd(3,8,2)", None, pure("bd").euclid(3, 8, 2)),
83 | ("bd(<3 5>,8,<2 4>)", None, pure("bd").euclid(slowcat(3, 5), 8, slowcat(2, 4))),
84 | ("bd _ _ sd", None, mini("bd@3 sd")),
85 | ("bd cp . sd", None, polyrhythm([cat("bd", "cp"), "sd"])),
86 | ("bd*<2 3 4>", TimeSpan(0, 4), pure("bd").fast(slowcat(2, 3, 4))),
87 | ("bd/[2 3]", TimeSpan(0, 4), pure("bd").slow(cat(2, 3))),
88 | ],
89 | )
90 | def test_eval(input_code, query_span, expected_pat):
91 | pat = mini(input_code)
92 | assert isinstance(pat, Pattern)
93 | if not query_span:
94 | query_span = TimeSpan(0, 1)
95 | assert sorted(pat.query(query_span)) == sorted(expected_pat.query(query_span))
96 |
97 |
98 | # @pytest.mark.parametrize(
99 | # "test_input,expected",
100 | # [
101 | # # words
102 | # ("bd ", []),
103 | # ("bd#32", []),
104 | # ("drum_sound", []),
105 | # # sequences
106 | # ("bd bd", []),
107 | # ("bd bd bd ", []),
108 | # # modifiers
109 | # ("drum_sound/4", []),
110 | # ("sn*4 cp!4 bd@8 hh/3", []),
111 | # ("sn%4", []), # doesn't work in tidal but works here
112 | # ("sn*(3/5)", []), # scalar (fraction) argument of '*'
113 | # ("sn:35 sn:2 sn", []), # scalar (fraction) argument of '*'
114 | # # brackets
115 | # (" [ bd ] ", []),
116 | # ("[bd#32]", []),
117 | # ("[ bd bd bd ]", []),
118 | # ("[bd@3 ]", []),
119 | # # bracket modifiers
120 | # ("[bd#32@3 ]@3", []),
121 | # ("[-1.000!3 ]@3", []),
122 | # ("[-1.000!3 bd@3 ]@3", []),
123 | # # nesting
124 | # ("[[bd#32@3 ]]", []),
125 | # ("[ [bd@3 ]@3 bd ]", []),
126 | # (" [[ bd@3 ]@3] ", []),
127 | # (" [[ 0.3333@3 ]@3] ", []),
128 | # (" [[ bd@3 ]@3 bd!2]!3 ", []),
129 | # # deeper nesting
130 | # (" [ bd bd [bd bd]@3 [bd [bd bd]!3 ] ]", []),
131 | # (" [ bd bd [bd bd] [bd [bd bd] ] ]", []),
132 | # (" [ bd bd [bd bd] [bd [bd bd] ] ]@3", []),
133 | # (" [ bd [bd [bd [bd [bd [bd]]]]]]", []),
134 | # # angle brackets
135 | # ("< bd cp hh >", []),
136 | # ("< bd cp >", []),
137 | # ("< bd cp !2 >!3", []),
138 | # # curly brackets
139 | # ("{ bd cp bd }", []),
140 | # ("{ bd cp bd }%4", []),
141 | # ("{ bd cp {bd cp sn}%5 }%4", []),
142 | # # bracket mixtures
143 | # ("{ bd [bd hh ] }", []),
144 | # # euclidean
145 | # (" bd(3,8) ", []),
146 | # (" cp( 3,8, 2) ", []),
147 | # ("bd(3,4) cp( 3,8, 2) ", []),
148 | # (" cp( 3,8)!2 ", []),
149 | # (" cp( 3,8, 2)!2 ", []),
150 | # (" [bd cp ](3,8) ", []),
151 | # # patterned euclidean
152 | # (
153 | # "bd(3 5 2/3, 5)",
154 | # [],
155 | # ), # works but i think 3/2 is a fraction, not a slow-modified element
156 | # (
157 | # "bd(3 5 <2 3>, <5 7 4>)",
158 | # [],
159 | # ), # works but i don't undertand how we can pattern numbers yet.
160 | # # euclidean bracket mixtures
161 | # (
162 | # "{ bd(3,7) [bd hh(3,5) ] }",
163 | # [],
164 | # ),
165 | # # stacks
166 | # ("[bd, bd bd bd]", []),
167 | # ("[bd, bd bd bd, cp cp cp cp]", []),
168 | # ("[bd, [cp cp]!2, [sn sn sn]]", []),
169 | # ("[bd, [bd bd] bd [sn bd hh] hh hh ]", []),
170 | # # euclidan in stacks
171 | # ("[bd, cp(3,8) ]", []),
172 | # ("[bd,cp(3,8)]", []),
173 | # ("[bd, cp(3,8) sn(5,8) ]", []),
174 | # ("[bd, cp(3,8) sn!3 sn, cp ]", []),
175 | # ("[bd, cp(3,8), cp(5, 19) ]", []),
176 | # ("[bd, cp(3,8), bd(3,2,4), cp(5, 19) ]", []),
177 | # ("[bd, cp(3,8), bd(3 ,<3 8>,4), cp(5, 19) ]", []),
178 | # # nested stacks
179 | # ("[bd, [cp, sn!5] ]", []),
180 | # ("[bd, cp [cp*2, sn!5] ]", []),
181 | # pytest.param(
182 | # " [[ (3/8)@3 ]@3] ", [], marks=pytest.mark.xfail
183 | # ), # fails because number elements aren't handled yet.
184 | # pytest.param(
185 | # "[(-1.000/32)@3 ]@3", [], marks=pytest.mark.xfail
186 | # ), # fails because number elements aren't handled yet.
187 | # ],
188 | # )
189 | # def test_parse(benchmark, test_input, expected):
190 | # # FIXME: Assert expected output
191 | # assert benchmark(grammar.parse, test_input)
192 |
193 |
194 | # @pytest.mark.parametrize(
195 | # "test_input,expected",
196 | # [
197 | # ("bd", pure("bd")),
198 | # ("bd sd", cat(pure("bd"), pure("sd"))),
199 | # ("drum_sound/4", pure("drum_sound").slow(4)),
200 | # ],
201 | # )
202 | # def test_eval(test_input, expected):
203 | # assert mini(test_input).first_cycle() == expected.first_cycle()
204 |
--------------------------------------------------------------------------------
/test/test_mini_parser.py:
--------------------------------------------------------------------------------
1 | import pytest
2 |
3 | from vortex.mini import parse_mini
4 |
5 |
6 | @pytest.mark.parametrize(
7 | "input_code,expected_ast",
8 | [
9 | # numbers
10 | (
11 | "45",
12 | {
13 | "type": "sequence",
14 | "elements": [
15 | {
16 | "type": "element",
17 | "value": {"type": "number", "value": 45},
18 | "modifiers": [],
19 | }
20 | ],
21 | },
22 | ),
23 | (
24 | "-2.",
25 | {
26 | "type": "sequence",
27 | "elements": [
28 | {
29 | "type": "element",
30 | "value": {"type": "number", "value": -2.0},
31 | "modifiers": [],
32 | }
33 | ],
34 | },
35 | ),
36 | (
37 | "4.64",
38 | {
39 | "type": "sequence",
40 | "elements": [
41 | {
42 | "type": "element",
43 | "value": {"type": "number", "value": 4.64},
44 | "modifiers": [],
45 | }
46 | ],
47 | },
48 | ),
49 | (
50 | "-3",
51 | {
52 | "type": "sequence",
53 | "elements": [
54 | {
55 | "type": "element",
56 | "value": {"type": "number", "value": -3},
57 | "modifiers": [],
58 | }
59 | ],
60 | },
61 | ),
62 | # words
63 | (
64 | "foo",
65 | {
66 | "type": "sequence",
67 | "elements": [
68 | {
69 | "type": "element",
70 | "value": {"type": "word", "value": "foo", "index": 0},
71 | "modifiers": [],
72 | }
73 | ],
74 | },
75 | ),
76 | (
77 | "Bar:2",
78 | {
79 | "type": "sequence",
80 | "elements": [
81 | {
82 | "type": "element",
83 | "value": {"type": "word", "value": "Bar", "index": 2},
84 | "modifiers": [],
85 | }
86 | ],
87 | },
88 | ),
89 | # rest
90 | (
91 | "~",
92 | {
93 | "type": "sequence",
94 | "elements": [
95 | {"type": "element", "value": {"type": "rest"}, "modifiers": []}
96 | ],
97 | },
98 | ),
99 | # modifiers
100 | (
101 | "bd*2",
102 | {
103 | "type": "sequence",
104 | "elements": [
105 | {
106 | "type": "element",
107 | "value": {"type": "word", "value": "bd", "index": 0},
108 | "modifiers": [
109 | {
110 | "type": "modifier",
111 | "op": "fast",
112 | "value": {
113 | "type": "element",
114 | "value": {"type": "number", "value": 2},
115 | "modifiers": [],
116 | },
117 | }
118 | ],
119 | }
120 | ],
121 | },
122 | ),
123 | (
124 | "bd/3",
125 | {
126 | "type": "sequence",
127 | "elements": [
128 | {
129 | "type": "element",
130 | "value": {"type": "word", "value": "bd", "index": 0},
131 | "modifiers": [
132 | {
133 | "type": "modifier",
134 | "op": "slow",
135 | "value": {
136 | "type": "element",
137 | "value": {"type": "number", "value": 3},
138 | "modifiers": [],
139 | },
140 | }
141 | ],
142 | }
143 | ],
144 | },
145 | ),
146 | (
147 | "hh?",
148 | {
149 | "type": "sequence",
150 | "elements": [
151 | {
152 | "type": "element",
153 | "value": {"type": "word", "value": "hh", "index": 0},
154 | "modifiers": [
155 | {
156 | "type": "modifier",
157 | "op": "degrade",
158 | "value": {
159 | "type": "degrade_arg",
160 | "op": "count",
161 | "value": 1,
162 | },
163 | }
164 | ],
165 | }
166 | ],
167 | },
168 | ),
169 | (
170 | "hh???",
171 | {
172 | "type": "sequence",
173 | "elements": [
174 | {
175 | "type": "element",
176 | "value": {"type": "word", "value": "hh", "index": 0},
177 | "modifiers": [
178 | {
179 | "type": "modifier",
180 | "op": "degrade",
181 | "value": {
182 | "type": "degrade_arg",
183 | "op": "count",
184 | "value": 3,
185 | },
186 | }
187 | ],
188 | }
189 | ],
190 | },
191 | ),
192 | (
193 | "hh?4",
194 | {
195 | "type": "sequence",
196 | "elements": [
197 | {
198 | "type": "element",
199 | "value": {"type": "word", "value": "hh", "index": 0},
200 | "modifiers": [
201 | {
202 | "type": "modifier",
203 | "op": "degrade",
204 | "value": {
205 | "type": "degrade_arg",
206 | "op": "count",
207 | "value": 4,
208 | },
209 | }
210 | ],
211 | }
212 | ],
213 | },
214 | ),
215 | (
216 | "hh?4??",
217 | {
218 | "type": "sequence",
219 | "elements": [
220 | {
221 | "type": "element",
222 | "value": {"type": "word", "value": "hh", "index": 0},
223 | "modifiers": [
224 | {
225 | "type": "modifier",
226 | "op": "degrade",
227 | "value": {
228 | "type": "degrade_arg",
229 | "op": "count",
230 | "value": 6,
231 | },
232 | }
233 | ],
234 | }
235 | ],
236 | },
237 | ),
238 | (
239 | "hh??0.87",
240 | {
241 | "type": "sequence",
242 | "elements": [
243 | {
244 | "type": "element",
245 | "value": {"type": "word", "value": "hh", "index": 0},
246 | "modifiers": [
247 | {
248 | "type": "modifier",
249 | "op": "degrade",
250 | "value": {
251 | "type": "degrade_arg",
252 | "op": "value",
253 | "value": 0.87,
254 | },
255 | }
256 | ],
257 | }
258 | ],
259 | },
260 | ),
261 | (
262 | "hh!",
263 | {
264 | "type": "sequence",
265 | "elements": [
266 | {
267 | "type": "element",
268 | "value": {"type": "word", "value": "hh", "index": 0},
269 | "modifiers": [{"type": "modifier", "op": "repeat", "count": 1}],
270 | }
271 | ],
272 | },
273 | ),
274 | (
275 | "hh!!!",
276 | {
277 | "type": "sequence",
278 | "elements": [
279 | {
280 | "type": "element",
281 | "value": {"type": "word", "value": "hh", "index": 0},
282 | "modifiers": [{"type": "modifier", "op": "repeat", "count": 3}],
283 | }
284 | ],
285 | },
286 | ),
287 | (
288 | "hh!4",
289 | {
290 | "type": "sequence",
291 | "elements": [
292 | {
293 | "type": "element",
294 | "value": {"type": "word", "value": "hh", "index": 0},
295 | "modifiers": [{"type": "modifier", "op": "repeat", "count": 4}],
296 | }
297 | ],
298 | },
299 | ),
300 | (
301 | "hh!4!!",
302 | {
303 | "type": "sequence",
304 | "elements": [
305 | {
306 | "type": "element",
307 | "value": {"type": "word", "value": "hh", "index": 0},
308 | "modifiers": [{"type": "modifier", "op": "repeat", "count": 6}],
309 | }
310 | ],
311 | },
312 | ),
313 | (
314 | "hh@2",
315 | {
316 | "type": "sequence",
317 | "elements": [
318 | {
319 | "type": "element",
320 | "value": {"type": "word", "value": "hh", "index": 0},
321 | "modifiers": [{"type": "modifier", "op": "weight", "value": 2}],
322 | }
323 | ],
324 | },
325 | ),
326 | (
327 | "hh!!??!",
328 | {
329 | "type": "sequence",
330 | "elements": [
331 | {
332 | "type": "element",
333 | "value": {"type": "word", "value": "hh", "index": 0},
334 | "modifiers": [
335 | {"type": "modifier", "op": "repeat", "count": 2},
336 | {"type": "modifier", "op": "repeat", "count": 1},
337 | {
338 | "type": "modifier",
339 | "op": "degrade",
340 | "value": {
341 | "type": "degrade_arg",
342 | "op": "count",
343 | "value": 2,
344 | },
345 | },
346 | ],
347 | }
348 | ],
349 | },
350 | ),
351 | (
352 | "hh!/2?!",
353 | {
354 | "type": "sequence",
355 | "elements": [
356 | {
357 | "type": "element",
358 | "value": {"type": "word", "value": "hh", "index": 0},
359 | "modifiers": [
360 | {"type": "modifier", "op": "repeat", "count": 1},
361 | {
362 | "type": "modifier",
363 | "op": "slow",
364 | "value": {
365 | "type": "element",
366 | "value": {"type": "number", "value": 2},
367 | "modifiers": [
368 | {
369 | "type": "modifier",
370 | "op": "repeat",
371 | "count": 1,
372 | },
373 | {
374 | "type": "modifier",
375 | "op": "degrade",
376 | "value": {
377 | "type": "degrade_arg",
378 | "op": "count",
379 | "value": 1,
380 | },
381 | },
382 | ],
383 | },
384 | },
385 | ],
386 | }
387 | ],
388 | },
389 | ),
390 | # sequences
391 | (
392 | "bd sd",
393 | {
394 | "type": "sequence",
395 | "elements": [
396 | {
397 | "type": "element",
398 | "value": {"type": "word", "value": "bd", "index": 0},
399 | "modifiers": [],
400 | },
401 | {
402 | "type": "element",
403 | "value": {"type": "word", "value": "sd", "index": 0},
404 | "modifiers": [],
405 | },
406 | ],
407 | },
408 | ),
409 | (
410 | "bd hh sd",
411 | {
412 | "type": "sequence",
413 | "elements": [
414 | {
415 | "type": "element",
416 | "value": {"type": "word", "value": "bd", "index": 0},
417 | "modifiers": [],
418 | },
419 | {
420 | "type": "element",
421 | "value": {"type": "word", "value": "hh", "index": 0},
422 | "modifiers": [],
423 | },
424 | {
425 | "type": "element",
426 | "value": {"type": "word", "value": "sd", "index": 0},
427 | "modifiers": [],
428 | },
429 | ],
430 | },
431 | ),
432 | (
433 | "bd! hh? ~ sd/2 cp*3",
434 | {
435 | "type": "sequence",
436 | "elements": [
437 | {
438 | "type": "element",
439 | "value": {"type": "word", "value": "bd", "index": 0},
440 | "modifiers": [{"type": "modifier", "op": "repeat", "count": 1}],
441 | },
442 | {
443 | "type": "element",
444 | "value": {"type": "word", "value": "hh", "index": 0},
445 | "modifiers": [
446 | {
447 | "type": "modifier",
448 | "op": "degrade",
449 | "value": {
450 | "type": "degrade_arg",
451 | "op": "count",
452 | "value": 1,
453 | },
454 | }
455 | ],
456 | },
457 | {"type": "element", "value": {"type": "rest"}, "modifiers": []},
458 | {
459 | "type": "element",
460 | "value": {"type": "word", "value": "sd", "index": 0},
461 | "modifiers": [
462 | {
463 | "type": "modifier",
464 | "op": "slow",
465 | "value": {
466 | "type": "element",
467 | "value": {"type": "number", "value": 2},
468 | "modifiers": [],
469 | },
470 | }
471 | ],
472 | },
473 | {
474 | "type": "element",
475 | "value": {"type": "word", "value": "cp", "index": 0},
476 | "modifiers": [
477 | {
478 | "type": "modifier",
479 | "op": "fast",
480 | "value": {
481 | "type": "element",
482 | "value": {"type": "number", "value": 3},
483 | "modifiers": [],
484 | },
485 | }
486 | ],
487 | },
488 | ],
489 | },
490 | ),
491 | # polyrhythms
492 | (
493 | "[bd sd] hh",
494 | {
495 | "type": "sequence",
496 | "elements": [
497 | {
498 | "type": "element",
499 | "value": {
500 | "type": "polyrhythm",
501 | "seqs": [
502 | {
503 | "type": "sequence",
504 | "elements": [
505 | {
506 | "type": "element",
507 | "value": {
508 | "type": "word",
509 | "value": "bd",
510 | "index": 0,
511 | },
512 | "modifiers": [],
513 | },
514 | {
515 | "type": "element",
516 | "value": {
517 | "type": "word",
518 | "value": "sd",
519 | "index": 0,
520 | },
521 | "modifiers": [],
522 | },
523 | ],
524 | }
525 | ],
526 | },
527 | "modifiers": [],
528 | },
529 | {
530 | "type": "element",
531 | "value": {"type": "word", "value": "hh", "index": 0},
532 | "modifiers": [],
533 | },
534 | ],
535 | },
536 | ),
537 | # random sequence
538 | (
539 | "bd | sd cp",
540 | {
541 | "type": "random_sequence",
542 | "elements": [
543 | {
544 | "type": "sequence",
545 | "elements": [
546 | {
547 | "type": "element",
548 | "value": {"type": "word", "value": "bd", "index": 0},
549 | "modifiers": [],
550 | }
551 | ],
552 | },
553 | {
554 | "type": "sequence",
555 | "elements": [
556 | {
557 | "type": "element",
558 | "value": {"type": "word", "value": "sd", "index": 0},
559 | "modifiers": [],
560 | },
561 | {
562 | "type": "element",
563 | "value": {"type": "word", "value": "cp", "index": 0},
564 | "modifiers": [],
565 | },
566 | ],
567 | },
568 | ],
569 | },
570 | ),
571 | (
572 | "bd _ _ sd",
573 | {
574 | "type": "sequence",
575 | "elements": [
576 | {
577 | "type": "element",
578 | "value": {"type": "word", "value": "bd", "index": 0},
579 | "modifiers": [{"type": "modifier", "op": "weight", "value": 3}],
580 | },
581 | {
582 | "type": "element",
583 | "value": {"type": "word", "value": "sd", "index": 0},
584 | "modifiers": [],
585 | },
586 | ],
587 | },
588 | ),
589 | ("bd sd . cp . hh*2", parse_mini("[bd sd] [cp] [hh*2]")),
590 | (
591 | "bd*<2 3 4>",
592 | {
593 | "type": "sequence",
594 | "elements": [
595 | {
596 | "type": "element",
597 | "value": {"type": "word", "value": "bd", "index": 0},
598 | "modifiers": [
599 | {
600 | "type": "modifier",
601 | "op": "fast",
602 | "value": {
603 | "type": "element",
604 | "value": {
605 | "type": "polymeter",
606 | "seqs": [
607 | {
608 | "type": "sequence",
609 | "elements": [
610 | {
611 | "type": "element",
612 | "value": {
613 | "type": "number",
614 | "value": 2,
615 | },
616 | "modifiers": [],
617 | },
618 | {
619 | "type": "element",
620 | "value": {
621 | "type": "number",
622 | "value": 3,
623 | },
624 | "modifiers": [],
625 | },
626 | {
627 | "type": "element",
628 | "value": {
629 | "type": "number",
630 | "value": 4,
631 | },
632 | "modifiers": [],
633 | },
634 | ],
635 | }
636 | ],
637 | "steps": 1,
638 | },
639 | "modifiers": [],
640 | },
641 | }
642 | ],
643 | }
644 | ],
645 | },
646 | ),
647 | ],
648 | )
649 | def test_parse(input_code, expected_ast):
650 | ast = parse_mini(input_code)
651 | assert ast == expected_ast
652 |
--------------------------------------------------------------------------------
/test/test_pattern.py:
--------------------------------------------------------------------------------
1 | import math
2 | from itertools import groupby
3 |
4 | from vortex.control import (
5 | s,
6 | speed,
7 | n,
8 | create_param,
9 | create_params)
10 |
11 | from vortex.pattern import (
12 | Event,
13 | TimeSpan,
14 | choose,
15 | choose_cycles,
16 | choose_with,
17 | fast,
18 | fastcat,
19 | irand,
20 | perlin,
21 | pure,
22 | rand,
23 | randcat,
24 | rev,
25 | saw,
26 | slowcat,
27 | stack,
28 | timecat,
29 | wchoose,
30 | wchoose_with,
31 | )
32 |
33 |
34 | def assert_equal_patterns(input, expected, span=None):
35 | """Assert patterns by queyring them and comparing events"""
36 | if not span:
37 | span = TimeSpan(0, 1)
38 | assert sorted(input.query(span)) == sorted(expected.query(span))
39 |
40 |
41 | def test_add():
42 | assert_equal_patterns(pure(3) + 2, pure(5))
43 | assert_equal_patterns(3 + pure(5), pure(8))
44 |
45 |
46 | def test_sub():
47 | assert_equal_patterns(pure(3) - 1.5, pure(1.5))
48 | assert_equal_patterns(3 - pure(1), pure(2))
49 |
50 |
51 | def test_mul():
52 | assert_equal_patterns(pure(3) * 2, pure(6))
53 | assert_equal_patterns(10 * pure(3), pure(30))
54 |
55 |
56 | def test_truediv():
57 | assert_equal_patterns(pure(3) / 0.5, pure(6))
58 | assert_equal_patterns(3 / pure(2), pure(3 / 2))
59 |
60 |
61 | def test_floordiv():
62 | assert_equal_patterns(pure(3) // 2, pure(1))
63 | assert_equal_patterns(3 // pure(5), pure(0))
64 |
65 |
66 | def test_mod():
67 | assert_equal_patterns(pure(7) % 5, pure(2))
68 | assert_equal_patterns(3 % pure(2), pure(1))
69 |
70 |
71 | def test_pow():
72 | assert_equal_patterns(pure(3) ** 2, pure(9))
73 | assert_equal_patterns(2 ** pure(4), pure(16))
74 |
75 |
76 | def test_superimpose():
77 | assert_equal_patterns(
78 | pure("bd").superimpose(lambda p: p.fast(3)),
79 | stack(pure("bd"), pure("bd").fast(3)),
80 | )
81 |
82 |
83 | def test_layer():
84 | basepat = fastcat(pure("bd"), pure("sd"))
85 | assert_equal_patterns(
86 | basepat.layer(rev, lambda p: p.fast(2)),
87 | stack(basepat.rev(), basepat.fast(2)),
88 | )
89 |
90 |
91 | def test_iter():
92 | assert_equal_patterns(
93 | fastcat(pure("bd"), pure("hh"), pure("sn"), pure("cp")).iter(4),
94 | slowcat(
95 | fastcat(pure("bd"), pure("hh"), pure("sn"), pure("cp")),
96 | fastcat(pure("hh"), pure("sn"), pure("cp"), pure("bd")),
97 | fastcat(pure("sn"), pure("cp"), pure("bd"), pure("hh")),
98 | fastcat(pure("cp"), pure("bd"), pure("hh"), pure("sn")),
99 | ),
100 | span=TimeSpan(0, 4),
101 | )
102 |
103 |
104 | def test_reviter():
105 | assert_equal_patterns(
106 | fastcat(pure("bd"), pure("hh"), pure("sn"), pure("cp")).reviter(4),
107 | slowcat(
108 | fastcat(pure("bd"), pure("hh"), pure("sn"), pure("cp")),
109 | fastcat(pure("cp"), pure("bd"), pure("hh"), pure("sn")),
110 | fastcat(pure("sn"), pure("cp"), pure("bd"), pure("hh")),
111 | fastcat(pure("hh"), pure("sn"), pure("cp"), pure("bd")),
112 | ),
113 | span=TimeSpan(0, 4),
114 | )
115 |
116 |
117 | def test_fastgap():
118 | assert fastcat(pure("bd"), pure("sd")).fastgap(4).first_cycle() == [
119 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), "bd"),
120 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), "sd"),
121 | ]
122 |
123 |
124 | def test_compress():
125 | assert fastcat(pure("bd"), pure("sd")).compress(1 / 4, 3 / 4).first_cycle() == [
126 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), "bd"),
127 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), "sd"),
128 | ]
129 |
130 |
131 | def test_compress_invalid_span():
132 | assert pure("bd").fast(4).compress(1, 2).first_cycle() == []
133 | assert pure("bd").fast(4).compress(-1, 0).first_cycle() == []
134 |
135 |
136 | def test_compress_floats():
137 | assert fastcat(pure("bd"), pure("sd")).compress(1 / 4, 3 / 4).first_cycle() == [
138 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), "bd"),
139 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), "sd"),
140 | ]
141 |
142 |
143 | def test_timecat():
144 | assert timecat((3, pure("bd").fast(4)), (1, pure("hh").fast(8))).first_cycle() == [
145 | Event(TimeSpan(0, (3 / 16)), TimeSpan(0, (3 / 16)), "bd"),
146 | Event(TimeSpan((3 / 16), 3 / 8), TimeSpan((3 / 16), 3 / 8), "bd"),
147 | Event(TimeSpan(3 / 8, (9 / 16)), TimeSpan(3 / 8, (9 / 16)), "bd"),
148 | Event(TimeSpan((9 / 16), 3 / 4), TimeSpan((9 / 16), 3 / 4), "bd"),
149 | Event(TimeSpan(3 / 4, (25 / 32)), TimeSpan(3 / 4, (25 / 32)), "hh"),
150 | Event(TimeSpan((25 / 32), (13 / 16)), TimeSpan((25 / 32), (13 / 16)), "hh"),
151 | Event(TimeSpan((13 / 16), (27 / 32)), TimeSpan((13 / 16), (27 / 32)), "hh"),
152 | Event(TimeSpan((27 / 32), 7 / 8), TimeSpan((27 / 32), 7 / 8), "hh"),
153 | Event(TimeSpan(7 / 8, (29 / 32)), TimeSpan(7 / 8, (29 / 32)), "hh"),
154 | Event(TimeSpan((29 / 32), (15 / 16)), TimeSpan((29 / 32), (15 / 16)), "hh"),
155 | Event(TimeSpan((15 / 16), (31 / 32)), TimeSpan((15 / 16), (31 / 32)), "hh"),
156 | Event(TimeSpan((31 / 32), 1), TimeSpan((31 / 32), 1), "hh"),
157 | ]
158 |
159 |
160 | def test_striate():
161 | assert s(fastcat("bd", "sd")).striate(4).first_cycle() == [
162 | Event(
163 | TimeSpan(0, 1 / 8),
164 | TimeSpan(0, 1 / 8),
165 | {"s": "bd", "begin": 0.0, "end": 0.25},
166 | ),
167 | Event(
168 | TimeSpan(1 / 8, 1 / 4),
169 | TimeSpan(1 / 8, 1 / 4),
170 | {"s": "sd", "begin": 0.0, "end": 0.25},
171 | ),
172 | Event(
173 | TimeSpan(1 / 4, 3 / 8),
174 | TimeSpan(1 / 4, 3 / 8),
175 | {"s": "bd", "begin": 0.25, "end": 0.5},
176 | ),
177 | Event(
178 | TimeSpan(3 / 8, 1 / 2),
179 | TimeSpan(3 / 8, 1 / 2),
180 | {"s": "sd", "begin": 0.25, "end": 0.5},
181 | ),
182 | Event(
183 | TimeSpan(1 / 2, 5 / 8),
184 | TimeSpan(1 / 2, 5 / 8),
185 | {"s": "bd", "begin": 0.5, "end": 0.75},
186 | ),
187 | Event(
188 | TimeSpan(5 / 8, 3 / 4),
189 | TimeSpan(5 / 8, 3 / 4),
190 | {"s": "sd", "begin": 0.5, "end": 0.75},
191 | ),
192 | Event(
193 | TimeSpan(3 / 4, 7 / 8),
194 | TimeSpan(3 / 4, 7 / 8),
195 | {"s": "bd", "begin": 0.75, "end": 1.0},
196 | ),
197 | Event(
198 | TimeSpan(7 / 8, 1),
199 | TimeSpan(7 / 8, 1),
200 | {"s": "sd", "begin": 0.75, "end": 1.0},
201 | ),
202 | ]
203 |
204 |
205 | def test_range():
206 | assert_equal_patterns(saw().range(2, 7), saw() * (7 - 2) + 2)
207 |
208 |
209 | def test_rangex():
210 | assert_equal_patterns(
211 | saw().rangex(2, 7), saw().range(math.log(2), math.log(7)).fmap(math.exp)
212 | )
213 |
214 |
215 | def test_rand():
216 | assert rand().segment(4).first_cycle() == [
217 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), 0.3147844299674034),
218 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), 0.6004995740950108),
219 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), 0.1394200474023819),
220 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), 0.3935417253524065),
221 | ]
222 |
223 |
224 | def test_irand():
225 | assert irand(8).segment(4).first_cycle() == [
226 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), 2),
227 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), 4),
228 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), 1),
229 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), 3),
230 | ]
231 |
232 |
233 | def test_perlin():
234 | assert perlin().segment(4).first_cycle() == [
235 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), 0.008311405901167745),
236 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), 0.1424947878645071),
237 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), 0.3752773577048174),
238 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), 0.5094607396681567),
239 | ]
240 |
241 |
242 | def test_perlin_with():
243 | assert perlin(saw() * 4).segment(2).first_cycle() == [
244 | Event(TimeSpan(0, 1 / 2), TimeSpan(0, 1 / 2), 0.5177721455693245),
245 | Event(TimeSpan(1 / 2, 1), TimeSpan(1 / 2, 1), 0.8026083502918482),
246 | ]
247 |
248 |
249 | def test_choose():
250 | assert choose("a", "b", "c").segment(4).first_cycle() == [
251 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), "a"),
252 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), "b"),
253 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), "a"),
254 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), "b"),
255 | ]
256 |
257 |
258 | def test_choose_with():
259 | assert choose_with(perlin(), *range(8)).segment(4).first_cycle() == [
260 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), 0),
261 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), 1),
262 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), 3),
263 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), 4),
264 | ]
265 |
266 |
267 | def test_choose_distribution():
268 | values = [e.value for e in choose("a", "b", "c", "d").segment(100).first_cycle()]
269 | values_groupedby_count = {k: len(list(v)) for k, v in groupby(sorted(values))}
270 | # Check recurrence of values with uniform random distribution (each item should be around 25~)
271 | assert values_groupedby_count == {"a": 23, "b": 30, "c": 24, "d": 23}
272 |
273 |
274 | def test_wchoose():
275 | assert wchoose(("a", 1), ("e", 0.5), ("g", 2), ("c", 1)).segment(
276 | 4
277 | ).first_cycle() == [
278 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), "e"),
279 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), "g"),
280 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), "a"),
281 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), "g"),
282 | ]
283 |
284 |
285 | def test_wchoose_with():
286 | assert wchoose_with(
287 | rand().late(100), ("a", 1), ("e", 0.5), ("g", 2), ("c", 1)
288 | ).segment(4).first_cycle() == [
289 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 4), "a"),
290 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(1 / 4, 1 / 2), "g"),
291 | Event(TimeSpan(1 / 2, 3 / 4), TimeSpan(1 / 2, 3 / 4), "c"),
292 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 1), "a"),
293 | ]
294 |
295 |
296 | def test_wchoose_distribution():
297 | values = [
298 | e.value
299 | for e in wchoose(("a", 1), ("e", 0.5), ("g", 2), ("c", 1))
300 | .segment(100)
301 | .first_cycle()
302 | ]
303 | values_groupedby_count = {k: len(list(v)) for k, v in groupby(sorted(values))}
304 | # Check recurrence of values based on weights and uniform random distribution
305 | # a =~ 20, e =~ 10, g =~ 50, c =~ 20
306 | assert values_groupedby_count == {"a": 22, "e": 10, "g": 48, "c": 20}
307 |
308 |
309 | def test_choose_cycles():
310 | assert choose_cycles("bd", "sd", "hh").query(TimeSpan(0, 10)) == [
311 | Event(TimeSpan(0, 1), TimeSpan(0, 1), "bd"),
312 | Event(TimeSpan(1, 2), TimeSpan(1, 2), "sd"),
313 | Event(TimeSpan(2, 3), TimeSpan(2, 3), "sd"),
314 | Event(TimeSpan(3, 4), TimeSpan(3, 4), "sd"),
315 | Event(TimeSpan(4, 5), TimeSpan(4, 5), "hh"),
316 | Event(TimeSpan(5, 6), TimeSpan(5, 6), "bd"),
317 | Event(TimeSpan(6, 7), TimeSpan(6, 7), "bd"),
318 | Event(TimeSpan(7, 8), TimeSpan(7, 8), "sd"),
319 | Event(TimeSpan(8, 9), TimeSpan(8, 9), "sd"),
320 | Event(TimeSpan(9, 10), TimeSpan(9, 10), "bd"),
321 | ]
322 |
323 |
324 | def test_randcat():
325 | assert randcat("bd", "sd", "hh").query(TimeSpan(0, 10)) == choose_cycles(
326 | "bd", "sd", "hh"
327 | ).query(TimeSpan(0, 10))
328 |
329 |
330 | def test_degrade():
331 | assert_equal_patterns(
332 | pure("sd").fast(8).degrade(), pure("sd").fast(8).degrade_by(0.5, rand())
333 | )
334 |
335 |
336 | def test_degrade_by():
337 | assert pure("sd").fast(8).degrade_by(0.75).first_cycle() == [
338 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), "sd"),
339 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), "sd"),
340 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), "sd"),
341 | ]
342 |
343 |
344 | def test_degrade_by_diff_rand():
345 | assert pure("sd").fast(8).degrade_by(0.5, rand().late(100)).first_cycle() == [
346 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), "sd"),
347 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), "sd"),
348 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), "sd"),
349 | ]
350 |
351 |
352 | def test_undegrade():
353 | assert_equal_patterns(
354 | pure("sd").fast(8).undegrade(), pure("sd").fast(8).undegrade_by(0.5, rand())
355 | )
356 |
357 |
358 | def test_undegrade_by():
359 | assert pure("sd").fast(8).undegrade_by(0.25).first_cycle() == [
360 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), "sd")
361 | ]
362 |
363 |
364 | def test_undegrade_by_diff_rand():
365 | assert pure("sd").fast(8).undegrade_by(0.5, rand().late(100)).first_cycle() == [
366 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), "sd"),
367 | Event(TimeSpan(1 / 4, 3 / 8), TimeSpan(1 / 4, 3 / 8), "sd"),
368 | Event(TimeSpan(5 / 8, 3 / 4), TimeSpan(5 / 8, 3 / 4), "sd"),
369 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), "sd"),
370 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), "sd"),
371 | ]
372 |
373 |
374 | def test_sometimes():
375 | assert s("bd").fast(8).sometimes(lambda p: p << speed(2)).first_cycle() == [
376 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), {"speed": 2, "s": "bd"}),
377 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), {"s": "bd"}),
378 | Event(TimeSpan(1 / 4, 3 / 8), TimeSpan(1 / 4, 3 / 8), {"s": "bd"}),
379 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"s": "bd"}),
380 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), {"s": "bd"}),
381 | Event(TimeSpan(5 / 8, 3 / 4), TimeSpan(5 / 8, 3 / 4), {"speed": 2, "s": "bd"}),
382 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), {"s": "bd"}),
383 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), {"s": "bd"}),
384 | ]
385 |
386 |
387 | def test_sometimes_by():
388 | assert s("bd").fast(8).sometimes_by(
389 | 0.75, lambda p: p << speed(3)
390 | ).first_cycle() == [
391 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), {"speed": 3, "s": "bd"}),
392 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), {"s": "bd"}),
393 | Event(TimeSpan(1 / 4, 3 / 8), TimeSpan(1 / 4, 3 / 8), {"speed": 3, "s": "bd"}),
394 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"speed": 3, "s": "bd"}),
395 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), {"s": "bd"}),
396 | Event(TimeSpan(5 / 8, 3 / 4), TimeSpan(5 / 8, 3 / 4), {"speed": 3, "s": "bd"}),
397 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), {"s": "bd"}),
398 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), {"speed": 3, "s": "bd"}),
399 | ]
400 |
401 |
402 | def test_sometimes_pre():
403 | assert s("bd").fast(8).sometimes_pre(fast(2)).first_cycle() == [
404 | Event(TimeSpan(1 / 16, 1 / 8), TimeSpan(1 / 16, 1 / 8), {"s": "bd"}),
405 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), {"s": "bd"}),
406 | Event(TimeSpan(1 / 4, 5 / 16), TimeSpan(1 / 4, 5 / 16), {"s": "bd"}),
407 | Event(TimeSpan(1 / 4, 3 / 8), TimeSpan(1 / 4, 3 / 8), {"s": "bd"}),
408 | Event(TimeSpan(5 / 16, 3 / 8), TimeSpan(5 / 16, 3 / 8), {"s": "bd"}),
409 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"s": "bd"}),
410 | Event(TimeSpan(7 / 16, 1 / 2), TimeSpan(7 / 16, 1 / 2), {"s": "bd"}),
411 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), {"s": "bd"}),
412 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), {"s": "bd"}),
413 | Event(TimeSpan(13 / 16, 7 / 8), TimeSpan(13 / 16, 7 / 8), {"s": "bd"}),
414 | Event(TimeSpan(7 / 8, 15 / 16), TimeSpan(7 / 8, 15 / 16), {"s": "bd"}),
415 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), {"s": "bd"}),
416 | ]
417 |
418 |
419 | def test_sometimes_pre_by():
420 | assert s("bd").fast(8).sometimes_pre_by(0.25, fast(2)).first_cycle() == [
421 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), {"s": "bd"}),
422 | Event(TimeSpan(1 / 4, 3 / 8), TimeSpan(1 / 4, 3 / 8), {"s": "bd"}),
423 | Event(TimeSpan(5 / 16, 3 / 8), TimeSpan(5 / 16, 3 / 8), {"s": "bd"}),
424 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"s": "bd"}),
425 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), {"s": "bd"}),
426 | Event(TimeSpan(5 / 8, 3 / 4), TimeSpan(5 / 8, 3 / 4), {"s": "bd"}),
427 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), {"s": "bd"}),
428 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), {"s": "bd"}),
429 | ]
430 |
431 |
432 | def test_somecycles():
433 | assert s("sd").fast(2).somecycles(lambda p: p << speed(3)).query(
434 | TimeSpan(0, 4)
435 | ) == [
436 | Event(TimeSpan(0, 1 / 2), TimeSpan(0, 1 / 2), {"speed": 3, "s": "sd"}),
437 | Event(TimeSpan(1 / 2, 1), TimeSpan(1 / 2, 1), {"speed": 3, "s": "sd"}),
438 | Event(TimeSpan(1, 3 / 2), TimeSpan(1, 3 / 2), {"s": "sd"}),
439 | Event(TimeSpan(3 / 2, 2 / 1), TimeSpan(3 / 2, 2 / 1), {"s": "sd"}),
440 | Event(TimeSpan(2 / 1, 5 / 2), TimeSpan(2 / 1, 5 / 2), {"speed": 3, "s": "sd"}),
441 | Event(TimeSpan(5 / 2, 3 / 1), TimeSpan(5 / 2, 3 / 1), {"speed": 3, "s": "sd"}),
442 | Event(TimeSpan(3 / 1, 7 / 2), TimeSpan(3 / 1, 7 / 2), {"s": "sd"}),
443 | Event(TimeSpan(7 / 2, 4 / 1), TimeSpan(7 / 2, 4 / 1), {"s": "sd"}),
444 | ]
445 |
446 |
447 | def test_somecycles_by():
448 | assert s("sd").fast(2).somecycles_by(0.03, lambda p: p << speed(3)).query(
449 | TimeSpan(0, 6)
450 | ) == [
451 | Event(TimeSpan(0, 1 / 2), TimeSpan(0, 1 / 2), {"speed": 3, "s": "sd"}),
452 | Event(TimeSpan(1 / 2, 1), TimeSpan(1 / 2, 1), {"speed": 3, "s": "sd"}),
453 | Event(TimeSpan(1, 3 / 2), TimeSpan(1, 3 / 2), {"s": "sd"}),
454 | Event(TimeSpan(3 / 2, 2 / 1), TimeSpan(3 / 2, 2 / 1), {"s": "sd"}),
455 | Event(TimeSpan(2 / 1, 5 / 2), TimeSpan(2 / 1, 5 / 2), {"s": "sd"}),
456 | Event(TimeSpan(5 / 2, 3 / 1), TimeSpan(5 / 2, 3 / 1), {"s": "sd"}),
457 | Event(TimeSpan(3 / 1, 7 / 2), TimeSpan(3 / 1, 7 / 2), {"s": "sd"}),
458 | Event(TimeSpan(7 / 2, 4 / 1), TimeSpan(7 / 2, 4 / 1), {"s": "sd"}),
459 | Event(TimeSpan(4 / 1, 9 / 2), TimeSpan(4 / 1, 9 / 2), {"s": "sd"}),
460 | Event(TimeSpan(9 / 2, 5 / 1), TimeSpan(9 / 2, 5 / 1), {"s": "sd"}),
461 | Event(TimeSpan(5 / 1, 11 / 2), TimeSpan(5 / 1, 11 / 2), {"s": "sd"}),
462 | Event(TimeSpan(11 / 2, 6 / 1), TimeSpan(11 / 2, 6 / 1), {"s": "sd"}),
463 | ]
464 |
465 |
466 | def test_struct():
467 | assert pure("bd").struct(fastcat(1, 1, 0, 1, 0, 0, 1, 0)).first_cycle() == [
468 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), "bd"),
469 | Event(TimeSpan(1 / 8, 1 / 4), TimeSpan(1 / 8, 1 / 4), "bd"),
470 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), "bd"),
471 | Event(TimeSpan(3 / 4, 7 / 8), TimeSpan(3 / 4, 7 / 8), "bd"),
472 | ]
473 |
474 |
475 | def test_mask():
476 | assert s(fastcat("bd", "sd", "hh", "cp")).mask(
477 | fastcat(1, 1, 0, 1, 0, 0, 1, 0)
478 | ).first_cycle() == [
479 | Event(TimeSpan(0, 1 / 4), TimeSpan(0, 1 / 8), {"s": "bd"}),
480 | Event(TimeSpan(0, 1 / 4), TimeSpan(1 / 8, 1 / 4), {"s": "bd"}),
481 | Event(TimeSpan(1 / 4, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"s": "sd"}),
482 | Event(TimeSpan(3 / 4, 1), TimeSpan(3 / 4, 7 / 8), {"s": "cp"}),
483 | ]
484 |
485 |
486 | def test_euclid():
487 | assert s("sd").euclid(fastcat(3, 5), 8, fastcat(0, 1)).first_cycle() == [
488 | Event(TimeSpan(0, 1 / 8), TimeSpan(0, 1 / 8), {"s": "sd"}),
489 | Event(TimeSpan(3 / 8, 1 / 2), TimeSpan(3 / 8, 1 / 2), {"s": "sd"}),
490 | Event(TimeSpan(1 / 2, 5 / 8), TimeSpan(1 / 2, 5 / 8), {"s": "sd"}),
491 | Event(TimeSpan(5 / 8, 3 / 4), TimeSpan(5 / 8, 3 / 4), {"s": "sd"}),
492 | Event(TimeSpan(7 / 8, 1), TimeSpan(7 / 8, 1), {"s": "sd"}),
493 | ]
494 |
495 |
496 | def test_app_left():
497 | assert saw().segment(1).query(TimeSpan(0, 0.25)) == [
498 | Event(TimeSpan(0, 1), TimeSpan(0, 1 / 4), 0.5)
499 | ]
500 |
501 | def test_rshift():
502 | assert_equal_patterns(
503 | s("a") >> n("0 1"),
504 | s("a").combine_right(n("0 1"))
505 | )
506 | assert_equal_patterns(
507 | s("a").n("0 1"),
508 | s("a").combine_right(n("0 1"))
509 | )
510 |
511 | def test_lshift():
512 | assert_equal_patterns(
513 | s("a") << n("0 1"),
514 | s("a").combine_left(n("0 1"))
515 | )
516 |
517 | def test_create_param():
518 | _foo = create_param('foo')
519 | assert _foo(5).first_cycle() == [
520 | Event(TimeSpan(0, 1), TimeSpan(0, 1), {"foo": 5})
521 | ]
522 |
523 | def test_create_params():
524 | _foo, _bar = create_params(['foo', 'bar'])
525 | assert (_foo(17) >> _bar(42)).first_cycle() == [
526 | Event(TimeSpan(0, 1), TimeSpan(0, 1), {"foo": 17, "bar": 42})
527 | ]
528 | assert s('bd').foo(17).bar(42).first_cycle() == [
529 | Event(TimeSpan(0, 1), TimeSpan(0, 1), {"s": "bd", "foo": 17, "bar": 42})
530 | ]
531 |
--------------------------------------------------------------------------------
/test/test_py_vortex.py:
--------------------------------------------------------------------------------
1 | from fractions import Fraction
2 |
3 | import pytest
4 |
5 | import vortex as pyt
6 |
7 |
8 | @pytest.fixture
9 | def multi_list():
10 | return [[1, 2, 3], [4, 5, 6]]
11 |
12 |
13 | # Utilities
14 | def test_concat(multi_list):
15 | flat_list = pyt.flatten(multi_list)
16 | assert flat_list == [1, 2, 3, 4, 5, 6]
17 |
18 |
19 | def test_remove_none(multi_list):
20 | multi_list[0].append(None)
21 | no_none_list = pyt.remove_nones(multi_list[0])
22 | assert list(no_none_list) == [1, 2, 3]
23 |
24 |
25 | # Time Class tests
26 | def test_sam():
27 | a = Fraction(3, 2).sam()
28 | assert a == 1
29 | a = Fraction(3, 2).next_sam()
30 | assert a == 2
31 |
32 |
33 | def test_whole_cycle():
34 | a = Fraction(3, 2).whole_cycle()
35 | assert a.begin == 1
36 | assert a.end == 2
37 |
38 |
39 | # TimeSpan Class tests
40 | def test_intersection():
41 | a = pyt.TimeSpan(1, 4)
42 | span = a.intersection(pyt.TimeSpan(3, 6))
43 | assert span.begin == pyt.TimeSpan(3, 4).begin
44 | assert span.end == pyt.TimeSpan(3, 4).end
45 | a = pyt.TimeSpan(1, 2)
46 | try:
47 | span = a.intersection(pyt.TimeSpan(3, 6))
48 | except ValueError as v:
49 | assert (
50 | str(v)
51 | == "TimeSpan TimeSpan(Time(1, 1), Time(2, 1)) and TimeSpan TimeSpan(Time(3, 1), Time(6, 1)) do not intersect"
52 | )
53 |
54 |
55 | def test_with_time():
56 | a = pyt.TimeSpan(1, 4)
57 | wt = a.with_time(lambda x: x * 2)
58 | assert wt.begin == pyt.TimeSpan(2, 8).begin
59 | assert wt.end == pyt.TimeSpan(2, 8).end
60 |
61 |
62 | def test_span_cycles():
63 | a = pyt.TimeSpan(0.25, 2.5)
64 | sc = a.span_cycles()
65 | print(sc)
66 | assert sc[0].begin == a.begin
67 | assert sc[0].end == Fraction(1)
68 | assert sc[1].begin == Fraction(1)
69 | assert sc[1].end == Fraction(2)
70 | assert sc[2].begin == Fraction(2)
71 | assert sc[2].end == a.end
72 |
73 |
74 | # Event Class tests
75 | def test_event_span():
76 | e = pyt.Event(0.25, 0.5, 1)
77 | ws = e.with_span(lambda x: x * 2)
78 | assert ws.whole == 0.5
79 | assert ws.part == 1
80 | assert ws.value == 1
81 |
82 |
83 | def test_event_value():
84 | e = pyt.Event(pyt.TimeSpan(0, 1), pyt.TimeSpan(0.25, 0.5), 1)
85 | ws = e.with_value(lambda x: x * 2)
86 | print(ws)
87 | print(ws.whole)
88 | print(ws.whole.begin)
89 | assert ws.whole.begin == 0
90 | assert ws.whole.end == 1
91 | assert ws.part.begin == 0.25
92 | assert ws.part.end == 0.5
93 | assert ws.value == 2
94 |
95 |
96 | def test_has_onset():
97 | e = pyt.Event(pyt.TimeSpan(0.5, 1.5), pyt.TimeSpan(0.5, 1), "hello")
98 | assert e.has_onset
99 |
--------------------------------------------------------------------------------
/vortex/__init__.py:
--------------------------------------------------------------------------------
1 | import contextlib
2 | import importlib
3 |
4 | import pkg_resources
5 |
6 | try:
7 | # Change here if project is renamed and does not equal the package name
8 | package_name = "tidalvortex"
9 | __version__ = pkg_resources.get_distribution(package_name).version
10 | except pkg_resources.DistributionNotFound: # pragma: no cover
11 | __version__ = "unknown"
12 |
13 |
14 | from .control import *
15 | from .mini import mini, parse_mini
16 | from .pattern import *
17 | from .utils import *
18 | from .vortex import *
19 |
20 |
21 | @contextlib.contextmanager
22 | def vortex_dsl():
23 | """
24 | Create a Vortex DSL context, with a default LinkClock and some functions for
25 | managing Streams
26 |
27 | Returns
28 | -------
29 | ModuleType
30 | Vortex DSL module
31 |
32 | """
33 | # Import DSL module and get variables
34 | mod = importlib.import_module("vortex.boot")
35 | locals = vars(mod)
36 |
37 | # Start clock
38 | clock = locals["_default_clock"]
39 | clock.start()
40 |
41 | yield mod
42 |
43 | # We're exiting context, so stop clock thread
44 | clock.stop()
45 |
--------------------------------------------------------------------------------
/vortex/boot.py:
--------------------------------------------------------------------------------
1 | from vortex import *
2 | from vortex.stream import LinkClock, SuperDirtStream
3 |
4 | _default_clock = LinkClock(bpm=120)
5 | __streams = {}
6 |
7 |
8 | def p(key, pattern=None):
9 | if key not in __streams:
10 | __streams[key] = SuperDirtStream(name=key)
11 | _default_clock.subscribe(__streams[key])
12 | if pattern:
13 | __streams[key].pattern = pattern
14 | return __streams[key]
15 |
16 |
17 | def hush():
18 | for stream in __streams.values():
19 | stream.pattern = silence
20 | _default_clock.unsubscribe(stream)
21 | __streams.clear()
22 |
23 |
24 | class __Streams:
25 | def __setitem__(self, key, value):
26 | p(key, value)
27 |
28 |
29 | d = __Streams()
30 |
--------------------------------------------------------------------------------
/vortex/cli.py:
--------------------------------------------------------------------------------
1 | """
2 | Vortex REPL console script
3 | """
4 |
5 | import argparse
6 | import logging
7 | import sys
8 |
9 | from vortex import __version__
10 | from vortex.gui import start_gui
11 | from vortex.repl import start_repl
12 |
13 | _logger = logging.getLogger(__name__)
14 |
15 |
16 | def parse_args(args):
17 | """Parse command line parameters
18 |
19 | Args:
20 | args (List[str]): command line parameters as list of strings
21 | (for example ``["--help"]``).
22 |
23 | Returns:
24 | :obj:`argparse.Namespace`: command line parameters namespace
25 | """
26 | parser = argparse.ArgumentParser(description="Start Vortex editor or REPL")
27 |
28 | parser.add_argument(
29 | "--gui",
30 | default=True,
31 | action="store_true",
32 | help="Start a GUI code editor",
33 | )
34 | parser.add_argument(
35 | "--cli",
36 | dest="gui",
37 | action="store_false",
38 | help="Start the command line interpreter",
39 | )
40 |
41 | parser.add_argument(
42 | "--version",
43 | action="version",
44 | version="pyvortex {ver}".format(ver=__version__),
45 | )
46 | parser.add_argument(
47 | "-v",
48 | "--verbose",
49 | dest="loglevel",
50 | help="set loglevel to INFO",
51 | action="store_const",
52 | const=logging.INFO,
53 | )
54 | parser.add_argument(
55 | "-vv",
56 | "--very-verbose",
57 | dest="loglevel",
58 | help="set loglevel to DEBUG",
59 | action="store_const",
60 | const=logging.DEBUG,
61 | )
62 | return parser.parse_args(args)
63 |
64 |
65 | def setup_logging(loglevel):
66 | """Setup basic logging
67 |
68 | Args:
69 | loglevel (int): minimum loglevel for emitting messages
70 | """
71 | logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
72 | logging.basicConfig(
73 | level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S"
74 | )
75 |
76 |
77 | def main(args):
78 | """Wrapper allowing :func:`fib` to be called with string arguments in a CLI fashion
79 |
80 | Instead of returning the value from :func:`fib`, it prints the result to the
81 | ``stdout`` in a nicely formatted message.
82 |
83 | Args:
84 | args (List[str]): command line parameters as list of strings
85 | (for example ``["--verbose", "42"]``).
86 | """
87 | args = parse_args(args)
88 | setup_logging(args.loglevel)
89 |
90 | if args.gui:
91 | start_gui()
92 | else:
93 | start_repl()
94 |
95 |
96 | def run():
97 | """Calls :func:`main` passing the CLI arguments extracted from :obj:`sys.argv`
98 |
99 | This function can be used as entry point to create console scripts with setuptools.
100 | """
101 | main(sys.argv[1:])
102 |
103 |
104 | if __name__ == "__main__":
105 | run()
106 |
--------------------------------------------------------------------------------
/vortex/control.py:
--------------------------------------------------------------------------------
1 | import sys
2 |
3 | from .pattern import *
4 |
5 | # Create functions for making control patterns (patterns of dictionaries)
6 |
7 | generic_params = [
8 | ("s", "s", "sound"),
9 | ("s", "toArg", "for internal sound routing"),
10 | # ("f", "from", "for internal sound routing"), <- TODO - 'from' is a reserved word in python..
11 | ("f", "to", "for internal sound routing"),
12 | (
13 | "f",
14 | "accelerate",
15 | "a pattern of numbers that speed up (or slow down) samples while they play.",
16 | ),
17 | ("f", "amp", "like @gain@, but linear."),
18 | (
19 | "f",
20 | "attack",
21 | "a pattern of numbers to specify the attack time (in seconds) of an envelope applied to each sample.",
22 | ),
23 | (
24 | "f",
25 | "bandf",
26 | "a pattern of numbers from 0 to 1. Sets the center frequency of the band-pass filter.",
27 | ),
28 | (
29 | "f",
30 | "bandq",
31 | "a pattern of anumbers from 0 to 1. Sets the q-factor of the band-pass filter.",
32 | ),
33 | (
34 | "f",
35 | "begin",
36 | "a pattern of numbers from 0 to 1. Skips the beginning of each sample, e.g. `0.25` to cut off the first quarter from each sample.",
37 | ),
38 | ("f", "legato", "controls the amount of overlap between two adjacent sounds"),
39 | ("f", "clhatdecay", ""),
40 | (
41 | "f",
42 | "crush",
43 | "bit crushing, a pattern of numbers from 1 (for drastic reduction in bit-depth) to 16 (for barely no reduction).",
44 | ),
45 | (
46 | "f",
47 | "coarse",
48 | "fake-resampling, a pattern of numbers for lowering the sample rate, i.e. 1 for original 2 for half, 3 for a third and so on.",
49 | ),
50 | ("i", "channel", "choose the channel the pattern is sent to in superdirt"),
51 | (
52 | "i",
53 | "cut",
54 | "In the style of classic drum-machines, `cut` will stop a playing sample as soon as another samples with in same cutgroup is to be played. An example would be an open hi-hat followed by a closed one, essentially muting the open.",
55 | ),
56 | (
57 | "f",
58 | "cutoff",
59 | "a pattern of numbers from 0 to 1. Applies the cutoff frequency of the low-pass filter.",
60 | ),
61 | ("f", "cutoffegint", ""),
62 | ("f", "decay", ""),
63 | (
64 | "f",
65 | "delay",
66 | "a pattern of numbers from 0 to 1. Sets the level of the delay signal.",
67 | ),
68 | (
69 | "f",
70 | "delayfeedback",
71 | "a pattern of numbers from 0 to 1. Sets the amount of delay feedback.",
72 | ),
73 | (
74 | "f",
75 | "delaytime",
76 | "a pattern of numbers from 0 to 1. Sets the length of the delay.",
77 | ),
78 | ("f", "detune", ""),
79 | ("f", "djf", "DJ filter, below 0.5 is low pass filter, above is high pass filter."),
80 | (
81 | "f",
82 | "dry",
83 | "when set to `1` will disable all reverb for this pattern. See `room` and `size` for more information about reverb.",
84 | ),
85 | (
86 | "f",
87 | "end",
88 | "the same as `begin`, but cuts the end off samples, shortening them; e.g. `0.75` to cut off the last quarter of each sample.",
89 | ),
90 | (
91 | "f",
92 | "fadeTime",
93 | "Used when using begin/end or chop/striate and friends, to change the fade out time of the 'grain' envelope.",
94 | ),
95 | (
96 | "f",
97 | "fadeInTime",
98 | "As with fadeTime, but controls the fade in time of the grain envelope. Not used if the grain begins at position 0 in the sample.",
99 | ),
100 | ("f", "freq", ""),
101 | (
102 | "f",
103 | "gain",
104 | "a pattern of numbers that specify volume. Values less than 1 make the sound quieter. Values greater than 1 make the sound louder. For the linear equivalent, see @amp@.",
105 | ),
106 | ("f", "gate", ""),
107 | ("f", "hatgrain", ""),
108 | (
109 | "f",
110 | "hcutoff",
111 | "a pattern of numbers from 0 to 1. Applies the cutoff frequency of the high-pass filter. Also has alias @hpf@",
112 | ),
113 | (
114 | "f",
115 | "hold",
116 | "a pattern of numbers to specify the hold time (in seconds) of an envelope applied to each sample. Only takes effect if `attack` and `release` are also specified.",
117 | ),
118 | (
119 | "f",
120 | "hresonance",
121 | "a pattern of numbers from 0 to 1. Applies the resonance of the high-pass filter. Has alias @hpq@",
122 | ),
123 | ("f", "lagogo", ""),
124 | ("f", "lclap", ""),
125 | ("f", "lclaves", ""),
126 | ("f", "lclhat", ""),
127 | ("f", "lcrash", ""),
128 | ("f", "leslie", ""),
129 | ("f", "lrate", ""),
130 | ("f", "lsize", ""),
131 | ("f", "lfo", ""),
132 | ("f", "lfocutoffint", ""),
133 | ("f", "lfodelay", ""),
134 | ("f", "lfoint", ""),
135 | ("f", "lfopitchint", ""),
136 | ("f", "lfoshape", ""),
137 | ("f", "lfosync", ""),
138 | ("f", "lhitom", ""),
139 | ("f", "lkick", ""),
140 | ("f", "llotom", ""),
141 | (
142 | "f",
143 | "lock",
144 | "A pattern of numbers. Specifies whether delaytime is calculated relative to cps. When set to 1, delaytime is a direct multiple of a cycle.",
145 | ),
146 | (
147 | "f",
148 | "loop",
149 | "loops the sample (from `begin` to `end`) the specified number of times.",
150 | ),
151 | ("f", "lophat", ""),
152 | ("f", "lsnare", ""),
153 | ("f", "n", "The note or sample number to choose for a synth or sampleset"),
154 | ("f", "note", "The note or pitch to play a sound or synth with"),
155 | ("f", "degree", ""),
156 | ("f", "mtranspose", ""),
157 | ("f", "ctranspose", ""),
158 | ("f", "harmonic", ""),
159 | ("f", "stepsPerOctave", ""),
160 | ("f", "octaveR", ""),
161 | (
162 | "f",
163 | "nudge",
164 | "Nudges events into the future by the specified number of seconds. Negative numbers work up to a point as well (due to internal latency)",
165 | ),
166 | ("i", "octave", ""),
167 | ("f", "offset", ""),
168 | ("f", "ophatdecay", ""),
169 | (
170 | "i",
171 | "orbit",
172 | "a pattern of numbers. An `orbit` is a global parameter context for patterns. Patterns with the same orbit will share hardware output bus offset and global effects, e.g. reverb and delay. The maximum number of orbits is specified in the superdirt startup, numbers higher than maximum will wrap around.",
173 | ),
174 | ("f", "overgain", ""),
175 | ("f", "overshape", ""),
176 | (
177 | "f",
178 | "pan",
179 | "a pattern of numbers between 0 and 1, from left to right (assuming stereo), once round a circle (assuming multichannel)",
180 | ),
181 | (
182 | "f",
183 | "panspan",
184 | "a pattern of numbers between -inf and inf, which controls how much multichannel output is fanned out (negative is backwards ordering)",
185 | ),
186 | (
187 | "f",
188 | "pansplay",
189 | "a pattern of numbers between 0.0 and 1.0, which controls the multichannel spread range (multichannel only)",
190 | ),
191 | (
192 | "f",
193 | "panwidth",
194 | "a pattern of numbers between 0.0 and inf, which controls how much each channel is distributed over neighbours (multichannel only)",
195 | ),
196 | (
197 | "f",
198 | "panorient",
199 | "a pattern of numbers between -1.0 and 1.0, which controls the relative position of the centre pan in a pair of adjacent speakers (multichannel only)",
200 | ),
201 | ("f", "pitch1", ""),
202 | ("f", "pitch2", ""),
203 | ("f", "pitch3", ""),
204 | ("f", "portamento", ""),
205 | ("f", "rate", "used in SuperDirt softsynths as a control rate or 'speed'"),
206 | (
207 | "f",
208 | "release",
209 | "a pattern of numbers to specify the release time (in seconds) of an envelope applied to each sample.",
210 | ),
211 | (
212 | "f",
213 | "resonance",
214 | "a pattern of numbers from 0 to 1. Specifies the resonance of the low-pass filter.",
215 | ),
216 | ("f", "room", "a pattern of numbers from 0 to 1. Sets the level of reverb."),
217 | ("f", "sagogo", ""),
218 | ("f", "sclap", ""),
219 | ("f", "sclaves", ""),
220 | ("f", "scrash", ""),
221 | ("f", "semitone", ""),
222 | (
223 | "f",
224 | "shape",
225 | "wave shaping distortion, a pattern of numbers from 0 for no distortion up to 1 for loads of distortion.",
226 | ),
227 | (
228 | "f",
229 | "size",
230 | "a pattern of numbers from 0 to 1. Sets the perceptual size (reverb time) of the `room` to be used in reverb.",
231 | ),
232 | ("f", "slide", ""),
233 | (
234 | "f",
235 | "speed",
236 | "a pattern of numbers which changes the speed of sample playback, i.e. a cheap way of changing pitch. Negative values will play the sample backwards!",
237 | ),
238 | ("f", "squiz", ""),
239 | ("f", "stutterdepth", ""),
240 | ("f", "stuttertime", ""),
241 | ("f", "sustain", ""),
242 | ("f", "timescale", ""),
243 | ("f", "timescalewin", ""),
244 | ("f", "tomdecay", ""),
245 | (
246 | "s",
247 | "unit",
248 | 'used in conjunction with `speed`, accepts values of "r" (rate, default behavior), "c" (cycles), or "s" (seconds). Using `unit "c"` means `speed` will be interpreted in units of cycles, e.g. `speed "1"` means samples will be stretched to fill a cycle. Using `unit "s"` means the playback speed will be adjusted so that the duration is the number of seconds specified by `speed`.',
249 | ),
250 | ("f", "velocity", ""),
251 | ("f", "vcfegint", ""),
252 | ("f", "vcoegint", ""),
253 | ("f", "voice", ""),
254 | (
255 | "s",
256 | "vowel",
257 | "formant filter to make things sound like vowels, a pattern of either `a`, `e`, `i`, `o` or `u`. Use a rest (`~`) for no effect.",
258 | ),
259 | ("f", "waveloss", ""),
260 | ("f", "dur", ""),
261 | ("f", "modwheel", ""),
262 | ("f", "expression", ""),
263 | ("f", "sustainpedal", ""),
264 | (
265 | "f",
266 | "tremolodepth",
267 | "Tremolo Audio DSP effect | params are 'tremolorate' and 'tremolodepth'",
268 | ),
269 | (
270 | "f",
271 | "tremolorate",
272 | "Tremolo Audio DSP effect | params are 'tremolorate' and 'tremolodepth'",
273 | ),
274 | (
275 | "f",
276 | "phaserdepth",
277 | "Phaser Audio DSP effect | params are 'phaserrate' and 'phaserdepth'",
278 | ),
279 | (
280 | "f",
281 | "phaserrate",
282 | "Phaser Audio DSP effect | params are 'phaserrate' and 'phaserdepth'",
283 | ),
284 | ("f", "fshift", "frequency shifter"),
285 | ("f", "fshiftnote", "frequency shifter"),
286 | ("f", "fshiftphase", "frequency shifter"),
287 | ("f", "triode", "tube distortion"),
288 | ("f", "krush", "shape/bass enhancer"),
289 | ("f", "kcutoff", ""),
290 | ("f", "octer", "octaver effect"),
291 | ("f", "octersub", "octaver effect"),
292 | ("f", "octersubsub", "octaver effect"),
293 | ("f", "ring", "ring modulation"),
294 | ("f", "ringf", "ring modulation"),
295 | ("f", "ringdf", "ring modulation"),
296 | ("f", "distort", "noisy fuzzy distortion"),
297 | ("f", "freeze", "Spectral freeze"),
298 | ("f", "xsdelay", ""),
299 | ("f", "tsdelay", ""),
300 | ("f", "real", "Spectral conform"),
301 | ("f", "imag", ""),
302 | ("f", "enhance", "Spectral enhance"),
303 | ("f", "partials", ""),
304 | ("f", "comb", "Spectral comb"),
305 | ("f", "smear", "Spectral smear"),
306 | ("f", "scram", "Spectral scramble"),
307 | ("f", "binshift", "Spectral binshift"),
308 | ("f", "hbrick", "High pass sort of spectral filter"),
309 | ("f", "lbrick", "Low pass sort of spectral filter"),
310 | ("f", "midichan", ""),
311 | ("f", "control", ""),
312 | ("f", "ccn", ""),
313 | ("f", "ccv", ""),
314 | ("f", "polyTouch", ""),
315 | ("f", "midibend", ""),
316 | ("f", "miditouch", ""),
317 | ("f", "ctlNum", ""),
318 | ("f", "frameRate", ""),
319 | ("f", "frames", ""),
320 | ("f", "hours", ""),
321 | ("s", "midicmd", ""),
322 | ("f", "minutes", ""),
323 | ("f", "progNum", ""),
324 | ("f", "seconds", ""),
325 | ("f", "songPtr", ""),
326 | ("f", "uid", ""),
327 | ("f", "val", ""),
328 | ("f", "cps", ""),
329 | ]
330 |
331 | controls = []
332 |
333 | module_obj = sys.modules[__name__]
334 |
335 | # This had to go in its own function, for weird scoping reasons..
336 | def make_control(name):
337 | def ctrl(*args):
338 | return sequence(*[reify(arg) for arg in args]).fmap(lambda v: {name: v})
339 |
340 | def ctrl_pattern(self, *args):
341 | return self >> sequence(*[reify(arg) for arg in args]).fmap(lambda v: {name: v})
342 |
343 | # setattr(Pattern, name, lambda pat: Pattern(reify(pat).fmap(lambda v: {name: v}).query))
344 | setattr(module_obj, name, ctrl)
345 | setattr(Pattern, name, ctrl_pattern)
346 |
347 | return ctrl
348 |
349 |
350 | for t, name, desc in generic_params:
351 | make_control(name)
352 |
353 | def create_param(name):
354 | """ Creates a new control function with the given name """
355 | return make_control(name)
356 |
357 | def create_params(names):
358 | """ Creates a new control functions from the given list of names """
359 | return [make_control(name) for name in names]
360 |
361 | sound = s
362 |
--------------------------------------------------------------------------------
/vortex/euclid.py:
--------------------------------------------------------------------------------
1 | from typing import List
2 |
3 | from .utils import flatten
4 |
5 |
6 | def bjorklund(k: int, n: int, safe=True) -> List[int]:
7 | """Applies Bjorklund's algorithm for generating an euclidean rhythm sequence"""
8 |
9 | if not safe:
10 | if k > n:
11 | raise ValueError("k should be <= n")
12 | if k < 0 or n < 0:
13 | raise ValueError("k and n should be non-negative integers")
14 |
15 | # Instead of throwing exception, make sure `n` and `k are valid by taking
16 | # the absolute value of `n`` and `k % n` respectively.
17 | n = abs(n)
18 | k = abs(k % n)
19 |
20 | if n == 0 or k == 0:
21 | return []
22 |
23 | bins = [[1] for _ in range(k)]
24 | if n == k:
25 | return flatten(bins)
26 | remainders = [[0] for _ in range(n - k)]
27 |
28 | while len(remainders) > 1:
29 | new_remainders = []
30 | for i, bin in enumerate(bins):
31 | if not remainders:
32 | new_remainders.append(bin)
33 | else:
34 | bin += remainders.pop(0)
35 | bins[i] = bin
36 |
37 | if new_remainders:
38 | bins = bins[: -len(new_remainders)]
39 | remainders = new_remainders
40 |
41 | return flatten(bins + remainders)
42 |
--------------------------------------------------------------------------------
/vortex/gui.py:
--------------------------------------------------------------------------------
1 | import glob
2 | import logging
3 | import os
4 | import sys
5 | import time
6 |
7 | import pkg_resources
8 | from PyQt6.Qsci import *
9 | from PyQt6.QtCore import *
10 | from PyQt6.QtGui import *
11 | from PyQt6.QtWidgets import *
12 |
13 | from vortex import __version__, vortex_dsl
14 |
15 | _logger = logging.getLogger(__name__)
16 |
17 | RES_DIR = pkg_resources.resource_filename("vortex", "res")
18 | FONTS_DIR = os.path.join(RES_DIR, "fonts")
19 | HIGHLIGHT_INDICATOR_ID = 0
20 |
21 | DEFAULT_FONT_FAMILY = "Fira Code"
22 | DEFAULT_CODE = r"""# this is an example code
23 |
24 | # some block
25 |
26 | ##
27 | # another block
28 | #
29 |
30 | p("test", s(stack("gabba*4", "cp*3").every(3, fast(2)))
31 | >> speed("2 3")
32 | >> room(0.5)
33 | >> size(0.8)
34 | )
35 |
36 | ##
37 | # equivalent block
38 | #
39 |
40 | d["test"] = s(stack("gabba*4", "cp*3").every(3, fast(2)))
41 | .speed("2 3")
42 | .room(0.5)
43 | .size(0.8)
44 |
45 |
46 | hush()
47 |
48 | """.replace(
49 | "\n", "\r\n"
50 | )
51 |
52 |
53 | class HighlightLines(QRunnable):
54 | def __init__(self, editor, range, interval=0.1):
55 | super().__init__()
56 | self.editor = editor
57 | self.range = range
58 | self.interval = interval
59 |
60 | def run(self):
61 | start, end = self.range
62 | editor = self.editor
63 |
64 | line, index = editor.getCursorPosition()
65 | editor.setSelection(start, 0, end, 0)
66 | editor.setSelectionBackgroundColor(QColor("#ff00ff00"))
67 | editor.setSelectionForegroundColor(QColor("#ff000000"))
68 |
69 | _logger.info("Wait")
70 | time.sleep(self.interval)
71 |
72 | # TODO: Should clear from 0 to end of document, just in case...
73 | # editor.clearIndicatorRange(start, 0, end, 0, HIGHLIGHT_INDICATOR_ID)
74 | # editor.setCursorPosition(line, index)
75 | editor.resetSelectionBackgroundColor()
76 | editor.resetSelectionForegroundColor()
77 |
78 | _logger.info("Done")
79 |
80 |
81 | class VortexMainWindow(QMainWindow):
82 | def __init__(self, dsl_module):
83 | super(VortexMainWindow, self).__init__()
84 |
85 | self._dsl_module = dsl_module
86 |
87 | # Define the geometry of the main window
88 | # self.setGeometry(400, 100, 800, 600)
89 | self.setFixedSize(1280, 800)
90 | self.setWindowTitle(f"Vortex {__version__}")
91 |
92 | # Create frame and layout
93 | self._frame = QFrame(self)
94 | self._frame.setStyleSheet("QWidget { background-color: #ffeaeaea }")
95 | self._layout = QVBoxLayout()
96 | self._frame.setLayout(self._layout)
97 | self.setCentralWidget(self._frame)
98 |
99 | self._editorFont = QFont()
100 | self._editorFont.setPointSize(16)
101 | self._editorFont.setFamily(DEFAULT_FONT_FAMILY)
102 |
103 | # Create and configure Editor
104 | self._editor = QsciScintilla()
105 | self._editor.setText(DEFAULT_CODE)
106 | self._editor.setUtf8(True)
107 | self._editor.setIndentationsUseTabs(False)
108 | self._editor.setAutoIndent(True)
109 | self._editor.setTabIndents(True)
110 | self._editor.setTabWidth(4)
111 | self._editor.setIndentationGuides(True)
112 | self._editor.setCaretLineVisible(True)
113 | self._editor.setCaretLineBackgroundColor(QColor("#1fff0000"))
114 | self._editor.setCaretWidth(3)
115 | self._editor.setMarginType(0, QsciScintilla.MarginType.NumberMargin)
116 | self._editor.setMarginWidth(0, "000")
117 | self._editor.setMarginsForegroundColor(QColor("#ff888888"))
118 |
119 | # Create Python Lexer
120 | self._lexer = QsciLexerPython(self._editor)
121 | self._lexer.setFont(self._editorFont)
122 | self._editor.setLexer(self._lexer)
123 |
124 | self._editor.indicatorDefine(
125 | QsciScintilla.IndicatorStyle.FullBoxIndicator, HIGHLIGHT_INDICATOR_ID
126 | )
127 |
128 | # Commands and shortcuts
129 | commands = self._editor.standardCommands()
130 | command = commands.boundTo(Qt.KeyboardModifier.ControlModifier.value | Qt.Key.Key_Return.value)
131 | # Clear the default
132 | if command is not None:
133 | command.setKey(0)
134 | shortcut = QShortcut(Qt.KeyboardModifier.ControlModifier.value | Qt.Key.Key_Return.value, self._editor)
135 | shortcut.activated.connect(self.evaluate_block)
136 |
137 | # Add editor to layout
138 | self._layout.addWidget(self._editor)
139 |
140 | self.show()
141 |
142 | def evaluate_block(self):
143 | code, (start, end) = self.get_current_block()
144 | if code:
145 | _logger.info(f"Eval: '{code}'")
146 | try:
147 | exec(code, vars(self._dsl_module))
148 | except (TypeError, AttributeError) as e:
149 | _logger.info("error: %s", str(e))
150 | # self.highlight_block(start, end)
151 |
152 | def get_current_block(self):
153 | text = self._editor.text()
154 | lines = text.split("\n")
155 | line, _ = self._editor.getCursorPosition()
156 | if not lines[line].strip():
157 | return "", (line, line)
158 | start_line = line
159 | for i in reversed(range(0, line)):
160 | if not lines[i].strip():
161 | start_line = i + 1
162 | break
163 | end_line = line
164 | for i in range(line, len(lines)):
165 | if not lines[i].strip():
166 | end_line = i
167 | break
168 | _logger.debug("Block between lines %d and %d", start_line, end_line)
169 | block = "\n".join(lines[start_line : end_line + 1])
170 | return block, (start_line, end_line)
171 |
172 | def highlight_block(self, start_line, end_line):
173 | pool = QThreadPool.globalInstance()
174 | runnable = HighlightLines(self._editor, (start_line, end_line))
175 | pool.start(runnable)
176 |
177 |
178 | def load_fonts():
179 | font_files = glob.glob(os.path.join(FONTS_DIR, "*"))
180 | for font_file in font_files:
181 | font = QFontDatabase.addApplicationFont(font_file)
182 | if font == -1:
183 | _logger.warn("Failed to load font %s", font_file)
184 |
185 |
186 | def start_gui():
187 | app = QApplication(sys.argv)
188 | QApplication.setStyle(QStyleFactory.create("Fusion"))
189 |
190 | load_fonts()
191 |
192 | with vortex_dsl() as module:
193 | window = VortexMainWindow(dsl_module=module)
194 | app.exec()
195 |
--------------------------------------------------------------------------------
/vortex/mini/__init__.py:
--------------------------------------------------------------------------------
1 | import pprint
2 |
3 | from vortex.mini.grammar import grammar
4 | from vortex.mini.interpreter import MiniInterpreter, MiniVisitor
5 |
6 | visitor = MiniVisitor()
7 | interpreter = MiniInterpreter()
8 |
9 |
10 | def parse_mini(code):
11 | raw_ast = grammar.parse(code)
12 | return visitor.visit(raw_ast)
13 |
14 |
15 | def mini(code, print_ast=False):
16 | ast = parse_mini(code)
17 | if print_ast:
18 | pprint.pp(ast)
19 | return interpreter.eval(ast)
20 |
--------------------------------------------------------------------------------
/vortex/mini/grammar.py:
--------------------------------------------------------------------------------
1 | """
2 | Mini-notation grammar for Vortex.
3 |
4 | Grammar is defined using the PEG parsing library `parsimonious`.
5 |
6 | Given the set of rules and definitions (grammar) defined in this file, calling
7 | `grammar.parse(mn)` generates an abstract syntax tree (AST) for a given input
8 | mini-notation string named `mn`.
9 |
10 | Printing the tree object shows the generated ASTs. e.g.:
11 |
12 | ```
13 | tree = grammar.parse("bd(3, 8) cp")
14 | ```
15 |
16 | yields the following (truncated) AST, which can be pretty-printed with:
17 |
18 | ```
19 | print(tree.prettily())
20 | ```
21 |
22 | ```
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 | ...
32 |
33 |
34 |
35 |
36 |
37 |
38 | ```
39 |
40 | The parsimonious README (https://github.com/erikrose/parsimonious) was all I
41 | needed to get started writing a 'port' of the TidalCycles mini-notation grammar
42 | for Vortex.
43 |
44 | The strudel PEG grammar written in pegjs by Felix Roos was a valuable starting
45 | point, and many ideas were taken from there.
46 | https://github.com/tidalcycles/strudel/blob/main/packages/mini/krill.pegjs
47 |
48 | Reach out on the TidalCycles discord or club.tidalcycles.org if you have any
49 | bugs, optimizations, or questions.
50 |
51 | -Tyler
52 |
53 | """
54 |
55 | from parsimonious import Grammar
56 |
57 | grammar = Grammar(
58 | r"""
59 | root = ws? sequence ws?
60 |
61 | ##
62 | # Sequences
63 | #
64 | # A Sequence is a white-space separated collection of 2 or more elements
65 | # like "bd bd" or "[bd bd] [bd bd]". Underscores (continuation symbol) can
66 | # be part of a sequence but cannot be the first element.
67 | sequence = group (ws !'|' '.' ws group)* (ws? '|' ws? sequence)*
68 | group = element (ws !'.' element)*
69 |
70 | # An Element is an item of a Sequence, it can be a simple Term, or another
71 | # subsequence: Polymeters (braces), Polyrhythms (square brackets) or one-cycle
72 | # polymeter (angle brackets)
73 | element = element_value euclid_modifier? modifiers (ws '_')*
74 | element_value = term / polyrhythm_subseq / polymeter_subseq / polymeter1_subseq
75 |
76 | ##
77 | # Subsequences
78 | #
79 | polyrhythm_subseq = '[' ws? subseq_body ws? ']'
80 | polymeter_subseq = '{' ws? subseq_body ws? '}' polymeter_steps?
81 | polymeter1_subseq = '<' ws? subseq_body ws? '>'
82 | polymeter_steps = '%' number
83 | subseq_body = sequence (ws? ',' ws? sequence)*
84 |
85 | ##
86 | # Terms
87 | #
88 | term = number / word_with_index / rest
89 | word_with_index = word index?
90 | index = ':' number
91 |
92 | ##
93 | # Euclid modifier
94 | #
95 | euclid_modifier = '(' ws? sequence ws? ',' ws? sequence euclid_rotation_param? ws? ')'
96 | euclid_rotation_param = ws? ',' ws? sequence
97 |
98 | ##
99 | # Term modifiers
100 | #
101 | modifiers = modifier*
102 | modifier = fast / slow / repeat / degrade / weight
103 | fast = '*' element
104 | slow = '/' element
105 | repeat = (repeatn / repeat1)+
106 | repeatn = '!' !'!' pos_integer
107 | repeat1 = '!'
108 | degrade = degrader / degraden / degrade1
109 | degrader = '?' !'?' pos_real
110 | degraden = '?' !'?' !pos_real pos_integer
111 | degrade1 = '?'
112 | weight = '@' number
113 |
114 | ##
115 | # Primitives
116 | #
117 | # A primitive is a simple token like a word (string) or a number (real or
118 | # integer).
119 | word = ~"[-\w]+"
120 | number = real / integer
121 | real = integer '.' pos_integer?
122 | pos_real = pos_integer '.' pos_integer?
123 | integer = minus? pos_integer
124 | pos_integer = !minus ~"[0-9]+"
125 | rest = '~'
126 |
127 | ## Misc
128 | minus = '-'
129 | ws = ~"\s+"
130 | """
131 | )
132 |
--------------------------------------------------------------------------------
/vortex/mini/interpreter.py:
--------------------------------------------------------------------------------
1 | from fractions import Fraction
2 |
3 | from parsimonious import NodeVisitor
4 | from parsimonious.nodes import Node
5 |
6 | from vortex.control import n, s
7 | from vortex.pattern import pure # polymeter,
8 | from vortex.pattern import (
9 | choose_cycles,
10 | id,
11 | polyrhythm,
12 | sequence,
13 | silence,
14 | stack,
15 | timecat,
16 | )
17 | from vortex.utils import flatten
18 |
19 |
20 | class MiniVisitor(NodeVisitor):
21 | def visit_root(self, _node, children):
22 | _, sequence, _ = children
23 | return sequence
24 |
25 | def visit_sequence(self, _node, children):
26 | group, other_groups, other_seqs = children
27 | if isinstance(other_groups, Node):
28 | other_groups = []
29 | if isinstance(other_seqs, Node):
30 | other_seqs = []
31 | other_groups = [e[4] for e in other_groups]
32 | other_seqs = [e[3] for e in other_seqs]
33 | if other_groups:
34 | # Workaround: Re-build AST nodes as if it were a polyrhythm ("a b .
35 | # c" == "[a b] [c]")
36 | group = dict(
37 | type="sequence",
38 | elements=[
39 | dict(
40 | type="element",
41 | value=dict(type="polyrhythm", seqs=[group]),
42 | modifiers=[],
43 | ),
44 | *[
45 | dict(
46 | type="element",
47 | value=dict(type="polyrhythm", seqs=[g]),
48 | modifiers=[],
49 | )
50 | for g in other_groups
51 | ],
52 | ],
53 | )
54 | if other_seqs:
55 | return dict(type="random_sequence", elements=[group, *other_seqs])
56 | return group
57 |
58 | def visit_group(self, _node, children):
59 | element, other_elements = children
60 | if isinstance(other_elements, Node):
61 | other_elements = []
62 | other_elements = [e[2] for e in other_elements]
63 | return dict(type="sequence", elements=[element] + other_elements)
64 |
65 | def visit_element(self, _node, children):
66 | value, euclid_modifier, modifiers, elongate = children
67 | weight = 1 if isinstance(elongate, Node) else len(elongate) + 1
68 | element = dict(
69 | type="element",
70 | value=value,
71 | )
72 | if not isinstance(euclid_modifier, Node):
73 | element["euclid_modifier"] = euclid_modifier[0]
74 | weight_mod = next(
75 | (m for m in modifiers if m["op"] == "weight"),
76 | dict(type="modifier", op="weight", value=weight),
77 | )
78 | modifiers = [m for m in modifiers if m["op"] != "weight"]
79 | if weight_mod["value"] != 1:
80 | modifiers.append(weight_mod)
81 | element["modifiers"] = modifiers
82 | return element
83 |
84 | def visit_element_value(self, _node, children):
85 | return children[0]
86 |
87 | def visit_polyrhythm_subseq(self, _node, children):
88 | seqs = children[2]
89 | return dict(type="polyrhythm", seqs=seqs)
90 |
91 | def visit_polymeter_subseq(self, _node, children):
92 | seqs = children[2]
93 | steps = children[5]
94 | if isinstance(steps, Node):
95 | steps = 1
96 | else:
97 | steps = steps[0]
98 | return dict(type="polymeter", seqs=seqs, steps=steps)
99 |
100 | def visit_polymeter_steps(self, _node, children):
101 | _, number = children
102 | return number
103 |
104 | def visit_polymeter1_subseq(self, _node, children):
105 | seqs = children[2]
106 | return dict(type="polymeter", seqs=seqs, steps=1)
107 |
108 | def visit_subseq_body(self, _node, children):
109 | # sequence (ws? ',' ws? sequence)*
110 | seq, other_seqs = children
111 | if isinstance(other_seqs, Node):
112 | other_seqs = []
113 | other_seqs = [s[3] for s in other_seqs]
114 | return [seq] + other_seqs
115 |
116 | ##
117 | # Terms
118 | #
119 |
120 | def visit_term(self, _node, children):
121 | # Workaround to return an AST element "number" for numbers
122 | if not isinstance(children[0], dict):
123 | return dict(type="number", value=children[0])
124 | return children[0]
125 |
126 | def visit_rest(self, _node, _children):
127 | return dict(type="rest")
128 |
129 | def visit_word_with_index(self, _node, children):
130 | word, index = children
131 | index = 0 if isinstance(index, Node) else index[0]
132 | return dict(type="word", value=word, index=index)
133 |
134 | def visit_index(self, _node, children):
135 | _, number = children
136 | return number
137 |
138 | ##
139 | # Modifiers
140 | #
141 |
142 | def visit_euclid_modifier(self, _node, children):
143 | _, _, k, _, _, _, n, rotation, _, _ = children
144 | mod = dict(type="euclid_modifier", k=k, n=n)
145 | if not isinstance(rotation, Node):
146 | mod["rotation"] = rotation[0]
147 | return mod
148 |
149 | def visit_euclid_rotation_param(self, _node, children):
150 | _, _, _, rotation = children
151 | return rotation
152 |
153 | def visit_modifiers(self, _node, children):
154 | mods = [m for m in children if m["op"] not in ("degrade", "weight")]
155 |
156 | # The degrade modifier (?) does not take into account application order,
157 | # so we merge them into a single modifier.
158 | # There are two kinds of degrade modifiers, depending on its argument:
159 | # 1) "count" (degrade1/degraden) and 2) "value" (degrader). If there is
160 | # at least one "value" argument, the last occurrence takes precedences
161 | # and overwrites other degrade modifiers. Otherwise, we merge all other
162 | # "count" arguments into a single "count" modifier to simplify
163 | # representation.
164 | degrade_mods = [m for m in children if m["op"] == "degrade"]
165 | if degrade_mods:
166 | value_deg_mod = next(
167 | reversed([a for a in degrade_mods if a["value"]["op"] == "value"]), None
168 | )
169 | count_deg_mods = [a for a in degrade_mods if a["value"]["op"] == "count"]
170 | if value_deg_mod:
171 | mods.append(value_deg_mod)
172 | elif count_deg_mods:
173 | count_deg_mod = count_deg_mods[0].copy()
174 | deg_count = sum([m["value"]["value"] for m in count_deg_mods])
175 | count_deg_mod["value"]["value"] = deg_count
176 | mods.append(count_deg_mod)
177 |
178 | # The weight modifier (@) can be duplicated, but only the last one is
179 | # used, all others are ignored.
180 | weight_mods = [m for m in children if m["op"] == "weight"]
181 | if weight_mods:
182 | mods.append(weight_mods[-1])
183 |
184 | return mods
185 |
186 | def visit_modifier(self, _node, children):
187 | return children[0]
188 |
189 | def visit_fast(self, _node, children):
190 | _, number = children
191 | return dict(type="modifier", op="fast", value=number)
192 |
193 | def visit_slow(self, _node, children):
194 | _, number = children
195 | return dict(type="modifier", op="slow", value=number)
196 |
197 | def visit_repeat(self, _node, children):
198 | count = sum(flatten(children))
199 | return dict(type="modifier", op="repeat", count=count)
200 |
201 | def visit_repeatn(self, _node, children):
202 | _, _, count = children
203 | return count
204 |
205 | def visit_repeat1(self, _node, children):
206 | return 1
207 |
208 | def visit_degrade(self, _node, children):
209 | return dict(type="modifier", op="degrade", value=children[0])
210 |
211 | def visit_degrader(self, _node, children):
212 | _, _, value = children
213 | return dict(type="degrade_arg", op="value", value=value)
214 |
215 | def visit_degraden(self, _node, children):
216 | _, _, _, count = children
217 | return dict(type="degrade_arg", op="count", value=count)
218 |
219 | def visit_degrade1(self, _node, children):
220 | return dict(type="degrade_arg", op="count", value=1)
221 |
222 | def visit_weight(self, _node, children):
223 | _, number = children
224 | return dict(type="modifier", op="weight", value=number)
225 |
226 | ##
227 | # Primitives
228 | #
229 |
230 | def visit_word(self, node, _children):
231 | return node.text
232 |
233 | def visit_number(self, node, children):
234 | return children[0]
235 |
236 | def visit_real(self, node, _children):
237 | return float(node.text)
238 |
239 | def visit_integer(self, node, _children):
240 | return int(node.text)
241 |
242 | def visit_pos_integer(self, node, _children):
243 | return int(node.text)
244 |
245 | def visit_pos_real(self, node, _children):
246 | return float(node.text)
247 |
248 | ##
249 | # Others
250 | #
251 |
252 | def visit_ws(self, _node, _children):
253 | return
254 |
255 | def generic_visit(self, node, children):
256 | return children or node
257 |
258 |
259 | class MiniInterpreter:
260 | def eval(self, node):
261 | node_type = node["type"]
262 | eval_method = getattr(self, f"eval_{node_type}")
263 | return eval_method(node)
264 |
265 | def eval_sequence(self, node):
266 | return self._eval_sequence_elements(node["elements"])
267 |
268 | def _eval_sequence_elements(self, elements):
269 | elements = [self.eval(n) for n in elements]
270 | tc_args = []
271 | # Because each element might have been replicated/repeated, each element
272 | # is actually a list of tuples (weight, pattern, degrade_ratio).
273 | for es in elements:
274 | # We extract the weight and degrade_ratio from the first element (it
275 | # does not matter from which element, all have the same state
276 | # values).
277 | weight = es[0][0] if es else 1
278 | deg_ratio = es[0][2] if es else 0
279 | # Use the length of the replicated element as weight times the
280 | # `weight` modifier (if present). Build a sequence out of the
281 | # replicated elements and degrade by the accumulated degrade ratio.
282 | tc_args.append(
283 | (len(es) * weight, sequence(*[e[1] for e in es]).degrade_by(deg_ratio))
284 | )
285 | # Finally use timecat to create a pattern out of this sequence
286 | return timecat(*tc_args)
287 |
288 | def eval_random_sequence(self, node):
289 | seqs = [self.eval(e) for e in node["elements"]]
290 | return choose_cycles(*seqs)
291 |
292 | def eval_polyrhythm(self, node):
293 | return polyrhythm(*[self.eval(seq) for seq in node["seqs"]])
294 |
295 | def eval_polymeter(self, node):
296 | # FIXME: Is there a better way to do this? It'd be nice to use
297 | # `polymeter()`, but the sequences are already "sequence" patterns, not
298 | # a list of events. We might need to restructure grammar...
299 |
300 | # return polymeter(*[self.eval(seq) for seq in node["seqs"]], steps=node["steps"])
301 | fast_params = [
302 | Fraction(node["steps"], len(seq["elements"])) for seq in node["seqs"]
303 | ]
304 | return stack(
305 | *[
306 | self.eval(seq).fast(fparam)
307 | for seq, fparam in zip(node["seqs"], fast_params)
308 | ]
309 | )
310 |
311 | def eval_element(self, node):
312 | # Here we collect all modifier functions of an element and reduce them
313 | modifiers = [self.eval(m) for m in node["modifiers"]]
314 | pat = self.eval(node["value"])
315 | # Apply an euclid modifier if present
316 | if "euclid_modifier" in node:
317 | k, n, rotation = self.eval(node["euclid_modifier"])
318 | pat = pat.euclid(k, n, rotation)
319 | # The initial value is the tuple of 3 elements (see visit_modifier): a
320 | # default weight of 1, a "pure" pattern of the elements value and
321 | # degrade ratio of 0 (no degradation). It is a list of tuples, because
322 | # modifiers return a list of tuples (there might be repeat modifiers
323 | # that return multiple patterns).
324 | values = [(1, pat, 0)]
325 | for modifier in modifiers:
326 | # We eventually flatten list of lists into a single list
327 | values = flatten([modifier(v) for v in values])
328 | return values
329 |
330 | def eval_euclid_modifier(self, node):
331 | k = self.eval(node["k"])
332 | n = self.eval(node["n"])
333 | rotation = self.eval(node["rotation"]) if "rotation" in node else pure(0)
334 | return k, n, rotation
335 |
336 | def eval_modifier(self, node):
337 | # This is a bit ugly, but we maintain the "state" of modifiers by returning
338 | # a tuple of 3 elements: (weight, pattern, degrade_ratio), where:
339 | #
340 | # * `weight` is the current weight value for timecat
341 | # * `pattern` is the modified pattern
342 | # * `degrade_ratio` is the accumulated degrade ratio.
343 | #
344 | # The return value of the modifier functions is a list of Patterns,
345 | # because the repeat modifier might return multiple patterns of the
346 | # element, so we generalize it into a list for all modifiers.
347 | if node["op"] == "degrade":
348 | # Use the formula `n / (n + 1)` to increase the degrade ratio
349 | # "linearly". We expect there is a single degrade modifier
350 | # (guaranteed by the AST), so we can use the `count` as the final
351 | # count of degrade occurrences.
352 | arg = node["value"]
353 | if arg["op"] == "count":
354 | return lambda w_p: [
355 | (w_p[0], w_p[1], Fraction(arg["value"], arg["value"] + 1))
356 | ]
357 | elif arg["op"] == "value":
358 | return lambda w_p: [(w_p[0], w_p[1], arg["value"])]
359 | elif node["op"] == "repeat":
360 | return lambda w_p: [w_p] * (node["count"] + 1)
361 | elif node["op"] == "fast":
362 | param = self._eval_sequence_elements([node["value"]])
363 | return lambda w_p: [(w_p[0], w_p[1].fast(param), w_p[2])]
364 | elif node["op"] == "slow":
365 | param = self._eval_sequence_elements([node["value"]])
366 | return lambda w_p: [(w_p[0], w_p[1].slow(param), w_p[2])]
367 | elif node["op"] == "weight":
368 | # Overwrite current weight state value with the new weight from this
369 | # modifier. The AST will only contain a single "weight" modifier,
370 | # so there is no issue with replacing it.
371 | return lambda w_p: [(node["value"], w_p[1], w_p[2])]
372 | return id
373 |
374 | def eval_number(self, node):
375 | return pure(node["value"])
376 |
377 | def eval_word(self, node):
378 | if node["index"]:
379 | return s(node["value"]) << n(node["index"])
380 | else:
381 | return pure(node["value"])
382 |
383 | def eval_rest(self, node):
384 | return silence()
385 |
--------------------------------------------------------------------------------
/vortex/repl.py:
--------------------------------------------------------------------------------
1 | from IPython.terminal.embed import InteractiveShellEmbed
2 |
3 | from vortex import *
4 | from vortex import __version__
5 |
6 |
7 | def start_repl(*kwargs):
8 | """Start the interactive shell inside a Vortex environment"""
9 | with vortex_dsl() as module:
10 | ipshell = InteractiveShellEmbed(banner1=f"Vortex REPL, version {__version__}")
11 | ipshell(module=module)
12 |
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-Bold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-Bold.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-Light.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-Light.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-Medium.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-Medium.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-Regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-Regular.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-Retina.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-Retina.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/FiraCode-SemiBold.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/FiraCode-SemiBold.ttf
--------------------------------------------------------------------------------
/vortex/res/fonts/iosevka-term-regular.ttf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/tidalcycles/vortex/762200a75044eabf036ca3469810033931083fc6/vortex/res/fonts/iosevka-term-regular.ttf
--------------------------------------------------------------------------------
/vortex/stream.py:
--------------------------------------------------------------------------------
1 | from __future__ import annotations
2 |
3 | import logging
4 | import math
5 | import threading
6 | import time
7 | from abc import ABC
8 | from fractions import Fraction
9 | from typing import Any, Dict
10 |
11 | import liblo
12 | import link
13 |
14 | from vortex import *
15 |
16 | _logger = logging.getLogger(__name__)
17 |
18 |
19 | class LinkClock:
20 | """
21 | This class handles synchronization between different devices using the Link
22 | protocol.
23 |
24 | You can subscribe other objects (i.e. Streams), which will be notified on
25 | each clock tick. It expects that subscribers define a `notify_tick` method.
26 |
27 | Parameters
28 | ----------
29 | bpm: float
30 | beats per minute (default: 120)
31 |
32 | """
33 |
34 | def __init__(self, bpm=120):
35 | self.bpm = bpm
36 |
37 | self._subscribers = []
38 | self._link = link.Link(bpm)
39 | self._is_running = False
40 | self._mutex = threading.Lock()
41 |
42 | def subscribe(self, subscriber):
43 | """Subscribe an object to tick notifications"""
44 | with self._mutex:
45 | self._subscribers.append(subscriber)
46 |
47 | def unsubscribe(self, subscriber):
48 | """Unsubscribe from tick notifications"""
49 | with self._mutex:
50 | self._subscribers.remove(subscriber)
51 |
52 | def start(self):
53 | """Start the clock"""
54 | with self._mutex:
55 | if self._is_running:
56 | return
57 | self._is_running = True
58 | self._create_notify_thread()
59 |
60 | def stop(self):
61 | """Stop the clock"""
62 | with self._mutex:
63 | self._is_running = False
64 | # Wait until thread has stopped
65 | # Will block until (at least) the next start of frame
66 | self._notify_thread.join()
67 |
68 | @property
69 | def is_playing(self):
70 | """Returns whether clock is currently running"""
71 | return self._is_running
72 |
73 | def _create_notify_thread(self):
74 | self._notify_thread = threading.Thread(target=self._notify_thread_target)
75 | self._notify_thread.start()
76 |
77 | def _notify_thread_target(self):
78 | _logger.info("Link enabled")
79 | self._link.enabled = True
80 | self._link.startStopSyncEnabled = True
81 |
82 | start = self._link.clock().micros()
83 | mill = 1000000
84 | start_beat = self._link.captureSessionState().beatAtTime(start, 4)
85 | _logger.info("Start beat: %f", start_beat)
86 |
87 | ticks = 0
88 |
89 | # FIXME rate, bpc and latency should be constructor parameters
90 | rate = 1 / 20
91 | frame = rate * mill
92 | bpc = 4
93 |
94 | while self._is_running:
95 | ticks = ticks + 1
96 |
97 | logical_now = math.floor(start + (ticks * frame))
98 | logical_next = math.floor(start + ((ticks + 1) * frame))
99 |
100 | now = self._link.clock().micros()
101 |
102 | # wait until start of next frame
103 | wait = (logical_now - now) / mill
104 | if wait > 0:
105 | time.sleep(wait)
106 |
107 | if not self._is_running:
108 | break
109 |
110 | s = self._link.captureSessionState()
111 | cps = (s.tempo() / bpc) / 60
112 | cycle_from = s.beatAtTime(logical_now, 0) / bpc
113 | cycle_to = s.beatAtTime(logical_next, 0) / bpc
114 |
115 | try:
116 | for sub in self._subscribers:
117 | sub.notify_tick((cycle_from, cycle_to), s, cps, bpc, mill, now)
118 | except:
119 | pass
120 |
121 | # sys.stdout.write(
122 | # "cps %.2f | playing %s | cycle %.2f\r"
123 | # % (cps, s.isPlaying(), cycle_from)
124 | # )
125 |
126 | # sys.stdout.flush()
127 |
128 | self._link.enabled = False
129 | _logger.info("Link disabled")
130 | return
131 |
132 |
133 | class BaseStream(ABC):
134 | """
135 | A class for playing control pattern events
136 |
137 | It should be subscribed to a LinkClock instance.
138 |
139 | Parameters
140 | ----------
141 | name: Optional[str]
142 | Name of the stream instance
143 |
144 | """
145 |
146 | def __init__(self, name: str = None):
147 | self.name = name
148 | self.pattern = None
149 |
150 | def notify_tick(self, cycle, s, cps, bpc, mill, now):
151 | """Called by a Clock every time it ticks, when subscribed to it"""
152 | if not self.pattern:
153 | return
154 |
155 | cycle_from, cycle_to = cycle
156 | es = self.pattern.onsets_only().query(TimeSpan(cycle_from, cycle_to))
157 | if len(es):
158 | _logger.debug("%s", [e.value for e in es])
159 |
160 | for e in es:
161 | cycle_on = e.whole.begin
162 | cycle_off = e.whole.end
163 |
164 | link_on = s.timeAtBeat(cycle_on * bpc, 0)
165 | link_off = s.timeAtBeat(cycle_off * bpc, 0)
166 | delta_secs = (link_off - link_on) / mill
167 |
168 | # Maybe better to only calc this once??
169 | # + it would be better to send link time to supercollider..
170 | link_secs = now / mill
171 | liblo_diff = liblo.time() - link_secs
172 | nudge = e.value.get("nudge", 0)
173 | ts = (link_on / mill) + liblo_diff + self.latency + nudge
174 |
175 | # print("liblo time %f link_time %f link_on %f cycle_on %f liblo_diff %f ts %f" % (liblo.time(), link_secs, link_on, cycle_on, liblo_diff, ts))
176 | self.notify_event(
177 | e.value,
178 | timestamp=ts,
179 | cps=float(cps),
180 | cycle=float(cycle_on),
181 | delta=float(delta_secs),
182 | )
183 |
184 | def notify_event(
185 | self,
186 | event: Dict[str, Any],
187 | timestamp: float,
188 | cps: float,
189 | cycle: float,
190 | delta: float,
191 | ):
192 | """Called by `notify_tick` with the event and timestamp that should be played"""
193 | raise NotImplementedError
194 |
195 | def __repr__(self):
196 | pattern_repr = " \n" + repr(self.pattern) if self.pattern else ""
197 | return f"<{self.__class__.__name__} {repr(self.name)}{pattern_repr}>"
198 |
199 |
200 | class SuperDirtStream(BaseStream):
201 | """
202 | This Stream class sends control pattern messages to SuperDirt via OSC
203 |
204 | Parameters
205 | ----------
206 | port: int
207 | The port where SuperDirt is listening
208 | latency: float
209 | SuperDirt latency
210 |
211 | """
212 |
213 | def __init__(self, port=57120, latency=0.2, *args, **kwargs):
214 | super().__init__(*args, **kwargs)
215 |
216 | self.latency = latency
217 |
218 | self._port = port
219 | self._address = liblo.Address(port)
220 |
221 | @property
222 | def port(self):
223 | """SuperDirt listening port"""
224 | return self._port
225 |
226 | def notify_event(
227 | self,
228 | event: Dict[str, Any],
229 | timestamp: float,
230 | cps: float,
231 | cycle: float,
232 | delta: float,
233 | ):
234 | msg = []
235 | for key, val in event.items():
236 | if isinstance(val, Fraction):
237 | val = float(val)
238 | msg.append(key)
239 | msg.append(val)
240 | msg.extend(["cps", cps, "cycle", cycle, "delta", delta])
241 | _logger.info("%s", msg)
242 |
243 | # liblo.send(superdirt, "/dirt/play", *msg)
244 | bundle = liblo.Bundle(timestamp, liblo.Message("/dirt/play", *msg))
245 | liblo.send(self._address, bundle)
246 |
247 | def setup_logging(loglevel):
248 | """Setup basic logging
249 |
250 | Args:
251 | loglevel (int): minimum loglevel for emitting messages
252 | """
253 | logformat = "[%(asctime)s] %(levelname)s:%(name)s:%(message)s"
254 | logging.basicConfig(
255 | level=loglevel, stream=sys.stdout, format=logformat, datefmt="%Y-%m-%d %H:%M:%S"
256 | )
257 |
258 | if __name__ == "__main__":
259 | setup_logging(logging.DEBUG)
260 | clock = LinkClock(120)
261 | clock.start()
262 |
263 | stream = SuperDirtStream()
264 | clock.subscribe(stream)
265 |
266 | logging.info(">> Wait a sec")
267 | time.sleep(1)
268 |
269 | logging.info(">> Set pattern and let it play for 2 seconds")
270 | stream.pattern = s(stack("gabba*4", "cp*3")).speed("2 3") >> room(0.5).size(0.8)
271 | time.sleep(2)
272 |
273 | logging.info(">> Stop the clock momentarily")
274 | clock.stop()
275 |
276 | logging.info(">> Now, wait 3 secs")
277 | time.sleep(3)
278 |
279 | logging.info(">> Start again...")
280 | clock.start()
281 |
282 | time.sleep(2)
283 |
284 | logging.info(">> Stop the clock")
285 | clock.stop()
286 | logging.info(">> Done")
287 |
--------------------------------------------------------------------------------
/vortex/utils.py:
--------------------------------------------------------------------------------
1 | import operator
2 | from fractions import Fraction
3 | from functools import partial, reduce, wraps
4 |
5 |
6 | def flatten(lst) -> list:
7 | """Flattens a list of lists"""
8 | return [item for sublist in lst for item in sublist]
9 |
10 |
11 | def remove_nones(lst) -> list:
12 | """Removes 'None' values from given list"""
13 | return filter(lambda x: x != None, lst)
14 |
15 |
16 | def id(x):
17 | """Identity function"""
18 | return x
19 |
20 |
21 | def merge_dicts(a, b, op=operator.add):
22 | return dict(a.items() + b.items() + [(k, op(a[k], b[k])) for k in set(b) & set(a)])
23 |
24 |
25 | def rotate_left(lst, n):
26 | """Rotate an array `n` elements to the left"""
27 | return lst[n:] + lst[:n]
28 |
29 |
30 | def partial_function(f):
31 | """Decorator for functions to support partial application. When not given enough
32 | arguments, a decoracted function will return a new function for the remaining
33 | arguments"""
34 |
35 | def wrapper(*args):
36 | try:
37 | return f(*args)
38 | except (TypeError) as e:
39 | return partial(f, *args)
40 |
41 | return wrapper
42 |
43 |
44 | def show_fraction(frac):
45 | if frac == None:
46 | return "None"
47 |
48 | if frac.denominator == 1:
49 | return str(frac.numerator)
50 |
51 | lookup = {
52 | Fraction(1, 2): "½",
53 | Fraction(1, 3): "⅓",
54 | Fraction(2, 3): "⅔",
55 | Fraction(1, 4): "¼",
56 | Fraction(3, 4): "¾",
57 | Fraction(1, 5): "⅕",
58 | Fraction(2, 5): "⅖",
59 | Fraction(3, 5): "⅗",
60 | Fraction(4, 5): "⅘",
61 | Fraction(1, 6): "⅙",
62 | Fraction(5, 6): "⅚",
63 | Fraction(1, 7): "⅐",
64 | Fraction(1, 8): "⅛",
65 | Fraction(3, 8): "⅜",
66 | Fraction(5, 8): "⅝",
67 | Fraction(7, 8): "⅞",
68 | Fraction(1, 9): "⅑",
69 | Fraction(1, 10): "⅒",
70 | }
71 | if frac in lookup:
72 | result = lookup[frac]
73 | else:
74 | result = "(%d/%d)" % (frac.numerator, frac.denominator)
75 | return result
76 |
77 |
78 | def curry(f):
79 | @wraps(f)
80 | def _(arg):
81 | try:
82 | return f(arg)
83 | except TypeError:
84 | return curry(wraps(f)(partial(f, arg)))
85 |
86 | return _
87 |
88 |
89 | def uncurry(f):
90 | @wraps(f)
91 | def _(*args):
92 | return reduce(lambda x, y: x(y), args, f)
93 |
94 | return _
95 |
--------------------------------------------------------------------------------
/vortex/vortex.py:
--------------------------------------------------------------------------------
1 | """
2 | Experiment: porting Tidalcycles to Python 3.x.
3 | """
4 |
5 | from __future__ import annotations
6 |
7 | import logging
8 |
9 | from vortex.pattern import *
10 |
11 |
12 | def pattern_pretty_printing(pattern: Pattern, query_span: TimeSpan) -> None:
13 | """Better formatting for logging.debuging Tidal Patterns"""
14 | for event in pattern.query(query_span):
15 |
16 | logging.debug(event)
17 |
18 |
19 | if __name__ == "__main__":
20 | # Simple patterns
21 | a = pure("hello")
22 | b = pure("world")
23 | c = fastcat(a, b)
24 | d = stack(a, b)
25 |
26 | # printing the pattern
27 | logging.debug("\n== TEST PATTERN ==\n")
28 | logging.debug('Like: "hello world" (over two cycles)')
29 | pattern_pretty_printing(pattern=c, query_span=TimeSpan(0, 2))
30 |
31 | # printing the pattern with fast
32 | logging.debug("\n== SAME BUT FASTER==\n")
33 | logging.debug('Like: fast 4 "hello world"')
34 | pattern_pretty_printing(pattern=c._fast(2), query_span=TimeSpan(0, 1))
35 |
36 | # printing the pattern with patterned fast
37 | logging.debug("\n== PATTERNS OF FAST OF PATTERNS==\n")
38 | logging.debug('Like: fast "2 4" "hello world"')
39 | pattern_pretty_printing(pattern=c.fast(fastcat(2, 4)), query_span=TimeSpan(0, 1))
40 |
41 | # printing the pattern with stack
42 | logging.debug("\n== STACK ==\n")
43 | pattern_pretty_printing(pattern=d, query_span=TimeSpan(0, 1))
44 |
45 | # printing the pattern with late
46 | logging.debug("\n== LATE ==\n")
47 | pattern_pretty_printing(pattern=c.late(0.5), query_span=TimeSpan(0, 1))
48 |
49 | # Apply pattern of values to a pattern of functions
50 | logging.debug("\n== APPLICATIVE ==\n")
51 | x = fastcat(pure(lambda x: x + 1), pure(lambda x: x + 4))
52 | y = fastcat(3, 4, 5)
53 | z = x.app(y)
54 | pattern_pretty_printing(pattern=z, query_span=TimeSpan(0, 1))
55 |
56 | # Add number patterns together
57 | logging.debug("\n== ADDITION ==\n")
58 | numbers = fastcat(*[pure(v) for v in [2, 3, 4, 5]])
59 | more_numbers = fastcat(pure(10), pure(100))
60 | pattern_pretty_printing(pattern=numbers + more_numbers, query_span=TimeSpan(0, 1))
61 |
62 | logging.debug("\n== EMBEDDED SEQUENCES ==\n")
63 | # sequence([0,1,[2, [3, 4]]]) is the same as "[0 1 [2 [3 4]]]" in mininotation
64 | pattern_pretty_printing(
65 | pattern=sequence(0, 1, [2, [3, 4]]), query_span=TimeSpan(0, 1)
66 | )
67 |
68 | logging.debug("\n== Polyrhythm ==\n")
69 | pattern_pretty_printing(
70 | pattern=polyrhythm([0, 1, 2, 3], [20, 30]), query_span=TimeSpan(0, 1)
71 | )
72 |
73 | logging.debug("\n== Polyrhythm with fewer steps ==\n")
74 | pattern_pretty_printing(
75 | pattern=polyrhythm([0, 1, 2, 3], [20, 30], steps=2), query_span=TimeSpan(0, 1)
76 | )
77 |
78 | logging.debug("\n== Polymeter ==\n")
79 | pattern_pretty_printing(
80 | pattern=polymeter([0, 1, 2], [20, 30]), query_span=TimeSpan(0, 1)
81 | )
82 |
83 | logging.debug("\n== Polymeter with embedded polyrhythm ==\n")
84 | pattern_pretty_printing(
85 | pattern=pm(pr([100, 200, 300, 400], [0, 1]), [20, 30]),
86 | query_span=TimeSpan(0, 1),
87 | )
88 |
89 | logging.debug("\n== Every with partially applied 'fast' ==\n")
90 | pattern_pretty_printing(pattern=c.every(3, fast(2)), query_span=TimeSpan(0, 1))
91 |
--------------------------------------------------------------------------------