├── .gitignore
├── .idea
├── dictionaries
│ └── shimpe.xml
├── encodings.xml
├── expremigen.iml
├── misc.xml
├── modules.xml
└── vcs.xml
├── LICENSE
├── README.md
├── examples
├── bwv784_2voice_invention_13.py
├── dualphrase.py
├── example_drumpattern.py
├── example_nanonotation.py
├── example_readme.py
├── mispelchords.py
├── mispelpitchbend.py
├── output
│ ├── bwv784_2voice_invention_13.mid
│ ├── dualphrase.mid
│ ├── example_drumpattern.mid
│ ├── example_nanonotation.mid
│ ├── example_readme.mid
│ ├── mispelchords.mid
│ ├── mispelpitchbend.mid
│ ├── pitchbendanimation.mid
│ ├── rubato.mid
│ ├── singlephrase.mid
│ ├── tuplets.mid
│ └── twovoicewithchords.mid
├── pitchbendanimation.py
├── rubato.py
├── singlephrase.py
├── tuplets.py
└── twovoicewithchords.py
├── expremigen
├── __init__.py
├── io
│ ├── __init__.py
│ ├── constants.py
│ ├── midicontrolchanges.py
│ ├── pat2midi.py
│ └── phrase.py
├── mispel
│ ├── __init__.py
│ ├── exception.py
│ └── mispel.py
├── musicalmappings
│ ├── __init__.py
│ ├── constants.py
│ ├── durations.py
│ ├── dynamics.py
│ ├── nanonotation.py
│ ├── note2midi.py
│ ├── playeddurations.py
│ └── tempo.py
└── patterns
│ ├── __init__.py
│ ├── padd.py
│ ├── pattern.py
│ ├── pbinop.py
│ ├── pchord.py
│ ├── pconst.py
│ ├── pexprand.py
│ ├── pgeom.py
│ ├── prand.py
│ ├── pseq.py
│ ├── pseries.py
│ ├── pshuf.py
│ ├── ptween.py
│ ├── pwhite.py
│ └── utils.py
├── setup.cfg
├── setup.py
├── tests
├── __init__.py
├── testgeom.py
├── testmispel.py
├── testnanonotation.py
├── testnote2midi.py
├── testpadd.py
├── testpat2midi.py
├── testpchord.py
├── testpconst.py
├── testpexprand.py
├── testphrase.py
├── testphraseproperty.py
├── testprand.py
├── testpseq.py
├── testpseries.py
├── testpshuf.py
├── testptween.py
└── testpwhite.py
├── upload_to_pypi.sh
└── upload_to_testpypi.sh
/.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 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 |
103 | # idea
104 | .idea/workspace.xml
105 |
106 |
--------------------------------------------------------------------------------
/.idea/dictionaries/shimpe.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
--------------------------------------------------------------------------------
/.idea/encodings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/expremigen.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 | # Expremigen
2 | Expremigen is an **expre**ssive **mi**di **gen**eration library
3 |
4 | For quite a while I've been searching for a library that allows
5 | generation of expressive midi information. With expressive I mean that
6 | it should allow generating midi that doesn't sound like a mechanic
7 | robot. My current attempt is to make this possible by incorporating a
8 | way of animating midi properties over time.
9 |
10 | Expremigen models music as a collection of phrases. Within such a
11 | phrase you can specify and/or animate:
12 | * note values (melody, harmony)
13 | * durations (rhythm)
14 | * played durations (legato versus staccato)
15 | * lag (rubato),
16 | * volume (pppp to fffff, crescendo, decrescendo)
17 | * tempo (rallentando, accelerando)
18 | * midi control changes and pitchbend
19 |
20 | Specification of properties like note values or durations is done
21 | using a library of patterns. Each pattern can generate numbers
22 | according to its specifications. Patterns internallly use python
23 | generators to avoid memory and time explosion when you specify
24 | patterns with very large repeat values. These patterns are modeled
25 | after the more or less equivalent concept in [supercollider](http://supercollider.github.io/) and [isobar](https://github.com/ideoforms/isobar). Compared to isobar in particular, the patterns in expremigen are written in python 3, and heavily based on generators, which allows things like expressing patterns of very long lengths without blowing up the required time and memory space.
26 |
27 | Animations of properties are implemented by leveraging an
28 | animation library [pyvectortween](https://github.com/shimpe/pyvectortween) which has ample possibilities for
29 | specifying and combining advanced animations, and enrich them with
30 | all kinds of tweening and noise functions for maximum expressive
31 | results. A special pattern called Ptween applies the animations
32 | calculated by pyvectortween to the midi properties generated by
33 | patterns.
34 |
35 | # Dependencies
36 | To get the most out of this library you will need to install [MIDIUtil](https://github.com/MarkCWirt/MIDIUtil) (pip install MIDIUtil), [textX](https://github.com/igordejanovic/textX) (pip install textX) and [vectortween](https://github.com/shimpe/pyvectortween) (pip install vectortween).
37 |
38 | # Getting started: MISPEL
39 | Probably the easiest way to get started with expremigen is to use its domain specific **MI**di **SPE**cification **L**anguage, mispel. Mispel syntax reuses ideas from [lilypond](http://lilypond.org/), [abc notation](http://abcnotation.com/) and [music21](http://web.mit.edu/music21/)'s [tinynotation](http://web.mit.edu/music21/doc/moduleReference/moduleTinyNotation.html). A mispel based program could look as follows:
40 |
41 | ```python
42 | from expremigen.io.pat2midi import Pat2Midi
43 | from expremigen.mispel.mispel import Mispel
44 |
45 | outputfile = "output/example_readme.mid"
46 |
47 |
48 | def make_midi():
49 | m = Mispel()
50 | m.parse(r"""
51 | with track 0 channel 0:
52 | c4_16\vol{p} e g c5 b4 g f d c_4 r\vol{ff}
53 |
54 | with track 1 channel 1:
55 |
56 | """)
57 | p2m = Pat2Midi(m.get_no_of_tracks())
58 | m.add_to_pattern2midi(p2m)
59 | p2m.write(outputfile)
60 |
61 | if __name__ == "__main__":
62 | make_midi()
63 | ```
64 |
65 | This program generates a midi file containing two tracks on two different midi channels. The first track plays a crescendo arpeggio and the second track specifies three chords.
66 |
67 | ## Specifying notes and rhythms
68 | * As you can see you specify events in the form of notenames with octave numbers, e.g. a4 is a "la" in octave 4 (typically 440Hz). Acceptable note names are a, b, c, d, e, f, g, and r for a rest.
69 |
70 | * Sharps are indicated with #, e.g. ```a#```, double sharps with x, e.g. ```cx```, flats with -, e.g. ```e-``` and double flats with --, e.g. ```g--```.
71 |
72 | * To make chords, put notes in angular brackets: ``````. The properties of the first note in the chord are used for the whole chord. Properties other than note name and octave attached to the second and later notes are discarded.
73 |
74 | * Rhythm is indicated by using underscore and an (inverse) duration in beats, e.g. _16 means a sixteenth note. You can add one or more dots to indicate a dotted rhythm, e.g. ```d#3_8.``` is a "d sharp" in octave 3 with a length of one eighth plus one sixteenth.
75 |
76 | * To simplify specifying drum tracks (by convention these are always specified on channel 10) you can also use drum notes. Each drum note has a long form and a short form:
77 |
78 | | long | short | long | short |
79 | |------------------|:-----:|---------------|:-----:|
80 | | acousticbassdrum | abd | bassdrum | bad |
81 | | sidestick | sis | acousticsnare | acs |
82 | | brushtap | brt | handclap | hac |
83 | | brushslap | brs | electricsnare | els |
84 | | brushswirl | brw | lowfloortom | lft |
85 | | closedhihat | chh | highfloortom | hft |
86 | | pedalhihat | phh | lowtom | lot |
87 | | openhihat | ohh | lowmidtom | lmt |
88 | | highmidtom | hmt | crashsymbal1 | cs1 |
89 | | hightom | hit | ridecymbal1 | rc1 |
90 | | chinesecymbal | chc | ridebell | rib |
91 | | tambourine | tam | splashcymbal | spc |
92 | | cowbell | cob | crashsymbal2 | cc2 |
93 | | vibraslap | vis | ridecymbal2 | rc2 |
94 | | highbongo | hib | lowbongo | lob |
95 | | mutehiconga | mhc | openhiconga | ohc |
96 | | lowconga | loc | hightimbale | him |
97 | | lowtimbale | lom | highagogo | hag |
98 | | lowagogo | lag | cabasa | cab |
99 | | maracas | mar | shortwhistle | swh |
100 | | longwhistle | lwh | shortguiro | shg |
101 | | longguiro | log | claves | cla |
102 | | hiwoodblock | hwb | lowoodblock | lwb |
103 | | mutecuica | muc | opencuica | opc |
104 | | mutetriangle | mut | opentriangle | opt |
105 | | shaker | shk | | |
106 |
107 |
108 | ## Adding expressivity
109 | * To the notes you can add properties. The main difference between mispel and other midi domain specific languages (like [skini](https://ccrma.stanford.edu/software/stk/skini.html), [alda](https://github.com/alda-lang/alda), [semitone](https://github.com/benwbooth/semitone), [micromidi](https://github.com/arirusso/micromidi)) is the combination of a fairly concise syntax with an easy to use built-in property animation system.
110 |
111 | * Properties in *curly braces* ```\property{}``` are *animated* from this occurrence of the property to the next. In track 0 in the example above, the volume will be animated from p to ff (*crescendo*).
112 |
113 | * Properties in *square braces* ```\property[]``` keep a *constant* value until the next property of the same kind is encountered.
114 |
115 | * The properties you can specify are:
116 | * **vol** for volume - can be ppppp to ffff or an integer between 0-127
117 | * **pdur** for played duration - can be staccatissimo, staccato, normal, legato or legatissimo, or a number. The number is interpreted as a multiplier with which to multiply the specified duration. E.g. number 0.1 would specify staccatissimo and number 1 would specify legato.
118 | * **lag** for lag. Lag is a numeric value (where 1 stands for a full beat). By animating lag you can create a convincing rubato.
119 | * **tempo** by animating tempo you can speed up or slow down (accelerando and ritardando)
120 | * **cc** midi control changes. These are specified using two parameters, e.g. \cc{15, 100} specifies that midi control change for controller 15 should be set to 100 and this value will be animated until the next midi control change for controller 15 is encountered. Midi control changes are animated with a higher time resolution than individual notes meaning you can perfectly animate control message values between one long note and the next note.
121 | * *NOTE:* **pitchbend** in midi is not specified using a control change message, but in mispel it is. Just use controller value 128.
122 | * Vectortween also allows to specifying tweening options and noise function options. Only the tweening options are exposed in mispel, so if you wanted to get fancy you could write an animation like
123 | ```
124 | with track 0 channel 0:
125 | c4_16\vol{p, easeOutElastic, 30, 0.1} e g c5 b4 g f d c_4 r\vol{ff}
126 | ```
127 | * The supported tweening options are (see [this picture](http://easings.net/nl)) for a graphical display of what these mean:
128 | * linear,
129 | * easeInQuad, easeOutQuad,easeInOutQuad,
130 | * easeInCubic,easeOutCubic,easeInOutCubic,
131 | * easeInQuart,easeOutQuart,easeInOutQuart,
132 | * easeInQuint,easeOutQuint,easeInOutQuint,
133 | * easeInSine,easeOutSine,easeInOutSine,
134 | * easeInExpo,easeOutExpo,easeInOutExpo,
135 | * easeInCirc,easeOutCirc,easeInOutCirc,
136 | * easeInBounce,easeOutBounce,easeInOutBounce,
137 | * easeInElastic,easeOutElastic,easeInOutElastic (these require two extra float parameters: amplitude and damping)
138 | * easeInBack,easeOutBack,easeInOutBack (these require one extra float parameter: damping)
139 | ## Reducing duplication
140 | If two successive notes share the same octave you can leave out the octave in the second note. If two successive notes share the same duration, you can leave out the duration in the second notes. The following fragments are equivalent:
141 | ```python
142 | 'a4_4 b4_4 c#4_4 d#4_4 e4_1'
143 | ```
144 | and
145 | ```python
146 | 'a4_4 b c# d# e_1'
147 | ```
148 |
149 | # Going deeper
150 | If you don't like mispel, or you need more power than mispel exposes, you can of course tap into the raw power of patterns. Although a typical pattern-based expremigen program may look a bit daunting at first, it's actually quite simple. In a typical use case, you will concatenate phrases into a piece. Phrases are dictionaries containing patterns that specify the notes, the volumes, the durations, the played durations, the lag and the tempo.
151 |
152 | The following example shows off some of the possibilities for creating
153 | a phrase using tweened animations.
154 |
155 | The examples folder has more things to examine. The tests folder has unit tests for a substantial part of the library.
156 |
157 | ```python
158 | from expremigen.io.constants import PhraseProperty as PP
159 | from expremigen.io.pat2midi import Pat2Midi
160 | from expremigen.io.phrase import Phrase
161 | from expremigen.musicalmappings.durations import Durations as Dur
162 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
163 | from expremigen.musicalmappings.note2midi import Note2Midi
164 | from expremigen.patterns.pconst import Pconst
165 | from expremigen.patterns.pseq import Pseq
166 | from expremigen.patterns.ptween import Ptween
167 | from vectortween.NumberAnimation import NumberAnimation
168 | from vectortween.SequentialAnimation import SequentialAnimation
169 |
170 | outputfile = "output/singlephrase.mid"
171 |
172 | def create_phrase():
173 | # we will add a single phrase into a music piece
174 |
175 | # Note2Midi converts from music notation to midi numbers
176 | n = Note2Midi()
177 | # notes is a list of music notes
178 | notes = "c4 e4 g4 c5 b4 g4 f4 d4 c4".split(" ")
179 | # specify a (volume) animation that increases linearly from mp to f
180 | crescendo = NumberAnimation(frm=Dyn.mp, to=Dyn.f, tween=['linear'])
181 | # specify a (volume) animation that decreases using an easOutQuad
182 | # tween function from f to ppp
183 | decrescendo = NumberAnimation(frm=Dyn.f, to=Dyn.ppp,
184 | tween=['easeOutQuad'])
185 | # Combine both animations into one swell_dim animation.
186 | # Note that animations do not specify start and stop times
187 | # as these are specified in Ptween.
188 | # Animations are abstract descriptions of behavior,
189 | # not bound to time and can easily be reused in different
190 | # contexts or easily combined into SequentialAnimations.
191 | # Animations automatically stretch over the
192 | # number of events they encompass as specified in Ptween
193 | swell_dim = SequentialAnimation([crescendo, decrescendo])
194 | # specify an animation that will animate the playeddur
195 | increasing_staccato = NumberAnimation(frm=1, to=0.5)
196 | # specify the phrase properties
197 | properties = {
198 | # convert from note names to midi numbers
199 | # Pseq is a pattern that generates notes one by one from a list
200 | PP.NOTE: Pseq(n.convert2(notes)),
201 | # last note is longer than the rest
202 | # Pconst is a pattern that repeats its constant the requested number of times
203 | PP.DUR: Pseq([Pconst(Dur.quarter, len(notes) - 1), Pconst(Dur.whole, 1)]),
204 | # animate staccato
205 | # Ptween is a pattern that animates values over time as specified
206 | # in the animation argument
207 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
208 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
209 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
210 | # tempo: constant at 100 bpm
211 | PP.TEMPO: Pconst(100)
212 | }
213 | # with the above animated properties, build a phrase
214 | p = Phrase(properties)
215 | # take a pattern to midi object
216 | p2m = Pat2Midi()
217 | # add the phrase into the pattern to midi object
218 | total_dur = p2m.add_phrase(p)
219 | print(total_dur)
220 | # and write the result to midi file
221 | p2m.write(outputfile)
222 |
223 |
224 | if __name__ == "__main__":
225 | create_phrase()
226 | ```
--------------------------------------------------------------------------------
/examples/bwv784_2voice_invention_13.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.pat2midi import Pat2Midi
2 | from expremigen.mispel.mispel import Mispel
3 |
4 | outputfile = "output/bwv784_2voice_invention_13.mid"
5 |
6 |
7 | def create_bach():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0:
11 | r_16\pdur[legato]\vol{f} e4 a c5 b4 e b d5 c_8\pdur[staccato]\vol{ff} e g#4 e5
12 | a4_16\vol{f} e4_16\pdur[legato] a c5 b4 e b d5 c_8\vol{ff}\pdur[staccato] a4 r_4\vol{f}
13 | r_16 e5\vol{p}\pdur[legato] c e a4 c5 e4 g f_8\vol{ff}\pdur[staccato] a\vol{f} d5 f_8.\vol{p}
14 | d_16\pdur[legato] b4 d5 g4 b d f e_8\vol{ff}\pdur[staccato] g\vol{f} c5 e_8.\vol{p}
15 | c5_16\pdur[legato] a4 c5 f4_8\vol{ff}\pdur[staccato] d5_8.\vol{p}\pdur[legato] b4_16 g b
16 | e_8\vol{ff}\pdur[staccato] c5_8.\vol{p}\pdur[legato]
17 | a4_16 f a d_8\vol{ff}\pdur[staccato] b_8 c5_8 r_8 r_4
18 |
19 | with track 1:
20 | a2_8\vol{mf}\pdur[staccato] a3_4\pdur[legato]\vol{f} g#_8\vol{mf} a_16\pdur[staccato]\vol{f} e3\pdur[legato] a c4 b3 e b d4
21 | c_8\pdur[staccato]\vol{ff} a3 g# e a_16\vol{f} e\pdur[legato] a c4 b3 e b d4
22 | c_8\pdur[staccato]\vol{ff} a3 c4 a3
23 | d4_16\vol{f} a3\pdur[legato] f a d f a2 c3
24 | b2_8\vol{p}\pdur[staccato] d3 g b_8.\vol{f}\pdur[legato] g3_16 e g c e g2 b
25 | a_8\vol{p}\pdur[staccato] c3\vol{mf} d_16\pdur[legato] f b2 d3 g2_8\vol[f]\pdur[staccato] b c3_16\vol{f}\pdur[legato] e a2 c3
26 | f2_8\vol{p}\pdur[staccato] d g_16\vol{mp} g3\pdur[legato] f g c\vol{mf}\pdur[staccato] g\pdur[legato]
27 | c4 e d g3 d4 f e_8\vol{f}\pdur[staccato] c
28 |
29 | """)
30 | p2m = Pat2Midi(num_tracks=2)
31 | for s in range(m.get_no_of_sections()):
32 | p2m.add_phrase(m.phrase_for_section(s), m.track_for_section(s), m.channel_for_section(s), m.time_for_section(s))
33 |
34 | p2m.write(outputfile)
35 |
36 |
37 | if __name__ == "__main__":
38 | create_bach()
39 |
--------------------------------------------------------------------------------
/examples/dualphrase.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.constants import PhraseProperty as PP
2 | from expremigen.io.pat2midi import Pat2Midi
3 | from expremigen.io.phrase import Phrase
4 | from expremigen.musicalmappings.durations import Durations as Dur
5 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
6 | from expremigen.musicalmappings.note2midi import Note2Midi
7 | from expremigen.patterns.pconst import Pconst
8 | from expremigen.patterns.pseq import Pseq
9 | from expremigen.patterns.ptween import Ptween
10 |
11 | outputfile = "output/dualphrase.mid"
12 |
13 |
14 | def create_phrase():
15 | n = Note2Midi()
16 | notes = ["c4", "e4", "g4", "c5", "b4", "g4", "f4", "d4", "c4"]
17 | from vectortween.NumberAnimation import NumberAnimation
18 | from vectortween.SequentialAnimation import SequentialAnimation
19 | increase = NumberAnimation(frm=Dyn.mp, to=Dyn.f)
20 | decrease = NumberAnimation(frm=Dyn.f, to=Dyn.ppp)
21 | swell_dim = SequentialAnimation([increase, decrease])
22 | increasing_staccato = NumberAnimation(frm=1, to=0.5)
23 | properties1 = {
24 | # convert from note names to midi numbers
25 | PP.NOTE: Pseq(n.convert2(notes)),
26 | # last note is longer than the rest
27 | PP.DUR: Pseq([Pconst(Dur.eighth, len(notes) - 1), Pconst(Dur.whole, 1)]),
28 | # animate staccato
29 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
30 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
31 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
32 | }
33 | properties2 = {
34 | # convert from (reversed) note names to midi numbers
35 | PP.NOTE: Pseq(n.convert2(notes[::-1])),
36 | # last note is longer than the rest
37 | PP.DUR: Pseq([Pconst(Dur.eighth, len(notes) - 1), Pconst(Dur.whole, 1)]),
38 | # animate staccato
39 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
40 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
41 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
42 | }
43 |
44 | p1 = Phrase(properties1)
45 | p2 = Phrase(properties2)
46 | p2m = Pat2Midi()
47 | p2m.set_tempo(120)
48 | total_dur = p2m.add_phrases([p1, p2], start_time=1)
49 | print(total_dur)
50 | p2m.write(outputfile)
51 |
52 |
53 | if __name__ == "__main__":
54 | create_phrase()
55 |
--------------------------------------------------------------------------------
/examples/example_drumpattern.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.pat2midi import Pat2Midi
2 | from expremigen.mispel.mispel import Mispel
3 |
4 | outputfile = "output/example_drumpattern.mid"
5 |
6 |
7 | def make_midi():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0 channel 10:
11 | bassdrum r4 bassdrum r4 bassdrum r4
12 |
13 | with track 0 channel 10:
14 | r4 closedhihat r4 closedhihat
15 | """)
16 | p2m = Pat2Midi(m.get_no_of_tracks())
17 | m.add_to_pattern2midi(p2m)
18 | p2m.write(outputfile)
19 |
20 |
21 | if __name__ == "__main__":
22 | make_midi()
23 |
--------------------------------------------------------------------------------
/examples/example_nanonotation.py:
--------------------------------------------------------------------------------
1 | from itertools import tee
2 |
3 | from vectortween.NumberAnimation import NumberAnimation
4 | from vectortween.SequentialAnimation import SequentialAnimation
5 |
6 | from expremigen.io.constants import PhraseProperty as PP
7 | from expremigen.io.pat2midi import Pat2Midi
8 | from expremigen.io.phrase import Phrase
9 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
10 | from expremigen.musicalmappings.nanonotation import NanoNotation
11 | from expremigen.musicalmappings.note2midi import Note2Midi
12 | from expremigen.musicalmappings.playeddurations import PlayedDurations as PDur
13 | from expremigen.patterns.pconst import Pconst
14 | from expremigen.patterns.pseq import Pseq
15 | from expremigen.patterns.ptween import Ptween
16 |
17 | outputfile = "output/example_nanonotation.mid"
18 |
19 |
20 | def pairwise(iterable):
21 | """s -> (s0,s1), (s1,s2), (s2, s3), ..."""
22 | a, b = tee(iterable)
23 | next(b, None)
24 | return zip(a, b)
25 |
26 |
27 | class PhraseFactory:
28 | def __init__(self):
29 | self.note2midi = Note2Midi()
30 | self.nano = NanoNotation()
31 |
32 | def __call__(self,
33 | kind=None,
34 | nanonotation=None,
35 | volumes=None,
36 | last_note_is_final=False):
37 | notes = self.nano.notes(nanonotation)
38 | durations = self.nano.dur(nanonotation)
39 | return Phrase({
40 | PP.NOTE: self.note(notes),
41 | PP.VOL: self.volume(notes, volumes, None, None),
42 | PP.PLAYEDDUR: self.playeddur(notes, kind),
43 | PP.DUR: self.dur(durations),
44 | PP.LAG: self.lag(notes, last_note_is_final)
45 | })
46 |
47 | @classmethod
48 | def playeddur(cls, notes, kind="l2s"):
49 | """
50 | :param notes: list of notes that make up the phrase
51 | :param kind: one of "l2s" (legato-to-staccato) or "s2l" (staccato-to-legato)
52 | :return: pattern that generates the desired playeddur values
53 | """
54 | if kind == "l2s":
55 | anim = Pseq([Pconst(PDur.legato, len(notes) - 1), Pconst(PDur.staccato, 1)], 1)
56 | elif kind == "s2l":
57 | anim = Pseq([Pconst(PDur.staccato, len(notes) - 1), Pconst(PDur.legato, 1)], 1)
58 | elif kind == "s2s":
59 | anim = Pconst(PDur.staccato, len(notes))
60 | elif kind == "l2l":
61 | anim = Pconst(PDur.legato, len(notes))
62 | else:
63 | anim = None
64 | assert False
65 | return anim
66 |
67 | @classmethod
68 | def volume(cls, notes, volumes=None, individual_tween=None, overall_tween=None):
69 | """
70 | :param notes: list of notes that make up the phrase
71 | :param volumes: a list of volumes to evolve to over the course of the phrase, e.g. [Dyn.mp, Dyn.mf, Dyn.ppp]
72 | :param individual_tween: per segment tween
73 | :param overall_tween: tween over all segments
74 | :return: pattern that tweens between the successive volumes
75 | """
76 | if volumes is None:
77 | volumes = [Dyn.mf, Dyn.mf]
78 | if overall_tween is None:
79 | overall_tween = ['linear']
80 | if individual_tween is None:
81 | individual_tween = ['linear']
82 | if len(volumes) == 1:
83 | volumes = [volumes[0], volumes[0]]
84 | anims = []
85 | for v in pairwise(volumes):
86 | anims.append(NumberAnimation(frm=v[0], to=v[1], tween=individual_tween))
87 | s = SequentialAnimation(anims, tween=overall_tween)
88 | return Ptween(s, 0, 0, len(notes), len(notes))
89 |
90 | def note(self, notes):
91 | """
92 | :param notes: list of notes that make up the phrase
93 | :return: pattern that generates the notes one by one
94 | """
95 | return Pseq(self.note2midi.convert2(notes))
96 |
97 | @classmethod
98 | def lag(cls, notes, last_note_is_endnote=False):
99 | """
100 | :param last_note_is_endnote:
101 | :param notes: list of notes that make up the phrase
102 | :return: pattern that generates the desired lag
103 | """
104 | if last_note_is_endnote:
105 | return Pseq([Pconst(0, len(notes) - 1), Pconst(0.5, 1)], repeats=1)
106 | else:
107 | return Pconst(0, len(notes))
108 |
109 | @classmethod
110 | def dur(cls, durations):
111 | return Pseq(durations, repeats=1)
112 |
113 |
114 | def play_bach():
115 | p2m = Pat2Midi(num_tracks=2)
116 | ff = PhraseFactory()
117 |
118 | # upper voice
119 | uppervoice = []
120 | uppervoice_fragments = [
121 | ["l2s", "r_16 e4 a c5 b4 e b d5 c_8", [Dyn.f, Dyn.ff]],
122 | ["s2s", "e5_8 g#4 e5 a4_16", [Dyn.ff, Dyn.f]],
123 | ["l2s", "e4_16 a4 c5 b4 e b d5 c_8", [Dyn.f, Dyn.ff]],
124 | ["s2s", "a4_8 r_4", [Dyn.f]],
125 | ["l2s", "r_16 e5 c e a4 c5 e4 g f_8", [Dyn.p, Dyn.ff]],
126 | ["s2l", "a4_8 d5 f_8.", [Dyn.f, Dyn.p]],
127 | ["s2l", "d5_16 b4 d5 g4 b d f e_8", [Dyn.p, Dyn.ff]],
128 | ["s2l", "g4 c5 e_8.", [Dyn.f, Dyn.p]],
129 | ["l2s", "c5_16 a4 c5 f4_8", [Dyn.p, Dyn.ff]],
130 | ["s2l", "d5_8. b4_16 g b e_8", [Dyn.p, Dyn.ff]],
131 | ["l2s", "c5_8. a4_16 f a d_8", [Dyn.p, Dyn.ff]],
132 | ["s2s", "b4_8 c5_8 r_8 r_4", [Dyn.ff]]
133 | ]
134 | for fragment in uppervoice_fragments:
135 | uppervoice.append(ff(type=fragment[0],
136 | nanonotation=fragment[1],
137 | volumes=fragment[2]))
138 |
139 | lowervoice = []
140 | lowervoice_fragments = [
141 | ["s2s", "a2_8", [Dyn.mf]],
142 | ["l2s", "a3_4 g#_8 a_16", [Dyn.f, Dyn.mf, Dyn.f]],
143 | ["l2s", "e3_16 a c4 b3 e b d4 c_8", [Dyn.f, Dyn.ff]],
144 | ["s2s", "a3_8 g# e a_16", [Dyn.ff, Dyn.f]],
145 | ["l2s", "e3_16 a c4 b3 e b d4 c_8", [Dyn.f, Dyn.ff]],
146 | ["s2s", "a3_8 c4 a3 d4_16", [Dyn.ff, Dyn.f]],
147 | ["l2s", "a3_16 f a d f a2 c3 b2_8", [Dyn.f, Dyn.p]],
148 | ["s2l", "d3_8 g b_8.", [Dyn.p, Dyn.f]],
149 | ["l2s", "g3_16 e g c e g2 b a_8", [Dyn.f, Dyn.p]],
150 | ["s2s", "c3_8", [Dyn.mf]],
151 | ["l2s", "d3_16 f b2 d3 g2_8", [Dyn.mf, Dyn.f]],
152 | ["s2s", "b2_8", [Dyn.f]],
153 | ["l2s", "c3_16 e a2 c3 f2_8", [Dyn.f, Dyn.p]],
154 | ["s2s", "d2_8 g2_16", [Dyn.p, Dyn.mp]],
155 | ["l2s", "g3_16 f g c", [Dyn.mp, Dyn.mf]],
156 | ["l2s", "g3_16 c4 e d g3 d4 f e_8", [Dyn.mf, Dyn.f]]
157 | ]
158 | for fragment in lowervoice_fragments:
159 | lowervoice.append(ff(type=fragment[0],
160 | nanonotation=fragment[1],
161 | volumes=fragment[2]))
162 | p2m.add_phrases(uppervoice, start_time=0, track=0, channel=0)
163 | p2m.add_phrases(lowervoice, start_time=0, track=1, channel=0)
164 | p2m.set_tempo(86, 0)
165 | p2m.write(outputfile)
166 |
167 |
168 | if __name__ == "__main__":
169 | play_bach()
170 |
--------------------------------------------------------------------------------
/examples/example_readme.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.pat2midi import Pat2Midi
2 | from expremigen.mispel.mispel import Mispel
3 |
4 | outputfile = "output/example_readme.mid"
5 |
6 |
7 | def make_midi():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0 channel 0:
11 | c4_16\vol{p}\tempo{120} e g c5 b4 g f d c_4 r\vol{ff}\tempo{60}
12 |
13 | with track 1 channel 1:
14 |
15 | """)
16 | p2m = Pat2Midi(m.get_no_of_tracks())
17 | m.add_to_pattern2midi(p2m)
18 | p2m.write(outputfile)
19 |
20 |
21 | if __name__ == "__main__":
22 | make_midi()
23 |
--------------------------------------------------------------------------------
/examples/mispelchords.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.pat2midi import Pat2Midi
2 | from expremigen.mispel.mispel import Mispel
3 |
4 | outputfile = "output/mispelchords.mid"
5 |
6 |
7 | def make_midi():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0:
11 | c4_16 e g c5 b4 g f d c_4
12 |
13 | with track 1:
14 |
15 | """)
16 | p2m = Pat2Midi(num_tracks=2)
17 | for s in range(m.get_no_of_sections()):
18 | p2m.add_phrase(m.phrase_for_section(s), m.track_for_section(s), m.channel_for_section(s), m.time_for_section(s))
19 |
20 | p2m.write(outputfile)
21 |
22 |
23 | if __name__ == "__main__":
24 | make_midi()
25 |
--------------------------------------------------------------------------------
/examples/mispelpitchbend.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.pat2midi import Pat2Midi
2 | from expremigen.mispel.mispel import Mispel
3 |
4 | outputfile = "output/mispelpitchbend.mid"
5 |
6 |
7 | def make_midi():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0:
11 | c4_16\cc{128,-8000} c c c c c c c c c\cc[128,3000] c c\cc{128,8000} c c c c\cc{128,0}
12 |
13 | with track 1:
14 |
15 | """)
16 | p2m = Pat2Midi(num_tracks=2)
17 | for s in range(m.get_no_of_sections()):
18 | p2m.add_phrase(m.phrase_for_section(s), m.track_for_section(s), m.channel_for_section(s), m.time_for_section(s))
19 |
20 | p2m.write(outputfile)
21 |
22 |
23 | if __name__ == "__main__":
24 | make_midi()
25 |
--------------------------------------------------------------------------------
/examples/output/bwv784_2voice_invention_13.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/bwv784_2voice_invention_13.mid
--------------------------------------------------------------------------------
/examples/output/dualphrase.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/dualphrase.mid
--------------------------------------------------------------------------------
/examples/output/example_drumpattern.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/example_drumpattern.mid
--------------------------------------------------------------------------------
/examples/output/example_nanonotation.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/example_nanonotation.mid
--------------------------------------------------------------------------------
/examples/output/example_readme.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/example_readme.mid
--------------------------------------------------------------------------------
/examples/output/mispelchords.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/mispelchords.mid
--------------------------------------------------------------------------------
/examples/output/mispelpitchbend.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/mispelpitchbend.mid
--------------------------------------------------------------------------------
/examples/output/pitchbendanimation.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/pitchbendanimation.mid
--------------------------------------------------------------------------------
/examples/output/rubato.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/rubato.mid
--------------------------------------------------------------------------------
/examples/output/singlephrase.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/singlephrase.mid
--------------------------------------------------------------------------------
/examples/output/tuplets.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/tuplets.mid
--------------------------------------------------------------------------------
/examples/output/twovoicewithchords.mid:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/examples/output/twovoicewithchords.mid
--------------------------------------------------------------------------------
/examples/pitchbendanimation.py:
--------------------------------------------------------------------------------
1 | from vectortween.NumberAnimation import NumberAnimation
2 | from vectortween.SequentialAnimation import SequentialAnimation
3 |
4 | from expremigen.io.constants import PhraseProperty as PP
5 | from expremigen.io.midicontrolchanges import MidiControlChanges as MCC
6 | from expremigen.io.pat2midi import Pat2Midi
7 | from expremigen.io.phrase import Phrase
8 | from expremigen.musicalmappings.durations import Durations as Dur
9 | from expremigen.musicalmappings.note2midi import Note2Midi
10 | from expremigen.patterns.pconst import Pconst
11 | from expremigen.patterns.ptween import Ptween
12 |
13 | outputfile = "output/pitchbendanimation.mid"
14 |
15 |
16 | def create_phrase():
17 | n = Note2Midi()
18 | a = NumberAnimation(frm=0, to=8000, tween=['easeOutElastic', 1, 0.02])
19 | b = NumberAnimation(frm=8000, to=0, tween=['easeOutElastic', 1, 0.02])
20 | c = NumberAnimation(frm=0, to=-8000, tween=['easeOutBounce', 0.1, 0.02])
21 | d = NumberAnimation(frm=-8000, to=0, tween=['easeOutBounce', 0.1, 0.02])
22 | s = SequentialAnimation([a, b, c, d], repeats=10)
23 | properties = {
24 | PP.NOTE: n.convert2(Pconst("a4", 1)),
25 | PP.DUR: Pconst(Dur.whole * 16, 1), # single note for 16 beats
26 | PP.PLAYEDDUR: Pconst(1),
27 | PP.ctrl_dur_key(MCC.PitchWheel): Pconst(0.03125,
28 | int((1 / 0.03125) * Dur.whole * 16)),
29 | PP.ctrl_val_key(MCC.PitchWheel): Ptween(s,
30 | 0,
31 | 0,
32 | int((1 / 0.03125) * Dur.whole * 16) - 1,
33 | int((1 / 0.03125) * Dur.whole * 16) - 1,
34 | None)
35 | }
36 | p = Phrase(properties)
37 | p2m = Pat2Midi()
38 | p2m.add_phrase(p, track=0, channel=0, start_time=0)
39 | p2m.write(outputfile)
40 |
41 |
42 | if __name__ == "__main__":
43 | create_phrase()
44 |
--------------------------------------------------------------------------------
/examples/rubato.py:
--------------------------------------------------------------------------------
1 | from vectortween.NumberAnimation import NumberAnimation
2 | from vectortween.SequentialAnimation import SequentialAnimation
3 |
4 | from expremigen.io.constants import PhraseProperty as PP
5 | from expremigen.io.pat2midi import Pat2Midi
6 | from expremigen.io.phrase import Phrase
7 | from expremigen.musicalmappings.durations import Durations as Dur
8 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
9 | from expremigen.musicalmappings.note2midi import Note2Midi
10 | from expremigen.patterns.pconst import Pconst
11 | from expremigen.patterns.pseq import Pseq
12 | from expremigen.patterns.ptween import Ptween
13 |
14 | outputfile = "output/rubato.mid"
15 |
16 |
17 | def create_phrase():
18 | p = Pat2Midi()
19 | n = Note2Midi()
20 |
21 | # vary the lag to create the rubato feeling
22 | lag_inc = NumberAnimation(frm=0, to=0.3, tween=['easeOutQuad'])
23 | lag_dec = NumberAnimation(frm=0.3, to=0, tween=['easeInOutCubic'])
24 | lag = SequentialAnimation([lag_inc, lag_dec], [1, 3], 2)
25 |
26 | # vary the volume over time to keep it interesting
27 | vol_inc1 = NumberAnimation(frm=Dyn.f, to=Dyn.ff, tween=['linear'])
28 | vol_dec1 = NumberAnimation(frm=Dyn.ff, to=Dyn.mf, tween=['linear'])
29 |
30 | vol_inc2 = NumberAnimation(frm=Dyn.mf, to=Dyn.f, tween=['linear'])
31 | vol_dec2 = NumberAnimation(frm=Dyn.f, to=Dyn.mp, tween=['linear'])
32 |
33 | vol_inc3 = NumberAnimation(frm=Dyn.mp, to=Dyn.mf, tween=['linear'])
34 | vol_dec3 = NumberAnimation(frm=Dyn.mf, to=Dyn.pp, tween=['linear'])
35 | vol = SequentialAnimation([vol_inc1, vol_dec1, vol_inc2, vol_dec2, vol_inc3, vol_dec3])
36 |
37 | # and why not bounce a bit between legato and staccato while we're having fun?
38 | legato_to_staccato = NumberAnimation(frm=1, to=0.25, tween=['easeOutBounce'])
39 | staccato_to_legato = NumberAnimation(frm=0.1, to=1, tween=['easeOutBounce'])
40 | dur = SequentialAnimation([legato_to_staccato, staccato_to_legato])
41 |
42 | # animate the tempo
43 | tempo_slowdown = NumberAnimation(frm=120, to=80, tween=['easeOutQuad'])
44 |
45 | # play some random cadenza
46 | notes = n.convert2(
47 | "a5 b5 c6 a5 e5 d5 c5 d5 e5 c5 a4 g#4 a4 b4 c5 a4 e4 d4 c4 d4 e4 c4 a3 g#3 a3 b3 c4 d4 e4 g#4 a4".split(" "))
48 | notes2 = n.convert2(
49 | "d4 e4 f4 d4 a3 g3 f3 g3 a3 b3 c4 d4 c4 d4 e4 c4 g3 f3 e3 f3 g3 a3 b3 c4 a3 b3 c4 d4 e4 g#4 a4".split(" "))
50 | notes.extend(notes2)
51 |
52 | properties_plain = {
53 | PP.NOTE: Pseq(notes, 1),
54 | PP.VOL: Pconst(100),
55 | PP.PLAYEDDUR: Pconst(0.95),
56 | PP.DUR: Pseq([Pconst(Dur.sixteenth_triplet, len(notes2) - 1), Pconst(Dur.half, 1)], 2),
57 | PP.LAG: Pconst(0),
58 | PP.TEMPO: Pconst(120)
59 | }
60 | properties_rubato = {
61 | PP.NOTE: Pseq(notes, 1),
62 | PP.VOL: Ptween(vol, 0, 0, len(notes), len(notes), None),
63 | PP.PLAYEDDUR: Ptween(dur, 0, 0, len(notes), len(notes), None),
64 | PP.DUR: Pseq([Pconst(Dur.sixteenth_triplet, len(notes2) - 1), Pconst(Dur.half, 1)], 2),
65 | PP.LAG: Ptween(lag, 0, 0, len(notes), len(notes), None),
66 | PP.TEMPO: Ptween(tempo_slowdown, 0, 0, len(notes), len(notes), None)
67 | }
68 |
69 | ph = Phrase(properties_plain)
70 | ph2 = Phrase(properties_rubato)
71 | p.add_phrases([ph, ph2], 0, 0, 0)
72 |
73 | p.write(outputfile)
74 |
75 |
76 | if __name__ == "__main__":
77 | create_phrase()
78 |
--------------------------------------------------------------------------------
/examples/singlephrase.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.constants import PhraseProperty as PP
2 | from expremigen.io.pat2midi import Pat2Midi
3 | from expremigen.io.phrase import Phrase
4 | from expremigen.musicalmappings.durations import Durations as Dur
5 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
6 | from expremigen.musicalmappings.note2midi import Note2Midi
7 | from expremigen.patterns.pconst import Pconst
8 | from expremigen.patterns.pseq import Pseq
9 | from expremigen.patterns.ptween import Ptween
10 |
11 | outputfile = "output/singlephrase.mid"
12 |
13 |
14 | def create_phrase():
15 | n = Note2Midi()
16 | notes = ["c4", "e4", "g4", "c5", "b4", "g4", "f4", "d4", "c4"]
17 | from vectortween.NumberAnimation import NumberAnimation
18 | from vectortween.SequentialAnimation import SequentialAnimation
19 | increase = NumberAnimation(frm=Dyn.mp, to=Dyn.f)
20 | decrease = NumberAnimation(frm=Dyn.f, to=Dyn.ppp)
21 | swell_dim = SequentialAnimation([increase, decrease])
22 | increasing_staccato = NumberAnimation(frm=1, to=0.5)
23 | properties = {
24 | # convert from note names to midi numbers
25 | PP.NOTE: Pseq(n.convert2(notes)),
26 | # last note is longer than the rest
27 | PP.DUR: Pseq([Pconst(Dur.eighth, len(notes) - 1), Pconst(Dur.whole, 1)]),
28 | # animate staccato
29 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
30 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
31 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
32 | }
33 | p = Phrase(properties)
34 | p2m = Pat2Midi()
35 | p2m.set_tempo(120)
36 | total_dur = p2m.add_phrase(p)
37 | print(total_dur)
38 | p2m.write(outputfile)
39 |
40 |
41 | if __name__ == "__main__":
42 | create_phrase()
43 |
--------------------------------------------------------------------------------
/examples/tuplets.py:
--------------------------------------------------------------------------------
1 | from expremigen.mispel.mispel import Mispel
2 | from expremigen.io.pat2midi import Pat2Midi
3 |
4 | outputfile = "output/tuplets.mid"
5 |
6 |
7 | def make_midi():
8 | m = Mispel()
9 | m.parse(r"""
10 | with track 0 channel 0:
11 | r_1*4\tempo[160] |
12 | r_16 g#4\vol{p} a g# fx g# c#5 e\vol{mf} d# c# d# c# b#4 c#5 e g#\vol{p} |
13 | r_16 g#4\vol{p} a g# fx g# c#5 e\vol{mf} d# c# d# c# b#4 c#5 e g#\vol{p} |
14 | r_16 a4 c#5 d# f# a c#6 d# b a g# f# e d# f# c# |
15 | b#5 d#6 a5 g# f# a e d# f# c# b#4 d#5 a4 g# b a_8 |
16 | g#4_16\vol{p} a g# fx g# c#5 e\vol{mf} d# c# d# c# b#4 c#5 e g#\vol{p} |
17 |
18 | with track 1 channel 1:
19 | |
20 | g#3 c#4 e c# g#3 c# g# c#4 e c# g#3 |
21 | c# g# c#4 e c# g#3 c# g# c#4 e c# g#3\vol{p} |
22 | c# g# c#4 e c# g#3 e g# c#4 e c# g#3 |
23 | c# g# c#4 e c# g#3 e g# c#4 e c# g#3 |
24 | d# a c#4 f# c# a3 f# c#4 d# a d# c# |
25 | g#2 d#3 f# b# f# d# g#2 d#3 f# b# f# d# |
26 |
27 | """)
28 | p2m = Pat2Midi(m.get_no_of_tracks())
29 | m.add_to_pattern2midi(p2m)
30 | p2m.write(outputfile)
31 |
32 |
33 | if __name__ == "__main__":
34 | make_midi()
35 |
--------------------------------------------------------------------------------
/examples/twovoicewithchords.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.constants import PhraseProperty as PP
2 | from expremigen.io.pat2midi import Pat2Midi
3 | from expremigen.io.phrase import Phrase
4 | from expremigen.musicalmappings.durations import Durations as Dur
5 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
6 | from expremigen.musicalmappings.note2midi import Note2Midi
7 | from expremigen.patterns.pchord import Pchord as C
8 | from expremigen.patterns.pconst import Pconst
9 | from expremigen.patterns.pseq import Pseq
10 | from expremigen.patterns.ptween import Ptween
11 |
12 | outputfile = "output/twovoicewithchords.mid"
13 |
14 |
15 | def add_melody(pat2mid, track, channel):
16 | n = Note2Midi()
17 | notes = ["c4", "e4", "g4", "c5", "b4", "g4", "f4", "d4", "c4"]
18 | from vectortween.NumberAnimation import NumberAnimation
19 | from vectortween.SequentialAnimation import SequentialAnimation
20 | increase = NumberAnimation(frm=Dyn.mp, to=Dyn.f)
21 | decrease = NumberAnimation(frm=Dyn.f, to=Dyn.ppp)
22 | swell_dim = SequentialAnimation([increase, decrease])
23 | increasing_staccato = NumberAnimation(frm=1, to=0.5)
24 | properties = {
25 | # convert from note names to midi numbers
26 | PP.NOTE: Pseq(n.convert2(notes)),
27 | # last note is longer than the rest
28 | PP.DUR: Pseq([Pconst(Dur.quarter, len(notes) - 1), Pconst(Dur.whole, 1)]),
29 | # animate staccato
30 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
31 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
32 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
33 | }
34 | p = Phrase(properties)
35 | pat2mid.set_tempo(60)
36 | pat2mid.add_phrase(p, track=track, channel=channel, start_time=0)
37 | return pat2mid
38 |
39 |
40 | def add_chords(pat2mid, track, channel):
41 | n = Note2Midi()
42 | notes = [C(["c3", "e3", "g3"]), C(["b2", "d3", "g3"]), C(["c3", "e3", "g3", "c4"])]
43 | from vectortween.NumberAnimation import NumberAnimation
44 | decrease = NumberAnimation(frm=Dyn.f, to=Dyn.p)
45 | properties = {
46 | PP.NOTE: Pseq(n.convert2(notes)),
47 | PP.DUR: Pseq([Pconst(Dur.whole, 2), Pconst(Dur.doublewhole, 1)]),
48 | PP.PLAYEDDUR: Pconst(1),
49 | PP.VOL: Ptween(decrease, 0, 0, len(notes), len(notes), None)
50 | }
51 | p = Phrase(properties)
52 | pat2mid.add_phrase(p, track=track, channel=channel, start_time=0)
53 | return pat2mid
54 |
55 |
56 | if __name__ == "__main__":
57 | p2m = Pat2Midi(num_tracks=2)
58 | p2m = add_melody(p2m, 0, 0)
59 | p2m = add_chords(p2m, 1, 1)
60 | p2m.write(outputfile)
61 |
--------------------------------------------------------------------------------
/expremigen/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/expremigen/__init__.py
--------------------------------------------------------------------------------
/expremigen/io/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/expremigen/io/__init__.py
--------------------------------------------------------------------------------
/expremigen/io/constants.py:
--------------------------------------------------------------------------------
1 | NO_OF_OFFICIAL_CONTROLLERS = 128
2 | NO_OF_CONTROLLERS = 129
3 | NO_OF_TRACKS = 16
4 |
5 |
6 | class Defaults:
7 | """
8 | some default values used to fill in missing data
9 | """
10 | note = "a4"
11 | dur = 1 / 4
12 | playeddur = 0.9
13 | lag = 0
14 | vol = 70
15 | tempo = 100
16 | octave = "4"
17 |
18 |
19 | class PhraseProperty:
20 | """
21 | list of animatable properties
22 | """
23 | NOTE = "0"
24 | DUR = "1"
25 | PLAYEDDUR = "2"
26 | VOL = "3"
27 | LAG = "4"
28 | TEMPO = "5"
29 |
30 | @classmethod
31 | def ctrl_dur_key(cls, cc_number):
32 | """
33 | calculates a key for specifying control change duration value (internal usage)
34 | :param cc_number: control change number
35 | :return: cc key
36 | """
37 | return f"D{cc_number}"
38 |
39 | @classmethod
40 | def ctrl_val_key(cls, cc_number):
41 | """
42 | calculates a key for specifying control change value (internal usage)
43 | :param cc_number: control change number
44 | :return: cc key
45 | """
46 | return f"V{cc_number}"
47 |
--------------------------------------------------------------------------------
/expremigen/io/midicontrolchanges.py:
--------------------------------------------------------------------------------
1 | class MidiControlChanges:
2 | """
3 | list of midi control change messages
4 | """
5 | BankSelect = 0 # Bank Select Allows user to switch bank for patch selection.Program change used with
6 | # Bank Select. MIDI can access 16384 patches per MIDI channel.
7 |
8 | Modulation = 1 # Generally this CC controls a vibrato effect(pitch, loudness, brighness).What is modulated is
9 | # based n the patch.
10 |
11 | BreathController = 2 # Often times associated with aftertouch messages.It was originally intended for use with a
12 | # breath MIDI controller in which blowing harder produced higher MIDI control values.
13 | # It can be used for modulation as well.
14 |
15 | FootController = 4 # Often used with aftertouch messages.It can send a continuous stream of values based on how
16 | # the pedal is used.
17 |
18 | PortamentoTime = 5 # Controls portamento rate to slide between 2 notes played subsequently
19 |
20 | DataEntry = 6 # Data Entry Most Significant Bit(MSB) Controls Value for NRPN or RPN parameters.
21 |
22 | Volume = 7 # the volume of the channel
23 |
24 | Balance = 8 # Balance Controls the left and right balance, generally for stereo patches.
25 | # 0 = hard left, 64 = center, 127 = hard right
26 |
27 | Pan = 10 # Pan Controls the left and right balance, generally for mono patches.
28 | # 0 = hard left, 64 = center, 127 = hard right
29 |
30 | Expression = 11 # Expression is a percentage of volume(CC7).
31 |
32 | EffectController1 = 12 # Effect Controller. Usually used to control a parameter of an effect within the
33 | # synth / workstation.
34 | EffectController2 = 13 # Usually used to control a parameter of an effect within the synth / workstation.
35 |
36 | GeneralPurpose1 = 16 # General purpose MIDI CC
37 |
38 | GeneralPurpose2 = 17 # General purpose MIDI CC
39 |
40 | GeneralPurpose3 = 18 # General purpose MIDI CC
41 |
42 | GeneralPurpose4 = 19 # General purpose MIDI CC
43 |
44 | Controller0LSb = 32 # Least Significant Bit (LSB)
45 | Controller1LSb = 33 # Least Significant Bit (LSB)
46 | Controller2LSb = 34 # Least Significant Bit (LSB)
47 | Controller3LSb = 35 # Least Significant Bit (LSB)
48 | Controller4LSb = 36 # Least Significant Bit (LSB)
49 | Controller5LSb = 37 # Least Significant Bit (LSB)
50 | Controller6LSb = 38 # Least Significant Bit (LSB)
51 | Controller7LSb = 39 # Least Significant Bit (LSB)
52 | Controller8LSb = 40 # Least Significant Bit (LSB)
53 | Controller9LSb = 41 # Least Significant Bit (LSB)
54 | Controller10LSb = 42 # Least Significant Bit (LSB)
55 | Controller11LSb = 43 # Least Significant Bit (LSB)
56 | Controller12LSb = 44 # Least Significant Bit (LSB)
57 | Controller13LSb = 45 # Least Significant Bit (LSB)
58 | Controller14LSb = 46 # Least Significant Bit (LSB)
59 | Controller15LSb = 47 # Least Significant Bit (LSB)
60 | Controller16LSb = 48 # Least Significant Bit (LSB)
61 | Controller17LSb = 49 # Least Significant Bit (LSB)
62 | Controller18LSb = 50 # Least Significant Bit (LSB)
63 | Controller19LSb = 51 # Least Significant Bit (LSB)
64 | Controller20LSb = 52 # Least Significant Bit (LSB)
65 | Controller21LSb = 53 # Least Significant Bit (LSB)
66 | Controller22LSb = 54 # Least Significant Bit (LSB)
67 | Controller23LSb = 55 # Least Significant Bit (LSB)
68 | Controller24LSb = 56 # Least Significant Bit (LSB)
69 | Controller25LSb = 57 # Least Significant Bit (LSB)
70 | Controller26LSb = 58 # Least Significant Bit (LSB)
71 | Controller27LSb = 59 # Least Significant Bit (LSB)
72 | Controller28LSb = 60 # Least Significant Bit (LSB)
73 | Controller29LSb = 61 # Least Significant Bit (LSB)
74 | Controller30LSb = 62 # Least Significant Bit (LSB)
75 | Controller31LSb = 63 # Least Significant Bit (LSB)
76 |
77 | Damper = 64 # Damper Pedal / Sustain Pedal On / Off switch that controls sustain.(See also Sostenuto CC 66)
78 | # 0 to 63 = Off, 64 to 127 = On
79 |
80 | Portamento = 65 # Portamento On / Off Switch On / Off switch 0 to 63 = Off, 64 to 127 = On
81 |
82 | Sostenuto = 66 # Sostenuto On / Off Switch On / Off switch – Like the Sustain controller(CC 64), However it
83 | # only holds notes that were “On” when the pedal was pressed.People use it to “hold” chords”
84 | # and play melodies over the held chord. 0 to 63 = Off, 64 to 127 = On
85 |
86 | SoftPedal = 67 # Soft Pedal On / Off Switch On / Off switch - Lowers the volume of notes played.
87 | # 0 to 63 = Off, 64 to 127 = On
88 |
89 | Legato = 68 # Legato FootSwitch On / Off switch - Turns Legato effect between 2 subsequent notes
90 | # On or Off. 0 to 63 = Off, 64 to 127 = On
91 |
92 | Hold = 69 # Hold 2 Another way to “hold notes” (see MIDI CC 64 and MIDI CC 66).However notes fade out
93 | # according to their release parameter rather than when the pedal is released.
94 |
95 | SoundController1 = 70 # Sound Controller 1 Usually controls the way a sound is produced.Default = Sound Variation.
96 |
97 | SoundController2 = 71 # Sound Controller 2 Allows shaping the Voltage Controlled Filter(VCF).
98 | # Default = Resonance - also(Timbre or Harmonics)
99 | SoundController3 = 72 # Sound Controller 3 Controls release time of the Voltage controlled Amplifier(VCA).
100 | # Default = Release Time.
101 | SoundController4 = 73 # Sound Controller 4 Controls the “Attack’ of a sound.The attack is the amount of time it
102 | # takes forthe sound to reach maximum amplitude.
103 | SoundController5 = 74 # Sound Controller 5 Controls VCFs cutoff frequency of the filter.
104 |
105 | SoundController6 = 75 # Sound Controller 6 Generic – Some manufacturers may use to further shave their sounds.
106 |
107 | SoundController7 = 76 # Sound Controller 7 - Generic – Some manufacturers may use to further shave their sounds.
108 |
109 | SoundController8 = 77 # Sound Controller 8 - Generic – Some manufacturers may use to further shave their sounds.
110 |
111 | SoundController9 = 78 # Sound Controller 9 - Generic – Some manufacturers may use to further shave their sounds.
112 |
113 | SoundController10 = 79 # Sound Controller 10 - Generic – Some manufacturers may use to further shave their sounds.
114 |
115 | GeneralPurpose5 = 80 # General Purpose MIDI CC Controller Generic On / Off switch 0 to 63 = Off, 64 to 127 = On
116 |
117 | GeneralPurpose6 = 81 # General Purpose MIDI CC Controller Generic On / Off switch 0 to 63 = Off, 64 to 127 = On
118 |
119 | GeneralPurpose7 = 82 # General Purpose MIDI CC Controller Generic On / Off switch 0 to 63 = Off, 64 to 127 = On
120 |
121 | GeneralPurpose8 = 83 # General Purpose MIDI CC Controller Generic On / Off switch 0 to 63 = Off, 64 to 127 = On
122 |
123 | PortamentoCCControl = 84 # Controls the amount of Portamento.
124 |
125 | Effect1 = 91 # Effect 1 Depth Usually controls reverb send amount
126 | Effect2 = 92 # Effect 2 Depth Usually controls tremolo
127 | Effect3 = 93 # Effect 3 Depth Usually controls chorus amount
128 | Effect4 = 94 # Depth Usually controls detune amount MIDI CC 95
129 | Effect5 = 95 # Effect 5 Depth Usually controls phaser amount
130 |
131 | DataIncrement = 97 # Data Increment Usually tested to increment data for RPN and NRPN messages.
132 | DataDecrement = 96 # Usually used to decrement data for RPN and NRPN messages.
133 |
134 | NRNNoneRegParamLSB = 98 # Non - Registered Parameter Number LSB(NRPN) For controllers 6, 38, 96, and 97,
135 | # it selects the NRPN parameter.
136 | NRPNNonRegParamMSB = 99 # Non - Registered Parameter Number MSB(NRPN) For controllers 6, 38, 96, and 97,
137 | # it selects the NRPN parameter.
138 |
139 | ReParameterNumberLSBR = 100 # For controllers 6, 38, 96, and 97, it selects the RPN parameter.
140 |
141 | ReParameterNumberMSB = 101 # Registered Parameter Number MSB(RPN) For controllers
142 |
143 | ChannelModeMessage1 = 120 # 120 to 127 are “Channel Mode Messages.”
144 | AllSoundOff = 120 # All Sound Off Mutes all sounding notes.It does so regardless of release
145 | # time or sustain.(See MIDI CC 123)
146 | ResetAllControllers = 121 # reset all controllers. It will reset all controllers to their default.
147 | LocalOnOffSwitch = 122 # Local On / Off Switch Turns internal connection of a MIDI keyboard / workstation, etc.On
148 | # or if you use a computer, you will most likely want local control off to avoid notes
149 | # being played twice.Once locally and twice whent the note is sent back from the computer
150 | # to your keyboard.
151 | AllNotes = 123 # Off Mutes all sounding notes.Release time will still be maintained, and notes held sustain
152 | # will not turn off until sustain pedal is depressed.
153 | OmniMode = 124 # 1Omni Mode Off Sets to “Omni Off” mode. MIDI CC
154 | OmonModeOnSets = 125 # 125 Omni Mode On Sets to “Omni On” mode
155 | MonoModeMode = 126 # Mono Mode Sets device mode to Monophonic.
156 | PolyMode = 127 # Poly Mode Sets device mode to Polyphonic.
157 |
158 | PitchWheel = 128 # Own addition...
159 |
--------------------------------------------------------------------------------
/expremigen/io/pat2midi.py:
--------------------------------------------------------------------------------
1 | from midiutil import MIDIFile
2 |
3 | from expremigen.io.constants import Defaults, NO_OF_CONTROLLERS, NO_OF_OFFICIAL_CONTROLLERS, NO_OF_TRACKS
4 | from expremigen.io.constants import PhraseProperty as PP
5 | from expremigen.io.midicontrolchanges import MidiControlChanges
6 | from expremigen.io.phrase import Phrase
7 | from expremigen.musicalmappings.constants import REST
8 | from expremigen.musicalmappings.note2midi import Note2Midi
9 | from expremigen.patterns.pchord import Pchord
10 |
11 |
12 | class Pat2Midi:
13 | """
14 | class to convert Pattern to Midi
15 | """
16 |
17 | def __init__(self, num_tracks: int = 1, remove_duplicates: bool = True, deinterleave: bool = True,
18 | file_format: int = 1):
19 | """
20 |
21 | :param num_tracks: number of tracks (default: 1)
22 | :param remove_duplicates: remove notes if they start at the same time on the same channel if they have
23 | the same pitch (default: True)
24 | :param deinterleave: clean up two note-ons with no note-off in between (default: True)
25 | :param file_format: 1 or 2 (default: 1)
26 | """
27 | self.midiFile = MIDIFile(numTracks=num_tracks, removeDuplicates=remove_duplicates, deinterleave=deinterleave,
28 | adjust_origin=False, file_format=file_format)
29 | self.last_set_tempo = [Defaults.tempo for _ in range(16)] # set every track to default tempo
30 | self.set_tempo(Defaults.tempo, 0)
31 | self.last_set_cc = [[None for _ in range(NO_OF_CONTROLLERS)] for _ in range(NO_OF_TRACKS)]
32 | self.note2midi = Note2Midi()
33 |
34 | def set_tempo(self, tempo=100, time=0):
35 | """
36 |
37 | :param tempo: bpm (default: 100)
38 | :param time: time at which the tempo change should be inserted in the midi stream (default: 0)
39 | """
40 | self.midiFile.addTempo(track=0, time=time, tempo=tempo)
41 | self.last_set_tempo[0] = tempo
42 | self.last_set_cc = [[None for _ in range(NO_OF_CONTROLLERS)] for _ in range(NO_OF_TRACKS)]
43 |
44 | def add_phrase(self, phrase: Phrase, track=0, channel=0, start_time=0):
45 | """
46 |
47 | :param phrase: a Phrase containing patterns and animations
48 | :param track: default: 0
49 | :param channel: default: 0
50 | :param start_time: time at which the phrase should be inserted default: 0
51 | :return: total duration of the inserted phrase
52 | """
53 | for event in phrase:
54 | # set tempo events only if they changed since last time
55 | # handle note events
56 | if PP.NOTE in event:
57 | if event[PP.TEMPO] != self.last_set_tempo[track]:
58 | self.midiFile.addTempo(track, start_time + phrase.generated_duration(), event[PP.TEMPO])
59 | self.last_set_tempo[track] = event[PP.TEMPO]
60 | # set notes always
61 | if isinstance(event[PP.NOTE], Pchord):
62 | for n in event[PP.NOTE].notes:
63 | try:
64 | intnote = int(n)
65 | except ValueError:
66 | intnote = self.note2midi.lookup(n)
67 | if intnote == REST:
68 | continue
69 |
70 | self.midiFile.addNote(
71 | track=track,
72 | channel=channel,
73 | pitch=intnote,
74 | time=start_time + phrase.generated_duration() + event[PP.LAG],
75 | duration=event[PP.DUR] * event[PP.PLAYEDDUR],
76 | volume=int(event[PP.VOL]),
77 | annotation=None)
78 |
79 | else:
80 |
81 | try:
82 | intnote = int(event[PP.NOTE])
83 | except ValueError:
84 | intnote = self.note2midi.lookup(event[PP.NOTE])
85 | if intnote == REST:
86 | continue
87 |
88 | self.midiFile.addNote(
89 | track=track,
90 | channel=channel,
91 | pitch=intnote,
92 | time=start_time + phrase.generated_duration() + event[PP.LAG],
93 | duration=event[PP.DUR] * event[PP.PLAYEDDUR],
94 | volume=int(event[PP.VOL]),
95 | annotation=None)
96 |
97 | self.handle_control_changes(channel, event, phrase, start_time, track)
98 |
99 | # handle controller events (only if they changed since last time)
100 | else:
101 | self.handle_control_changes(channel, event, phrase, start_time, track)
102 |
103 | return phrase.generated_duration()
104 |
105 | def handle_control_changes(self, channel, event, phrase, start_time, track):
106 | """
107 | iterate over all control changes in the phrase and add them to the midi file
108 | :param channel: midi channel
109 | :param event: python dict containing phrase properties
110 | :param phrase:
111 | :param start_time: time offset
112 | :param track: midi track id
113 | :return:
114 | """
115 | for cc in range(NO_OF_OFFICIAL_CONTROLLERS):
116 | if PP.ctrl_dur_key(cc) in event:
117 | time = start_time + phrase.generated_ctrl_duration(cc)
118 | value = event[PP.ctrl_val_key(cc)]
119 | if value is not None:
120 | self.midiFile.addControllerEvent(track=track,
121 | channel=channel,
122 | time=time,
123 | controller_number=cc,
124 | parameter=value)
125 | for cc in [MidiControlChanges.PitchWheel]:
126 | if PP.ctrl_dur_key(cc) in event:
127 | time = start_time + phrase.generated_ctrl_duration(cc)
128 | pwvalue = event[PP.ctrl_val_key(cc)]
129 | if pwvalue is not None:
130 | self.midiFile.addPitchWheelEvent(track=track,
131 | channel=channel,
132 | time=time,
133 | pitchWheelValue=pwvalue)
134 |
135 | def add_phrases(self, list_of_phrase, track=0, channel=0, start_time=0):
136 | """
137 |
138 | :param list_of_phrase: a list of Phrase
139 | :param track: default: 0
140 | :param channel: midi channel, deafult: 0
141 | :param start_time: default: 0
142 | :return: total duration of piece from begin until end of list of phrases
143 | """
144 | time_delta = 0
145 | for phrase in list_of_phrase:
146 | duration = self.add_phrase(phrase, track, channel, start_time + time_delta)
147 | time_delta += duration
148 | return start_time + time_delta
149 |
150 | def write(self, filename):
151 | """
152 | write to midi file
153 | :param filename: filename
154 | """
155 | try:
156 | with open(filename, "wb") as f:
157 | self.midiFile.writeFile(fileHandle=f)
158 | except Exception as e:
159 | print("we hit a SNAFU while writing to {0}: {1}".format(filename, e))
160 |
--------------------------------------------------------------------------------
/expremigen/io/phrase.py:
--------------------------------------------------------------------------------
1 | from expremigen.io.constants import PhraseProperty as PP, Defaults, NO_OF_CONTROLLERS, NO_OF_OFFICIAL_CONTROLLERS
2 | from expremigen.io.midicontrolchanges import MidiControlChanges as MCC
3 | from expremigen.musicalmappings.constants import REST
4 | from expremigen.musicalmappings.note2midi import Note2Midi
5 | from expremigen.patterns.pchord import Pchord
6 | from expremigen.patterns.pconst import Pconst
7 |
8 |
9 | class Phrase:
10 | """
11 | class to hold a Phrase, i.e. a dictionary of (animated) phrase properties
12 | The key is one of
13 | PhraseProperty.NOTE,
14 | PhraseProperty.DUR,
15 | PhraseProperty.LAG,
16 | PhraseProperty.PLAYEDDUR,
17 | PhraseProperty.VOL,
18 | PhraseProperty.TEMPO,
19 | PhraseProperty.CtrlDur(CCNumber)
20 | PhraseProperty.CtrlVal(CCNumber)
21 | """
22 |
23 | def __init__(self, properties: dict = None):
24 | self.n2m = Note2Midi()
25 | if properties is None:
26 | properties = {}
27 | self.p = properties
28 | if PP.NOTE not in self.p:
29 | self.p[PP.NOTE] = Pconst(self.n2m.lookup(Defaults.note), 1)
30 | if PP.DUR not in self.p:
31 | self.p[PP.DUR] = Pconst(Defaults.dur)
32 | if PP.LAG not in self.p:
33 | self.p[PP.LAG] = Pconst(Defaults.lag)
34 | if PP.PLAYEDDUR not in self.p:
35 | self.p[PP.PLAYEDDUR] = Pconst(Defaults.playeddur)
36 | if PP.VOL not in self.p:
37 | self.p[PP.VOL] = Pconst(Defaults.vol)
38 | if PP.TEMPO not in self.p:
39 | self.p[PP.TEMPO] = Pconst(Defaults.tempo)
40 |
41 | self.note_time = 0
42 | self.ctrl_time = [0 for _ in range(NO_OF_CONTROLLERS)]
43 |
44 | def __iter__(self):
45 | """
46 | converts the phrase to an iterable containing events
47 |
48 | :return: total time taken by this phrase
49 | """
50 | self.note_time = 0
51 | self.ctrl_time = [0 for _ in range(NO_OF_CONTROLLERS)]
52 |
53 | # note events are basically governed by the DUR key
54 | for value in zip(self.p[PP.NOTE], self.p[PP.DUR], self.p[PP.PLAYEDDUR], self.p[PP.VOL], self.p[PP.LAG],
55 | self.p[PP.TEMPO]):
56 | if isinstance(value[0], Pchord) or value[0] != REST: # 128 denotes a rest
57 | yield {
58 | PP.NOTE: value[0],
59 | PP.DUR: value[1] * 4, # convert from quarter note to beat
60 | PP.PLAYEDDUR: value[2],
61 | PP.VOL: int(value[3]),
62 | PP.LAG: value[4],
63 | PP.TEMPO: value[5]
64 | }
65 | self.note_time += value[1] * 4 # convert from quarter note to beat
66 |
67 | # control change events can have their own timeline (e.g. this allows for pitchbend or modwheel variations
68 | # while notes are playing)
69 | for cc in range(NO_OF_OFFICIAL_CONTROLLERS):
70 | if PP.ctrl_dur_key(cc) in self.p and PP.ctrl_val_key(cc) in self.p:
71 | for value in zip(self.p[PP.ctrl_dur_key(cc)], self.p[PP.ctrl_val_key(cc)]):
72 | if value[0] is not None and value[1] is not None:
73 | yield {
74 | PP.ctrl_dur_key(cc): value[0] * 4,
75 | PP.ctrl_val_key(cc): value[1]
76 | }
77 | self.ctrl_time[cc] += value[0] * 4
78 | for cc in [MCC.PitchWheel]:
79 | if PP.ctrl_dur_key(cc) in self.p and PP.ctrl_val_key(cc) in self.p:
80 | for value in zip(self.p[PP.ctrl_dur_key(cc)], self.p[PP.ctrl_val_key(cc)]):
81 | if value[0] is not None and value[1] is not None:
82 | yield {
83 | PP.ctrl_dur_key(cc): value[0] * 4,
84 | PP.ctrl_val_key(cc): int(value[1])
85 | }
86 | self.ctrl_time[cc] += value[0] * 4
87 |
88 | def generated_duration(self):
89 | """
90 |
91 | :return: total duration of this note phrase
92 | """
93 | # only works as expected after you iterated over the phrase already
94 | return self.note_time
95 |
96 | def generated_ctrl_duration(self, cc_value):
97 | """
98 | :param cc_value: midi control change id
99 | :return: total duration taken by control changes for controller cc_value
100 | """
101 | # only works as expected after you iterated over the phrase already
102 | return self.ctrl_time[cc_value]
103 |
--------------------------------------------------------------------------------
/expremigen/mispel/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/expremigen/mispel/__init__.py
--------------------------------------------------------------------------------
/expremigen/mispel/exception.py:
--------------------------------------------------------------------------------
1 | class ValidationException(Exception):
2 | """
3 | Exception thrown if a mispel string has valid syntax, but specifies non-sensical things
4 | """
5 | pass
6 |
--------------------------------------------------------------------------------
/expremigen/mispel/mispel.py:
--------------------------------------------------------------------------------
1 | from collections import defaultdict
2 |
3 | from textx.metamodel import metamodel_from_str
4 | from vectortween.NumberAnimation import NumberAnimation
5 |
6 | from expremigen.io.constants import Defaults, NO_OF_CONTROLLERS
7 | from expremigen.io.constants import PhraseProperty as PP
8 | from expremigen.io.phrase import Phrase
9 | from expremigen.mispel.exception import ValidationException
10 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
11 | from expremigen.musicalmappings.playeddurations import PlayedDurations as PDur
12 | from expremigen.musicalmappings.tempo import Tempo
13 | from expremigen.musicalmappings.note2midi import Note2Midi
14 | from expremigen.patterns.pchord import Pchord
15 | from expremigen.patterns.pconst import Pconst
16 | from expremigen.patterns.pseq import Pseq
17 | from expremigen.patterns.ptween import Ptween
18 | from expremigen.patterns.utils import take
19 |
20 |
21 | class Mispel:
22 | """
23 | Mispel = MIdi SPEcification Language
24 | """
25 |
26 | def __init__(self):
27 | self.note2midi = Note2Midi()
28 | self.grammar = r"""
29 | SectionModel:
30 | sections+=Section
31 | ;
32 | Section:
33 | 'with' headerspecs=HeaderSpec ':' events+=Event
34 | ;
35 | HeaderSpec:
36 | (TimeDrivenHeaderSpec | NoteDrivenHeaderSpec)
37 | ;
38 | TimeDrivenHeaderSpec:
39 | (track=TrackSpec)? (channel=ChannelSpec)? (time=TimeSpec)? (driver='timedriven')
40 | ;
41 | NoteDrivenHeaderSpec:
42 | (track=TrackSpec)? (channel=ChannelSpec)? (time=TimeSpec)? (driver='notedriven')?
43 | ;
44 | TimeSpec:
45 | 'time' value=FLOAT
46 | ;
47 | ChannelSpec:
48 | 'channel' id=INT
49 | ;
50 | TrackSpec:
51 | 'track' id=INT
52 | ;
53 | Event:
54 | (ks=ChordSpec | ns=NoteSpec | cs=CcSpec)
55 | ;
56 | ChordSpec:
57 | '<' notes+=NoteSpec '>'
58 | ;
59 | CcSpec:
60 | (acc=AnimatedControlChange|scc=StaticControlChange)
61 | ;
62 | Note:
63 | NoteName NoteModifier?
64 | ;
65 | DrumNote:
66 | {0}
67 | ;
68 | NoteName:
69 | 'a' | 'b' | 'c' | 'd' | 'e' | 'f' | 'g' | 'r'
70 | ;
71 | NoteModifier:
72 | '#' | '--' | '-' | 'x'
73 | ;
74 | OneOrTwoDigits:
75 | Digit Digit?
76 | ;
77 | Digit:
78 | '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
79 | ;
80 | NoteSpec:
81 | ((name=DrumNote) | (name=Note (octave=OneOrTwoDigits)?)) (invdur=UnderScoreInt)? properties*=NoteProperties
82 | ;
83 | UnderScoreInt:
84 | '_' value=MyFloat dots*='.' ('*' num=INT ('/' den=INT)?)?
85 | ;
86 | NoteProperties:
87 | (avol=AnimatedVol|svol=StaticVol|apdur=AnimatedPDur|spdur=StaticPDur|alag=AnimatedLag|slag=StaticLag|
88 | atempo=AnimatedTempo|stempo=StaticTempo|acc=AnimatedControlChange|scc=StaticControlChange)
89 | ;
90 | StaticControlChange:
91 | '\cc' '[' id=INT ',' value=INT ']'
92 | ;
93 | AnimatedControlChange:
94 | '\cc' '{' id=INT ',' value=INT (tweenoptions=TweenOptions)? '}'
95 | ;
96 | StaticTempo:
97 | '\tempo' '[' (symval=SymTempo|value=NumTempo) ']'
98 | ;
99 | AnimatedTempo:
100 | '\tempo' '{' (symval=SymTempo|value=NumTempo) (tweenoptions=TweenOptions)? '}'
101 | ;
102 | NumTempo:
103 | value=INT
104 | ;
105 | SymTempo:
106 | (symval='larghissimo' | symval='grave' | symval='lento' | symval='largho' | symval='larghetto' |
107 | symval='adagissimo' | symval='adagio' | symval='adagietto' | symval='andante' | symval='andantino' |
108 | symval='moderato' | symval='allegretto' | symval='allegro' | symval='vivace' | symval='allegro_vivace' |
109 | symval='vivacissimo' | symval='allegro_assai' | symval='presto' | symval='prestissimo')
110 | ;
111 | StaticLag:
112 | '\lag' '[' value=NumLag ']'
113 | ;
114 | AnimatedLag:
115 | '\lag' '{' value=NumLag (tweenoptions=TweenOptions)? '}'
116 | ;
117 | NumLag:
118 | value=FLOAT
119 | ;
120 | StaticPDur:
121 | '\pdur' '[' (symval=SymPDur | value=NumPDur) ']'
122 | ;
123 | AnimatedPDur:
124 | '\pdur' '{' (symval=SymPDur | value=NumPDur) (tweenoptions=TweenOptions)? '}'
125 | ;
126 | NumPDur:
127 | value=FLOAT
128 | ;
129 | SymPDur:
130 | symval='staccatissimo' | symval='staccato' | symval='legatissimo' | symval='legato' | symval='normal'
131 | ;
132 | StaticVol:
133 | '\vol' '[' (symval=SymVol|value=NumVol) ']'
134 | ;
135 | AnimatedVol:
136 | '\vol' '{' (symval=SymVol|value=NumVol) (tweenoptions=TweenOptions)? '}'
137 | ;
138 | TweenOptions:
139 | ',' (tweentype=TweenType) ','? extra_options*=MyFloat[',']
140 | ;
141 | TweenType:
142 | 'linear' | 'easeInQuad' | 'easeOutQuad'| 'easeInOutQuad'| 'easeInCubic'| 'easeOutCubic'| 'easeInOutCubic'|
143 | 'easeInQuart'| 'easeOutQuart'| 'easeInOutQuart'| 'easeInQuint'| 'easeOutQuint'| 'easeInOutQuint'|
144 | 'easeInSine'| 'easeOutSine'| 'easeInOutSine'| 'easeInExpo'| 'easeOutExpo'| 'easeInOutExpo'|
145 | 'easeInCirc'| 'easeOutCirc'| 'easeInOutCirc'| 'easeInBounce'| 'easeOutBounce'| 'easeInOutBounce'|
146 | 'easeInElastic'| 'easeOutElastic'| 'easeInOutElastic'| 'easeInBack'| 'easeOutBack'| 'easeInOutBack'
147 | ;
148 | NumVol:
149 | value=INT
150 | ;
151 | SymVol:
152 | symval='ppppp' | symval='pppp' | symval='ppp' | symval='pp' | symval='p' | symval='mp' | symval='mf' |
153 | symval='ffff' | symval='fff' | symval='ff' | symval='f'
154 | ;
155 | MyFloat:
156 | /\d+(\.\d+)?/
157 | ;
158 | Comment:
159 | /\/\/.*$/ |
160 | /\/\*(.|\n)*?\*\//
161 | ;
162 | """.replace("{0}", self.note2midi.get_drumnotes_for_grammar())
163 | self.mm = metamodel_from_str(self.grammar, ws = "' '\n\t'|'")
164 | object_processors = { 'MyFloat': lambda x: float(x) }
165 | self.mm.register_obj_processors(object_processors)
166 | self.model = None
167 | self.last_octave = Defaults.octave
168 | self.last_duration = 1 / Defaults.dur
169 | self.last_dynamic = ('num', 'static', Defaults.vol)
170 | self.last_lag = ('num', 'static', Defaults.lag)
171 | self.last_pdur = ('num', 'static', Defaults.playeddur)
172 | self.last_tempo = ('num', 'static', Defaults.tempo)
173 | self.last_cc = defaultdict(lambda: None)
174 |
175 | def parse(self, thestring):
176 | """
177 | parses a mispel string into an internal model
178 | :param thestring: string in mispel syntax
179 | :return: parsed model
180 | """
181 | self.model = self.mm.model_from_str(thestring)
182 | return self.model
183 |
184 | def get_no_of_sections(self):
185 | """
186 |
187 | :return: returns the number of sections in the parsed mispel string
188 | """
189 | if self.model.sections:
190 | return len(self.model.sections)
191 | return 0
192 |
193 | def section(self, section_id):
194 | """
195 |
196 | :param section_id: integer
197 | :return: parsed section
198 | """
199 | if self.model.sections is None:
200 | raise ValidationException("Fatal Error! Expected sections to be defined.")
201 | if len(self.model.sections) <= section_id:
202 | raise ValidationException(f"Fatal Error! Trying to access non-existing section {section_id}")
203 | return self.model.sections[section_id]
204 |
205 | def track_for_section(self, section_id):
206 | """
207 |
208 | :param section_id: integer
209 | :return: the midi track number that was specified for this section
210 | """
211 | section = self.section(section_id)
212 | if section.headerspecs.track is None:
213 | return 0
214 | return int(section.headerspecs.track.id)
215 |
216 | def channel_for_section(self, section_id):
217 | """
218 |
219 | :param section_id: integer
220 | :return: the midi channel id that was specified for this section
221 | """
222 | section = self.section(section_id)
223 | if section.headerspecs.channel is None:
224 | return 0
225 | return int(section.headerspecs.channel.id)
226 |
227 | def time_for_section(self, section_id):
228 | """
229 |
230 | :param section_id: integer
231 | :return: the time offset specified for this section
232 | """
233 | section = self.section(section_id)
234 | if section.headerspecs.time is None:
235 | return 0
236 | return section.headerspecs.time.value
237 |
238 | def driver_for_section(self, section_id):
239 | """
240 |
241 | :param section_id: integer
242 | :return: the driver ("notedriven" or "timedriven") specified for this section
243 | """
244 | section = self.section(section_id)
245 | if not section.headerspecs.driver:
246 | return 'notedriven'
247 | return section.headerspecs.driver
248 |
249 | def events_for_section(self, section_id):
250 | """
251 |
252 | :param section_id: integer
253 | :return: list of parsed events (= notes with associated properties)
254 | """
255 | section = self.section(section_id)
256 | return section.events
257 |
258 | def name_for_notespec(self, notespec):
259 | """
260 |
261 | :param notespec: parsed notespec (see grammar)
262 | :return: name of the note
263 | """
264 | if notespec is None:
265 | raise ValidationException("Fatal Error! Asking name only makes sense for note events.")
266 | if notespec.name is None:
267 | raise ValidationException("Fatal Error! Note needs a name.")
268 | return notespec.name
269 |
270 | def octave_for_notespec(self, notespec):
271 | """
272 |
273 | :param notespec: parsed notespec (see grammar)
274 | :return: the octave associated to this notespec
275 | """
276 | if notespec.octave is None:
277 | return self.last_octave
278 | if notespec.name != "r":
279 | self.last_octave = notespec.octave
280 | return self.last_octave
281 |
282 | def duration_for_notespec(self, notespec):
283 | """
284 |
285 | :param notespec: parsed notespec (see grammar)
286 | :return: the duration associated to this notespec
287 | """
288 | if notespec.invdur is None:
289 | return self.last_duration
290 | if notespec.invdur.value is None:
291 | return self.last_duration
292 | duration = notespec.invdur.value
293 | if notespec.invdur.dots:
294 | numdots = len(notespec.invdur.dots)
295 | duration = 1 / ((1 / duration) * (2 - 1 / pow(2, numdots)))
296 | multiplier = 1
297 | if notespec.invdur.num and notespec.invdur.den:
298 | multiplier = notespec.invdur.den / notespec.invdur.num # inverted to make more intuitive!
299 | elif notespec.invdur.num:
300 | multiplier = 1 / notespec.invdur.num
301 | self.last_duration = duration * multiplier
302 | return self.last_duration
303 |
304 | def notes_for_section(self, section_id):
305 | """
306 |
307 | :param section_id: integer
308 | :return: list of all notes (ready for note2midi conversion) in this section
309 | """
310 | driver = self.driver_for_section(section_id)
311 | if driver != 'notedriven':
312 | raise ValidationException("Fatal Error! notes can only be specified in notedriven track")
313 | notes = []
314 | for event in self.events_for_section(section_id):
315 | if event.cs is not None:
316 | raise ValidationException(
317 | "Fatal Error! in note driven sections, control changes must be attached to notes")
318 | if event.ns is None and event.ks is None:
319 | raise ValidationException("Fatal Error! Expected a NoteSpec or a ChordSpec.")
320 | if event.ns:
321 | name = self.name_for_notespec(event.ns)
322 | octave = self.octave_for_notespec(event.ns)
323 | if name == "r" or name in self.note2midi.all_drum_notes:
324 | notes.append(f"{name}")
325 | else:
326 | notes.append(f"{name}{octave}")
327 | elif event.ks:
328 | chordnotes = []
329 | for note in event.ks.notes:
330 | name = self.name_for_notespec(note)
331 | octave = self.octave_for_notespec(note)
332 | if name == "r":
333 | assert ValidationException("Fatal Error! No rests allowed inside chords.")
334 | else:
335 | chordnotes.append(f"{name}{octave}")
336 | notes.append(Pchord(chordnotes))
337 | return notes
338 |
339 | def note_generator_for_section(self, section_id):
340 | """
341 |
342 | :param section_id: integer
343 | :return: expremigen pattern generating all notes in this section
344 | """
345 | return Pseq(self.notes_for_section(section_id), 1)
346 |
347 | def durations_for_section(self, section_id):
348 | """
349 |
350 | :param section_id: 0
351 | :return: a list of all durations used in this section
352 | """
353 | driver = self.driver_for_section(section_id)
354 | if driver != 'notedriven':
355 | raise ValidationException("Fatal Error! durations can only be specified in notedriven track")
356 | durations = []
357 | for event in self.events_for_section(section_id):
358 | if event.cs is not None:
359 | raise ValidationException(
360 | "Fatal Error! in note driven sections, control changes must be attached to notes")
361 | if event.ns is None and event.ks is None:
362 | raise ValidationException(f"Fatal Error! Expected a NoteSpec/ChordSpec {event}")
363 |
364 | notespec = None
365 | if event.ns:
366 | notespec = event.ns
367 | elif event.ks:
368 | notespec = event.ks.notes[0]
369 | duration = self.duration_for_notespec(notespec)
370 | durations.append(1 / duration)
371 |
372 | return durations
373 |
374 | def duration_generator_for_section(self, section_id):
375 | """
376 |
377 | :param section_id: integer
378 | :return: an expremigen pattern generating all durations in this section
379 | """
380 | return Pseq(self.durations_for_section(section_id), 1)
381 |
382 | def cc_properties_for_section(self, section_id):
383 | """
384 |
385 | :param section_id: integer
386 | :return: a dictionary: for each control change id encountered, returns a list of control
387 | change properties in this section
388 | """
389 | driver = self.driver_for_section(section_id)
390 | if driver != 'notedriven':
391 | raise ValidationException("Fatal Error! cc_properties_for_section only makes sense in notedriven track")
392 | cc_properties = defaultdict(list)
393 | cc_count_since_previous_event = defaultdict(lambda: 0)
394 | for event in self.events_for_section(section_id):
395 | if event.cs is not None:
396 | raise ValidationException(
397 | f"Fatal Error! cc_properties_for_section extracts from note and chordspecs only {event}")
398 | if event.ns is None and event.ks is None:
399 | raise ValidationException(f"Fatal Error! Expected a NoteSpec/ChordSpec {event}")
400 | if event.ns:
401 | notespec = event.ns
402 | elif event.ks:
403 | notespec = event.ks.notes[0]
404 | else:
405 | continue
406 | for p in notespec.properties:
407 | if p.acc is not None:
408 | ccid = p.acc.id
409 | ccval = p.acc.value
410 | prop = ('num', 'anim', ccval)
411 | cc_properties[ccid].append((self.last_cc[ccid], prop, cc_count_since_previous_event[ccid]))
412 | self.last_cc[ccid] = prop
413 | cc_count_since_previous_event[ccid] = 0
414 | elif p.scc is not None:
415 | ccid = p.scc.id
416 | ccval = p.scc.value
417 | prop = ('num', 'static', ccval)
418 | cc_properties[ccid].append((self.last_cc[ccid], prop, cc_count_since_previous_event[ccid]))
419 | self.last_cc[ccid] = prop
420 | cc_count_since_previous_event[ccid] = 0
421 | for i in range(NO_OF_CONTROLLERS):
422 | cc_count_since_previous_event[i] += 1
423 | for key in cc_properties:
424 | cc_properties[key].append((self.last_cc[key], self.last_cc[key], cc_count_since_previous_event[key]))
425 |
426 | return cc_properties
427 |
428 | def cc_properties_generators_for_section(self, section_id):
429 | """
430 |
431 | :param section_id: integer
432 | :return: a python dictionary: for every control change id encountered, returns a generator generating all
433 | control changes in this section
434 | """
435 | cc_properties = self.cc_properties_for_section(section_id)
436 | patterns = defaultdict(lambda: defaultdict(list))
437 | for cc in cc_properties:
438 | note_durations = self.duration_generator_for_section(section_id)
439 | for segment in cc_properties[cc]:
440 | frm = segment[0]
441 | to = segment[1]
442 | durkey = PP.ctrl_dur_key(cc)
443 | valkey = PP.ctrl_val_key(cc)
444 | if segment[0] is None:
445 | no_of_notes = int(segment[2])
446 | dur = sum(take(no_of_notes, note_durations))
447 | patterns[cc][durkey].append(Pconst(dur, 1))
448 | patterns[cc][valkey].append(Pconst(None, 1))
449 | else:
450 | no_of_notes = int(segment[2])
451 | dur = sum(take(no_of_notes, note_durations))
452 | if frm[1] == "anim":
453 | n = NumberAnimation(frm=int(frm[2]), to=int(to[2]))
454 | patterns[cc][durkey].append(Pconst(0.1 * dur / no_of_notes, int(no_of_notes / 0.1)))
455 | patterns[cc][valkey].append(Ptween(n, 0, 0, int(no_of_notes / 0.1), int(no_of_notes / 0.1)))
456 | elif frm[1] == "static":
457 | patterns[cc][durkey].append(Pconst(dur, 1))
458 | patterns[cc][valkey].append(Pconst(int(frm[2]), 1))
459 | else:
460 | raise ValidationException(f"Fatal Error. Unknown animation type {frm}")
461 | return patterns
462 |
463 | def extract_extra_tween_options(self, animatedproperty):
464 | """
465 |
466 | :param animatedproperty: parsed animated property
467 | :return: extra tween options as found in the animated property, in a form usable for pyvectortween
468 | """
469 | if animatedproperty.tweenoptions is not None:
470 | tweentype = [animatedproperty.tweenoptions.tweentype]
471 | if animatedproperty.tweenoptions.extra_options:
472 | tweentype.extend(animatedproperty.tweenoptions.extra_options)
473 | return tweentype
474 | return None
475 |
476 | def extract_dynamics(self, notespec):
477 | """
478 |
479 | :param notespec: a parsed notespec (see grammar)
480 | :return: associated dynamics for this notespec
481 | """
482 | for p in notespec.properties:
483 | if p.avol is not None:
484 | tweenoptions = self.extract_extra_tween_options(p.avol)
485 | if p.avol.symval is not None:
486 | if tweenoptions is not None:
487 | return "sym", "anim", p.avol.symval.symval, tweenoptions
488 | else:
489 | return "sym", "anim", p.avol.symval.symval
490 | elif p.avol.value is not None:
491 | if tweenoptions is not None:
492 | return "num", "anim", p.avol.value.value, tweenoptions
493 | else:
494 | return "num", "anim", p.avol.value.value
495 | else:
496 | raise ValidationException(f"Fatal! Couldn't understand animated dynamics specification {p.avol}")
497 | elif p.svol is not None:
498 | if p.svol.symval is not None:
499 | return "sym", "static", p.svol.symval.symval
500 | elif p.svol.value is not None:
501 | return "num", "static", p.svol.value.value
502 | else:
503 | raise ValidationException(f"Fatal! Couldn't understand static dynamics specification {p.svol}")
504 | return None
505 |
506 | def extract_pdur(self, notespec):
507 | """
508 |
509 | :param notespec: a parsed notespec
510 | :return: associated playedduration for this notespec
511 | """
512 | for p in notespec.properties:
513 | if p.apdur is not None:
514 | tweenoptions = self.extract_extra_tween_options(p.apdur)
515 | if p.apdur.symval is not None:
516 | if tweenoptions is not None:
517 | return "sym", "anim", p.apdur.symval.symval, tweenoptions
518 | else:
519 | return "sym", "anim", p.apdur.symval.symval
520 | elif p.apdur.value is not None:
521 | if tweenoptions is not None:
522 | return "num", "anim", p.apdur.value.value, tweenoptions
523 | else:
524 | return "num", "anim", p.apdur.value.value
525 | else:
526 | raise ValidationException(f"Fatal! Couldn't understand animated pdur specification {p.apdur}")
527 | elif p.spdur is not None:
528 | if p.spdur.symval is not None:
529 | return "sym", "static", p.spdur.symval.symval
530 | elif p.spdur.value is not None:
531 | return "num", "static", p.spdur.value.value
532 | else:
533 | raise ValidationException(f"Fatal! Couldn't understand static pdur specification {p.spdur}")
534 | return None
535 |
536 | def extract_tempo(self, notespec):
537 | """
538 |
539 | :param notespec: parsed notespec
540 | :return: tempo associated to this notespec
541 | """
542 | for p in notespec.properties:
543 | if p.atempo is not None:
544 | tweenoptions = self.extract_extra_tween_options(p.atempo)
545 | if p.atempo.symval is not None:
546 | if tweenoptions is not None:
547 | return "sym", "anim", p.atempo.symval.symval, tweenoptions
548 | else:
549 | return "sym", "anim", p.atempo.symval.symval
550 | elif p.atempo.value is not None:
551 | if tweenoptions is not None:
552 | return "num", "anim", p.atempo.value.value, tweenoptions
553 | else:
554 | return "num", "anim", p.atempo.value.value
555 | else:
556 | raise ValidationException(f"Fatal! Couldn't understand animated pdur specification {p.atempo}")
557 | elif p.stempo is not None:
558 | if p.stempo.symval is not None:
559 | return "sym", "static", p.stempo.symval.symval
560 | elif p.stempo.value is not None:
561 | return "num", "static", p.stempo.value.value
562 | else:
563 | raise ValidationException(f"Fatal! Couldn't understand static pdur specification {p.stempo}")
564 | return None
565 |
566 | def extract_lag(self, notespec):
567 | """
568 |
569 | :param notespec: parsed notespec
570 | :return: lag associated to this notespec
571 | """
572 | for p in notespec.properties:
573 | if p.alag is not None:
574 | tweenoptions = self.extract_extra_tween_options(p.alag)
575 | if p.alag.value is not None:
576 | if tweenoptions is not None:
577 | return "num", "anim", p.alag.value.value, tweenoptions
578 | else:
579 | return "num", "anim", p.alag.value.value
580 | elif p.slag is not None:
581 | if p.slag.value is not None:
582 | return "num", "static", p.slag.value.value
583 | return None
584 |
585 | def property_for_section(self, section_id, property_from_notespec_fn, default_value):
586 | """
587 | :param section_id: id of the section (integer)
588 | :param property_from_notespec_fn: function that extracts some property from a notespec
589 | :param default_value: value to use of the property is not specified - this value can be updated as defaults
590 | change (e.g. last used octave is remembered as a new default octave)
591 | :return: list of (from_property, to_property, distance)
592 | where from_property and to_property correspond to ('num' or 'sym', 'anim' or 'static', distance)
593 | """
594 | properties = []
595 | count_since_previous_event = 0
596 | for event in self.events_for_section(section_id):
597 | if event.ns:
598 | notespec = event.ns
599 | elif event.ks:
600 | notespec = event.ks.notes[0]
601 | else:
602 | continue
603 | prop = property_from_notespec_fn(notespec)
604 | if prop is not None:
605 | properties.append((default_value, prop, count_since_previous_event))
606 | default_value = prop
607 | count_since_previous_event = 0
608 | count_since_previous_event += 1
609 | properties.append((default_value, default_value, count_since_previous_event))
610 | return properties
611 |
612 | def property_generator_for_section(self, section_id, symvalue_from_string_fn, property_from_notespec_fn,
613 | default_value):
614 | """
615 |
616 | :param section_id: integer
617 | :param symvalue_from_string_fn: function that maps a symbolic specification into a number (e.g. ff => 100)
618 | :param property_from_notespec_fn: function that extracts a given property from a parsed notespec
619 | :param default_value: value that tracks the default value (may update dynamically, e.g. to track last used
620 | octave)
621 | :return: returns a python generator generating all values for the given property
622 | """
623 | dynamics = self.property_for_section(section_id, property_from_notespec_fn, default_value)
624 | patterns = []
625 | for d in dynamics:
626 | frm_dyn = d[0]
627 | to_dyn = d[1]
628 | distance = d[2]
629 | try:
630 | tweenoptions = d[0][3]
631 | except IndexError:
632 | tweenoptions = ['linear']
633 | if distance:
634 | from_value_type = frm_dyn[0]
635 | if from_value_type == 'sym':
636 | from_value = symvalue_from_string_fn(frm_dyn[2])
637 | else:
638 | from_value = frm_dyn[2]
639 | to_value_type = to_dyn[0]
640 | if to_value_type == 'sym':
641 | to_value = symvalue_from_string_fn(to_dyn[2])
642 | else:
643 | to_value = to_dyn[2]
644 | animation_type = frm_dyn[1]
645 | if animation_type == 'anim':
646 | n = Ptween(NumberAnimation(frm=from_value, to=to_value, tween=tweenoptions), 0, 0, distance,
647 | distance,
648 | None)
649 | elif animation_type == 'static':
650 | n = Ptween(NumberAnimation(frm=from_value, to=from_value, tween=['linear']), 0, 0, distance,
651 | distance, None)
652 | else:
653 | print(animation_type)
654 | assert False
655 | patterns.append(n)
656 | return Pseq(patterns, 1)
657 |
658 | def dynamics_for_section(self, section_id):
659 | """
660 | :param section_id: integer
661 | :return: list of (fromdynamic, todynamic, distance)
662 | where fromdynamic and todynamic correspond to ('num' or 'sym', 'anim' or 'static', distance)
663 | """
664 | return self.property_for_section(section_id, self.extract_dynamics, self.last_dynamic)
665 |
666 | def dynamics_generator_for_section(self, section_id):
667 | """
668 |
669 | :param section_id: integer
670 | :return: generator generating all values for dynamics in this section (one per note)
671 | """
672 | return self.property_generator_for_section(section_id, Dyn.from_string, self.extract_dynamics,
673 | self.last_dynamic)
674 |
675 | def lag_for_section(self, section_id):
676 | """
677 | :param section_id:
678 | :return: list of (fromlag, tolag, distance)
679 | where fromlag and tolag correspond to ('num' or 'sym', 'anim' or 'static', distance)
680 | """
681 | return self.property_for_section(section_id, self.extract_lag, self.last_lag)
682 |
683 | def lag_generator_for_section(self, section_id):
684 | """
685 |
686 | :param section_id: integer
687 | :return: generator generating all values for lag in this section (one per note)
688 | """
689 | return self.property_generator_for_section(section_id, None, self.extract_lag, self.last_lag)
690 |
691 | def pdur_for_section(self, section_id):
692 | """
693 |
694 | :param section_id: integer
695 | :return: list of all values for playedduration in this section
696 | """
697 | return self.property_for_section(section_id, self.extract_pdur, self.last_pdur)
698 |
699 | def pdur_generator_for_section(self, section_id):
700 | """
701 |
702 | :param section_id: integer
703 | :return: generator generating all values for playedduration in this section (one per note)
704 | """
705 | return self.property_generator_for_section(section_id, PDur.from_string, self.extract_pdur, self.last_pdur)
706 |
707 | def tempo_for_section(self, section_id):
708 | """
709 |
710 | :param section_id: integer
711 | :return: list of tempi for this section
712 | """
713 | return self.property_for_section(section_id, self.extract_tempo, self.last_tempo)
714 |
715 | def tempo_generator_for_section(self, section_id):
716 | """
717 |
718 | :param section_id: integer
719 | :return: generator generating all tempi in this section (one per note)
720 | """
721 | return self.property_generator_for_section(section_id, Tempo.from_string, self.extract_tempo, self.last_tempo)
722 |
723 | def phrase_properties_for_section(self, section_id):
724 | """
725 |
726 | :param section_id: 0
727 | :return: returns a collection of phrase properties for given section
728 | """
729 | pp = {
730 | PP.NOTE: self.note_generator_for_section(section_id),
731 | PP.VOL: self.dynamics_generator_for_section(section_id),
732 | PP.DUR: self.duration_generator_for_section(section_id),
733 | PP.PLAYEDDUR: self.pdur_generator_for_section(section_id),
734 | PP.LAG: self.lag_generator_for_section(section_id),
735 | PP.TEMPO: self.tempo_generator_for_section(section_id)
736 | }
737 |
738 | ccs = self.cc_properties_generators_for_section(section_id)
739 | for key in ccs:
740 | pp[PP.ctrl_dur_key(key)] = Pseq(ccs[key][PP.ctrl_dur_key(key)], 1)
741 | pp[PP.ctrl_val_key(key)] = Pseq(ccs[key][PP.ctrl_val_key(key)], 1)
742 |
743 | return pp
744 |
745 | def phrase_for_section(self, section_id):
746 | """
747 |
748 | :param section_id: integer
749 | :return: expremigen Phrase for section
750 | """
751 | return Phrase(self.phrase_properties_for_section(section_id))
752 |
753 | def get_no_of_tracks(self):
754 | """
755 |
756 | :return: number of unique tracks found in mispel string
757 | """
758 | no_of_sections = self.get_no_of_sections()
759 | tracks = set([])
760 | for section_id in range(no_of_sections):
761 | tracks.add(self.track_for_section(section_id))
762 | return len(tracks)
763 |
764 | def add_to_pattern2midi(self, pattern2midi):
765 | """
766 |
767 | :param pattern2midi: Pattern2Midi object to which this mispel model will be added
768 | :return: nothing; the Pattern2Midi object is initialized with the mispel info
769 | """
770 | for s in range(self.get_no_of_sections()):
771 | pattern2midi.add_phrase(self.phrase_for_section(s), self.track_for_section(s), self.channel_for_section(s),
772 | self.time_for_section(s))
773 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/expremigen/musicalmappings/__init__.py
--------------------------------------------------------------------------------
/expremigen/musicalmappings/constants.py:
--------------------------------------------------------------------------------
1 | # note value outside midi range of note values with a special meaning
2 | REST = 128
3 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/durations.py:
--------------------------------------------------------------------------------
1 | class Durations:
2 | """
3 | a convenience class of note durations
4 | """
5 | onehundredtwentyeighth = 1 / 128
6 | onehundredtwentyeighth_triplet = onehundredtwentyeighth * 2 / 3
7 | sixtyfourth = 1 / 64
8 | sixtyfourth_triplet = sixtyfourth * 2 / 3
9 | thirtysecond = 1 / 32
10 | thirtysecond_triplet = thirtysecond * 2 / 3
11 | sixteenth = 1 / 16
12 | sixteenth_triplet = sixteenth * 2 / 3
13 | eighth = 1 / 8
14 | eighth_triplet = eighth * 2 / 3
15 | quarter = 1 / 4
16 | quarter_triplet = quarter * 2 / 3
17 | half = 1 / 2
18 | half_triplet = half * 2 / 3
19 | whole = 1
20 | whole_triplet = whole * 2 / 3
21 | doublewhole = 2
22 | doublewhole_triplet = doublewhole * 2 / 3
23 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/dynamics.py:
--------------------------------------------------------------------------------
1 | class Dynamics:
2 | """
3 | a convenience class containing some dynamics
4 | """
5 | ppppp = 10
6 | pppp = 20
7 | ppp = 30
8 | pp = 40
9 | p = 60
10 | mp = 80
11 | mf = 90
12 | f = 100
13 | ff = 110
14 | fff = 120
15 | ffff = 127
16 |
17 | @classmethod
18 | def from_string(cls, thestring):
19 | """
20 |
21 | :param thestring: a string containing a symbolic volume indication
22 | :return: the string mapped to a number
23 | """
24 | lut = {
25 | 'ppppp': Dynamics.ppppp,
26 | 'pppp': Dynamics.pppp,
27 | 'ppp': Dynamics.ppp,
28 | 'pp': Dynamics.pp,
29 | 'p': Dynamics.p,
30 | 'mp': Dynamics.mp,
31 | 'mf': Dynamics.mf,
32 | 'f': Dynamics.f,
33 | 'ff': Dynamics.ff,
34 | 'fff': Dynamics.fff,
35 | 'ffff': Dynamics.ffff
36 | }
37 | if thestring in lut:
38 | return lut[thestring]
39 | else:
40 | return 0
41 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/nanonotation.py:
--------------------------------------------------------------------------------
1 | import re
2 |
3 | from expremigen.musicalmappings.note2midi import Note2Midi
4 |
5 |
6 | class NanoNotation:
7 | """
8 | simple text-based note entry
9 | each note consists of at least the note name, and then some optional parts:
10 | note name is one of a, b, c, d, e, f, g
11 | note name optionally can be followed by one of #, x, b, bb modifiers (note: modifiers are not remembered from previous notes)
12 | modifier is optionally followed by _[inverseduration (e.g. _8 for an eighth note)]
13 | inverse duration is optionally followed by one of \pdur{s} \pdur{l} \pdur{n} \pdur[s] \pdur[l] \pdur[n] for
14 | (staccato, legato, normal), or -\pdur{1.2} or -\pdur[0.3]
15 | note: parameters in {} will animate from this value to the next value
16 | parameters in [] will remain constant until the next value
17 | staccato/legato is optionally followed by dynamics: one of \dyn{ppppp}, ..., \dyn{ffff} or \dyn[ppppp] ... \dyn[ffff],
18 | or \dyn{43} or \dyn[23]
19 | note: parameters in {} will animate from this value to the next value
20 | parameters in [] will remain constant until the next value
21 | dynamics is optionally followed by \lag{0.125} or \lag[0.125] to specify a lag of 0.125
22 | note: parameters in {} will animate from this value to the next value
23 | parameters in [] will remain constant until the next value
24 | lag is optionally followed by \tempo{80} or \tempo[80] to indicate tempo of 80 bpm
25 | note: parameters in {} will animate from this value to the next value
26 | parameters in [] will remain constant until the next value
27 | """
28 |
29 | def __init__(self):
30 | self.note2midi = Note2Midi()
31 | self.note = re.compile("[a-g][#|-|x|(--)]?")
32 | self.note_octave = re.compile("[a-g][#|-|x|(--)]?(?P\d+)")
33 | self.last_dur = 1
34 | self.last_octave = 4
35 |
36 | def notes(self, a_phrase):
37 | """
38 | return the list of midi note numbers in a_string
39 | :param a_phrase: consisting of "[notename][octave]_[inverseduration] ..."
40 | e.g. "a5_8 e5_8 d4 c4 a3_2"
41 | :returns list of midi note numbers
42 | """
43 | note_durs = a_phrase.split(" ")
44 | notes = []
45 | for notedur in note_durs:
46 | if "_" in notedur:
47 | note = notedur.split("_")[0].lower()
48 | else:
49 | note = notedur.lower()
50 |
51 | m = re.match(self.note_octave, note)
52 | if m:
53 | self.last_octave = int(m.group("octave"))
54 | else:
55 | m2 = re.match(self.note, note)
56 | if m2:
57 | note = f"{note}{self.last_octave}"
58 | else:
59 | pass # note = note ;)
60 | notes.append(note)
61 | return notes
62 |
63 | def midinumbers(self, a_phrase):
64 | """
65 | :param a_phrase: a nanonotaion string "[notename][octave]_[inverseduration]..."
66 | :return: list of midi note numbers
67 | """
68 | return self.note2midi.convert2(self.notes(a_phrase))
69 |
70 | def dur(self, a_phrase):
71 | """
72 | :param a_phrase:
73 | :return: list of durations
74 | """
75 | note_durs = a_phrase.split(" ")
76 | durs = []
77 | for notedur in note_durs:
78 | if "_" in notedur:
79 | dur = notedur.split("_")[1]
80 | cnt = 0
81 | while dur.endswith("."):
82 | dur = dur[:-1]
83 | cnt += 1
84 | float_dur = 1 / int(dur)
85 | for c in range(cnt):
86 | pointed_dur = (float_dur / (2 * (c + 1)))
87 | float_dur = float_dur + pointed_dur
88 |
89 | durs.append(float_dur)
90 | self.last_dur = float_dur
91 | else:
92 | durs.append(self.last_dur)
93 | return durs
94 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/note2midi.py:
--------------------------------------------------------------------------------
1 | from expremigen.musicalmappings.constants import REST
2 | from expremigen.patterns.pchord import Pchord
3 |
4 |
5 | class Note2Midi:
6 | """
7 | class to convert note names to midi numbers
8 |
9 | a note name consists of
10 | [note name][modifier][octave]
11 | where
12 | note name: one of a, b, c, d, e, f, g
13 | modifier: one of #, b, x, bb
14 | octave: 0-10
15 |
16 | anything not recognized as a note becomes a rest
17 | """
18 | chromatic_scale = [['c', 'b#', 'dbb', 'd--'], # one row contains all synonyms (i.e. synonym for our purpose)
19 | ['c#', 'bx', 'db', 'd-'],
20 | ['d', 'cx', 'ebb', 'e--'],
21 | ['d#', 'eb', 'e-', 'fbb', 'f--'],
22 | ['e', 'dx', 'fb', 'f-'],
23 | ['f', 'e#', 'gbb', 'g--'],
24 | ['f#', 'ex', 'gb', 'g-'],
25 | ['g', 'fx', 'abb', 'a--'],
26 | ['g#', 'ab', 'a-'],
27 | ['a', 'gx', 'bbb', 'b--'],
28 | ['a#', 'bb', 'b-', 'cbb', 'c--'],
29 | ['b', 'ax', 'cb', 'c-']]
30 |
31 | corner_case_octave_lower = {"b#", "bx"}
32 | corner_case_octave_higher = {"cb", "c-", "cbb", "c--"}
33 |
34 | drummap = {
35 | ('acousticbassdrum', 'abd'): 35,
36 | ('bassdrum', 'bad'): 36,
37 | ('sidestick', 'sis'): 37,
38 | ('acousticsnare', 'acs'): 38,
39 | ('brushtap', 'brt'): 38, # brush kit instead of drum kit
40 | ('handclap', 'hac'): 39,
41 | ('brushslap', 'brs'): 39, # brush kit instead of drum kit
42 | ('electricsnare', 'els'): 40,
43 | ('brushswirl', 'brw'): 40, # brush kit instead of drum kit
44 | ('lowfloortom', 'lft'): 41,
45 | ('closedhihat', 'chh'): 42,
46 | ('highfloortom', 'hft'): 43,
47 | ('pedalhihat', 'phh'): 44,
48 | ('lowtom', 'lot'): 45,
49 | ('openhihat', 'ohh'): 46,
50 | ('lowmidtom', 'lmt'): 47,
51 | ('highmidtom', 'hmt'): 48,
52 | ('crashsymbal1', 'cs1'): 49,
53 | ('hightom', 'hit'): 50,
54 | ('ridecymbal1', 'rc1'): 51,
55 | ('chinesecymbal', 'chc'): 52,
56 | ('ridebell', 'rib'): 53,
57 | ('tambourine', 'tam'): 54,
58 | ('splashcymbal', 'spc'): 55,
59 | ('cowbell', 'cob'): 56,
60 | ('crashsymbal2', 'cc2'): 57,
61 | ('vibraslap', 'vis'): 58,
62 | ('ridecymbal2', 'rc2'): 59,
63 | ('highbongo', 'hib'): 60,
64 | ('lowbongo', 'lob'): 61,
65 | ('mutehiconga', 'mhc'): 62,
66 | ('openhiconga', 'ohc'): 63,
67 | ('lowconga', 'loc'): 64,
68 | ('hightimbale', 'him'): 65,
69 | ('lowtimbale', 'lom'): 66,
70 | ('highagogo', 'hag'): 67,
71 | ('lowagogo', 'lag'): 68,
72 | ('cabasa', 'cab'): 69,
73 | ('maracas', 'mar'): 70,
74 | ('shortwhistle', 'swh'): 71,
75 | ('longwhistle', 'lwh'): 72,
76 | ('shortguiro', 'shg'): 73,
77 | ('longguiro', 'log'): 74,
78 | ('claves', 'cla'): 75,
79 | ('hiwoodblock', 'hwb'): 76,
80 | ('lowoodblock', 'lwb'): 77,
81 | ('mutecuica', 'muc'): 78,
82 | ('opencuica', 'opc'): 79,
83 | ('mutetriangle', 'mut'): 80,
84 | ('opentriangle', 'opt'): 81,
85 | ('shaker', 'shk'): 82
86 | }
87 |
88 | def __init__(self):
89 | # '#' denotes a sharp, 'b' denotes a flat, x denotes a double sharp, bb denotes a double flat
90 | self.note_to_midi = {}
91 | notenum = 0
92 | for octave in range(10):
93 | for note_synonyms in self.chromatic_scale:
94 | if notenum <= 127:
95 | for note in note_synonyms:
96 |
97 | o = octave - 1
98 | if note in self.corner_case_octave_lower:
99 | o = o - 1
100 | elif note in self.corner_case_octave_higher:
101 | o = o + 1
102 | self.note_to_midi["{0}{1}".format(note, o)] = notenum
103 | notenum += 1
104 |
105 | self.all_drum_notes = set([])
106 | for d in self.drummap:
107 | self.note_to_midi["{0}".format(d[0])] = self.drummap[d]
108 | self.note_to_midi["{0}".format(d[1])] = self.drummap[d]
109 | # check that we didn't use the same acronym twice...
110 | assert d[0] not in self.all_drum_notes
111 | assert d[1] not in self.all_drum_notes
112 | self.all_drum_notes.add(d[0])
113 | self.all_drum_notes.add(d[1])
114 |
115 | def get_drumnotes_for_grammar(self):
116 | """
117 | internal helper function
118 | :return: list of drumnotes for inclusion in the textX grammar
119 | """
120 | from functools import cmp_to_key
121 | def mycmp(s1, s2):
122 | if len(s1) < len(s2):
123 | return 1
124 | if len(s1) > len(s2):
125 | return -1
126 | if s1 < s2:
127 | return 1
128 | if s1 > s2:
129 | return -1
130 | return 0
131 |
132 | strng = "|".join(sorted(["'" + d.strip() + "'" for d in self.all_drum_notes], key=cmp_to_key(mycmp)))
133 | return strng
134 |
135 | def lookup(self, note):
136 | """
137 |
138 | :param note: lookup simple note or Pchord
139 | :return: midi number corresponding to the note name or the notes in the Pchord
140 | """
141 | try:
142 | if isinstance(note, Pchord):
143 | return Pchord([self.note_to_midi[n.lower()] for n in note.notes])
144 | else:
145 | return self.note_to_midi[note.lower()]
146 | except KeyError:
147 | return REST
148 |
149 | def convert(self, notelist):
150 | """
151 |
152 | :param notelist: list of music notes
153 | :return: iterator iterating over the converted list of notes
154 | """
155 | for n in notelist:
156 | yield self.lookup(n)
157 |
158 | def convert2(self, notelist):
159 | """
160 |
161 | :param notelist: listof music notes and/or Pchords
162 | :return: list of midi numbers and Pchords of midi numbers
163 | """
164 | return [self.lookup(note) for note in notelist]
165 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/playeddurations.py:
--------------------------------------------------------------------------------
1 | class PlayedDurations:
2 | """
3 | convenience class defining some common played durations
4 | """
5 | staccatissimo = 0.1
6 | staccato = 0.25
7 | normal = 0.9
8 | legato = 1
9 | super_legato = 1.1
10 |
11 | @classmethod
12 | def from_string(cls, thestring):
13 | """
14 |
15 | :param thestring: symbolic indication of playedduration
16 | :return: the symbolic indication mapped to number; real duration is multiplied with playedduration
17 | """
18 | lut = {
19 | 'staccatissimo': 0.1,
20 | 'staccato': 0.25,
21 | 'normal': 0.9,
22 | 'legato': 1,
23 | 'legatissimo': 1.1
24 | }
25 |
26 | if thestring in lut:
27 | return lut[thestring]
28 | else:
29 | return 0.9
30 |
--------------------------------------------------------------------------------
/expremigen/musicalmappings/tempo.py:
--------------------------------------------------------------------------------
1 | class Tempo:
2 | """
3 | convert some italian tempo indications to bpm
4 | (in reality the names indicate a range of tempi;
5 | I just selected one at random)
6 | """
7 | larghissimo = 20
8 | grave = 40
9 | lento = 44
10 | largho = 50
11 | larghetto = 60
12 | adagissimo = 63
13 | adagio = 69
14 | adagietto = 72
15 | andante = 80
16 | andantino = 86
17 | moderato = 112
18 | allegretto = 120
19 | allegro = 132
20 | vivace = 144
21 | allegro_vivace = 152
22 | vivacissimo = 160
23 | allegro_assai = 176
24 | presto = 184
25 | prestissimo = 208
26 |
27 | @classmethod
28 | def from_string(cls, thestring):
29 | """
30 |
31 | :param thestring: symbolic tempo indication
32 | :return: number corresponding to symbolic tempo
33 | """
34 | lut = {
35 | 'larghissimo': 20,
36 | 'grave': 40,
37 | 'lento': 44,
38 | 'largho': 50,
39 | 'larghetto': 60,
40 | 'adagissimo': 63,
41 | 'adagio': 69,
42 | 'adagietto': 72,
43 | 'andante': 80,
44 | 'andantino': 86,
45 | 'moderato': 112,
46 | 'allegretto': 120,
47 | 'allegro': 132,
48 | 'vivace': 144,
49 | 'allegro vivace': 152,
50 | 'vivacissimo': 160,
51 | 'allegro assai': 176,
52 | 'presto': 184,
53 | 'prestissimo': 208,
54 | }
55 | if thestring in lut:
56 | return lut[thestring]
57 | else:
58 | return 80
59 |
--------------------------------------------------------------------------------
/expremigen/patterns/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/expremigen/patterns/__init__.py
--------------------------------------------------------------------------------
/expremigen/patterns/padd.py:
--------------------------------------------------------------------------------
1 | import itertools
2 | import operator
3 |
4 | from expremigen.patterns.pattern import Pattern
5 | from expremigen.patterns.pbinop import Pbinop
6 | from expremigen.patterns.utils import flatten
7 |
8 |
9 | class Padd(Pbinop):
10 | """
11 | pattern that returns the sum of two other patterns
12 | """
13 |
14 | def __init__(self, a: Pattern, b: Pattern):
15 | super().__init__(a, b)
16 |
17 | def __iter__(self):
18 | return flatten(i for i in itertools.starmap(operator.__add__, zip(self.a, self.b)))
19 |
--------------------------------------------------------------------------------
/expremigen/patterns/pattern.py:
--------------------------------------------------------------------------------
1 | import abc
2 |
3 |
4 | class Pattern(metaclass=abc.ABCMeta):
5 | """
6 | abstract base class for a Pattern
7 | """
8 |
9 | def __str__(self):
10 | return "{0}".format(self.__class__.__name__)
11 |
12 | def __repr__(self):
13 | return self.__str__()
14 |
--------------------------------------------------------------------------------
/expremigen/patterns/pbinop.py:
--------------------------------------------------------------------------------
1 | import abc
2 |
3 | from expremigen.patterns.pattern import Pattern
4 |
5 |
6 | class Pbinop(Pattern, metaclass=abc.ABCMeta):
7 | """
8 | abstract base class for patterns that rely on two patterns
9 | """
10 |
11 | def __init__(self, a: Pattern, b: Pattern):
12 | super().__init__()
13 | self.a = a
14 | self.b = b
15 |
16 | def __str__(self):
17 | return "{0}({1}, {2})".format(self.__class__.__name__, self.a, self.b)
18 |
--------------------------------------------------------------------------------
/expremigen/patterns/pchord.py:
--------------------------------------------------------------------------------
1 | from expremigen.patterns.pattern import Pattern
2 |
3 |
4 | class Pchord(Pattern):
5 | """
6 | special pattern that is never flattened; interpreted as a chord by the rest of the system
7 | """
8 |
9 | def __init__(self, notes=0):
10 | super().__init__()
11 | self.notes = notes
12 |
13 | def __str__(self):
14 | return "{0}({1})".format(self.__class__.__name__, self.notes)
15 |
16 | def __iter__(self):
17 | yield Pchord(self.notes)
18 |
19 | def __repr__(self):
20 | return self.__str__()
21 |
22 | def __eq__(self, other):
23 | return self.notes == other.notes
24 |
--------------------------------------------------------------------------------
/expremigen/patterns/pconst.py:
--------------------------------------------------------------------------------
1 | import itertools
2 | import sys
3 |
4 | from expremigen.patterns.pattern import Pattern
5 | from expremigen.patterns.utils import flatten
6 |
7 |
8 | class Pconst(Pattern):
9 | """
10 | pattern that returns a given "constant" for "repeats" time
11 | """
12 |
13 | def __init__(self, constant=0, repeats=sys.maxsize):
14 | super().__init__()
15 | self.constant = constant
16 | self.repeats = repeats
17 |
18 | def __str__(self):
19 | return "{0}({1}, {2})".format(self.__class__.__name__, self.constant, self.repeats)
20 |
21 | def __iter__(self):
22 | return flatten(c for c in itertools.repeat(self.constant, self.repeats))
23 |
24 | def __repr__(self):
25 | return self.__str__()
26 |
--------------------------------------------------------------------------------
/expremigen/patterns/pexprand.py:
--------------------------------------------------------------------------------
1 | import math
2 | import random
3 | import sys
4 |
5 | from expremigen.patterns.pattern import Pattern
6 |
7 |
8 | class Pexprand(Pattern):
9 | """
10 | pattern that returns random numbers with a uniform logarithmic distribution
11 | """
12 |
13 | def __init__(self, lo=1, hi=10, repeats=sys.maxsize):
14 | """
15 |
16 | :param lo: lowerbound for random numbers: != 0
17 | :param hi: upperbound for random numbers: != 0
18 | :param repeats: counter to repeat generating extra numbers
19 |
20 | note: lo and hi should be != 0 and should have same sign
21 | """
22 | super().__init__()
23 | assert (lo * hi) > 0 # need same sign and != 0
24 | self.lo = lo
25 | self.hi = hi
26 | self.repeats = repeats
27 |
28 | def __str__(self):
29 | return "{0}({1}, {2}, {3})".format(self.__class__.__name__, self.lo, self.hi, self.repeats)
30 |
31 | def __iter__(self):
32 | for _ in range(self.repeats):
33 | yield self.lo * math.exp(math.log(self.hi / self.lo) * random.random())
34 |
35 | def __repr__(self):
36 | return self.__str__()
37 |
--------------------------------------------------------------------------------
/expremigen/patterns/pgeom.py:
--------------------------------------------------------------------------------
1 | from expremigen.patterns.pattern import Pattern
2 | from expremigen.patterns.utils import take, geom
3 |
4 |
5 | class Pgeom(Pattern):
6 | """
7 | pattern that generates numbers in geometric series, e.g. Pgeom(1, 2, 5) -> 1, 2, 4, 8, 16
8 | """
9 |
10 | def __init__(self, frm=0, factor=1, length=5):
11 | """
12 |
13 | :param frm: starting number
14 | :param factor: factor by which to keep multiplying the starting number
15 | :param length: length of generated sequence
16 | """
17 | super().__init__()
18 | self.frm = frm
19 | self.factor = factor
20 | self.length = length
21 |
22 | def __iter__(self):
23 | return take(self.length, geom(self.frm, self.factor))
24 |
25 | def __str__(self):
26 | return "{0}({1}, {2}, {3})".format(self.__class__.__name__, self.frm, self.factor, self.length)
27 |
--------------------------------------------------------------------------------
/expremigen/patterns/prand.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import itertools
3 | import sys
4 |
5 | from expremigen.patterns.pattern import Pattern
6 | from expremigen.patterns.utils import flatten, take
7 | from expremigen.patterns.utils import random_permutation
8 |
9 |
10 | class Prand(Pattern):
11 | """
12 | Pattern used to draw random numbers from a list
13 | (numbers may repeat themselves)
14 | """
15 |
16 | def __init__(self, alist=None, repeats=sys.maxsize):
17 | """
18 | pattern that
19 | :param alist: possible numbers
20 | :param repeats: how many numbers to draw
21 | """
22 | super().__init__()
23 | if alist is None:
24 | alist = []
25 | self.alist = copy.deepcopy(alist)
26 | self.repeats = repeats
27 |
28 | def __iter__(self):
29 | # following shuffles the list after repeating
30 | return flatten(take(self.repeats, (i for i in random_permutation(
31 | itertools.chain.from_iterable(itertools.repeat(self.alist, self.repeats))))))
32 |
33 | def __str__(self):
34 | return "{0}({1}, {2})".format(self.__class__.__name__, self.alist, self.repeats)
35 |
--------------------------------------------------------------------------------
/expremigen/patterns/pseq.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import itertools
3 | import sys
4 |
5 | from expremigen.patterns.pattern import Pattern
6 | from expremigen.patterns.utils import flatten
7 |
8 |
9 | class Pseq(Pattern):
10 | """
11 | pattern that generates numbers one by one from a list
12 | """
13 |
14 | def __init__(self, alist=None, repeats=sys.maxsize):
15 | super().__init__()
16 | if alist is None:
17 | alist = []
18 | self.alist = copy.deepcopy(alist)
19 | self.repeats = repeats
20 |
21 | def __iter__(self):
22 | return flatten(j for i in itertools.repeat(self.alist, self.repeats) for j in i)
23 |
24 | def __str__(self):
25 | return "{0}({1}, {2})".format(self.__class__.__name__, self.alist, self.repeats)
26 |
--------------------------------------------------------------------------------
/expremigen/patterns/pseries.py:
--------------------------------------------------------------------------------
1 | import itertools
2 |
3 | from expremigen.patterns.pattern import Pattern
4 | from expremigen.patterns.utils import take
5 |
6 |
7 | class Pseries(Pattern):
8 | """
9 | pattern to generate an arithmetic series, e.g. Pseries(0, 1, 5) -> 0, 1, 2, 3, 4
10 | """
11 |
12 | def __init__(self, frm=0, step=1, length=5):
13 | super().__init__()
14 | self.frm = frm
15 | self.step = step
16 | self.length = length
17 |
18 | def __iter__(self):
19 | return take(self.length, itertools.count(self.frm, self.step))
20 |
21 | def __str__(self):
22 | return "{0}({1}, {2}, {3})".format(self.__class__.__name__, self.frm, self.step, self.length)
23 |
--------------------------------------------------------------------------------
/expremigen/patterns/pshuf.py:
--------------------------------------------------------------------------------
1 | import copy
2 | import itertools
3 | import sys
4 |
5 | from expremigen.patterns.pattern import Pattern
6 | from expremigen.patterns.utils import random_permutation
7 |
8 |
9 | class Pshuf(Pattern):
10 | """
11 | pattern to randomly shuffle elements from a list; the randomly shuffled list
12 | then is repeated verbatim for repats times
13 | """
14 |
15 | def __init__(self, alist=None, repeats=sys.maxsize):
16 | super().__init__()
17 | if alist is None:
18 | alist = []
19 | self.alist = copy.deepcopy(alist)
20 | self.repeats = repeats
21 |
22 | def __iter__(self):
23 | # following shuffles the list after repeating
24 | # return (i for i in random_permutation(itertools.chain.from_iterable(itertools.repeat(self.alist,
25 | # self.repeats))))
26 |
27 | # following shuffles the non-repeated list once and repeats it every time
28 | return (i for i in
29 | itertools.chain.from_iterable(itertools.repeat(random_permutation(self.alist), self.repeats)))
30 |
31 | # following reshuffles the non-repeated list over and over again
32 | # return flatten(i for i in itertools.chain.from_iterable(myrepeat(self.alist, random_permutation,
33 | # self.repeats)))
34 |
35 | def __str__(self):
36 | return "{0}({1}, {2})".format(self.__class__.__name__, self.alist, self.repeats)
37 |
--------------------------------------------------------------------------------
/expremigen/patterns/ptween.py:
--------------------------------------------------------------------------------
1 | from vectortween.Animation import Animation
2 |
3 | from expremigen.patterns.pattern import Pattern
4 |
5 |
6 | class Ptween(Pattern):
7 | """
8 | class to glue pyvectortween to expremigen
9 | """
10 |
11 | def __init__(self, animation: Animation, birthframe=0, startframe=0, stopframe=0,
12 | deathframe=0, noiseframe=None):
13 | super().__init__()
14 | self.animation = animation
15 | self.bf = birthframe
16 | self.staf = startframe
17 | self.stof = stopframe
18 | self.df = deathframe
19 | self.nf = noiseframe
20 | self.current_frame = 0
21 |
22 | def __iter__(self):
23 | for i in range(int(self.df)):
24 | yield self.animation.make_frame(i, self.bf, self.staf, self.stof, self.df, self.nf)
25 |
26 | def __str__(self):
27 | return "{0}(, {1}, {2}, {3}, {4}, {5})".format(self.__class__.__name__, self.bf,
28 | self.staf, self.stof, self.df, self.nf)
29 |
--------------------------------------------------------------------------------
/expremigen/patterns/pwhite.py:
--------------------------------------------------------------------------------
1 | import random
2 | import sys
3 |
4 | from expremigen.patterns.pattern import Pattern
5 |
6 |
7 | class Pwhite(Pattern):
8 | """
9 | class to generate random numbers
10 | """
11 |
12 | def __init__(self, lo=0, hi=1, repeats=sys.maxsize):
13 | super().__init__()
14 | self.lo = lo
15 | self.hi = hi
16 | self.repeats = repeats
17 |
18 | def __str__(self):
19 | return "{0}({1}, {2}, {3})".format(self.__class__.__name__, self.lo, self.hi, self.repeats)
20 |
21 | def __iter__(self):
22 | for _ in range(self.repeats):
23 | yield random.uniform(self.lo, self.hi)
24 |
25 | def __repr__(self):
26 | return self.__str__()
27 |
--------------------------------------------------------------------------------
/expremigen/patterns/utils.py:
--------------------------------------------------------------------------------
1 | import itertools
2 | import random
3 |
4 | from expremigen.patterns.pattern import Pattern
5 | from expremigen.patterns.pchord import Pchord
6 |
7 |
8 | def random_permutation(iterable, r=None):
9 | """Random selection from itertools.permutations(iterable, r)"""
10 | pool = tuple(iterable)
11 | r = len(pool) if r is None else r
12 | return tuple(random.sample(pool, r))
13 |
14 |
15 | def myrepeat(what, fn, times=None):
16 | """
17 |
18 | :param what: something to repeat
19 | :param fn: extra function to apply
20 | :param times: number of times to repeat
21 | :return:
22 | """
23 | if times is None:
24 | while True:
25 | if fn is not None:
26 | yield fn(what)
27 | else:
28 | yield what
29 | else:
30 | for i in range(times):
31 | if fn is not None:
32 | yield fn(what)
33 | else:
34 | yield what
35 |
36 |
37 | def flatten(l):
38 | """
39 |
40 | :param l: list l
41 | :return: iterator to flatten list l; Pchord are not flattened
42 | """
43 | for el in l:
44 | if isinstance(el, Pattern) and not isinstance(el, Pchord):
45 | yield from flatten(el)
46 | else:
47 | yield el
48 |
49 |
50 | def take(n, iterable):
51 | """Return first n items of the iterable as a list"""
52 | return itertools.islice(iterable, n)
53 |
54 |
55 | def geom(start=1, factor=2):
56 | """
57 | iterator to generate geometric series
58 | :param start: start number
59 | :param factor: constant factor to apply
60 | :return: geometric series, e.g. geom(16, 0.5) -> 16 8 4 2 1 0.5 ...
61 | """
62 | # geom(1) --> 1 2 4 8 ...
63 | # geom(16, 0.5) -> 16 8 4 2 1 0.5 ...
64 | n = start
65 | while True:
66 | yield n
67 | n *= factor
68 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | description-file = README.md
3 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 | from setuptools import find_packages
3 |
4 | setup(
5 | name='expremigen',
6 | version='0.0.2',
7 | packages=find_packages(exclude=['build', 'dist', 'tests']),
8 | install_requires=['vectortween', 'MIDIUtil', 'textX'],
9 | url='https://github.com/shimpe/expremigen',
10 | python_requires='>=3',
11 | license='GPLv3+',
12 | author='stefaan himpe',
13 | author_email='stefaan.himpe@gmail.com',
14 | description='Expressive Midi Generation',
15 | long_description='Expressive Midi Generation',
16 | classifiers=["Development Status :: 3 - Alpha",
17 | "Intended Audience :: Other Audience",
18 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
19 | "Operating System :: OS Independent",
20 | "Programming Language :: Python :: 3 :: Only",
21 | "Topic :: Artistic Software",
22 | "Topic :: Multimedia :: Sound/Audio :: MIDI",
23 | "Topic :: Software Development :: Libraries :: Python Modules"]
24 | )
25 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/shimpe/expremigen/93b7a8ed1cab15f89a94443271dd9ffec1d25246/tests/__init__.py
--------------------------------------------------------------------------------
/tests/testgeom.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pgeom import Pgeom
4 |
5 |
6 | class TestPgeom(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pgeom(1, 10, 5)]
9 | self.assertEqual(a, [1, 10, 100, 1000, 10000])
10 |
11 | def test_negativestep(self):
12 | a = [i for i in Pgeom(1, -10, 5)]
13 | self.assertEqual(a, [1, -10, 100, -1000, 10000])
14 |
15 | def test_stepzero(self):
16 | a = [i for i in Pgeom(1, 0, 5)]
17 | self.assertEqual(a, [1, 0, 0, 0, 0])
18 |
19 | def test_zerolength(self):
20 | a = [i for i in Pgeom(0, 10, 0)]
21 | self.assertEqual(a, [])
22 |
23 | def test_repr(self):
24 | self.assertEqual("{0}".format(Pgeom(0, 10, 5)), "Pgeom(0, 10, 5)")
25 |
26 |
27 | if __name__ == '__main__':
28 | unittest.main()
29 |
--------------------------------------------------------------------------------
/tests/testmispel.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from textx.exceptions import TextXSyntaxError
4 |
5 | from expremigen.io.constants import PhraseProperty as PP
6 | from expremigen.mispel.mispel import Mispel
7 | from expremigen.patterns.pchord import Pchord
8 | from expremigen.patterns.pseq import Pseq
9 |
10 |
11 | class TestPat2Midi(unittest.TestCase):
12 | def test_header1(self):
13 | m = Mispel()
14 | model = m.parse("with track 5 channel 2 time 0 notedriven :\n a3")
15 | for section in model.sections:
16 | self.assertEqual(section.headerspecs.track.id, 5)
17 | self.assertEqual(section.headerspecs.channel.id, 2)
18 | self.assertEqual(section.headerspecs.time.value, 0)
19 | self.assertEqual(section.headerspecs.driver, 'notedriven')
20 |
21 | def test_headershort(self):
22 | m = Mispel()
23 | model = m.parse("with channel 2 timedriven :\n a3")
24 | for section in model.sections:
25 | self.assertEqual(section.headerspecs.track, None)
26 | self.assertEqual(section.headerspecs.channel.id, 2)
27 | self.assertEqual(section.headerspecs.time, None)
28 | self.assertEqual(section.headerspecs.driver, 'timedriven')
29 |
30 | def test_headerbad(self):
31 | m = Mispel()
32 | try:
33 | m.parse("with chanel 2 buzzdriven :\n a3")
34 | self.assertTrue(False) # will fail unless the above throws an exception
35 | except TextXSyntaxError:
36 | self.assertTrue(True)
37 |
38 | def test_events1(self):
39 | m = Mispel()
40 | model = m.parse("with channel 2 notedriven :\n a3_8. b-_16 c#3_16.5\\vol{100}\\tempo[vivace] ")
41 | for section in model.sections:
42 | event = section.events[0]
43 | self.assertEqual(event.cs, None)
44 | self.assertTrue(event.__class__.__name__, 'NoteSpec')
45 | self.assertEqual(event.ns.name, 'a')
46 | self.assertEqual(event.ns.octave, '3')
47 | self.assertEqual(event.ns.invdur.value, 8)
48 | self.assertListEqual(event.ns.invdur.dots, ['.'])
49 | self.assertEqual(event.ns.properties, [])
50 | event = section.events[1]
51 | self.assertEqual(event.ns.name, 'b-')
52 | self.assertEqual(event.ns.octave, None)
53 | self.assertEqual(event.ns.invdur.value, 16)
54 | self.assertListEqual(event.ns.invdur.dots, [])
55 | self.assertEqual(event.ns.properties, [])
56 | event = section.events[2]
57 | self.assertEqual(event.ns.name, 'c#')
58 | self.assertEqual(event.ns.octave, '3')
59 | self.assertEqual(event.ns.invdur.value, 16.5)
60 | for p in event.ns.properties:
61 | if p.avol:
62 | self.assertEqual(p.avol.symval, None)
63 | self.assertEqual(p.avol.value.value, 100)
64 | elif p.stempo:
65 | self.assertEqual(p.stempo.symval.symval, 'vivace')
66 | self.assertEqual(p.stempo.value, None)
67 |
68 | self.assertListEqual(m.notes_for_section(0), ["a3", "b-3", "c#3"])
69 | self.assertListEqual(m.durations_for_section(0), [1 / 8 + 1 / 16, 1 / 16, 1 / 16.5])
70 |
71 | def test_durationmultiplier(self):
72 | m = Mispel()
73 | m.parse(r"""
74 | with track 0 channel 0: cx4_4*2/3 d3 e-_4 g--_4.*2/3 r_1*10/1 a#2_1*5
75 | """)
76 | durs = [d for d in m.durations_for_section(0)]
77 | self.assertListEqual(durs, [0.16666666666666666, 0.16666666666666666, 0.25, 0.25, 10.0, 5.0])
78 |
79 | def test_sections(self):
80 | m = Mispel()
81 | m.parse(r"""
82 | with track 0:
83 | c4_8\vol{p}\pdur[legato] e g c5 b4 g f d c_2\vol{f}\pdur[staccato]
84 |
85 | with track 1:
86 | e3_8\vol{ff}\lag{0.5} g c4 e d b3 g f e_2\vol{p}\lag{0}
87 | """)
88 | self.assertEqual(m.get_no_of_sections(), 2)
89 |
90 | def test_dynamicsforsection(self):
91 | m = Mispel()
92 | m.parse(r"""
93 | with track 0:
94 | a3_8\vol[mf] b c4_4 d\vol{ff} e f\vol{30} e f-- r ax d\vol[20] c
95 | """)
96 | self.assertListEqual(m.notes_for_section(0),
97 | ["a3", "b3", "c4", "d4", "e4", "f4", "e4", "f--4", "r", "ax4", "d4", "c4"])
98 | self.assertListEqual(m.dynamics_for_section(0), [(('num', 'static', 70), ('sym', 'static', 'mf'), 0),
99 | (('sym', 'static', 'mf'), ('sym', 'anim', 'ff'), 3),
100 | (('sym', 'anim', 'ff'), ('num', 'anim', 30), 2),
101 | (('num', 'anim', 30), ('num', 'static', 20), 5),
102 | (('num', 'static', 20), ('num', 'static', 20), 2)]
103 | )
104 |
105 | def test_dynamicsgeneratorforsection1(self):
106 | m = Mispel()
107 | m.parse(r"""
108 | with track 0:
109 | a3_8\vol[mf] b c4_4 d\vol{10} e f\vol[30] e f-- r ax d\vol{90} c
110 | """)
111 | vols = [v for v in m.dynamics_generator_for_section(0)]
112 | self.assertListEqual(vols, [90, 90, 90, 10, 20, 30, 30, 30, 30, 30, 90, 90])
113 |
114 | def test_dynamicsgeneratorforsection_lastvolume_at_end(self):
115 | m = Mispel()
116 | m.parse(r"""
117 |
118 | with track 0:
119 | a3_8\vol[mf] b c4_4 d\vol{10} e f\vol[30] e f-- r ax d\vol{90}
120 |
121 | """)
122 | vols = [v for v in m.dynamics_generator_for_section(0)]
123 | self.assertListEqual(vols, [90, 90, 90, 10, 20, 30, 30, 30, 30, 30, 90])
124 |
125 | def test_lagforsection(self):
126 | m = Mispel()
127 | m.parse(r"""
128 | with track 0:
129 | a2_4 a3 a4_16\lag[0.9] b c5 d e f g a b a g f\lag{1} e d c b\lag{0.3}
130 | """)
131 | self.assertListEqual(m.notes_for_section(0),
132 | "a2 a3 a4 b4 c5 d5 e5 f5 g5 a5 b5 a5 g5 f5 e5 d5 c5 b5".split(" "))
133 | self.assertListEqual(m.lag_for_section(0),
134 | [(('num', 'static', 0), ('num', 'static', 0.9), 2),
135 | (('num', 'static', 0.9), ('num', 'anim', 1.0), 11),
136 | (('num', 'anim', 1.0), ('num', 'anim', 0.3), 4),
137 | (('num', 'anim', 0.3), ('num', 'anim', 0.3), 1)]
138 | )
139 |
140 | def test_laggeneratorforsection(self):
141 | m = Mispel()
142 | m.parse(r"""
143 | with track 0:
144 | a2_4 a3 a4_16\lag[0.9] b c5 d e f g a b a g f\lag{1} e d c b\lag{0.5}
145 | """)
146 | lags = [l for l in m.lag_generator_for_section(0)]
147 | self.assertListEqual(lags,
148 | [0.0, 0.0, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 1.0, 0.875, 0.75, 0.625,
149 | 0.5])
150 |
151 | def test_pdurforsection(self):
152 | m = Mispel()
153 | m.parse(r"""
154 | with track 1 channel 1 time 0:
155 | c4_4\pdur{staccato} d e f g a b c5\pdur[legato] d e d c_1\pdur[staccato]
156 | """)
157 | self.assertListEqual(m.pdur_for_section(0),
158 | [(('num', 'static', 0.9), ('sym', 'anim', 'staccato'), 0),
159 | (('sym', 'anim', 'staccato'), ('sym', 'static', 'legato'), 7),
160 | (('sym', 'static', 'legato'), ('sym', 'static', 'staccato'), 4),
161 | (('sym', 'static', 'staccato'), ('sym', 'static', 'staccato'), 1)]
162 | )
163 |
164 | def test_pdurgeneratorforsection(self):
165 | m = Mispel()
166 | m.parse(r"""
167 | with track 1 channel 1 time 0:
168 | c4_4\pdur{staccato} d e f g a b c5\pdur[legato] d e d c_1\pdur[staccato]
169 | """)
170 | pdurs = [pd for pd in m.pdur_generator_for_section(0)]
171 | self.assertListEqual(pdurs,
172 | [0.25, 0.35714285714285715, 0.4642857142857143, 0.5714285714285714, 0.6785714285714286,
173 | 0.7857142857142857,
174 | 0.8928571428571429, 1.0, 1.0, 1.0, 1.0, 0.25])
175 |
176 | def test_tempoforsection(self):
177 | m = Mispel()
178 | m.parse(r"""
179 | with track 1 channel 1 time 0:
180 | c4_4\pdur{staccato}\tempo[allegretto] d e f g a b c5\pdur[legato] d e\tempo{120} d c_1\tempo[40]\pdur[staccato]
181 | """)
182 | self.assertListEqual(m.tempo_for_section(0), [(('num', 'static', 100), ('sym', 'static', 'allegretto'), 0),
183 | (('sym', 'static', 'allegretto'), ('num', 'anim', 120), 9),
184 | (('num', 'anim', 120), ('num', 'static', 40), 2),
185 | (('num', 'static', 40), ('num', 'static', 40), 1)]
186 | )
187 |
188 | def test_tempogeneratorforsection(self):
189 | m = Mispel()
190 | m.parse(r"""
191 | with track 1 channel 1 time 0:
192 | c4_4\pdur{staccato}\tempo[allegretto] d e f g a b c5\pdur[legato] d e\tempo{120} d c_1\tempo[40]\pdur[staccato]
193 | """)
194 |
195 | tempos = [t for t in m.tempo_generator_for_section(0)]
196 | self.assertListEqual(tempos, [120, 120, 120, 120, 120, 120, 120, 120, 120, 120, 80, 40])
197 |
198 | def test_dot(self):
199 | m = Mispel()
200 | m.parse("with channel 2 notedriven :\n a3_8. b-16")
201 | durs = [d for d in m.duration_generator_for_section(0)]
202 | self.assertEqual(durs, [(1 / 8 + 1 / 16), (1 / 8 + 1 / 16)])
203 |
204 | def test_chord(self):
205 | m = Mispel()
206 | m.parse("with track 0 : a3_4\\vol[20] a\\vol[30]")
207 | notes = [n for n in m.note_generator_for_section(0)]
208 | self.assertListEqual(notes, ['a3', Pchord(['c3', 'e3', 'g3']), 'a3'])
209 | vols = [v for v in m.dynamics_generator_for_section(0)]
210 | self.assertListEqual(vols, [20.0, 20.0, 30.0])
211 |
212 | def test_ccpropertiesforsection(self):
213 | m = Mispel()
214 | m.parse(r"""
215 | with track 0 : a3\pdur[legato]\cc[15,100] b e\cc[15,90] f a g\cc[16,40] b
216 | """)
217 | self.assertDictEqual(m.cc_properties_for_section(0),
218 | {15: [(None, ('num', 'static', 100), 0),
219 | (('num', 'static', 100), ('num', 'static', 90), 3),
220 | (('num', 'static', 90), ('num', 'static', 90), 5)],
221 | 16: [(None, ('num', 'anim', 23), 2),
222 | (('num', 'anim', 23), ('num', 'static', 40), 4),
223 | (('num', 'static', 40), ('num', 'static', 40), 2)]})
224 |
225 | def test_ccpropertiesgeneratorsforsection(self):
226 | m = Mispel()
227 | m.parse(r"""
228 | with track 0: a3\pdur[legato]\cc[15,100] b e\cc[15,90] f a g\cc[16,40] b
229 | """)
230 | p = m.cc_properties_generators_for_section(0)
231 |
232 | dur15 = [d for d in Pseq(p[15][PP.ctrl_dur_key(15)], 1)]
233 | val15 = [v for v in Pseq(p[15][PP.ctrl_val_key(15)], 1)]
234 |
235 | dur16 = [d for d in Pseq(p[16][PP.ctrl_dur_key(16)], 1)]
236 | val16 = [v for v in Pseq(p[16][PP.ctrl_val_key(16)], 1)]
237 |
238 | self.assertListEqual(dur15, [0, 0.75, 1.25])
239 | self.assertListEqual(val15, [None, 100, 90])
240 |
241 | self.assertListEqual(dur16,
242 | [0.5, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025,
243 | 0.025, 0.025, 0.025,
244 | 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025,
245 | 0.025, 0.025, 0.025,
246 | 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.025, 0.5])
247 | self.assertListEqual(val16,
248 | [None, 23.0, 23.425, 23.85, 24.275, 24.7, 25.125, 25.55, 25.975, 26.4, 26.825, 27.25,
249 | 27.675, 28.1, 28.525,
250 | 28.95, 29.375, 29.8, 30.225, 30.65, 31.075, 31.5, 31.925, 32.35, 32.775, 33.2, 33.625,
251 | 34.05, 34.475, 34.9,
252 | 35.325, 35.75, 36.175, 36.6, 37.025, 37.45, 37.875, 38.3, 38.725, 39.15, 39.575, 40])
253 |
254 | def test_animationtypes(self):
255 | m = Mispel()
256 | m.parse(r"""
257 | with track 0:
258 | a4_4\vol{mp, easeOutQuad} b c d\vol{f, easeOutElastic, 2, 0.01}
259 | """)
260 | vols = [v for v in m.dynamics_for_section(0)]
261 | self.assertListEqual(vols,
262 | [(('num', 'static', 70), ('sym', 'anim', 'mp', ['easeOutQuad']), 0),
263 | (('sym', 'anim', 'mp', ['easeOutQuad']),
264 | ('sym', 'anim', 'f', ['easeOutElastic', 2.0, 0.01]), 3),
265 | (('sym', 'anim', 'f', ['easeOutElastic', 2.0, 0.01]),
266 | ('sym', 'anim', 'f', ['easeOutElastic', 2.0, 0.01]), 1)])
267 |
268 | def test_animationtypes_generator(self):
269 | m = Mispel()
270 | m.parse(r"""
271 | with track 0:
272 | a4_4\vol{mp, easeOutQuad} b c d\vol{f, easeOutElastic, 50, 0.1} e f g a b c d e f g a b c d e f g a b c d e f g\vol[mp]
273 | """)
274 | vols2 = [v for v in m.dynamics_generator_for_section(0)]
275 | self.assertListEqual(vols2,
276 | [80.0, 91.11111111111111, 97.77777777777777, 100.0, 80, 100, 80, 100, 80, 80, 100, 80, 100,
277 | 80, 100, 80.62500000000003, 80, 95.3611067738703, 80, 88.42426702280262, 80, 80,
278 | 82.14053136466876, 80, 82.32220556599769, 80, 80.629068677026, 80.0])
279 |
280 | def test_drumnotes(self):
281 | m = Mispel()
282 | m.parse(r"""
283 | with track 0 channel 11:
284 | bassdrum_4 openhihat_8*2/3 openhihat ohh
285 | """)
286 | notes = m.notes_for_section(0)
287 | self.assertListEqual(notes, ['bassdrum', 'openhihat', 'openhihat', 'ohh'])
288 | durs = m.durations_for_section(0)
289 | self.assertListEqual(durs, [0.25, 0.08333333333333333, 0.08333333333333333, 0.08333333333333333])
290 |
291 |
292 | if __name__ == '__main__':
293 | unittest.main()
294 |
--------------------------------------------------------------------------------
/tests/testnanonotation.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.musicalmappings.nanonotation import NanoNotation
4 |
5 |
6 | class TestNanoNotation(unittest.TestCase):
7 | def test_notes(self):
8 | nn = NanoNotation()
9 | the_notes = nn.notes("r_8 c4 e4_16 f#4_8.")
10 | self.assertEqual(the_notes, "r c4 e4 f#4".split(" "))
11 |
12 | def test_durs(self):
13 | nn = NanoNotation()
14 | the_durs = nn.dur("r_8 c4 e4_16 f4_8.")
15 | self.assertEqual(the_durs, [1 / 8, 1 / 8, 1 / 16, 1 / 8 + 1 / 16])
16 |
17 | def test_octaves(self):
18 | nn = NanoNotation()
19 | the_notes = nn.notes("r_8 c3 e g4 a_2 e")
20 | self.assertEqual(the_notes, "r c3 e3 g4 a4 e4".split(" "))
21 |
22 |
23 | if __name__ == '__main__':
24 | unittest.main()
25 |
--------------------------------------------------------------------------------
/tests/testnote2midi.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.musicalmappings.constants import REST
4 | from expremigen.musicalmappings.note2midi import Note2Midi
5 | from expremigen.patterns.pchord import Pchord
6 |
7 |
8 | class TestNote2Midi(unittest.TestCase):
9 | def test_lookup(self):
10 | n = Note2Midi()
11 | self.assertEqual(n.lookup("a4"), 69)
12 | self.assertEqual(n.lookup("c4"), 60)
13 | self.assertEqual(n.lookup("bx3"), 61)
14 | self.assertEqual(n.lookup("c#4"), 61)
15 | self.assertEqual(n.lookup("db4"), 61)
16 | self.assertEqual(n.lookup("dbb3"), 48)
17 | self.assertEqual(n.lookup("b10"), REST) # note number > 127 not allowed
18 |
19 | def test_map(self):
20 | n = Note2Midi()
21 | m = n.convert(["a4", "b4", "c5", "d5", "e5", "f5", "g#4", "f5", "e5", "d5", "UNKNOWN", "b4"])
22 | m2 = [i for i in m]
23 | expected = [69, 71, 72, 74, 76, 77, 68, 77, 76, 74, REST, 71]
24 | self.assertListEqual(m2, expected)
25 |
26 | def test_chord(self):
27 | n = Note2Midi()
28 | m = n.convert(["a3", Pchord(["c3", "e3", "g3"]), "d4"])
29 | m2 = [i for i in m]
30 | expected = [57, Pchord([48, 52, 55]), 62]
31 | self.assertEqual(m2, expected)
32 | q = n.convert2(["a3", Pchord(["c3", "e3", "g3"]), "d4"])
33 | q2 = [i for i in q]
34 | self.assertEqual(q2, expected)
35 |
36 | def test_drum(self):
37 | n = Note2Midi()
38 | m = n.convert(["openhihat", "ohh"])
39 | m2 = [i for i in m]
40 | expected = [46, 46]
41 | self.assertEqual(m2, expected)
42 |
43 | if __name__ == '__main__':
44 | unittest.main()
45 |
--------------------------------------------------------------------------------
/tests/testpadd.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.padd import Padd
4 | from expremigen.patterns.pconst import Pconst
5 | from expremigen.patterns.pseq import Pseq
6 |
7 |
8 | class TestPadd(unittest.TestCase):
9 | def test_normal(self):
10 | a = [i for i in Padd(Pconst(4, 3), Pseq([1, 2, 3], 1))]
11 | self.assertEqual(a, [5, 6, 7])
12 |
13 | def test_firstlonger(self):
14 | a = [i for i in Padd(Pconst(4, 5), Pseq([1, 2, 3], 1))]
15 | self.assertEqual(a, [5, 6, 7])
16 |
17 | def test_secondlonger(self):
18 | a = [i for i in Padd(Pconst(4, 3), Pseq([1, 2, 3, 70], 1))]
19 | self.assertEqual(a, [5, 6, 7])
20 |
21 | def test_firstempty(self):
22 | a = [i for i in Padd(Pconst(4, 0), Pseq([1, 2, 3, 70], 1))]
23 | self.assertEqual(a, [])
24 |
25 | def test_secondempty(self):
26 | a = [i for i in Padd(Pconst(4, 3), Pseq([1, 2, 3, 70], 0))]
27 | self.assertEqual(a, [])
28 |
29 | def test_rightlazy(self):
30 | a = [i for i in Padd(Pconst(4, 3), Pseq([1, 2, 3, 70], int(5e5)))]
31 | self.assertEqual(a, [5, 6, 7])
32 |
33 | def test_leftlazy(self):
34 | a = [i for i in Padd(Pconst(4, int(5e8)), Pseq([1, 2, 3, 70], 2))]
35 | self.assertEqual(a, [5, 6, 7, 74, 5, 6, 7, 74])
36 |
37 | def test_repr(self):
38 | tested = "{0}".format(Padd(Pconst(4, 5), Pseq([1, 2, 3], 1)))
39 | expected = "Padd(Pconst(4, 5), Pseq([1, 2, 3], 1))"
40 | self.assertEqual(tested, expected)
41 |
42 | def test_nesting(self):
43 | a = [i for i in Padd(Padd(Pseq([1, 2], 2), Pconst(10, 3)), Pseq([4, 5], 2))]
44 | self.assertEqual(a, [15, 17, 15])
45 |
46 |
47 | if __name__ == '__main__':
48 | unittest.main()
49 |
--------------------------------------------------------------------------------
/tests/testpat2midi.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.io.constants import PhraseProperty as PP
4 | from expremigen.io.pat2midi import Pat2Midi
5 | from expremigen.io.phrase import Phrase
6 | from expremigen.musicalmappings.durations import Durations as Dur
7 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
8 | from expremigen.musicalmappings.note2midi import Note2Midi
9 | from expremigen.patterns.pconst import Pconst
10 |
11 |
12 | class TestPat2Midi(unittest.TestCase):
13 | def test_addPhrase(self):
14 | n = Note2Midi()
15 | properties = {
16 | PP.NOTE: Pconst(n.lookup("f#3"), 3),
17 | PP.VOL: Pconst(Dyn.mf),
18 | PP.DUR: Pconst(Dur.quarter),
19 | PP.PLAYEDDUR: Pconst(0.9),
20 | PP.LAG: Pconst(0)
21 | }
22 | p = Phrase(properties)
23 | p2m = Pat2Midi()
24 | duration = p2m.add_phrase(p)
25 | self.assertEqual(duration, 3 * 4 * Dur.quarter)
26 | duration2 = p2m.add_phrase(p, start_time=duration)
27 | # just adding a single phrase returns the duration of that phrase only
28 | self.assertEqual(duration, duration2)
29 | # adding a list of phrases returns the total duration
30 | total_duration = p2m.add_phrases([p], start_time=duration + duration2)
31 | self.assertEqual(total_duration, 3 * duration)
32 |
33 |
34 | if __name__ == '__main__':
35 | unittest.main()
36 |
--------------------------------------------------------------------------------
/tests/testpchord.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pchord import Pchord
4 |
5 |
6 | class TestPchord(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pchord(["a4", "c#5", "e5"])]
9 | self.assertEqual(a[0].notes, ["a4", "c#5", "e5"])
10 |
11 | def test_repr(self):
12 | self.assertEqual("{0}".format(Pchord(["c3", "e3", "g3"])), "Pchord(['c3', 'e3', 'g3'])")
13 |
14 |
15 | if __name__ == '__main__':
16 | unittest.main()
17 |
--------------------------------------------------------------------------------
/tests/testpconst.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pconst import Pconst
4 |
5 |
6 | class TestPconst(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pconst(4, 10)]
9 | self.assertEqual(a, [4] * 10)
10 |
11 | def test_empty(self):
12 | b = [i for i in Pconst(4, 0)]
13 | self.assertEqual(b, [])
14 |
15 | def test_negative(self):
16 | c = [i for i in Pconst(-10, 100)]
17 | self.assertEqual(c, [-10] * 100)
18 |
19 | def test_adult(self):
20 | d = [i for i in Pconst("x", 3)]
21 | self.assertEqual(d, ["x"] * 3)
22 |
23 | def test_repr(self):
24 | self.assertEqual("{0}".format(Pconst(10, 3)), "Pconst(10, 3)")
25 |
26 | def test_defaultvalue(self):
27 | e = [i for i in Pconst(repeats=2)]
28 | self.assertEqual(e, [0, 0])
29 |
30 |
31 | if __name__ == '__main__':
32 | unittest.main()
33 |
--------------------------------------------------------------------------------
/tests/testpexprand.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pexprand import Pexprand
4 |
5 |
6 | class TestPexprand(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pexprand(4, 5, 10)]
9 | # print(a)
10 | self.assertEqual(len(a), 10)
11 | for i in range(10):
12 | self.assertTrue(4 < a[i] < 5)
13 |
14 | def test_negative(self):
15 | a = [i for i in Pexprand(-4, -5, 10)]
16 | # print(a)
17 | self.assertEqual(len(a), 10)
18 | for i in range(10):
19 | self.assertTrue(-5 < a[i] < -4)
20 |
21 | def test_empty(self):
22 | a = [i for i in Pexprand(4, 5, 0)]
23 | self.assertEqual(a, [])
24 |
25 | def test_repr(self):
26 | self.assertEqual("{0}".format(Pexprand(0.1, 1.5, 4)), "Pexprand(0.1, 1.5, 4)")
27 |
28 |
29 | if __name__ == '__main__':
30 | unittest.main()
31 |
--------------------------------------------------------------------------------
/tests/testphrase.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import unittest
3 |
4 | from expremigen.io.constants import Defaults, PhraseProperty as PP
5 | from expremigen.io.phrase import Phrase
6 | from expremigen.musicalmappings.durations import Durations as Dur
7 | from expremigen.musicalmappings.dynamics import Dynamics as Dyn
8 | from expremigen.musicalmappings.note2midi import Note2Midi
9 | from expremigen.patterns.pconst import Pconst
10 | from expremigen.patterns.pseq import Pseq
11 | from expremigen.patterns.pseries import Pseries
12 | from expremigen.patterns.ptween import Ptween
13 |
14 |
15 | class TestPhrase(unittest.TestCase):
16 | def test_defaults(self):
17 | n = Note2Midi()
18 | p = Phrase()
19 | result = []
20 | for event in p:
21 | result.append(event)
22 | self.assertEqual(len(result), 1)
23 | self.assertEqual(result[0][PP.NOTE], n.lookup(Defaults.note))
24 | self.assertEqual(result[0][PP.VOL], Defaults.vol)
25 | self.assertEqual(result[0][PP.DUR], 4 * Defaults.dur)
26 | self.assertEqual(result[0][PP.PLAYEDDUR], Defaults.playeddur)
27 | self.assertEqual(result[0][PP.LAG], Defaults.lag)
28 | self.assertEqual(result[0][PP.TEMPO], Defaults.tempo)
29 |
30 | def test_phrase(self):
31 | n = Note2Midi()
32 | properties = {
33 | PP.NOTE: Pseries(n.lookup("c4"), 1, 12),
34 | PP.VOL: Pconst(100, sys.maxsize),
35 | PP.DUR: Pconst(1 / 16, sys.maxsize),
36 | PP.PLAYEDDUR: Pconst(0.9, sys.maxsize),
37 | PP.LAG: Pconst(0, sys.maxsize)
38 | }
39 | p = Phrase(properties)
40 | result = []
41 | for event in p:
42 | result.append(event)
43 | self.assertEqual(len(result), 12)
44 | self.assertEqual(result[1][PP.NOTE], n.lookup("c#4"))
45 | self.assertEqual(result[5][PP.VOL], 100)
46 | self.assertEqual(result[9][PP.DUR], 4 * 0.0625)
47 |
48 | def test_phrase2(self):
49 | n = Note2Midi()
50 | notes = ["c4", "e4", "g4", "c5", "b4", "g4", "f4", "d4", "c4"]
51 | from vectortween.NumberAnimation import NumberAnimation
52 | from vectortween.SequentialAnimation import SequentialAnimation
53 | increase = NumberAnimation(frm=Dyn.mp, to=Dyn.f)
54 | decrease = NumberAnimation(frm=Dyn.f, to=Dyn.ppp)
55 | swell_dim = SequentialAnimation([increase, decrease])
56 | increasing_staccato = NumberAnimation(frm=1, to=0.8)
57 | properties = {
58 | # convert from note names to midi numbers
59 | PP.NOTE: Pseq(n.convert2(notes)),
60 | # last note is longer than the rest
61 | PP.DUR: Pseq([Pconst(Dur.quarter, len(notes) - 1), Pconst(Dur.whole, 1)]),
62 | # animate staccato
63 | PP.PLAYEDDUR: Ptween(increasing_staccato, 0, 0, len(notes), len(notes)),
64 | # volume should linearly go up from mp to f, then go down from f to ppp as the phrase progresses
65 | PP.VOL: Ptween(swell_dim, 0, 0, len(notes), len(notes), None),
66 | }
67 | p = Phrase(properties)
68 | result = []
69 | for event in p:
70 | result.append(event)
71 | self.assertEqual(len(result), 9)
72 | # check that last note longer
73 | self.assertEqual(result[7][PP.DUR], 4 * 1 / 4)
74 | self.assertEqual(result[8][PP.DUR], 4 * 1)
75 | # check that volume increases then decreases
76 | self.assertLess(result[0][PP.VOL], result[4][PP.VOL])
77 | self.assertLess(result[8][PP.VOL], result[4][PP.VOL])
78 | self.assertLess(result[8][PP.VOL], result[0][PP.VOL])
79 | # check that staccato increases
80 | for i in range(8):
81 | self.assertTrue(result[i][PP.PLAYEDDUR] > result[i + 1][PP.PLAYEDDUR])
82 | self.assertEqual(result[8][PP.NOTE], n.lookup("c4"))
83 |
84 | def test_cc(self):
85 | properties = {
86 | PP.NOTE: Pconst(67, 5),
87 | PP.DUR: Pconst(1 / 2, 5),
88 | "D35": Pconst(1 / 4, 10),
89 | "V35": Pseq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10),
90 | "D34": Pconst(1 / 8, 20),
91 | "V34": Pseq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 20)
92 | }
93 | p = Phrase(properties)
94 | result = []
95 | for event in p:
96 | result.append(event)
97 | self.assertEqual(len(result), 5 + 10 + 20)
98 | self.assertEqual(result[-2]["V35"], 9)
99 | self.assertEqual(result[-2]["D35"], 4 * 1 / 4)
100 | self.assertEqual(result[-12]["V34"], 19)
101 | self.assertEqual(result[-12]["D34"], 4 * 1 / 8)
102 |
103 |
104 | if __name__ == '__main__':
105 | unittest.main()
106 |
--------------------------------------------------------------------------------
/tests/testphraseproperty.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.io.constants import PhraseProperty
4 |
5 |
6 | class TestPrand(unittest.TestCase):
7 | def test_phraseproperty(self):
8 | self.assertEqual(PhraseProperty.ctrl_val_key(45), "V45")
9 | self.assertEqual(PhraseProperty.ctrl_dur_key(67), "D67")
10 |
11 |
12 | if __name__ == '__main__':
13 | unittest.main()
14 |
--------------------------------------------------------------------------------
/tests/testprand.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.prand import Prand
4 |
5 |
6 | class TestPrand(unittest.TestCase):
7 | def test_shorter(self):
8 | a = [i for i in Prand([4, 5, 6], 2)]
9 | self.assertEqual(len(a), 2)
10 |
11 | def test_longer(self):
12 | b = [i for i in Prand([4, 5, 6], 10)]
13 | self.assertEqual(len(b), 10)
14 |
15 | def test_repr(self):
16 | self.assertEqual("{0}".format(Prand([1, -1, 2], 3)), "Prand([1, -1, 2], 3)")
17 |
18 |
19 | if __name__ == '__main__':
20 | unittest.main()
21 |
--------------------------------------------------------------------------------
/tests/testpseq.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pchord import Pchord
4 | from expremigen.patterns.pconst import Pconst
5 | from expremigen.patterns.pseq import Pseq
6 |
7 |
8 | class TestPseq(unittest.TestCase):
9 | def test_normal(self):
10 | a = [i for i in Pseq([4, 5, 6], 2)]
11 | self.assertEqual(a, [4, 5, 6] * 2)
12 |
13 | def test_empty(self):
14 | b = [i for i in Pseq([4, 5, 6], 0)]
15 | self.assertEqual(b, [])
16 |
17 | def test_adult(self):
18 | d = [i for i in Pseq(["X", "Y", "X"], 3)]
19 | self.assertEqual(d, ["X", "Y", "X"] * 3)
20 |
21 | def test_repr(self):
22 | self.assertEqual("{0}".format(Pseq([1, -1, Pconst(2, 2)], 3)), "Pseq([1, -1, Pconst(2, 2)], 3)")
23 |
24 | def test_defaultvalue(self):
25 | e = [i for i in Pseq(repeats=2)]
26 | self.assertEqual(e, [])
27 |
28 | def test_nesting(self):
29 | f = [i for i in Pseq([Pseq([1, Pconst(2, 2)], 2), Pseq([3, 4], 2)], 2)]
30 | self.assertEqual(f, [1, 2, 2, 1, 2, 2, 3, 4, 3, 4, 1, 2, 2, 1, 2, 2, 3, 4, 3, 4])
31 |
32 | def test_withchord(self):
33 | f = [i for i in Pseq([Pseq([1, Pconst(2, 2)], 2), Pseq(Pchord([3, 4]), 2)], 2)]
34 | self.assertEqual(f, [1, 2, 2, 1, 2, 2, Pchord([3, 4]), Pchord([3, 4]), 1, 2, 2, 1, 2, 2, Pchord([3, 4]),
35 | Pchord([3, 4])])
36 |
37 |
38 | if __name__ == '__main__':
39 | unittest.main()
40 |
--------------------------------------------------------------------------------
/tests/testpseries.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pseries import Pseries
4 |
5 |
6 | class TestPseries(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pseries(0, 10, 5)]
9 | self.assertEqual(a, [0, 10, 20, 30, 40])
10 |
11 | def test_negativestep(self):
12 | a = [i for i in Pseries(0, -10, 5)]
13 | self.assertEqual(a, [0, -10, -20, -30, -40])
14 |
15 | def test_stepzero(self):
16 | a = [i for i in Pseries(0, 0, 5)]
17 | self.assertEqual(a, [0, 0, 0, 0, 0])
18 |
19 | def test_zerolength(self):
20 | a = [i for i in Pseries(0, 10, 0)]
21 | self.assertEqual(a, [])
22 |
23 | def test_repr(self):
24 | self.assertEqual("{0}".format(Pseries(0, 10, 5)), "Pseries(0, 10, 5)")
25 |
26 |
27 | if __name__ == '__main__':
28 | unittest.main()
29 |
--------------------------------------------------------------------------------
/tests/testpshuf.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pshuf import Pshuf
4 |
5 |
6 | class TestPshuf(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pshuf([4, 5, 6, 7, 8, 9, 10], 2)]
9 | self.assertCountEqual(a, [4, 5, 6, 7, 8, 9, 10] * 2)
10 | self.assertNotEqual(a, [4, 5, 6, 7, 8, 9, 10] * 2)
11 | self.assertEqual(a[:7], a[7:]) # check supercollider semantics
12 |
13 | def test_empty(self):
14 | b = [i for i in Pshuf([4, 5, 6], 0)]
15 | self.assertEqual(b, [])
16 |
17 | def test_repr(self):
18 | self.assertEqual("{0}".format(Pshuf([1, -1, 2], 3)), "Pshuf([1, -1, 2], 3)")
19 |
20 |
21 | if __name__ == '__main__':
22 | unittest.main()
23 |
--------------------------------------------------------------------------------
/tests/testptween.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from vectortween.NumberAnimation import NumberAnimation
4 |
5 | from expremigen.patterns.ptween import Ptween
6 |
7 |
8 | class TestPtween(unittest.TestCase):
9 | def test_normal(self):
10 | n = NumberAnimation(frm=60, to=90, tween=['linear'])
11 | a = [i for i in Ptween(n, 0, 0, 10, 10, None)]
12 | self.assertEqual(a, [60, 63, 66, 69, 72, 75, 78, 81, 84, 87])
13 |
14 | def test_repr(self):
15 | n = NumberAnimation(frm=60, to=90, tween=['linear'])
16 | self.assertEqual("{0}".format(Ptween(n, 0, 0, 10, 10)), "Ptween(, 0, 0, 10, 10, None)")
17 |
18 |
19 | if __name__ == '__main__':
20 | unittest.main()
21 |
--------------------------------------------------------------------------------
/tests/testpwhite.py:
--------------------------------------------------------------------------------
1 | import unittest
2 |
3 | from expremigen.patterns.pwhite import Pwhite
4 |
5 |
6 | class TestPwhite(unittest.TestCase):
7 | def test_normal(self):
8 | a = [i for i in Pwhite(4, 5, 10)]
9 | # print(a)
10 | self.assertEqual(len(a), 10)
11 |
12 | def test_empty(self):
13 | a = [i for i in Pwhite(4, 5, 0)]
14 | self.assertEqual(a, [])
15 |
16 | def test_repr(self):
17 | self.assertEqual("{0}".format(Pwhite(0, 1.5, 4)), "Pwhite(0, 1.5, 4)")
18 |
19 |
20 | if __name__ == '__main__':
21 | unittest.main()
22 |
--------------------------------------------------------------------------------
/upload_to_pypi.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
3 | echo "there are uncommitted changes";
4 | else
5 | echo "all local changes are committed (didn't check for new files!)";
6 | rm dist/*.tar.gz
7 | echo "Make sure you've increased the version number in setup.py. Then, type that version here (e.g. 1.1.4), followed by [ENTER]:"
8 | read -e tag
9 | git tag "$tag" -m "tag version $tag"
10 | git push --tags origin master
11 | python setup.py sdist
12 | twine upload dist/*
13 | fi
14 |
15 |
--------------------------------------------------------------------------------
/upload_to_testpypi.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | if [ -n "$(git status --porcelain --untracked-files=no)" ]; then
3 | echo "there are uncommitted changes";
4 | else
5 | echo "all local changes are committed (didn't check for new files!)";
6 | rm dist/*.tar.gz
7 | # echo "Make sure you've increased the version number in setup.py. Then, type that version here (e.g. 1.1.4), followed by [ENTER]:"
8 | # read -e tag
9 | # git tag "$tag" -m "tag version $tag"
10 | # git push --tags origin master
11 | python setup.py sdist
12 | twine upload dist/* -r testpypi
13 | fi
14 |
15 |
--------------------------------------------------------------------------------