diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b8ecda1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,14 @@
+*.lisp~
+*.*~
+*.xfasl
+*.64xfasl
+*.ofasl
+*.*ufasl
+#*#
+
+.DS_Store
+
+# don't track auto-generated html's:
+/**/reference/*.*
+*.lisp#
+*.zip
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/RQ.lisp b/RQ.lisp
new file mode 100644
index 0000000..a2550eb
--- /dev/null
+++ b/RQ.lisp
@@ -0,0 +1,94 @@
+(in-package :om)
+
+(defpackage "RQ"
+ (:use "COMMON-LISP" "CL-USER" "OM-API" "LISPWORKS" "OM-LISP" "OPENMUSIC")
+ (:import-from "CL-USER")
+ )
+
+;----------------------
+; Loading files
+;----------------------
+(mapc
+ #'(lambda (file) (om::compile&load (om-relative-path (car file) (cadr file))))
+ '((("src" "algorithm" "structure") "complexity")
+ (("src" "algorithm" "structure") "distance")
+ (("src" "algorithm" "structure") "heap")
+ (("src" "algorithm" "structure") "input")
+ (("src" "algorithm" "structure") "path")
+ (("src" "algorithm" "structure") "weight")
+ (("src" "algorithm" "structure") "k-list")
+ (("src" "algorithm" "structure") "k-best")
+
+ (("src" "algorithm") "subdivision")
+ (("src" "algorithm") "ratio")
+ (("src" "algorithm") "rq")
+ (("src" "algorithm") "interface")
+ (("src" "algorithm") "k-best-segment-quantification")
+ (("src" "algorithm") "k-best-segment-quantification-automaton-with-tempo")
+ (("src" "algorithm") "k-best-segment-quantification-automaton")
+ (("src" "algorithm") "k-best-segment-quantification-automatons")
+ (("src" "algorithm") "tatum-seg-algorithm")
+ (("src" "algorithm") "tempo-smoothing")
+
+ (("src" "gui" "panel") "multi-poly-panel")
+ (("src" "gui" "panel") "quant-voice-panel")
+ (("src" "gui" "panel") "quant-chord-seq-panel")
+ (("src" "gui" "panel") "tree-view")
+ (("src" "gui") "quant-multi-poly")
+ (("src" "gui" "editor") "quant-voice-editor")
+ (("src" "gui" "editor") "multi-poly-editor")
+ (("src" "gui" "editor") "quant-chord-seq-editor")
+ (("src" "gui") "choice-table")
+ (("src" "gui") "quant-voice")
+ (("src" "gui") "quant-chord-seq")
+ (("src" "gui" "analysis") "k-best-data")
+ (("src" "gui" "analysis") "k-best-analysis")
+ (("src" ) "rq-class")
+ (("src" "gui" "window") "k-best-data-window")
+ (("src" "gui" "box") "quant-box")
+ (("src" "gui" "editor") "quant-editor")))
+
+
+
+
+;--------------------------------------------------
+; Setting the menu and sub-menu structure, and filling packages
+; The sub-list syntax:
+; ("sub-pack-name" subpackage-lists class-list function-list class-alias-list)
+;--------------------------------------------------
+(om::fill-library
+ '(("RQ" nil (rq::rq) (rq::get-voice rq::get-k-best-list) nil)
+ )
+ (find-library "RQ"))
+
+(set-lib-release 1.0)
+
+
+(print "
+;;;===================================================
+;;;
+;;; RQ - Rhythm Quantification for OM
+;;;
+;;;===================================================
+")
+
+
+;----------------------
+; Export functions
+;----------------------
+
+(in-package :rq)
+
+(export '(
+ rq
+ get-voice
+ get-k-best-list
+ ))
+
+;To make these symbols usable in the OM package
+(import '(
+ rq
+ get-voice
+ get-k-best-list
+ )
+ :om)
diff --git a/TODO.txt b/TODO.txt
new file mode 100644
index 0000000..307003c
--- /dev/null
+++ b/TODO.txt
@@ -0,0 +1,26 @@
+
+;;;;; TODO LIST ;;;;;
+
+=============
+Short Term :
+=============
+
+- COMMENT AND CLEAN THE CODE ! make sure every function has a description
+
+=============
+Long Term :
+=============
+
+
+Implementation :
+
+- Use threads in order to run the algorithm in background, and not block the interface during the computations
+- "Expert" interface in order to be able to specify each complexity coefficient (maybe not, cf Florent's work)
+- Limit recursions in order to be able to process longer units without "stack overflow"
+- Use gn-chords to display gracenotes correctly, and treat them differently than a regular chord with offset (in particular, adapt get-cons-list function so that we differenciate grace notes and chords. Current implementation has to do that in order to get the same results when a grace note is selected in "chord" mode or in "group" mode)
+
+
+Research :
+
+- Adapt the algorithm to polyphony
+- Tempo curves
diff --git a/examples/patch exemple RQ.omp b/examples/patch exemple RQ.omp
new file mode 100644
index 0000000..74255b5
--- /dev/null
+++ b/examples/patch exemple RQ.omp
@@ -0,0 +1,4 @@
+; OM File Header - Saved 2016/06/22 16:12:20
+; (6.1001 :patc (om-make-point 10 10) (om-make-point 254 204) (om-make-point 885 647) "" 183 0 "2016/06/17 17:49:00" "2016/06/22 16:12:20")
+; End File Header
+(in-package :om)(load-lib-for (quote ("RQ")))(setf *om-current-persistent* (om-load-patch1 "patch exemple rq" (quote ((let ((box (om-load-boxcall (quote genfun) "GET-VOICE" (quote get-voice) (quote ((om-load-inputfun (quote input-funbox) "rq" "RQ" nil))) (om-make-point 261 351) nil nil nil nil 1))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-boxcomment "comment 3" (om-make-point 303 75) (quote "Here is the result of quantification.$Do not forget to block the rq box before evaluating the voice !") "" (om-make-point 495 454) nil (om-make-color 0 0 0) (om-make-font "Verdana" 12 :family "Verdana" :style (quote (:plain)) :mode (quote nil))))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-editor-box1 "VOICE" (quote voice) (quote ((om-load-inputfun (quote input-funbox) "object" "self" nil) (om-load-inputfun (quote input-funbox) "a list representing a rhythm tree" "tree" (list (quote ?) (list (list (list 4 4) (list 1 1 1 1))))) (om-load-inputfun (quote input-funbox) "a chord object, a list of chords, a list of midics, a list of lists of midics..." "chords" (list (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (1000)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord))) (om-load-inputfun (quote input-funbox) "frequency of the quarter-note (default 60/mn)" "tempo" 60) (om-load-inputfun (quote input-funbox) "overlapping percentage between every successive chords, calculated from the second chord's duration" "legato" 100) (om-load-inputfun (quote input-funbox) "sub lists (one sub list per chord) indicating notes to be tied to notes of the same value, in a next chord" "ties" nil))) (om-make-point 239 442) (om-make-point 241 88) (let ((newobj (when (find-class (quote voice) nil) (make-instance (quote voice) :tree (quote (2 (((4 4) ((1 (1 1)) (1 (1 1)) 1 1)) ((4 4) ((1 (1 1)) (1 (1 1)) 2))))) :chords (load-obj-list-from-save (quote ((let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6400)) :ldur (quote (500)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (500)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6400)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (992)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord)))) :tempo (quote ((1/4 120) (((1 0) (1/4 121))))) :legato 100 :ties (quote (nil nil nil nil nil nil nil nil nil nil nil)))))) (load-port-info newobj (quote nil)) (init-mus-color newobj (quote nil)) (set-extra-pairs newobj (quote nil)) (set-patch-pairs newobj (quote nil)) (set-name newobj nil) (set-tonalite newobj nil) newobj) nil nil (pairlis (quote (approx fontsize staff cmnpref deltapict outport inport player zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)) (list 2 24 (quote g) (let ((newobj (make-instance (quote edition-values)))) (setf (paper-size newobj) (om-make-point 600 800)) (setf (top-margin newobj) 2) (setf (left-margin newobj) 1) (setf (right-margin newobj) 1) (setf (bottom-margin newobj) 1) (setf (orientation newobj) nil) (setf (scale newobj) nil) (setf (system-space newobj) (quote (1))) (setf (system-color newobj) (quote nil)) (setf (line-space newobj) 1) (setf (title newobj) nil) (setf (show-title? newobj) nil) (setf (show-page? newobj) nil) (setf (sheet-id newobj) nil) (setf (page-mode newobj) nil) newobj) (om-make-point 0 0) nil nil (quote :midi-player) 1 nil 1000 0 (om-make-point 658 307) (om-make-point 409 147) 0 2 (quote :normal) (quote t) nil)) t nil nil nil))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-boxcomment "comment 2" (om-make-point 134 52) (quote "Double-click to open the user interface") "" (om-make-point 358 289) nil (om-make-color 0 0 0) (om-make-font "Verdana" 12 :family "Verdana" :style (quote (:plain)) :mode (quote nil))))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-boxcomment "comment" (om-make-point 190 35) (quote "list of segmentation marks") "" (om-make-point 459 202) nil (om-make-color 0 0 0) (om-make-font "Verdana" 12 :family "Verdana" :style (quote (:plain)) :mode (quote nil))))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-boxcall (quote bastype) "list" (quote list) (quote nil) (om-make-point 382 206) (om-make-point 73 30) (list 0 2000) "(0 2000 )" nil))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-editor-box1 "RQ" (quote rq) (quote ((om-load-inputfun (quote input-funbox) "object" "self" nil) (om-load-inputfun (quote input-funbox) "chord-seq to quantify" "chord-seq" nil) (om-load-inputfun (quote input-funbox) "list of segmentation marks" "marks" (list 0)))) (om-make-point 275 283) (om-make-point 70 50) (let ((qs (if (find-class (quote rq) nil) (make-instance (quote rq) :chord-seq (let ((object (let ((newobj (when (find-class (quote rq::quant-chord-seq) nil) (make-instance (quote rq::quant-chord-seq) :lmidic (quote ((6000) (6000) (6000) (6200) (6400) (6200) (6000) (6400) (6200) (6200) (6000))) :lonset (quote (0 245 503 748 997 1528 1997 2289 2518 2726 2987 3987)) :ldur (quote ((1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000))) :lvel (quote ((100) (100) (100) (100) (100) (100) (100) (100) (100) (100) (100))) :loffset (quote ((0) (0) (0) (0) (0) (0) (0) (0) (0) (0) (0))) :lchan (quote ((1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1))) :legato 0)))) (setf (rq::pulse-flag newobj) (quote t)) (load-port-info newobj (quote ((0) (0) (0) (0) (0) (0) (0) (0) (0) (0) (0)))) (init-mus-color newobj (quote nil)) (set-extra-pairs newobj (quote nil)) (set-patch-pairs newobj (quote ((nil (om-load-patch-abs1 "patch" (quote nil) (quote nil) 6.1001 nil "" (om-make-point 200 200) (om-make-point 400 500)))))) (set-name newobj nil) (set-tonalite newobj nil) newobj))) (set-object-analysis object (list (if (find-class (quote k-best-analysis) nil) (make-instance (quote k-best-analysis) :analysis-segments (list (if (find-class (quote marker-segment) nil) (make-instance (quote marker-segment) :segment-data (make-instance (quote rq::k-best-data) :tempo (quote nil) :tempomerge (quote t) :schema (quote ((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))) :n-solution 10 :precision 0.5 :gracepen 2 :updateflag t :slur nil :grid (quote ((1/8 1/8) (1/8 1/8) 1/4 1/4))) :color (om-make-color 0.7 0.3 0.3) :tb 0 :te 2000 :mrk-time 0 :from-file t)) (if (find-class (quote marker-segment) nil) (make-instance (quote marker-segment) :segment-data (make-instance (quote rq::k-best-data) :tempo (quote nil) :tempomerge (quote t) :schema (quote ((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))) :n-solution 10 :precision 0.5 :gracepen 2 :updateflag t :slur 997 :grid (quote ((1/8 1/8) (1/8 1/8) 1/4 1/4))) :color (om-make-color 0.7 0.3 0.3) :tb 2000 :te 3987 :mrk-time 2000 :from-file t))) :segments=beats nil :n-beats-per-seg 1 :segpen 5 :from-file t)))) object) :marks (list 0 2000) :from-file t)))) (setf (rq::color-flag qs) t) (setf (rq::pulse-flag qs) t) (setf (rq::display-mode qs) :open) (rq::compute-k-best qs) (setf (rq::wp qs) (rq::make-working-poly qs)) (setf (rq::current-poly (rq::wp qs)) 1 (rq::selections (rq::wp qs)) (quote (0 2))) (setf (rq::solution qs) (let ((qv (let ((newobj (when (find-class (quote rq::quant-voice) nil) (make-instance (quote rq::quant-voice) :tree (quote (2 (((4 4) ((4 ((1 (1 1)) (1 (1 1)) 1 1)))) ((4 4) ((4 ((1 (1 1)) (1 (1 1)) 1 1.0))))))) :chords (load-obj-list-from-save (quote ((let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (250)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6400)) :ldur (quote (500)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (500)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6400)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6200)) :ldur (quote (248)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord) (let ((thechord (make-instance (quote chord) :lmidic (quote (6000)) :ldur (quote (496)) :lvel (quote (100)) :loffset (quote (0)) :lchan (quote (1))))) (load-port-info thechord (quote (0))) (init-mus-color thechord (quote nil)) (set-extra-pairs thechord (quote nil)) (set-tonalite thechord nil) thechord)))) :tempo (quote ((1/4 120) (((1 0) (1/4 121))))) :legato 100 :ties (quote (nil nil nil nil nil nil nil nil nil nil nil)))))) (setf (rq::colorflag newobj) (quote t)) (setf (rq::editflag newobj) (quote t)) (setf (rq::choices newobj) (list (let* ((choice (make-instance (quote rq::choice-table)))) (setf (rq::table choice) (make-hash-table :test (quote equalp))) (setf (gethash (rq::make-path (quote nil) 0 151351200 1) (rq::table choice)) (list (quote ((1) (1) (1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 227028.0 151348.0 227032.0 2118920.0 227024.0) #(-1 1 -1 1 1 -1 1) 151351200 0.022000025 t) :cpty (load-complexity (quote nil) 0 0) :val 3.1100002) (quote (1)) (quote (7))) (gethash (rq::make-path (quote ((4 . 3))) 75675600 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2) (2 . 1))) 37837800 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 227028.0 151348.0 0.0 0.0 0.0) #(0 0 -1 1 0 0 0) 151351200 0.0024999867 t) :cpty (load-complexity (quote nil) 1 0) :val 0.012499933) (quote (3)) (quote (4))) (gethash (rq::make-path (quote ((4 . 1))) 0 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 0.0 0.0 0.0 0.0 0.0) #(-1 1 0 0 0 0 0) 151351200 0.0025 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.5125) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 4))) 113513400 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 2118920.0 227024.0) #(0 0 0 0 0 -1 1) 151351200 0.015500003 t) :cpty (load-complexity (quote nil) 1 0) :val 0.077500016) (quote (6)) (quote (7))) (gethash (rq::make-path (quote ((4 . 2))) 37837800 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 227028.0 151348.0 227032.0 0.0 0.0) #(0 0 -1 1 1 0 0) 151351200 0.004000021 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.5200001) (quote (3)) (quote (5))) (gethash (rq::make-path (quote ((4 . 2) (2 . 2))) 56756700 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 227032.0 0.0 0.0) #(0 0 0 0 1 0 0) 151351200 0.0015000344 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0075001717) (quote nil) (quote (5))) (gethash (rq::make-path (quote ((4 . 1) (2 . 2))) 18918900 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 1) (2 . 1))) 0 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 0.0 0.0 0.0 0.0 0.0) #(-1 1 0 0 0 0 0) 151351200 0.0025 t) :cpty (load-complexity (quote nil) 1 0) :val 0.012499999) (quote (1)) (quote (2)))) (setf (rq::modified choice) nil) (setf (rq::user-edit choice) (quote nil)) choice) (let* ((choice (make-instance (quote rq::choice-table)))) (setf (rq::table choice) (make-hash-table :test (quote equalp))) (setf (gethash (rq::make-path (quote nil) 0 151351200 1) (rq::table choice)) (list (quote ((2) (1) (1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 1618624.0 1456768.0 495104.0 0.0) #(-1 -1 -1 1 1 0) 151351200 0.044036188 t) :cpty (load-complexity (quote nil) 0 0) :val 3.220181) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 3))) 75675600 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2) (2 . 1))) 37837800 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 1618624.0 1456768.0 0.0 0.0) #(0 0 -1 1 0 0) 151351200 0.020319576 t) :cpty (load-complexity (quote nil) 1 0) :val 0.101597876) (quote (3)) (quote (4))) (gethash (rq::make-path (quote ((4 . 1))) 0 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 0.0 0.0 0.0 0.0) #(-1 -1 0 0 0 0) 151351200 0.020445388 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.602227) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 4))) 113513400 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2))) 37837800 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 1618624.0 1456768.0 495104.0 0.0) #(0 0 -1 1 1 0) 151351200 0.023590802 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.617954) (quote (3)) (quote (5))) (gethash (rq::make-path (quote ((4 . 2) (2 . 2))) 56756700 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 495104.0 0.0) #(0 0 0 0 1 0) 151351200 0.003271226 t) :cpty (load-complexity (quote nil) 1 0) :val 0.016356131) (quote nil) (quote (5))) (gethash (rq::make-path (quote ((4 . 1) (2 . 2))) 18918900 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 0.0 0.0 0.0 0.0) #(0 -1 0 0 0 0) 151351200 0.020445388 t) :cpty (load-complexity (quote nil) 1 0) :val 0.10222694) (quote (2)) (quote nil)) (gethash (rq::make-path (quote ((4 . 1) (2 . 1))) 0 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(-1 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote (1)) (quote nil))) (setf (rq::modified choice) nil) (setf (rq::user-edit choice) (quote nil)) choice))) (setf (rq::slurs newobj) (list nil 997)) (setf (rq::ks newobj) (list 1 3)) (setf (rq::indexes newobj) (list 0 0)) (load-port-info newobj (quote nil)) (init-mus-color newobj (quote nil)) (set-extra-pairs newobj (quote nil)) (set-patch-pairs newobj (quote ((nil (om-load-patch-abs1 "patch" (quote nil) (quote nil) 6.1001 nil "" (om-make-point 200 200) (om-make-point 400 500)))))) (set-name newobj nil) (set-tonalite newobj nil) newobj))) (setf (rq::indexes qv) (quote (0 0)) (rq::ks qv) (quote (1 3)) (rq::slurs qv) (quote (nil 997)) (rq::choices qv) (list (let* ((choice (make-instance (quote rq::choice-table)))) (setf (rq::table choice) (make-hash-table :test (quote equalp))) (setf (gethash (rq::make-path (quote nil) 0 151351200 1) (rq::table choice)) (list (quote ((1) (1) (1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 227028.0 151348.0 227032.0 2118920.0 227024.0) #(-1 1 -1 1 1 -1 1) 151351200 0.022000025 t) :cpty (load-complexity (quote nil) 0 0) :val 3.1100002) (quote (1)) (quote (7))) (gethash (rq::make-path (quote ((4 . 3))) 75675600 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2) (2 . 1))) 37837800 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 227028.0 151348.0 0.0 0.0 0.0) #(0 0 -1 1 0 0 0) 151351200 0.0024999867 t) :cpty (load-complexity (quote nil) 1 0) :val 0.012499933) (quote (3)) (quote (4))) (gethash (rq::make-path (quote ((4 . 1))) 0 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 0.0 0.0 0.0 0.0 0.0) #(-1 1 0 0 0 0 0) 151351200 0.0025 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.5125) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 4))) 113513400 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 2118920.0 227024.0) #(0 0 0 0 0 -1 1) 151351200 0.015500003 t) :cpty (load-complexity (quote nil) 1 0) :val 0.077500016) (quote (6)) (quote (7))) (gethash (rq::make-path (quote ((4 . 2))) 37837800 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 227028.0 151348.0 227032.0 0.0 0.0) #(0 0 -1 1 1 0 0) 151351200 0.004000021 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.5200001) (quote (3)) (quote (5))) (gethash (rq::make-path (quote ((4 . 2) (2 . 2))) 56756700 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 227032.0 0.0 0.0) #(0 0 0 0 1 0 0) 151351200 0.0015000344 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0075001717) (quote nil) (quote (5))) (gethash (rq::make-path (quote ((4 . 1) (2 . 2))) 18918900 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 1) (2 . 1))) 0 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 378378.0 0.0 0.0 0.0 0.0 0.0) #(-1 1 0 0 0 0 0) 151351200 0.0025 t) :cpty (load-complexity (quote nil) 1 0) :val 0.012499999) (quote (1)) (quote (2)))) (setf (rq::modified choice) nil) (setf (rq::user-edit choice) (quote nil)) choice) (let* ((choice (make-instance (quote rq::choice-table)))) (setf (rq::table choice) (make-hash-table :test (quote equalp))) (setf (gethash (rq::make-path (quote nil) 0 151351200 1) (rq::table choice)) (list (quote ((2) (1) (1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 1618624.0 1456768.0 495104.0 0.0) #(-1 -1 -1 1 1 0) 151351200 0.044036188 t) :cpty (load-complexity (quote nil) 0 0) :val 3.220181) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 3))) 75675600 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2) (2 . 1))) 37837800 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 1618624.0 1456768.0 0.0 0.0) #(0 0 -1 1 0 0) 151351200 0.020319576 t) :cpty (load-complexity (quote nil) 1 0) :val 0.101597876) (quote (3)) (quote (4))) (gethash (rq::make-path (quote ((4 . 1))) 0 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 0.0 0.0 0.0 0.0) #(-1 -1 0 0 0 0) 151351200 0.020445388 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.602227) (quote (1)) (quote nil)) (gethash (rq::make-path (quote ((4 . 4))) 113513400 37837800 4) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(0 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote nil) (quote nil)) (gethash (rq::make-path (quote ((4 . 2))) 37837800 37837800 4) (rq::table choice)) (list (quote ((1) (1))) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 1618624.0 1456768.0 495104.0 0.0) #(0 0 -1 1 1 0) 151351200 0.023590802 t) :cpty (load-complexity (quote ((1 1))) 2 0) :val 0.617954) (quote (3)) (quote (5))) (gethash (rq::make-path (quote ((4 . 2) (2 . 2))) 56756700 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 495104.0 0.0) #(0 0 0 0 1 0) 151351200 0.003271226 t) :cpty (load-complexity (quote nil) 1 0) :val 0.016356131) (quote nil) (quote (5))) (gethash (rq::make-path (quote ((4 . 1) (2 . 2))) 18918900 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 3094434.0 0.0 0.0 0.0 0.0) #(0 -1 0 0 0 0) 151351200 0.020445388 t) :cpty (load-complexity (quote nil) 1 0) :val 0.10222694) (quote (2)) (quote nil)) (gethash (rq::make-path (quote ((4 . 1) (2 . 1))) 0 18918900 8) (rq::table choice)) (list (quote nil) (rq::make-weight :dist (rq::make-distance #(0.0 0.0 0.0 0.0 0.0 0.0) #(-1 0 0 0 0 0) 151351200 0.0 t) :cpty (load-complexity (quote nil) 1 0) :val 0.0) (quote (1)) (quote nil))) (setf (rq::modified choice) nil) (setf (rq::user-edit choice) (quote nil)) choice)) (rq::editflag qv) t (rq::colorflag qv) t) qv)) (setf (rq (rq::solution qs)) qs) (setf (rq::k-bests (rq::solution qs)) (rq::k-bests qs)) (initialize-instance (rq::solution qs) :tree (tree (rq::solution qs)) :chords (get-chords (chord-seq qs)) :tempo (rq::get-tempo (rq::wp qs))) (rq::update-grids (rq::solution qs)) qs) "x" nil (pairlis (quote (rq::poly-zoom rq::voice-zoom rq::chord-seq-zoom winpos winsize cursor-mode obj-mode fontsize mode score-mode notechancolor? show-stems approx cmnpref staff grillestep scale rq::display-mode rq::voice-mode)) (list 1 1 1 (om-make-point 10 40) (om-make-point 1500 590) (quote :normal) 1 24 0 0 nil (quote t) 2 (let ((newobj (make-instance (quote edition-values)))) (setf (paper-size newobj) (om-make-point 600 800)) (setf (top-margin newobj) 2) (setf (left-margin newobj) 1) (setf (right-margin newobj) 1) (setf (bottom-margin newobj) 1) (setf (orientation newobj) nil) (setf (scale newobj) nil) (setf (system-space newobj) (quote (2 2 2 2 2 2 2 2 2 3))) (setf (system-color newobj) (quote nil)) (setf (line-space newobj) 1) (setf (title newobj) nil) (setf (show-title? newobj) nil) (setf (show-page? newobj) nil) (setf (sheet-id newobj) nil) (setf (page-mode newobj) nil) newobj) (list (quote g) (quote g) (quote g) (quote g) (quote g) (quote g) (quote g) (quote g) (quote g) (quote g)) 1000 nil (quote :open) (quote :render))) nil nil nil nil))) (when (fboundp (quote set-active)) (set-active box nil)) box) (let ((box (om-load-editor-box1 "CHORD-SEQ" (quote chord-seq) (quote ((om-load-inputfun (quote input-funbox) "object" "self" nil) (om-load-inputfun (quote input-funbox) "pitches (mc): list or list of lists" "lmidic" (list 6000)) (om-load-inputfun (quote input-funbox) "onsets (ms): list" "lonset" (list 0 1000)) (om-load-inputfun (quote input-funbox) "durations (ms): list or list of lists" "ldur" (list 1000)) (om-load-inputfun (quote input-funbox) "velocities (0-127): list or list of lists" "lvel" (list 100)) (om-load-inputfun (quote input-funbox) "offsets (ms): list or list of lists" "loffset" (list 0)) (om-load-inputfun (quote input-funbox) "MIDI channels (1-16): list or list of lists" "lchan" (list 1)) (om-load-inputfun (quote input-funbox) "relative chords duration (0-100)" "legato" 0))) (om-make-point 146 69) (om-make-point 237 94) (let ((newobj (when (find-class (quote chord-seq) nil) (make-instance (quote chord-seq) :lmidic (quote ((6000) (6000) (6000) (6200) (6400) (6200) (6000) (6400) (6200) (6200) (6000))) :lonset (quote (0 245 503 748 997 1528 1997 2289 2518 2726 2987 3987)) :ldur (quote ((1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000) (1000))) :lvel (quote ((100) (100) (100) (100) (100) (100) (100) (100) (100) (100) (100))) :loffset (quote ((0) (0) (0) (0) (0) (0) (0) (0) (0) (0) (0))) :lchan (quote ((1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1))) :legato 0)))) (load-port-info newobj (quote ((0) (0) (0) (0) (0) (0) (0) (0) (0) (0) (0)))) (init-mus-color newobj (quote nil)) (set-extra-pairs newobj (quote nil)) (set-patch-pairs newobj (quote ((nil (om-load-patch-abs1 "patch" (quote nil) (quote nil) 6.1001 nil "" (om-make-point 200 200) (om-make-point 400 500))) ((9) (om-load-patch-abs1 "patch" (quote nil) (quote nil) 6.1001 nil "" (om-make-point 200 200) (om-make-point 400 500)))))) (set-name newobj nil) (set-tonalite newobj nil) newobj) "x" nil (pairlis (quote (approx fontsize staff cmnpref deltapict outport inport player zoom notechancolor? grillestep mode winsize winpos score-mode obj-mode cursor-mode show-stems scale)) (list 2 24 (quote g) (let ((newobj (make-instance (quote edition-values)))) (setf (paper-size newobj) (om-make-point 600 800)) (setf (top-margin newobj) 2) (setf (left-margin newobj) 1) (setf (right-margin newobj) 1) (setf (bottom-margin newobj) 1) (setf (orientation newobj) nil) (setf (scale newobj) nil) (setf (system-space newobj) (quote (1))) (setf (system-color newobj) (quote nil)) (setf (line-space newobj) 1) (setf (title newobj) nil) (setf (show-title? newobj) nil) (setf (show-page? newobj) nil) (setf (sheet-id newobj) nil) (setf (page-mode newobj) nil) newobj) (om-make-point 0 0) nil nil (quote :midi-player) 177/100 nil 1000 0 (om-make-point 1010 304) (om-make-point 499 337) 0 1 (quote :normal) (quote t) nil)) t nil nil nil))) (when (fboundp (quote set-active)) (set-active box nil)) box))) (quote ((6 0 0 0 nil 0) (0 0 2 0 nil 0) (7 0 6 1 nil 0) (5 0 6 2 nil 0))) nil 6.1001))
diff --git a/quantify.class.violet.html b/quantify.class.violet.html
new file mode 100644
index 0000000..ee0ef21
--- /dev/null
+++ b/quantify.class.violet.html
@@ -0,0 +1,2448 @@
+
+
+
+
+
+
+
+
+ This file was generated with Violet UML Editor 2.1.0.
+ ( View Source / Download Violet )
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/src/algorithm/interface.lisp b/src/algorithm/interface.lisp
new file mode 100644
index 0000000..057ab15
--- /dev/null
+++ b/src/algorithm/interface.lisp
@@ -0,0 +1,245 @@
+;;; Interfaces for k-best quantification
+;; Most of the functions here are now obsolete (everything replaced by the GUI)
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+(export '(k-best-quantify) :rq)
+
+(defun to-input (onsets durations schema sig tempo)
+ "Takes a list of onsets and a list of durations (of same length) and returns an input object"
+ (let ((mesdur (* (* (first sig) (/ 4 (second sig))) (/ 60 tempo) 1000)))
+ ;creates the output list and the mask from the onsets and durations
+ (labels ((out-mask (onsets durations output mask)
+ (if (or (null onsets) (null durations))
+ (values (append output (list mesdur)) (append mask (list -1)))
+ (let ((on1 (first onsets))
+ (dur1 (first durations))
+ (on2 (second onsets))
+ (dur2 (second durations)))
+ (if (or (null on2) (null dur2)) ;on1 is the last note
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1)))
+ (if (< (+ on1 dur1) on2) ;if there is a silence between the current note and the next one
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1)))
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1)) (append mask (list 1)))))))))
+ (multiple-value-bind (output mask) (out-mask onsets durations nil nil)
+ (input-make schema (coerce output 'vector) (coerce mask 'vector))))))
+
+(defun cut-measures (onsets durations signatures tempo)
+ " cuts the onsets and durations lists in measures
+ the note series has to be monophonic, otherwise, the results are not guaranteed.
+ output onsets are given as the duration between the beginning of the measure and the onset of the note
+
+OUTPUTS :
+ on-mes holds the onsets grouped in measures
+ dur-mes holds the durations grouped in measures
+ slur is a list : the nth element is 1 if the last note of the nth measure is slurred with the next one, nil otherwise"
+ (labels ((make-measures (onsets durations sig temp &optional (on-mes nil) (dur-mes nil) (slur nil) (sigs nil) (temps nil))
+ (let* ((current-sig (first sig))
+ (current-temp (first temp))
+ (mes-duration (* (* (first current-sig) (/ 4 (second current-sig))) (/ 60 current-temp) 1000)) ;duration of a measure in ms
+ (end mes-duration) ;the beginning of the measure is always 0
+ (index (position-if #'(lambda (x) (>= x end)) onsets)) ;index of the first element of the next measures
+ (last-on (if index (nth (1- index) onsets) (car (last onsets)))) ;if there are no elements in the next measures (ie current measure is last), last on is the last onset, otherwise it is the index-th element of onsets
+ (last-dur (if index (nth (1- index) durations) (car (last durations)))) ;idem
+ (exceed (> (+ last-on last-dur) end)) ;true iff the last note of the measure lasts after the end of the measure
+ (new-sig (if (null (rest sig)) ;if there are not enough signatures or tempo given, we continue with the last one
+ sig
+ (rest sig)))
+ (new-temp (if (null (rest temp))
+ temp
+ (rest temp))))
+ (if (null exceed)
+ (if (null index)
+ ; the current measure is the last : there are no notes after the end of the measure
+ (values (append on-mes (list onsets)) (append dur-mes (list durations)) (append slur (list nil)) (append sigs (list current-sig)) (append temps (list current-temp)))
+ ;the current measure is not the last, we iterate
+ (make-measures (update-onsets (subseq onsets index) mes-duration) (subseq durations index) new-sig new-temp (append on-mes (list (subseq onsets 0 index))) (append dur-mes (list (subseq durations 0 index))) (append slur (list nil)) (append sigs (list current-sig)) (append temps (list current-temp)) ))
+ ;if the last note is cut by the measure bar, we cut it into two notes, and put 1 in slur (the measures are slurred)
+ (let* ((new-dur (- end last-on))
+ (excess (- last-dur new-dur)))
+ (if (null index)
+ ;if there are no notes after, we just add a measure for the end of the note
+ (values (append on-mes (list onsets) (list (list 0))) (append dur-mes (list (append (butlast durations) (list new-dur))) (list (list excess))) (append slur (list 1 nil)) (append sigs (list current-sig (car new-sig))) (append temps (list current-temp (car new-temp))) )
+ ;if there are notes after, we iterate
+ (make-measures (append (list 0) (update-onsets (subseq onsets index) mes-duration)) (append (list excess) (subseq durations index)) new-sig new-temp (append on-mes (list (subseq onsets 0 index))) (append dur-mes (list (append (subseq durations 0 (1- index)) (list new-dur)))) (append slur (list 1)) (append sigs (list current-sig)) (append temps (list current-temp))))))))
+ (update-onsets (onsets measure)
+ (mapcar #'(lambda (x) (- x measure)) onsets)))
+ (if (listp (car signatures)) ;if a list of signatures is given
+ (if (listp tempo) ;if a list of tempo is given
+ () ;we do nothing
+ ;if a list of signatures is provided, but only 1 tempo is given
+ (setq tempo (make-list (length signatures) :initial-element tempo)))
+ ;if only one signature is given
+ (if (listp tempo)
+ (setq signatures (make-list (length tempo) :initial-element signatures))
+ ;if only one signature and one tempo is given
+ (progn
+ (setq signatures (list signatures))
+ (setq tempo (list tempo)))))
+ (make-measures onsets (remove-overlap onsets (normalize-durations durations)) signatures tempo)))
+
+(defun normalize-durations (durations &optional (buffer nil))
+ "if durations is the output of a chord-seq, it is a list of lists of length 1, otherwise, the input is a normal list
+This function transforms the durations output of a chord-seq into a normal list
+The chord-seq has to be monophonic"
+ (if (null durations)
+ buffer
+ (let ((current (car durations)))
+ (if (listp current)
+ (normalize-durations (rest durations) (append buffer (list (reduce #'max current))))
+ (normalize-durations (rest durations) (append buffer (list current)))))))
+
+(defun remove-overlap (onsets durations &optional (dur-buf nil))
+ (let ((on1 (first onsets))
+ (dur1 (first durations))
+ (on2 (second onsets))
+ (dur2 (second durations)))
+ (if (or (null on2) (null dur2))
+ (append dur-buf (list dur1))
+ (if (< (+ on1 dur1) on2) ;if there is a silence between the current note and the next one)
+ (remove-overlap (rest onsets) (rest durations) (append dur-buf (list dur1)))
+ (remove-overlap (rest onsets) (rest durations) (append dur-buf (list (- on2 on1))))))))
+
+(defun create-inputs (onsets durations schema sigs tempo schema-measure?)
+ "returns a list of input objects, each corresponding to a measure"
+ (labels ((create-schemas (siglist schema)
+ (mapcar #'(lambda (sig) (append (list (car sig)) schema)) siglist)))
+ (multiple-value-bind (onlist durlist slurs siglist templist) (cut-measures onsets durations sigs tempo)
+ (if schema-measure?
+ (values (mapcar #'to-input onlist durlist (make-list (length onlist) :initial-element schema) siglist templist) slurs siglist templist)
+ (values (mapcar #'to-input onlist durlist (create-schemas siglist schema) siglist templist) slurs siglist templist)))))
+
+(om::defmethod! k-best-quantify (onsets durations k schema sigs tempo &optional (precision 0.5) (schema-measure? nil))
+ :initvals '((0) (1000) 10 '(4 2 2) '(4 4) 60 0.5 nil)
+ :indoc '("onsets" "durations" "number of solutions" "schema" "signatures" "tempo" "precision (0.0-1.0)" "schema-measure?")
+ :icon '(252)
+ :doc "Quantizes a list of onsets and a list of durations. The output is given as a list of possible rhythm trees.
+ : a list of onsets in 1/1000th of a second
+ : a list of durations in 1/1000th of a second
+ : number of output solutions
+ : a subdivision schema applied to each time unit (by default : each quarter note). A subdivision schema is given in the form of a list. For example : (2 2 3) means that each time unit is divided in two, then each part is again divided in two, and finally, each of these parts is divided in 3.
+
+If an element of the list is a list itself, it means that the choice is given between the values of the list. For example : (2 (2 3 5) 3) means (2 2 3) or (2 3 3) or (2 5 3).
+
+If an element of the list is a list of lists, it means that the choice is given between various successions of subdivisions. For example : ( ((2 3) (3 2)) ) means (2 3) or (3 2).
+
+Example : ((2 3) ((2 3) ((3 5) 2))) means (2 2 3) or (2 3 2) or (2 5 2) or (3 2 3) or (3 3 2) or (3 5 2).
+
+ Non prime numbers can be used as, for exemple, dividing in 2 then in 2 gives a different notation than dividing in 4.
+
+ : the signature to be used for each measure. If there are various signatures, a list of signatures can be given (ex : ((3 4) (4 4)) means the signature of the first measure is (3 4), and the signature of the following measures is (4 4))
+ : the tempo to be used. If the tempo changes from measure to measure, a list of tempo can be given (ex : (60 50) means the tempo of the first measure is 60, and the tempo of the following measures is 50)
+
+ : a float in (0.0 .. 1.0). Smaller values mean 'simplicity' while bigger values mean 'precision'.
+
+ : a boolean. If true, the schema is applied to each measure. If false, the schema is applied to each pulse. False by default.
+"
+ (labels ((add-signatures (trees signatures &optional (buffer nil))
+ (if (null trees)
+ buffer
+ (add-signatures (cdr trees) (cdr signatures) (append buffer (list (loop for tree in (car trees) collect (list (car signatures) tree))))))))
+ (multiple-value-bind (inputs slurs siglist templist) (create-inputs (butlast onsets) durations schema sigs tempo schema-measure?)
+ (let ((trees nil)
+ (N (length inputs))
+ (slurs (append '(0) slurs))) ;we add a 0 to math the indexes : a 1 in slurs now means the current measure is slurred with the previous, and not that the next is slurred with the current.
+ (if (equalp *weight-precision* precision)
+ ()
+ (setf *weight-precision* precision))
+ ;for each measure, computation of the k best solutions
+ (setq trees (loop for n from 0 to (1- N)
+ collect
+ (let ((ktable (init (transitions (nth n inputs)))))
+ (loop for i from 1 to k
+ collect (rq-to-omtree ktable (nth n inputs) i (nth n slurs))))))
+ ;we add the signatures
+ (setq trees (add-signatures trees siglist))
+ ;we have a list of size n_measures, containing lists of length k. Instead, we want a list o length k, containing lists of size n_measure
+ ;In other words, we want to have a list indexed by the rank of the solution, not by the number of the measure.
+ (setq trees (loop for i from 0 to (1- k) collect
+ (loop for tree in trees collect
+ (nth i tree))))
+ (mapcar #'(lambda (x) (append (list '?) (list x))) trees)))))
+
+(defun rq-to-omtree (ktable inst k flag &optional (slur nil) (gracenotes 0) (path nil) (previous -1))
+"Function to reconstruct a rhythm tree from the hashtable
+ The slur parameter is nil when the current measure is not slurred with the previous one, an integer when it is"
+ (let ((rootp (or path (path-empty inst)))
+ (slurred nil) ;nil when the first note has not been slurred yet, t when if has.
+ (grace (if gracenotes gracenotes 0)) ;number of grace notes in the previous step
+ (prev (if previous previous -1))) ;prev : sign of the last input in the previous subdivision (1: note, -1: silence). By default : we begin with a silence
+ (labels ((to-omtree (inst p k flag)
+ (multiple-value-bind (run w) (rq-best ktable inst p k flag)
+ (let ((r (length run))
+ (y nil)) ;buffer to hold the sub-tree
+ (if (> r 0)
+ ; (list 1 (mapcar #'(lambda (k i) (to-omtree inst (path-addi p r i) k)) run (from-1-to r)))
+ (list 1 (loop for i from 1 to r
+ for krun in run
+ collect (to-omtree inst (path-addi p r i) (car krun) (cdr krun))))
+ ;if the node considered is a leaf
+ (multiple-value-bind (ll rr) (align ktable p)
+ ;processing ll
+ (if (null ll) ;if there are no inputs aligned to the left
+ (if (> grace 0) ;if there were notes aligned to the right in the previous subdivision
+ (if (equalp grace 1) ;if there is only one note
+ (setq y 1)
+ (setq y (list 1 (append (make-list (1- grace) :initial-element 0) (list 1)))))
+ ;if there is no input in the subdivision and there was no note aligned to the right before
+ (if (equalp prev 1)
+ (setq y 1.0) ;if there was a note before, tie it to the current
+ (setq y -1))) ;if there was a silence, return a silence
+ ;if there are inputs aligned to the left
+ (if (and (equalp grace 0) (equalp (length ll) 1))
+ (setq y (* (input-sign inst (car ll)) 1)) ;if there is only 1 input aligned to the left
+ (let ((ll0 (remove-silences ll inst)))
+ (if (null ll0) ;if there are only rests aligned to the left (at least 1)
+ (if (> grace 0) ;if there were notes aligned to the right in the previous subdivision
+ (if (equalp grace 1) ;if there is only one note
+ (setq y 1)
+ (setq y (list 1 (append (make-list (1- grace) :initial-element 0) (list 1)))))
+ ;if there are only rests in the subdivision and there was no note aligned to the right before
+ (setq y -1))
+ ;if there are notes aligned to the left
+ (if (and (equalp (length ll0) 1) (equalp grace 0)) ;if there is exactly one note aligned to the left
+ (setq y 1)
+ ;if there is at least 1 note aligned to the left or 1 note aligned to the right before
+ (setq y (list 1 (append (make-list (1- (+ grace (length ll0))) :initial-element 0) (list 1)))))))))
+ ;if the current note is the first and if it has to be slurred, we slur it and remember that the first note has already been slurred
+ (if (and (null slurred) slur)
+ (progn
+ (if (listp y) ;if the note to slur has grace-notes : the exceeding part of the previous measure was aligned to the left so we delete it
+ (if (equalp (second y) '(0 1))
+ (setq y 1)
+ (setq y (list 1 (rest (second y)))))
+ (setq y (float y)))
+ (setq slurred t)))
+ ;otherwise, we do nothing
+ ;processing rr
+ (if (null rr)
+ (if (not (null ll))
+ (setq prev (input-sign inst (car (last ll)))) ;if there are no notes aligned to the right, but there are some to the left
+ ;if there are no notes in the subdivision, we do nothing
+ )
+ (setq prev (input-sign inst (car (last rr)))))
+ (setq grace (length (remove-silences rr inst)))
+ y))))))
+ (if (weight-infinityp (nth-value 1 (rq-best ktable inst rootp k flag)))
+ (setq out -1)
+ (setq out (to-omtree inst rootp k flag)))
+ (list out))))
+
+(defun rq-remove-top-level (tree)
+ (if (or (equalp tree '(1)) (equalp tree '(-1)) (equalp tree '(1.0)) (equalp tree '(-1.0))) ;we remove the first top-level (1 (...)), except when we only have a 1
+ tree
+ (second (car tree))))
+
+(defun output (tree &optional (sig '(1 4)))
+ (list '? (list (list sig tree))))
+
+(defun get-nth-measure (tree n)
+ (nth n (second tree)))
+
+(defun concatenate-measures (&rest trees)
+ (list '? trees))
diff --git a/src/algorithm/k-best-segment-quantification-automaton-with-tempo.lisp b/src/algorithm/k-best-segment-quantification-automaton-with-tempo.lisp
new file mode 100644
index 0000000..8336eb8
--- /dev/null
+++ b/src/algorithm/k-best-segment-quantification-automaton-with-tempo.lisp
@@ -0,0 +1,34 @@
+(in-package :rq)
+
+;;;; Functions to run the algorithm (ie build a k-best structure) on one segment
+;; In this version, only 1 input and 1 table are created, and they take into account 1 tempo only (such that the segment's length is an integer multiple of the length of a beat)
+
+(defun k-best-segment-quantify-automaton-with-tempo (onsets durations k schema segment-dur tempo &optional (precision 0.5) (gracepen 2) (initial-slur nil))
+ "Version with a given tempo"
+ (let* ((input (k-best-segment-create-input-with-tempo onsets (normalize-durations durations) schema tempo segment-dur precision gracepen initial-slur))
+ (ktable (init (transitions input))))
+ (rq-best-top ktable input k )
+ (make-instance 'k-best :ktables (list ktable) :inputs (list input) :slur initial-slur :gracenotes (list (loop for i from 1 to k collect (k-best-segment-get-gracenotes ktable input i))) :n-solution k :tempomerge nil)))
+
+(defun k-best-segment-create-input-with-tempo (onsets durations schema tempo segment-dur precision gracepen initial-slur)
+ "Creates an input structure when the tempo is given. The tempo will be approximated so that the segment's length is an integer multiple of the length of a beat."
+ (labels ((create-schema (onsets segment-dur schema tempo)
+ (let* ((beat-dur (/ 60000 tempo))
+ )
+ (multiple-value-bind (nbeats rest) (round segment-dur beat-dur)
+ (append (list (max nbeats 1)) schema))))
+ (append-initial-slur (onsets durations initial-slur)
+ (if (and (equalp onsets '(0)) (null durations)) ;if the segment is empty
+ (if initial-slur
+ (values (list 0 initial-slur) (list initial-slur))
+ (valuea onsets durations))
+ (if (zerop (first onsets))
+ (values onsets durations)
+ (if (< (first onsets) initial-slur)
+ (values (append (list 0) onsets) (append (list (first onsets)) durations))
+ (values (append (list 0) onsets) (append (list initial-slur) durations)))))))
+ (if initial-slur
+ (multiple-value-bind (onsets durations) (append-initial-slur onsets durations initial-slur)
+ (k-best-segment-to-input onsets durations (create-schema onsets segment-dur schema tempo) segment-dur precision gracepen))
+ (k-best-segment-to-input onsets durations (create-schema onsets segment-dur schema tempo) segment-dur precision gracepen))))
+
diff --git a/src/algorithm/k-best-segment-quantification-automaton.lisp b/src/algorithm/k-best-segment-quantification-automaton.lisp
new file mode 100644
index 0000000..a648229
--- /dev/null
+++ b/src/algorithm/k-best-segment-quantification-automaton.lisp
@@ -0,0 +1,63 @@
+
+
+(use-package :om :rq)
+(in-package :rq)
+
+;;;; Functions to run the algorithm (ie build a k-best structure) on one segment
+;; In this version, only 1 input and 1 table are created, and they take into account all admissible tempi.
+;; In this way, all the solutions are ranked across all possible tempi. The best solution thus also gives the best tempo.
+;; However, it is not possible to compute more solutions for one particular tempo.
+;; Called when "Merge tempi" is ticked
+
+(defun k-best-segment-quantify-automaton (onsets durations k schema segment-dur &optional (precision 0.5) (gracepen 2) (initial-slur nil) (tempo-min 40) (tempo-max 200))
+ "Computes a k-best structure with only one ktable (all tempi merged)"
+ (let* ((input (k-best-segment-create-input onsets (normalize-durations durations) schema segment-dur initial-slur tempo-min tempo-max precision gracepen))
+ (ktable (init (transitions input))))
+ (rq-best-top ktable input k)
+ ;put ktable and input inside a list for compatibility reasons
+ (make-instance 'k-best :ktables (list ktable) :inputs (list input) :slur initial-slur :gracenotes (list (loop for i from 1 to k collect (k-best-segment-get-gracenotes ktable input i))) :n-solution k :tempomerge t)))
+
+(defun k-best-segment-create-input (onsets durations schema segment-dur initial-slur tempo-min tempo-max precision gracepen)
+ "Create one single input structure to quantify with all tempi merged"
+ (labels ((create-schema (segment-dur schema)
+ (let* ((beat-min (/ 60000 tempo-max))
+ (beat-max (/ 60000 tempo-min))
+ (ndiv-min (max (round segment-dur beat-max) 1))
+ (ndiv-max (max (round segment-dur beat-min) 1)))
+ (append (list (loop for i from ndiv-min to ndiv-max collect i)) schema)))
+ (append-initial-slur (onsets durations initial-slur)
+ (if (and (equalp onsets '(0)) (null durations)) ;if the segment is empty
+ (if initial-slur
+ (values (list 0 initial-slur) (list initial-slur))
+ (values onsets durations))
+ (if (zerop (first onsets))
+ (values onsets durations)
+ (if (< (first onsets) initial-slur)
+ (values (append (list 0) onsets) (append (list (first onsets)) durations))
+ (values (append (list 0) onsets) (append (list initial-slur) durations)))))))
+ (if initial-slur
+ (multiple-value-bind (onsets durations) (append-initial-slur onsets durations initial-slur)
+ (k-best-segment-to-input onsets durations (create-schema segment-dur schema) segment-dur precision gracepen))
+ (k-best-segment-to-input onsets durations (create-schema segment-dur schema) segment-dur precision gracepen))))
+
+
+(defun k-best-segment-to-input (onsets durations schema segment-dur precision gracepen)
+ "Takes a list of onsets and a list of durations (of same length) and returns an input object.
+Used in the case of one single input."
+ ;creates the output list and the mask from the onsets and durations
+ (labels ((out-mask (onsets durations output mask)
+ (if (or (null onsets) (null durations))
+ (values (append output (list segment-dur)) (append mask (list -1)))
+ (let ((on1 (first onsets))
+ (dur1 (first durations))
+ (on2 (second onsets))
+ (dur2 (second durations)))
+ (if (or (null on2) (null dur2)) ;on1 is the last note
+ (if (> (+ on1 dur1) segment-dur)
+ (values (append output (list on1 segment-dur)) (append mask (list 1 -1)))
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1))))
+ (if (< (+ on1 dur1) on2) ;if there is a silence between the current note and the next one
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1)))
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1)) (append mask (list 1)))))))))
+ (multiple-value-bind (output mask) (out-mask onsets durations nil nil)
+ (input-make schema (coerce output 'vector) (coerce mask 'vector) precision gracepen))))
diff --git a/src/algorithm/k-best-segment-quantification-automatons.lisp b/src/algorithm/k-best-segment-quantification-automatons.lisp
new file mode 100644
index 0000000..703b6e9
--- /dev/null
+++ b/src/algorithm/k-best-segment-quantification-automatons.lisp
@@ -0,0 +1,69 @@
+
+(use-package :om :rq)
+(in-package :rq)
+
+;;;; Functions to run the algorithm (ie build a k-best structure) on one segment
+;; In this version, one input and one table is created for each tempo, and each correspond to one tempo only.
+;; In this way, the solutions are ranked independently for each tempo.
+;; It gives the possibility to compute more solutions for one particular tempo.
+;; Called when "Merge tempi" is not ticked
+
+(defun k-best-segment-quantify-automatons (onsets durations k schema segment-dur &optional (precision 0.5) (gracepen 2) (initial-slur nil) (tempo-min 40) (tempo-max 200))
+ "Computes a k-best structure containing several ktables and several inputs, one for each tempo"
+ (let* ((inputs (k-best-segment-create-inputs onsets (normalize-durations durations) schema segment-dur initial-slur tempo-min tempo-max precision gracepen))
+ (ktables (loop for input in inputs collect (init (transitions input))))
+ (N (length ktables)))
+ (loop for ktable in ktables
+ for input in inputs do
+ (rq-best-top ktable input k ))
+ (let ((gracenotes (loop for i from 0 to (1- N) collect
+ (loop for j from 1 to k collect (k-best-segment-get-gracenotes (nth i ktables) (nth i inputs) j)))))
+ (make-instance 'k-best :ktables ktables :inputs inputs :slur initial-slur :gracenotes gracenotes :n-solution k :tempomerge nil))))
+
+(defun k-best-segment-create-inputs (onsets durations schema segment-dur initial-slur tempo-min tempo-max precision gracepen)
+ "this version returns a list of inputs, each corresponding to one tempo"
+ (labels ((create-schemas (segment-dur schema)
+ (let* ((beat-min (/ 60000 tempo-max))
+ (beat-max (/ 60000 tempo-min))
+ (ndiv-min (max (round segment-dur beat-max) 1))
+ (ndiv-max (max (round segment-dur beat-min) 1)))
+ (loop for i from ndiv-min to ndiv-max collect (append (list i) schema))))
+ (append-initial-slur (onsets durations initial-slur)
+ (if (and (equalp onsets '(0)) (null durations)) ;if the segment is empty
+ (if initial-slur
+ (values (list 0 initial-slur) (list initial-slur))
+ (values onsets durations))
+ (if (zerop (first onsets))
+ (values onsets durations)
+ (if (< (first onsets) initial-slur)
+ (values (append (list 0) onsets) (append (list (first onsets)) durations))
+ (values (append (list 0) onsets) (append (list initial-slur) durations)))))))
+ (let ((schema-list (or (create-schemas segment-dur schema)
+ (list (append (list 1) schema)))))
+ (if initial-slur
+ (multiple-value-bind (onsets durations) (append-initial-slur onsets durations initial-slur)
+ (k-best-segment-to-inputs onsets durations schema-list segment-dur precision gracepen))
+ (k-best-segment-to-inputs onsets durations schema-list segment-dur precision gracepen)))))
+
+(defun k-best-segment-to-inputs (onsets durations schema-list segment-dur precision gracepen)
+ "Takes a list of onsets and a list of durations (of same length) and returns a list of input objects
+Used in the case of multiple inputs"
+
+ ;creates the output list and the mask from the onsets and durations
+ (labels ((out-mask (onsets durations output mask)
+ (if (or (null onsets) (null durations))
+ (values (append output (list segment-dur)) (append mask (list -1)))
+ (let ((on1 (first onsets))
+ (dur1 (first durations))
+ (on2 (second onsets))
+ (dur2 (second durations)))
+ (if (or (null on2) (null dur2)) ;on1 is the last note
+ (if (> (+ on1 dur1) segment-dur)
+ (values (append output (list on1 segment-dur)) (append mask (list 1 -1)))
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1))))
+ (if (< (+ on1 dur1) on2) ;if there is a silence between the current note and the next one
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1 (+ on1 dur1))) (append mask (list 1 -1)))
+ (out-mask (cdr onsets) (cdr durations) (append output (list on1)) (append mask (list 1)))))))))
+ (multiple-value-bind (output mask) (out-mask onsets durations nil nil)
+ (loop for schema in schema-list collect
+ (input-make schema (coerce output 'vector) (coerce mask 'vector) precision gracepen)))))
diff --git a/src/algorithm/k-best-segment-quantification.lisp b/src/algorithm/k-best-segment-quantification.lisp
new file mode 100644
index 0000000..a100d70
--- /dev/null
+++ b/src/algorithm/k-best-segment-quantification.lisp
@@ -0,0 +1,93 @@
+
+
+(use-package :om :rq)
+(in-package :rq)
+
+;;; General functions, used whatever is the number of inputs and tables for the current segment.
+
+
+(defmethod k-best-segment-get-gracenotes (ktable inst k &optional (flag nil) (path (path-empty inst)))
+ "Returns the number of grace notes for the segment given by path (ie, number of note onsets aligned to the right of the segment)."
+ (length (remove-silences (nth-value 3 (rq-best ktable inst path k flag)) inst)))
+
+;;; New rq-eval and rq-best for the first level of subdivision
+;; (subdivision in beats, the complexity measure is not the same)
+
+(defun rq-best-top (ktable inst k)
+ "Special rq-best function for top-level subdivision (subdivision in beats, the weight functions are different)"
+ (let ((p (path-empty inst)))
+ (labels ((process-next (e run w)
+ (multiple-value-bind (ll rr) (align-run ktable inst p run)
+ (if (or (and (not (null run)) (is-redundant ktable inst p ll rr)) (not (check-flags run (length run))))
+ () ;if the current run gives a redundant alignment (ie equivalent to not subdividing further), we only add the nexts to the cand list (we do not put the run in the best list)
+ (setf (best-best0 (entry-best e)) (k-list-add run w ll rr (best-best0 (entry-best e))))) ;if not, we add it to the list and add the nexts to the cand list
+ (map nil #'(lambda (x) (setf (cand-cand0 (entry-cand e)) (queue-insert (cand-cand0 (entry-cand e)) (make-undef) x))) (nexts run))))
+ (check-flags (run arity &optional (direction 1)) ;checks if all the flags are compatible (true iff note aligned to the right and note to the left in the next segment)
+ (if (<= (length run) 1)
+ t
+ (let* ((flag1 (cdar run))
+ (flag2 (cdadr run))
+ (k1 (caar run))
+ (k2 (caadr run))
+ (rr01 (remove-silences (nth-value 3 (rq-best ktable inst (path-addi p arity direction) k1 flag1)) inst))
+ (ll02 (remove-silences (nth-value 2 (rq-best ktable inst (path-addi p arity (1+ direction)) k2 flag2)) inst)))
+ (if (or (and ll02 flag1) (and (null flag1) (or (null ll02) (null rr01))))
+ (check-flags (cdr run) arity (1+ direction))
+ nil)))))
+ (let* ((e (gethash p ktable))
+ (bests (best-best0 (entry-best e)))
+ (candidates (cand-cand0 (entry-cand e))))
+ (if (<= k (length bests)) ;if the k-th best has already been computed
+ (let ((result (k-list-ith (1- k) bests)))
+ (values (first result) (second result) (third result) (fourth result)))
+ (if (queue-empty candidates) ;if there is no candidate left (ie all the possible k-bests have already been computed)
+ (values nil (make-infinity))
+ (multiple-value-bind (w run cands) (queue-extract candidates) ;otherwise, compute the next best
+ (if (weight-infinityp w) ;if the only candidates left are impossible
+ (values nil (make-infinity))
+ (progn
+ (setf (cand-cand0 (entry-cand e)) cands)
+ (if (weight-defp w)
+ (progn
+ (process-next e run w)
+ (rq-best-top ktable inst k)) ;repeat until k-best is constructed
+ (let ((w0 (rq-eval-top ktable inst run)))
+ (if (weight-defp w0) ;if the weight of the candidate was undefined and has been successfully computed
+ (progn
+ (setf (cand-cand0 (entry-cand e)) (queue-reinsert cands w0 run))
+ (rq-best-top ktable inst k))
+ (rq-best-top ktable inst k))))))))))))) ;otherwise, the candidate cannot be weighted, discard it and retry with next
+
+(defun rq-eval-top (ktable inst run)
+ "Special rq-eval function for top-level subdivision (subdivision in beats, the weight functions are different)"
+ (let ((p (path-empty inst)))
+ (multiple-value-bind (e found) (gethash p ktable)
+ (labels ((best-weights (pkl) ;for each element of the list pkl of elements (path . k-index), get the k-th best for the given path. if impossible, return weight infinity, othewise, return the list of weights.
+ (if (null pkl)
+ nil
+ (let* ((current (first pkl))
+ (x (car current))
+ (k (cadr current))
+ (flag (cddr current))
+ (weight (nth-value 1 (rq-best ktable inst x k flag))))
+ (if (weight-infinityp weight)
+ (list (make-infinity))
+ (append (list weight) (best-weights (rest pkl)))))))
+ (weight-addall-top (wl)
+ (cond ((find-if #'weight-undefp wl) (make-undef))
+ ((find-if #'weight-infinityp wl) (make-infinity))
+ (t (multiple-value-bind (dl cl) (weight-split wl)
+ (weight-make (distance-addall dl) (complexity-addall-top cl) (input-precision inst) (input-gracepen inst)))))))
+ (assert found)
+ (let ((r (length run)))
+ (if (equalp 0 r) ;if we do not subdivise futher, ie we have a leaf, the distance is already computed and stored in e (function register-state)
+ (let ((d (entry-dist e))
+ (c (complexity-make1 ktable inst p e nil))
+ (penalty (when (atom (car (input-sch inst))) (car (input-sch inst))))) ;when tempi are not merged, we add a penalty to compensate the one added in complexity-addall-top
+ (weight-make d c (input-precision inst) (input-gracepen inst) :penalty penalty))
+ (let* ((pl (path-children p r))
+ (pkl (mapcar #'cons pl run))
+ (wl (best-weights pkl)))
+ (weight-addall-top wl))))))))
+
+
diff --git a/src/algorithm/ratio.lisp b/src/algorithm/ratio.lisp
new file mode 100644
index 0000000..bb440a5
--- /dev/null
+++ b/src/algorithm/ratio.lisp
@@ -0,0 +1,27 @@
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+;;; Functions to remove redundant solutions.
+;; Redundant runs are deleted in each entry of the table
+;; A run is considered redundant when it gives the same alignments to the left and right boundaries as the cas when the segment is not divided.
+;; Note that even when a run is deleted, the next candidates are still added to the cand list.
+
+
+(defun align-run (ktable inst p run)
+ "Returns the indexes of the notes aligned to the left and right bounds of the segment given by path, for the run given."
+ (if (null run)
+ (align ktable p)
+ (let* ((r (length run))
+ (path1 (path-addi p r 1))
+ (pathr (path-addi p r r)))
+ (multiple-value-bind (run1 weight1 ll1 rr1) (rq-best ktable inst path1 (caar run) (cdar run))
+ (multiple-value-bind (run1 weight1 ll2 rr2) (rq-best ktable inst pathr (caar (last run)) (cdar (last run)))
+ (values ll1 rr2))))))
+
+
+(defun is-redundant (ktable inst p ll rr)
+ "True iff the alignments ll and rr are the same as when the segment given by p is not divided any further."
+ (multiple-value-bind (ll1 rr1) (align ktable p)
+ (and (equalp ll1 ll) (equalp rr1 rr))))
diff --git a/src/algorithm/rq.lisp b/src/algorithm/rq.lisp
new file mode 100644
index 0000000..3e6fd4f
--- /dev/null
+++ b/src/algorithm/rq.lisp
@@ -0,0 +1,329 @@
+;;; K-best parsing for rhythm quantification
+;; Author : Adrien Ycart
+
+; The implemented algorithm is based on the one described in : Better k-best Parsing - L. Huang & D. Chiang, 2005
+
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+; A run is a list of couples (index flag).
+; If we consider a node that has n sons, the run will have n elements :
+; the first element is the index in the k-best list of the first son,
+; the second is the index in the k-best list of the second son,
+; etc.
+
+(defun run-make (flaglist)
+ (loop for flag in flaglist collect (cons 1 flag)))
+
+; An entry of the ktable.
+; ktable is a hashtable in which keys are paths
+
+(defstruct (entry)
+ (args) ; the list of possible next subdivisions (0 always belongs to the list, 0 means we don't subdivise further)
+ (dist) ; distance object, holding the distance computed considering the node given by path is a leaf (see distance.lisp)
+ (flagp) ;if flagp is nil, it means the gracenote flag cannot be true for this segment (no notes are aligned to the right)
+ (cand) ; heap holding candidate k-lists (ie couples (run . weight) for the next-best (initialized at (1 1 ... 1))) (see heap.lisp, run.lisp). runs can have different length (if different subdivisions are possible)
+ (best)) ; ordered list of bests (ie lists (run weight ll rr)). (see k-list.lisp, run.lisp). runs can have different length (if different subdivisions are possible)
+
+(defstruct (cand)
+ (cand1) ;list of candidates when the gracenote flag is 1
+ (cand0)) ;list of candidates when the gracenote flag is 0
+
+(defun entry-candidates (e flag)
+ (if flag
+ (cand-cand1 (entry-cand e))
+ (cand-cand0 (entry-cand e))))
+
+(defstruct (best)
+ (best1) ;list of bests when the gracenote flag is 1
+ (best0)) ;list of bests when the gracenote flag is 0
+
+(defun entry-bestlist (e flag)
+ (if flag
+ (best-best1 (entry-best e))
+ (best-best0 (entry-best e))))
+
+(defun cand-make (flagp)
+ (if (null flagp)
+ (make-cand :cand0 (empty-queue) :cand1 nil)
+ (make-cand :cand0 (empty-queue) :cand1 (empty-queue))))
+
+
+(defun print-table (table)
+ (let ((sts 0) ; number of states
+ (trs 0)) ; number of transitions
+ (flet ((print-entry (p e)
+ (let ((al (entry-args e))
+ (d (entry-dist e)))
+ (multiple-value-bind (ll lr) (distance-align d)
+ (progn
+ (print-path p)
+ (format t " : args = ~a left = ~a right = ~a~%" al ll lr)
+ (setq sts (1+ sts))
+ (setq trs (+ trs (length al))))))))
+ (progn
+ (format t "----------------------------------------------------------------------~%Transition table~%----------------------------------------------------------------------~%")
+ (maphash #'print-entry table)
+ (format t "----------------------------------------------------------------------~%")
+ (format t "states : ~d~%" sts)
+ (format t "transitions : ~d~%" trs)
+ (format t "----------------------------------------------------------------------~%")))))
+
+(defun puthash (key value ktable)
+ "add an entry to the hashtable"
+ (setf (gethash key ktable) value))
+
+(defun rq-linsert (e il)
+ "insert an element in the args list
+il : ordered int list without repetition"
+ (if (null il)
+ (list e)
+ (let ((a (car il)))
+ (cond ((< e a) (append (list e) il))
+ ((> e a) (append (list a) (rq-linsert e (rest il))))
+ (t il))))) ; a==e, we do not change anything (no repetition)
+
+(defun register-state (ktable inst p)
+ "create an entry, add it in the ktable (associated to path p) and return it
+also initialises the distance"
+ (let* ((dist (distance-make1 inst p))
+ (rr (nth-value 1 (distance-align dist)))
+ (flagp (not (null (remove-silences rr inst)))))
+ (puthash p (make-entry :args (list 0) :dist dist :flagp flagp :cand (cand-make flagp) :best (make-best)) ktable)))
+
+(defun inhabited (e)
+ "true iff there are input points in the interval defined by the path associated to e"
+ (distance-inhabitedp (entry-dist e)))
+
+(defun transitions (inst)
+ "construct transition table : create all the possible paths, and put it in the table associated to empty entries"
+ ;creation of a new table
+ (let ((ktable (make-hash-table :test 'equalp)))
+ (labels ((transitions-inner (inst schema p r i)
+ (progn
+ (transitions-state inst schema (path-addi p r i))
+ (if (equalp r i)
+ nil
+ (transitions-inner inst schema p r (1+ i)))))
+ (transitions-state (inst schema p)
+ (assert (null (nth-value 1 (gethash p ktable))))
+ (let ((e (register-state ktable inst p)))
+ (if (inhabited e)
+ (let* ((tops (schema-top schema))
+ (al (reduce #'rq-linsert tops :initial-value (entry-args e) :from-end t)))
+ (progn
+ (setf (entry-args e) al)
+ (map nil #'(lambda (x) (transitions-inner inst (schema-pop x schema) p x 1)) tops)))))))
+ (let ((rootp (path-empty inst)))
+ (transitions-state inst (input-sch inst) rootp))) ;add all transitions with target state rootp (path empty, the root of the derivation tree);
+ ktable))
+
+(defun init (ktable)
+ "initialises the candidates for the entries linked to each path created by the function transition
+each entry's candidate list is initialised with a list (1 1... 1) of length r for each subdivision r possible"
+ (labels ((init-cand (p e)
+ (map nil #'(lambda (x) (add-heap p x e)) (entry-args e)))
+ (add-heap (p n e)
+ (let ((lflagps (get-flagps-sons p n e))
+ (cand (entry-cand e))
+ (flagp (entry-flagp e)))
+ (labels ((add-run-flags (lflagps lastflag &optional (lflags nil))
+ (if (null lflagps) ;when all the possibilities are done
+ (if lastflag
+ (setf (cand-cand1 cand) (queue-insert (cand-cand1 cand) (make-undef) (run-make lflags)))
+ (setf (cand-cand0 cand) (queue-insert (cand-cand0 cand) (make-undef) (run-make lflags))))
+ (if (null (cdr lflagps)) ;when only the last flag is left
+ (add-run-flags (cdr lflagps) lastflag (append lflags (list lastflag)))
+ (if (car lflagps) ;if flagp is t, we add both 1 and 0 flags, only 0 otherwise.
+ (progn
+ (add-run-flags (cdr lflagps) lastflag (append lflags (list t)))
+ (add-run-flags (cdr lflagps) lastflag (append lflags (list nil))))
+ (add-run-flags (cdr lflagps) lastflag (append lflags (list nil))))))
+ ))
+ ;if (last lflagps) is nil, we add nothing to cand1, and we add all possible combinations in cand0
+ ;if (last lflagps) is t, we add all possible conbinations in cand1 and cand0
+ (if (or (and flagp (car (last lflagps))) (and flagp (null lflagps)))
+ (progn
+ (add-run-flags lflagps nil)
+ (add-run-flags lflagps t))
+ (add-run-flags lflagps nil)))))
+ (get-flagps-sons (p n e)
+ (loop for i from 1 to n collect (entry-flagp (gethash (path-addi p n i) ktable)))))
+ (maphash #'init-cand ktable)
+ ktable))
+
+(defun rq-eval (ktable inst p run flag)
+ "evaluate the weight of a tree given a run (ie the list of indices in the k-best list of each son)"
+ (labels ((best-weights (pkl) ;for each element of the list pkl of elements (path . k-index), get the k-th best for the given path. if impossible, return weight infinity, othewise, return the list of weights.
+ (if (null pkl)
+ nil
+ (let* ((current (first pkl))
+ (x (car current))
+ (k (cadr current))
+ (flag (cddr current))
+ (weight (nth-value 1 (rq-best ktable inst x k flag))))
+ (if (weight-infinityp weight)
+ (list (make-infinity))
+ (append (list weight) (best-weights (rest pkl))))))))
+ (multiple-value-bind (e found) (gethash p ktable)
+ (assert found)
+ (let ((r (length run)))
+ (if (equalp 0 r) ;if we do not subdivise futher, ie we have a leaf, the distance is already computed and stored in e (function register-state)
+ (let ((d (entry-dist e))
+ (c (complexity-make1 ktable inst p e flag)))
+ (weight-make d c (input-precision inst) (input-gracepen inst)))
+ (let* ((pl (path-children p r))
+ (pkl (mapcar #'cons pl run))
+ (wl (best-weights pkl)))
+ (weight-addall wl (input-precision inst) (input-gracepen inst))))))))
+
+
+
+(defmethod rq-best (ktable inst p k flag)
+ "returns the k-th best run and its weight given an input and a path (root if the tree for a whole measure is wanted)"
+ (labels ((process-next (e run w)
+ (multiple-value-bind (ll rr) (align-run ktable inst p run)
+ (if (or (and (not (null run)) (is-redundant ktable inst p ll rr)) (not (check-flags run (length run))))
+ () ;if the current run gives a redundant alignment (ie equivalent to not subdividing further), we only add the nexts to the cand list (we do not put the run in the best list)
+ (if flag ;if not, we add it to the list and add the nexts to the cand list
+ (setf (best-best1 (entry-best e)) (k-list-add run w ll rr (best-best1 (entry-best e))))
+ (setf (best-best0 (entry-best e)) (k-list-add run w ll rr (best-best0 (entry-best e))))))
+ (if flag
+ (map nil #'(lambda (x) (setf (cand-cand1 (entry-cand e)) (queue-insert (cand-cand1 (entry-cand e)) (make-undef) x))) (nexts run))
+ (map nil #'(lambda (x) (setf (cand-cand0 (entry-cand e)) (queue-insert (cand-cand0 (entry-cand e)) (make-undef) x))) (nexts run)))))
+ (check-flags (run arity &optional (direction 1)) ;checks if all the flags are compatible (true iff note aligned to the right and note to the left in the next segment)
+ (if (<= (length run) 1)
+ t
+ (let* ((flag1 (cdar run))
+ (flag2 (cdadr run))
+ (k1 (caar run))
+ (k2 (caadr run))
+ (rr01 (remove-silences (nth-value 3 (rq-best ktable inst (path-addi p arity direction) k1 flag1)) inst))
+ (ll02 (remove-silences (nth-value 2 (rq-best ktable inst (path-addi p arity (1+ direction)) k2 flag2)) inst)))
+ (if (or (and ll02 flag1) (and (null flag1) (or (null ll02) (null rr01))))
+ (check-flags (cdr run) arity (1+ direction))
+ nil)))))
+ (let* ((e (gethash p ktable))
+ (bests (entry-best e))
+ (best (if flag (best-best1 bests) (best-best0 bests)))
+ (candidates (entry-cand e))
+ (cand (if flag (cand-cand1 candidates) (cand-cand0 candidates))))
+ (if (<= k (length best)) ;if the k-th best has already been computed
+ (let ((result (k-list-ith (1- k) best)))
+ (values (first result) (second result) (third result) (fourth result)))
+ (if (queue-empty cand) ;if there is no candidate left (ie all the possible k-bests have already been computed)
+ (values nil (make-infinity))
+ (multiple-value-bind (w run cands) (queue-extract cand) ;otherwise, compute the next best
+ (if flag
+ (setf (cand-cand1 (entry-cand e)) cands)
+ (setf (cand-cand0 (entry-cand e)) cands))
+ (if (weight-defp w)
+ (progn
+ (process-next e run w)
+ (rq-best ktable inst p k flag)) ;repeat until k-best is constructed
+ (let ((w0 (rq-eval ktable inst p run flag)))
+ (if (weight-defp w0) ;if the weight of the candidate was undefined and has been successfully computed
+ (progn
+ (if flag
+ (setf (cand-cand1 (entry-cand e)) (queue-reinsert cands w0 run))
+ (setf (cand-cand0 (entry-cand e)) (queue-reinsert cands w0 run)))
+ (rq-best ktable inst p k flag))
+ (rq-best ktable inst p k flag)))))))))) ;otherwise, the candidate cannot be weighted, discard it and retry with next
+
+(defun nexts (list)
+ "given a run (i1, i2, ... , in), returns a list of n runs (i1+1, i2, ..., in), (i1, i2+1, ... , in), ..., (i1, i2, ... , in+1)"
+ (if (null list)
+ nil
+ (let* ((a (car list))
+ (l (rest list))
+ (n (append (list (cons (1+ (car a)) (cdr a))) l)))
+ (append (list n) (reverse (mapcar #'(lambda (x) (append (list a) x)) (nexts l)))))))
+
+(defmethod align (ktable p)
+ "Returns the list of input points aligned to the left and to the right of the segment given by p"
+ (distance-align (entry-dist (gethash p ktable))))
+
+(defmethod notes-align (ktable inst p)
+ "Returns the list of input NOTES aligned to the left and to the right of the segment given by p (rests are discarded)"
+ (distance-notes-align (entry-dist (gethash p ktable)) inst))
+
+(defun rq-printk (ktable inst k)
+ (let ((rootp (path-empty inst)))
+ (multiple-value-bind (run w) (rq-best ktable inst rootp k)
+ (progn
+ (format t "~%~d-best = ~%" k)
+ (format t "weight=")
+ (print-weight w)
+ (format t " run=~a ~%" run)))))
+
+(defun remove-silences (list inst)
+ "Removes from the list all the input points that correspond to the beginning of a rest (not in-place)"
+ (remove-if #'(lambda (x) (input-silencep inst x)) list))
+
+(defun rq-to-ratio-from-top (ktable inst k &optional (slur nil))
+ (let ((out nil)
+ (prev (if slur 1 -1))
+ (grace 0))
+ (labels ((to-ratio (p k)
+ (multiple-value-bind (run w) (rq-best ktable inst p k)
+ (let ((r (length run)))
+ (if (zerop r)
+ ;if we have a leaf
+ (let ((len (path-len p)))
+ (multiple-value-bind (ll rr) (align ktable p)
+ ;processing ll
+ (if (null ll) ;if there are no inputs aligned to the left
+ (if (> grace 0) ;if there were notes aligned to the right in the previous subdivision
+ (if (equalp grace 1) ;if there is only one note
+ (setq out (append out (list len)))
+ (setq out (append out (make-list (1- grace) :initial-element 0) (list len))))
+ ;if there is no input in the subdivision and there was no note aligned to the right before
+ (if (equalp prev 1)
+ (if (> (car (last out)) 0)
+ (setf (car (last out)) (+ (car (last out)) len))
+ (setq out (append out (list len))))
+ (if (> (car (last out)) 0)
+ (setq out (append out (list (- len))))
+ (setf (car (last out)) (- (car (last out)) len)))))
+ ;if there are inputs aligned to the left
+ (if (and (equalp grace 0) (equalp (length ll) 1))
+ (setq out (append out (list (* (input-sign inst (car ll)) len)))) ;if there is only 1 input aligned to the left
+ (let ((ll0 (remove-silences ll inst)))
+ (if (null ll0) ;if there are only rests aligned to the left (at least 1)
+ (if (> grace 0) ;if there were notes aligned to the right in the previous subdivision
+ (if (equalp grace 1) ;if there is only one note
+ (setq out (append out (list len)))
+ (setq out (append out (make-list (1- grace) :initial-element 0) (list len))))
+ ;if there are only rests in the subdivision and there was no note aligned to the right before
+ (setq out (append out (list (- len)))))
+ ;if there are notes aligned to the left
+ (if (and (equalp (length ll0) 1) (equalp grace 0)) ;if there is exactly one note aligned to the left
+ (setq out (append out (list len)))
+ ;if there is more than 1 note aligned to the left or at least 1 note aligned to the right before and 1 to the left in this subdivision
+ (setq out (append out (make-list (1- (+ grace (length ll0))) :initial-element 0) (list len))))))))
+ ;processing rr
+ (if (null rr)
+ (if (not (null ll))
+ (setq prev (input-sign inst (car (last ll)))) ;if there are no notes aligned to the right, but there are some to the left
+ ;if there are no notes in the subdivision, we do nothing
+ )
+ (setq prev (input-sign inst (car (last rr)))))
+ (setq grace (length (remove-silences rr inst)))))
+ ;if run is a list, ie, if we subdivise further
+ (loop for i from 1 to r
+ for krun in run
+ do (to-ratio (path-addi p r i) krun)))))))
+ (let* ((p (path-empty inst))
+ (len-tot (path-len p)))
+ (to-ratio (path-empty inst) k)
+ (mapcar #'(lambda (x) (/ x len-tot)) out)))))
+
+(in-package :om)
+
+;;OBSOLETE : TODO : adapt to the new best and cand structures
+;;Not used in the newer save functions : instead of being saved, the table is recomputed each time the patch is opened
+(defmethod om::omng-save ((self rq::entry) &optional values?)
+ `(let ((best ,(append (list `list) (mapcar #'(lambda (elt) `(list ',(first elt) ,(om::omng-save (second elt)) ',(third elt) ',(fourth elt))) (rq::entry-best self)))))
+ (rq::make-entry :args ',(rq::entry-args self) :dist ,(om::omng-save (rq::entry-dist self)) :cand ,(om::omng-save (rq::entry-cand self)) :best best )))
diff --git a/src/algorithm/structure/complexity.lisp b/src/algorithm/structure/complexity.lisp
new file mode 100644
index 0000000..1fc9107
--- /dev/null
+++ b/src/algorithm/structure/complexity.lisp
@@ -0,0 +1,116 @@
+;;; Complexity
+;; Author : Adrien Ycart
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+(defstruct (complexity
+ (:print-function print-complexity))
+ (arity) ; Holds the number of each arities in the subtree (the ith element is the number of subtrees of arity i+1 (i from 0 to 18)). The arities are ordered by complexity as follows : 1 2 4 3 6 5 8 7 10 12 16 9 14 11 13 15 17...
+ (depth) ; Complexity value for the depth : propotional to the depth of the sub-tree
+ (gracenotes) ; Complexity value for the grace notes.
+ (val))
+
+; order of arities (taken from omquantify) :
+;1 2 4 3 6 5 8 7 10 12 16 9 14 11 13 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
+
+(defun print-complexity (c &optional (stream t) (depth 0))
+ (format stream "[a=~d; d=~d; g=~d; val=~d]"
+ (complexity-arity-reduce (complexity-arity c))
+ (complexity-depth c)
+ (complexity-gracenotes c)
+ (complexity-val c)))
+
+(defun complexity-make (c) c)
+
+(defun complexity-make1 (ktable inst p e flag)
+ (make-complexity :val nil :arity (make-array 19 :initial-element 0) :depth 1 :gracenotes (complexity-get-gracenotes ktable inst p e flag)))
+
+(defun complexity-get-gracenotes (ktable inst p e flag)
+ ""
+ (let ((d (entry-dist e))
+ (grace (if flag 1 0)))
+ (multiple-value-bind (ll0 rr0) (notes-align ktable inst p)
+ (if (> (length ll0) 1)
+ (setq grace (+ grace (1- (length ll0)))))
+ (if (> (length rr0) 1)
+ (setq grace (+ grace (1- (length rr0)))))
+ grace)))
+
+(defun complexity-value (c &optional (gracepen 2))
+ ""
+ (if (complexity-val c)
+ (complexity-val c)
+ (let ((ca (complexity-arity c))
+ (cd (complexity-depth c))
+ (cg (complexity-gracenotes c)))
+ (setf (complexity-val c) (+ (* 1 (complexity-arity-reduce ca)) (* 0 cd) (* gracepen cg))))))
+
+(defun complexity-min (l)
+ (reduce #'min l))
+
+(defun complexity-addall (cl)
+ (+ (1- (length cl)) (* 2.0 (reduce #'+ cl)))); 2*(sum of elements) + (arity -1)
+
+(defun complexity-addall1 (cl)
+ (let ((al (mapcar #'complexity-arity cl))
+ (dl (mapcar #'complexity-depth cl))
+ (gl (mapcar #'complexity-gracenotes cl)))
+ (make-complexity :arity (complexity-arity-addall al) :depth (complexity-depth-addall dl) :gracenotes (reduce #'+ gl) :val nil)))
+
+(defun complexity-addall-top (cl)
+ (let ((cvals (mapcar #'complexity-value cl)))
+ ; (print "test")
+ (make-complexity :val (+ (reduce #'+ cvals) (length cl)) ;we add (length cl) in order to penalize the cases where the tempo is fast and results in an all-quarternotes transcription
+ :arity (make-array 19 :initial-element 0)
+ :depth 0
+ :gracenotes 0)))
+
+;when arity is just an integer and not a vector
+(defun complexity-arity-addall1 (al)
+ (let ((order '(1 2 4 3 6 5 8 7 10 12 16 9 14 11 13 15 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50)))
+
+ (flet ((get-weight (a)
+ (position a order)))
+ (* (get-weight (length al)) (reduce #'+ al)))))
+
+(defun complexity-arity-addall (al)
+ "adds the arities in the entry list and returns the arity correponding to the sum"
+ (let ((out (make-array 19 :initial-element 0)))
+ (labels ((arity-add (alist buffer)
+ (let ((current (car alist)))
+ (if (null current)
+ buffer
+ (progn
+ (loop for i from 0 to 18 do (setf (aref buffer i) (+ (aref buffer i) (aref current i))))
+ (arity-add (cdr alist) buffer))))))
+ (arity-add al out))
+ (setf (aref out (1- (length al))) (1+ (aref out (1- (length al)))))
+ out))
+
+(defun complexity-arity-reduce (a)
+ "returns a score for the arity given as entry"
+ (reduce #'+ (mapcar #'(lambda (x y) (* x y)) (coerce a 'list) (list 0 1 3 2 5 4 7 6 11 8 13 9 14 12 15 10 16 17 18))))
+
+
+(defun complexity-depth-addall (dl)
+ (1+ (reduce #'max dl)))
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::complexity) &optional values?)
+ (labels ((serialize-arities (arities)
+ (loop for i from 0 to 18 unless (zerop (aref arities i))
+ collect (list i (aref arities i)))))
+ `(load-complexity ',(serialize-arities (rq::complexity-arity self)) ,(rq::complexity-depth self) ,(rq::complexity-gracenotes self))))
+
+(defmethod load-complexity (aritylist depth gracenotes)
+ (let ((arities (make-array 19 :initial-element 0)))
+ (labels ((make-arities (list)
+ (when list
+ (setf (aref arities (caar list)) (cadar list))
+ (make-arities (cdr list)))))
+ (make-arities aritylist)
+ (rq::make-complexity :arity arities :depth depth :gracenotes gracenotes))))
+
diff --git a/src/algorithm/structure/distance.lisp b/src/algorithm/structure/distance.lisp
new file mode 100644
index 0000000..09611bd
--- /dev/null
+++ b/src/algorithm/structure/distance.lisp
@@ -0,0 +1,137 @@
+;;; Distance run-input (pointwise distance) and computation of alignment to paths
+;; Adrien Ycart
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+; Distance is represented by a vector of size N (with N the number of inputs). Given a certain path, the nth element of the vector is the distance between the nth input and the nearest bound of the segment represented by path.
+; Mask is a vector of size N. mask[i] = 0 if ith input is outside of the interval
+; -1 if ith input is aligned to the left of the interval
+; 1 if ith input is aligned to the right of the interval
+(defstruct (distance
+ (:constructor make-distance ( vec mask res val &optional (normalized nil)))
+ (:constructor empty-distance (&optional (vec #()) (mask #()) (res 0) (val 0.0) (normalized nil))))
+ (vec nil :type array)
+ (mask nil :type array)
+ (res 0 :type integer) ; resolution as in input
+ (val 0 :type float) ; value of the distance (norm of vector vec)
+ (normalized nil :type boolean)) ; true iff val is the computed norm of the current distance vector vec (in that cas we don't have to compute it again)
+
+(defun aset (array index value)
+ "to set a value in an array"
+ (setf (aref array index) value))
+
+(defun distance-dim (dist)
+ (length (distance-vec dist)))
+
+(defun distance-inhabitedp (dist)
+ "true iff there are input points in the segment corresponding to the path considered"
+ (notevery #'(lambda (x) (equalp 0 x)) (distance-mask dist)))
+
+(defun distance-align (dist)
+ " return a pair of lists (ll, lr). ll (respectively lr) is the list of indexes of points in the input instance aligned to the left (right) bound of the interval defined by p "
+ (labels ((align1 (ll lr i list)
+ (let ((val (car list))
+ (l (cdr list)))
+ (cond ((null list) (values (reverse ll) (reverse lr)))
+ ((equalp val -1) (align1 (cons i ll) lr (1+ i) l))
+ ((equalp val 1) (align1 ll (cons i lr) (1+ i) l))
+ ((equalp val 0) (align1 ll lr (1+ i) l))
+ (t (error "error in distance-align"))))))
+ (align1 nil nil 1 (coerce (distance-mask dist) 'list))))
+
+(defun distance-notes-align (dist inst)
+ (multiple-value-bind (ll rr) (distance-align dist)
+ (values (remove-silences ll inst) (remove-silences rr inst))))
+
+(defun distance-make (dim res)
+ (make-distance (make-array dim :initial-element 0.0) (make-array dim :initial-element 0) res 0.0 nil))
+
+(defun distance-make0 (inst)
+ (distance-make (input-dim inst) (input-res inst)))
+
+(defun distance-make1 (inst p)
+ "returns a distance stucture holding the pointwise distance for the alignment of the subarray of inputs between the bounds of the interval given by p to the nearest bound of the interval."
+ (let ((pleft (path-left p))
+ (pright (path-right p))
+ (linput (coerce (input-input inst) 'list))
+ (dist (distance-make0 inst)))
+ (labels ((make11 (pl pr d i li)
+ (if (null li)
+ d
+ (let ((a (car li))
+ (l (cdr li)))
+ (if (< a pl)
+ (make11 pl pr d (1+ i) l) ;point i out of interval of p (i not treated, we treat the next one)
+ (if (< a pr) ;point i inside interval
+ (let ((dtol (- a pl)) ;distance to left
+ (dtor (- pr a)));distance to right
+ (if (< dtol dtor)
+ (progn ;align to left
+ (aset (distance-vec d) i dtol)
+ (aset (distance-mask d) i -1)
+ (make11 pl pr d (1+ i) l))
+ (progn ;align to right
+ (aset (distance-vec d) i dtor)
+ (aset (distance-mask d) i 1)
+ (make11 pl pr d (1+ i) l))
+ ))
+ d ;point i and following outside of p
+ ))))))
+ (make11 pleft pright dist 0 linput))))
+
+(defun distance-add (dist1 dist2)
+ "adds two distances. The modification is done in-place, the result is stored in dist1. The norm is not computed"
+ (let ((dim (distance-dim dist1))
+ (d1 (distance-vec dist1))
+ (d2 (distance-vec dist2))
+ (m1 (distance-mask dist1))
+ (m2 (distance-mask dist2)))
+ (progn
+ (loop for i from 0 to (- dim 1)
+ do
+ (aset d1 i (+ (aref d1 i) (aref d2 i)))
+ (aset m1 i (+ (aref m1 i) (aref m2 i))))
+ (setf (distance-normalized dist1) nil) ;distance vector is modified, we have to recompute the norm
+ dist1)))
+
+(defun distance-addall (dlist)
+ "adds all the vectors in dlist. The norm is not computed"
+ (let* ((d1 (car dlist))
+ (d0 (distance-make (distance-dim d1) (distance-res d1))))
+ (reduce #'distance-add dlist :initial-value d0)))
+
+(defun minkowski (vec n)
+ (expt (reduce #'(lambda (y x) (+ y (expt x n))) vec :initial-value 0.0) (/ 1 n)))
+
+(defun sum (vec)
+ (minkowski vec 1))
+
+(defun euclidian (vec)
+ (minkowski vec 2))
+
+(defun cubic (vec)
+ (minkowski vec 3))
+
+(defun distance-norm (dist)
+ "if not already computed, computes the norm of the distance vector, and in both cases, returns it"
+ (if (distance-normalized dist)
+ (distance-val dist)
+ (let ((res (float (distance-res dist))))
+ (progn
+ (setf (distance-val dist) (/ (sum (distance-vec dist)) res))
+ (setf (distance-normalized dist) t)
+ (distance-val dist)))))
+
+(defun distance-to-float (dist)
+ (distance-norm dist))
+
+(defun distance-normalized-by-length (dist path)
+ (let ((length (float (path-len path))))
+ (/ (sum (distance-vec dist)) length)))
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::distance) &optional values?)
+ `(rq::make-distance ,(rq::distance-vec self) ,(rq::distance-mask self) ,(rq::distance-res self) ,(rq::distance-val self) ,(rq::distance-normalized self)))
diff --git a/src/algorithm/structure/heap.lisp b/src/algorithm/structure/heap.lisp
new file mode 100644
index 0000000..1d10ea7
--- /dev/null
+++ b/src/algorithm/structure/heap.lisp
@@ -0,0 +1,167 @@
+;;; Priority Queue ;;;
+;; Author : Adrien Ycart
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+;; A heap used to hold all the candidates
+
+(defstruct (heap (:print-function print-queue))
+ (elts) ; a list of all the elements that have already been created. Used to forbid duplicates.
+ (queue)) ; the queue containing all the elements and their weights. It is a node structure.
+
+(defstruct (node
+ (:constructor make-node ( w elt left right &optional (empty nil)))
+ (:constructor empty-node (&optional (w nil) (elt nil) (left nil) (right nil) (empty t)))
+ (:print-function print-node ))
+ (w) ; weight of the candidate (see weight.lisp)
+ (elt ) ; the run associated to the candidate (see run.lisp)
+ (left ) ; the left tree of the current node (a node structure)
+ (right ) ; the right tree of the current node (a node structure)
+ (empty t :type boolean)) ; true iff the node is empty
+
+(defun make-queue (w elt left right &optional (empty nil))
+ (make-heap :elts nil :queue (make-node w elt left right empty)))
+
+(defun empty-queue (&optional (w nil) (elt nil) (left nil) (right nil) (empty t))
+ (make-heap :elts nil :queue (empty-node w elt left right empty)))
+
+(defun queue-empty (heap)
+ (or (node-empty (heap-queue heap))
+ (weight-infinityp (node-w (heap-queue heap)))))
+
+(defun print-node (queue stream depth)
+ (if (node-empty queue)
+ (format stream "~A EMPTY" (make-sequence 'string depth :initial-element #\Space))
+ (progn
+
+ (format stream "~A([~D, ~A]~%"
+ (make-sequence 'string depth :initial-element #\Space) ;pour indanter l'affichage
+ (node-w queue)
+ (node-elt queue)
+ )
+ (print-node (node-left queue) stream (1+ depth))
+ (format stream "~%")
+ (print-node (node-right queue) stream (1+ depth))
+ (format stream "~%~A)" (make-sequence 'string depth :initial-element #\Space)))))
+
+(defun print-queue (heap stream depth)
+ (print-node (heap-queue heap) stream depth))
+
+
+
+
+(defun queue-insert (heap weight elt)
+ "Insert an element in the heap if it has not already been created (NOT in-place)"
+ (if (find elt (heap-elts heap) :test #'equalp)
+ ;if the element has been created before, we do not add it, we return the heap not modified
+ heap
+ ;if the element is new, we put it in the heap and we add it to elts
+ (make-heap :elts (append (heap-elts heap) (list elt)) :queue (queue-insert1 (heap-queue heap) weight elt))))
+
+;; Insert an element in the heap (takes a node as entry)
+(defun queue-insert1 (queue weight elt)
+
+ (if (node-empty queue)
+ (make-node weight elt (empty-node) (empty-node))
+ (let
+ ((w (node-w queue))
+ (e (node-elt queue))
+ (left (node-left queue) )
+ (right (node-right queue)))
+
+ (if (<= (weight-compare weight w) 0 )
+ (make-node weight elt (queue-insert1 right w e ) left) ;we add the node at this place and we switch the left and right trees
+ (make-node w e (queue-insert1 right weight elt) left ))))) ;we add the node in the left tree and we switch the left and right trees (in order to equilibrate the tree)
+
+
+
+
+
+
+
+(defun queue-reinsert (heap weight elt)
+ "Insert back an element after it has been evaluated"
+ (make-heap :elts (heap-elts heap) :queue (queue-insert1 (heap-queue heap) weight elt))
+)
+
+
+
+;; Error when a queue is empty
+(define-condition queue-is-empty (error)
+ ()
+ (:report (lambda (condition stream)
+ (format stream "Queue is empty !"))))
+
+
+
+(defun queue-top (heap)
+ "returns the smallest element of the heap"
+ (let ((queue (heap-queue heap)))
+ (if (node-empty queue)
+ (error (make-condition 'queue-is-empty))
+ (values (node-elt queue) (node-w queue)))))
+
+
+
+(defun queue-remove-top (queue)
+ "removes the smallest element of the heap"
+
+ (if (node-empty queue)
+ (error (make-condition 'queue-is-empty))
+ (let
+ ((w (node-w queue))
+ (e (node-elt queue))
+ (left (node-left queue) )
+ (right (node-right queue) ))
+ (cond
+ ((node-empty left)
+ right)
+ ((node-empty right)
+ left)
+ (t
+ (let
+ ((lw (node-w left))
+ (le (node-elt left))
+ (rw (node-w right))
+ (re (node-elt right)))
+ (if (<= (weight-compare lw rw) 0)
+ (make-node lw le (queue-remove-top left) right)
+ (make-node rw re left (queue-remove-top right)))
+ ))))))
+
+
+
+
+
+
+(defun queue-extract (heap)
+ "given a heap, returns the smallest weight, the corresponding run, and the heap with the smallest element removed"
+ (let ((queue (heap-queue heap)))
+ (if (node-empty queue)
+ (error (make-condition 'queue-is-empty))
+ (values (node-w queue) (node-elt queue) (make-heap :elts (heap-elts heap) :queue (queue-remove-top queue))))))
+
+
+
+
+
+;;;===================
+;;; Save
+;;;===================
+
+
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::heap) &optional values?)
+ `(rq::make-heap :elts ',(rq::heap-elts self) :queue ,(om::omng-save (rq::heap-queue self))))
+
+(defmethod om::omng-save ((self rq::node) &optional values?)
+ (if (rq::node-empty self)
+ `(rq::empty-node)
+ `(let ((left ,(om::omng-save (rq::node-left self)))
+ (right ,(om::omng-save (rq::node-right self)))
+ (w ,(om::omng-save (rq::node-w self))))
+ (rq::make-node w ',(rq::node-elt self) left right ,(rq::node-empty self)))))
diff --git a/src/algorithm/structure/input.lisp b/src/algorithm/structure/input.lisp
new file mode 100644
index 0000000..8ad7b0f
--- /dev/null
+++ b/src/algorithm/structure/input.lisp
@@ -0,0 +1,90 @@
+;;;; Problem input
+;;; v.1 input = sequence of dates (float) in [0..t] starting with 0, ending with t
+;;;
+;;; input represents a sequence of onsets.
+;;; Each onset corresponds to a note or a silence, depending on the value of mask (1: note, -1: silence)
+;;; The duration of this note is given by the difference between two successive onsets.
+;;; The first element of input is always 0.0, the last is the end of the last note (= the beginning of the first of the next segment)
+;;; The last value of the mask doesn't matter : the last element of input is not a note but the marker of the end of the segment
+;;;
+;;; input is given by a sequence of dates
+;;; = float array of length > 1
+;;;
+;;;
+;;; v.1 normalized input = sequence of dates (float) in [0..RES] starting with 0, ending with RES
+;;; RES is resolution value
+;;; 0 is the first sample of the current segment
+;;; RES-1 is the last sample of the current segment
+;;; RES is the first sample of the next segment
+;;;
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+
+(defstruct (input)
+ (sch) ;subdivision schema (see subdivision.lisp)
+ (rinput nil :type array) ;input as described above, not normalized
+ (mask nil :type array) ;vector of same size as input : 1 means note, -1 means silence
+ (res ) ;resolution of the schema
+ (input nil :type array) ;input normalized
+
+ (precision) ;precision parameter to determine the relative importance of the complexity and distance measures
+ (gracepen)) ;penalty weight for gracenotes
+
+(defun input-emptyp (in)
+ (equalp (length (input-input in)) 0))
+
+
+(defun input-dim (in)
+ "dimension of the input"
+ (length (input-input in)))
+
+(defun input-dur (in)
+ "duration of the input"
+ (aref (input-rinput in) (1- (length (input-rinput in)))))
+
+
+(defun input-sample (ri mask res)
+ "normalises and samples the array to float values in [0..res]"
+ (let* ((nb (length ri))
+ (fres (float res))
+ (max (if (equalp nb 0)
+ 0.0
+ (aref ri (1- nb)))))
+ ;if ri doesn't begin with 0.0, we add it, and assume it begins with a silence
+ (assert (equalp (length ri) (length mask)))
+ (cond ((equalp (length ri) 0) (values (map 'vector #'(lambda (x) (* (/ x max) fres)) ri) mask))
+ ((equalp (aref ri 0) 0.0) (values (map 'vector #'(lambda (x) (* (/ x max) fres)) ri) mask))
+ (t (let ((ri0 (coerce (append (list 0.0) (coerce ri 'list)) 'vector))
+ (mask0 (coerce (append (list -1) (coerce mask 'list)) 'vector)))
+ (values (map 'vector #'(lambda (x) (* (/ x max) fres)) ri0) mask0))))))
+
+(defun input-make (s ri mask precision gracepen)
+ (let ((res (schema-resolution s)))
+ (multiple-value-bind (rs mask) (input-sample ri mask res)
+ (if (equalp (length ri) 0)
+ (make-input :sch s :rinput ri :mask mask :res res :input rs :precision precision :gracepen gracepen)
+ ;we delete the last element (boundary limit, is the first element of the next segment)
+ (make-input :sch s :rinput ri :mask (subseq mask 0 (1- (length mask))) :res res :input (subseq rs 0 (1- (length rs))) :precision precision :gracepen gracepen)))))
+
+
+(defun input-sign (inst index)
+ "returns 1 if the input point at position index is a note, -1 if it is a rest"
+ (aref (input-mask inst) (1- index)))
+
+(defun input-silencep (inst index)
+ (equalp (input-sign inst index) -1))
+
+(defun input-print (inst)
+ (let ((lr (coerce (input-rinput inst) 'list))
+ (li (coerce (input-input inst) 'list)))
+ (progn
+ (format t "__________________________________~%Problem Instance~%__________________________________~%")
+ (format t "resolution : ~D ~%dimension : ~D ~%rinput : ~S ~%input : ~S ~%" (input-res inst) (input-dim inst) (input-rinput inst) (input-input inst)))))
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::input) &optional values?)
+ `(rq::make-input :sch ',(rq::input-sch self) :rinput ,(rq::input-rinput self) :mask ,(rq::input-mask self) :res ,(rq::input-res self) :input ,(rq::input-input self)))
diff --git a/src/algorithm/structure/k-best.lisp b/src/algorithm/structure/k-best.lisp
new file mode 100644
index 0000000..a6fe6e9
--- /dev/null
+++ b/src/algorithm/structure/k-best.lisp
@@ -0,0 +1,127 @@
+(use-package :om :rq)
+(in-package :rq)
+
+
+;;; The k-best structure is the structure holding all the elements relative to the k-best algorithm
+
+(defclass! k-best ()
+ ((ktables :accessor ktables :initform nil :initarg :ktables) ;list of hashtables (might have only 1 element)
+ (inputs :accessor inputs :initform nil :initarg :inputs) ;list of input structures (might only have 1 element). The ktables and inputs lists always have the same number of elements.
+ (slur :accessor slur :initform nil :initarg :slur) ; nil or a number, indicates if each measure has to be slurred with the previous
+ (gracenotes :accessor gracenotes :initform nil :initarg :gracenotes) ;list of size n-solution, indicates the number of grace notes to be added in the next measure for each solution
+ (n-solution :accessor n-solution :initform nil :initarg :n-solution) ;number of solutions per automaton
+ (tempomerge :accessor tempomerge :initform nil :initarg :tempomerge) ;true iff there is 1 input for all tempi
+ ))
+
+(defun k-best-to-poly (k-best &optional (chords (list 6000)))
+ "Generates poly objects"
+ (let* ((ktables (ktables k-best))
+ (inputs (inputs k-best))
+ (N (length ktables))
+ (slur (slur k-best))
+ (n-solution (n-solution k-best))
+ (gracenotes (append (loop for n from 1 to N collect (make-list list-n-solution :initial-element 0)) (gracenotes k-best))))
+ (k-best-create-poly ktables inputs n-solution slur gracenotes chords)))
+
+(defun k-best-create-poly (ktables inputs n-solution slur gracenotes tempomerge &optional (chords '(6000)))
+ "Creates a poly containing all the computed solutions"
+
+ ;Always output a couple of lists (one for the sigs, one for the tempi) of size (length inputs), composed of lists of size n-solution
+ (labels ((get-signatures-and-tempi (ktables insts n-solution)
+ (let ((segment-dur (aref (input-rinput (car inputs)) (1- (length (input-rinput (car inputs)))))))
+ ;when there is only 1 input (tempi merged)
+ (if tempomerge
+ (let* ((ktable (car ktables))
+ (inst (car insts))
+ (sigs (loop for k from 1 to n-solution collect (get-signature ktable inst tempomerge k))))
+ (values
+ (list sigs)
+ (list (mapcar #'(lambda (sig) (round (* (/ 60000 segment-dur) (car sig)))) sigs))))
+ ;when there are multiple inputs (1 automaton per tempo)
+ (let ((sigs (loop for inst in insts
+ for ktable in ktables
+ collect
+ (loop for k from 1 to n-solution collect (get-signature ktable inst tempomerge)))))
+ (values
+ sigs
+ (loop for list in sigs
+ collect (mapcar #'(lambda (sig) (round (* (/ 60000 segment-dur) (car sig)))) list))))))))
+ (let* ((trees nil)
+ (N (length ktables)))
+ (multiple-value-bind (signatures tempi) (get-signatures-and-tempi ktables inputs n-solution)
+ (setq trees (loop for n from 0 to (1- N) collect
+ (loop for k from 1 to n-solution collect (rq-remove-top-level (rq-to-omtree (nth n ktables) (nth n inputs) k nil slur (nth (1- k) (nth n gracenotes)))))))
+ (setq trees (loop for n from 0 to (1- N) collect
+ (mapcar #'(lambda (sig tree) (list (list sig tree))) (nth n signatures) (nth n trees))))
+ (setq trees (loop for n from 0 to (1- N) collect
+ (mapcar #'(lambda (x) (append (list '?) (list x))) (nth n trees))))
+ (make-instance 'poly
+ :voices (loop for n from 0 to (1- N)
+ append (mapcar #'(lambda (rtree tempo) (make-instance 'voice
+ :tree (reducetree rtree)
+ :chords chords
+ :tempo tempo))
+ (nth n trees) (nth n tempi))))))))
+
+
+(defmethod get-signature (table input tempomerge &optional (k 1))
+ "Gets the signature of a particular solution : (number-of-pulses 4)"
+ (if tempomerge
+ (list (max (length (rq-best table input (path-empty input) k nil)) 1) 4)
+ (list (or (car (input-sch input)) 1) 4))
+)
+
+(defmethod get-tempi-weigths-ks (k-best)
+ "Returns the list of tempi with no doubles, with corresponding weights and indexes"
+ (let ((tempi nil)
+ (weights nil)
+ (ks nil))
+ (if (tempomerge k-best)
+ (let* ((ktable (car (ktables k-best)))
+ (input (car (inputs k-best)))
+ (input-dur (input-dur input)))
+ (loop for i from 1 to (n-solution k-best)
+ do
+ (let* ((n-beats (max (length (rq-best ktable input (path-empty input) i nil)) 1))
+ (tempo (round (* (/ 60000 input-dur) n-beats))))
+ (unless (find tempo tempi)
+ (setq tempi (append tempi (list tempo))
+ weights (append weights (list (rq::weight-val (nth-value 1 (rq::rq-best-top ktable input i)))))
+ ks (append ks (list (1- i))))))))
+ (let ((ktables (ktables k-best))
+ (inputs (inputs k-best))
+ (n-solution (n-solution k-best)))
+ (loop for ktable in ktables
+ for input in inputs
+ for i = 0 then (+ i n-solution)
+ do
+ (setq tempi (append tempi (list (round (* (/ 60000 (rq::input-dur input)) (car (rq::input-sch input)))))))
+ (setq weights (append weights (list (rq::weight-val (nth-value 1 (rq::rq-best-top ktable input 1))))))
+ (setq ks (append ks (list i))))))
+ (values tempi weights ks)
+))
+
+
+
+(defmethod get-distances (k-bests)
+ "Returns a list containing all the distances for all the computed solutions"
+ (loop for k-best in k-bests collect
+ (let* ((inputs (inputs k-best))
+ (ktables (ktables k-best))
+ (n-solution (n-solution k-best)))
+ (loop for ktable in ktables
+ for input in inputs append
+ (loop for k from 1 to n-solution collect
+ (/ (round (* 1000 (weight-distance (nth-value 1 (rq-best-top ktable input k))))) 10.0)))))) ;distance in percents, rounded to 1 decimal
+
+
+(in-package :om)
+
+;; Not used anymore : the k-bests are recomputed each time a patch is opened
+(defmethod om::omng-save ((self rq::k-best) &optional values?)
+ `(let ((ktables ,(append (list `list) (mapcar #'(lambda (elt) (om::omng-save elt)) (rq::ktables self))))
+ (inputs ,(append (list `list) (mapcar #'(lambda (elt) (om::omng-save elt)) (rq::inputs self))))
+ (slur ,(rq::slur self))
+ (gracenotes ',(rq::gracenotes self))
+ (n-solution ,(rq::n-solution self)))
+ (make-instance 'rq::k-best :ktables ktables :inputs inputs :slur slur :gracenotes gracenotes :n-solution n-solution)))
diff --git a/src/algorithm/structure/k-list.lisp b/src/algorithm/structure/k-list.lisp
new file mode 100644
index 0000000..075721e
--- /dev/null
+++ b/src/algorithm/structure/k-list.lisp
@@ -0,0 +1,24 @@
+;;;; Storage of k elements sorted by weight
+;;; k list is a list whose elements are lists of the form :
+;;; (run weight ll rr), with weights sorted in reverse order
+;;; (the first element of the list is the greatest)
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+(defun k-list-empty () nil)
+
+(defun k-list-length (list)
+ (length list))
+
+(defun k-list-add (x w ll rr list)
+ (if (null list)
+ (list (list x w ll rr))
+ (progn
+ (assert (<= (weight-compare (second (first list)) w) 0))
+ (append (list (list x w ll rr)) list))))
+
+(defun k-list-ith (i list)
+ "returns the ith greatest element. (k-list-ith 0 list) returns the smallest element in list"
+ (nth (1- (- (length list) i)) list))
diff --git a/src/algorithm/structure/path.lisp b/src/algorithm/structure/path.lisp
new file mode 100644
index 0000000..96fe87a
--- /dev/null
+++ b/src/algorithm/structure/path.lisp
@@ -0,0 +1,145 @@
+;;; Paths
+;;Author : Adrien Ycart
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+;a path p defines an interval of positions in [0..res] where res is the resolution associated to the given schema
+
+(defstruct (path
+ (:constructor make-path (val begin len dur) )
+ (:constructor empty-path (&optional (val nil) (begin 0) (len 0) (dur 0))))
+ (val :list) ; p-val is a list of couples : each couple holds the arity of the node and the branch chosen : ((arity1 . choice1) (arity2 . choice2) ... )
+ (begin :int) ; left bound of interval in [0..res]
+ (len :int) ;length of interval
+ (dur :int)) ;inverse of duration defined by p
+
+(defun path-empty (inst)
+ (make-path nil 0 (input-res inst) 1))
+
+(defun path-emptyp (path)
+ (equalp (path-val path) nil))
+
+(defun path-left (path)
+ "left bound of interval"
+ (path-begin path))
+
+(defun path-end (path)
+ "right bound of interval"
+ (+ (path-begin path) (path-len path)))
+
+(defun path-right (path)
+ "right bound of interval"
+ (path-end path))
+
+(defun path-depth (path)
+ "depth of the path"
+ (length (path-val path)))
+
+(defun path-projection (val)
+ ""
+ (if (null val)
+ nil
+ (let ((label (first val)))
+ (list (cdr label) (car label) (path-projection (rest val))))))
+
+(defun path-add (path element)
+ "add an element to path (ie we subdivide further) and updates the other fields "
+ (let* ((arity (car element))
+ (direction (cdr element))
+ (pval (path-val path))
+ (pbegin (path-begin path))
+ (plen (path-len path))
+ (pdur (path-dur path))
+ (len (floor plen arity)) ;duration of the new path : old duration/arity
+ (val (append pval (list element))))
+ (make-path val (+ pbegin (* (1- direction) len)) len (* pdur arity))))
+
+(defun path-addi (path arity direction)
+ "add an element to path (ie we subdivide further in arity and we choose the direction-th branch)"
+ (path-add path (cons arity direction)))
+
+(defun path-previous (path)
+ ""
+ (let* ((pval (path-val path))
+ (arity (caar (last pval)))
+ (direction (cdar (last pval)))
+ (pbegin (path-begin path))
+ (plen (path-len path))
+ (pdur (path-dur path)))
+ (assert (< 1 (print direction)))
+ (make-path (append (reverse (cdr (reverse pval))) (list (cons arity (1- direction)))) (- pbegin plen) plen pdur)))
+
+(defun path-father (path)
+ ""
+ (let* ((pval (path-val path))
+ (arity (caar (last pval)))
+ (direction (cdar (last pval)))
+ (pbegin (path-begin path))
+ (plen (path-len path))
+ (pdur (path-dur path)))
+ (assert pval)
+ (make-path (reverse (cdr (reverse pval))) (- pbegin (* (1- direction) plen)) (* plen arity) (floor pdur arity))))
+
+(defun path-make (inst list &optional (path (path-empty inst)))
+ "makes a path from a list of couples (arity . direction)"
+ (if (null list)
+ path
+ (path-make inst (cdr list) (path-add path (car list)))))
+
+(defun path-memberp (pos path)
+ "true iff the position pos belongs to the segment given by path"
+ (and (<= (path-begin path) pos) (< pos (path-end path))))
+
+(defun path-compare (p1 p2)
+ ""
+ (let ((len1 (path-len p1))
+ (len2 (path-len p2))
+ (begin1 (path-begin p1))
+ (begin2 (path-begin p2)))
+ (if (> len1 len2)
+ -1
+ (if (< len1 len2)
+ 1
+ (if (< begin1 begin2)
+ -1
+ (if (> begin1 begin2)
+ 1
+ 0))))))
+
+(defun path-children (path arity &optional (i 1))
+ "gives the list of the paths corresponding to the current path"
+ (if (<= i arity)
+ (append (list (path-addi path arity i)) (path-children path arity (1+ i)))
+ nil))
+
+(defun path-to-intlist (path)
+ ""
+ (reverse (path-projection (path-val path))))
+
+(defun path-to-position (path)
+ ""
+ (reverse (mapcar #'cdr (path-val path))))
+
+(defun print-pathlabel (label &optional (s t))
+ ""
+ (format s "[~D]~D" (car label) (cdr label)))
+
+(defun print-path (path &optional (stream t) (depth nil))
+ ""
+ (labels ((print-val (val s)
+ (if (null val)
+ (format s "E")
+ (progn
+ (print-pathlabel (first val))
+ (when (> (length (rest val)) 0)
+ (progn
+ (format s ".")
+ (print-val (rest val) s)))))))
+ (print-val (path-val path) stream)))
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::path) &optional values?)
+ `(rq::make-path ',(rq::path-val self) ,(rq::path-begin self) ,(rq::path-len self) ,(rq::path-dur self)))
diff --git a/src/algorithm/structure/weight.lisp b/src/algorithm/structure/weight.lisp
new file mode 100644
index 0000000..0d15314
--- /dev/null
+++ b/src/algorithm/structure/weight.lisp
@@ -0,0 +1,119 @@
+;;;; A structure for holding weights
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+(defstruct (weight
+ (:print-function print-weight))
+ (dist) ; a distance object (see distance.lisp)
+ (cpty) ; a complexity value (float) (see complexity.lisp)
+ (val)) ; val can have the following values : UNDEF = most-negative-fixnum , INFINITY = most-positive-fixnum , or a float (combination of distance and complexity)
+
+
+(defun print-weight (weight &optional (stream t) (depth 0))
+ (cond
+ ((weight-undefp weight) (format stream "UNDEF"))
+ ((weight-infinityp weight) (format stream "INFINITY"))
+ (t (format stream "{W=~5$; D=~5$; C=~$}" (weight-val weight) (weight-distance weight) (weight-complexity weight) ))))
+
+
+(defun weight-defp (weight)
+ (null (or (equalp (weight-val weight) most-negative-fixnum)
+ (equalp (weight-val weight) most-positive-fixnum))))
+
+(defun weight-undefp (weight)
+ (equalp (weight-val weight) most-negative-fixnum))
+
+(defun weight-infinityp (weight)
+ (equalp (weight-val weight) most-positive-fixnum))
+
+(defun weight-distance (weight)
+ (cond ((weight-undefp weight) 0.0)
+ ((weight-infinityp weight) -1.0)
+ (t (distance-to-float (weight-dist weight)))))
+
+
+;distance normalized by the length of the subdivision, not the total length
+(defun weight-distance-normalized-by-length (weight path)
+ (distance-normalized-by-length (weight-dist weight) path)
+)
+
+(defun weight-complexity (weight)
+ (weight-cpty weight)
+)
+
+
+(defun weight-compare (w1 w2)
+ "negative if w1 < w2, positive if w1 > w2, 0 if w1 = w2"
+
+ (let ((x1 (weight-val w1))
+ (x2 (weight-val w2)))
+ (cond ((equalp x1 most-negative-fixnum) (if (equalp x2 most-negative-fixnum)
+ 0
+ -1))
+ ((equalp x1 most-positive-fixnum) (if (equalp x2 most-positive-fixnum)
+ 0
+ 1))
+ (t (cond ((equalp x2 most-negative-fixnum) 1)
+ ((equalp x2 most-positive-fixnum) -1)
+ ((< x1 x2) -1)
+ ((> x1 x2) 1)
+ (t 0)))
+
+
+)))
+
+(defun make-undef ()
+ (make-weight :dist (empty-distance) :cpty nil :val most-negative-fixnum))
+
+(defun make-infinity ()
+ (make-weight :dist (empty-distance) :cpty nil :val most-positive-fixnum))
+
+; Function not linear when cd is taken into account : not monotonous in this case !
+(defun weight-combine (d c precision gracepen &optional (penalty nil) )
+ "returns the weight value corresponding to the distance and complexity"
+ (let ((dv (distance-norm d)))
+ (if penalty
+ (+ (* precision 10 dv) (* (- 1 precision) (complexity-value c gracepen)) penalty)
+ (+ (* precision 10 dv) (* (- 1 precision) (complexity-value c gracepen))))))
+
+
+
+(defun weight-make (d c precision gracepen &key (penalty nil))
+ (make-weight :dist d :cpty c :val (weight-combine d c precision gracepen penalty)))
+
+
+(defun weight-split (wlist)
+ "given a list of weights, return the list of distances and the list of complexities"
+ (if (null (first wlist))
+ (values nil nil)
+ (let* ((current (first wlist))
+ (d (weight-dist current))
+ (c (weight-cpty current)))
+ (multiple-value-bind (dl cl) (weight-split (rest wlist))
+ (values (append (list d) dl) (append (list c) cl))))))
+
+
+(defun weight-addall (wl precision gracepen)
+ "add all the weights in the entry list"
+ (cond ((find-if #'weight-undefp wl) (make-undef))
+ ((find-if #'weight-infinityp wl) (make-infinity))
+ (t (multiple-value-bind (dl cl) (weight-split wl)
+ (let ((d (distance-addall dl))
+ (c (complexity-addall1 cl)))
+ (weight-make d c precision gracepen))))))
+
+(defun weight-to-float (w)
+ (cond ((weight-undefp w) 0.0)
+ ((weight-infinityp w) -1.0)
+ (t (weight-val w))))
+
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::weight) &optional values?)
+ (cond ((rq::weight-undefp self) '(rq::make-undef))
+ ((rq::weight-infinityp self) '(rq::make-infinity))
+ (t `(rq::make-weight :dist ,(om::omng-save (rq::weight-dist self)) :cpty ,(om::omng-save (rq::weight-cpty self)) :val ,(rq::weight-val self)))))
+
diff --git a/src/algorithm/subdivision.lisp b/src/algorithm/subdivision.lisp
new file mode 100644
index 0000000..f60b6f5
--- /dev/null
+++ b/src/algorithm/subdivision.lisp
@@ -0,0 +1,68 @@
+;;; Subdivision schema
+
+;; A subdivision schema is given in the form of a list. For example : (2 2 3) means that each measure is divided in two, then each part is again divided in two, and finally, each of these parts is divided in 3.
+;; If an element of the list is a list itself, it means that the choice is given between the values of the list. For example : (2 (2 3 5) 3) means (2 2 3) or (2 3 3) or (2 5 3).
+;; If an element of the list is a list of lists, it means that the choice is given between various successions of subdivisions. For example : ( ((2 3) (3 2)) ) means (2 3) or (3 2).
+;; Example : ((2 3) ((2 3) ((3 5) 2))) means (2 2 3) or (2 3 2) or (2 5 2) or (3 2 3) or (3 3 2) or (3 5 2).
+;; Non prime numbers can be used as, for exemple, dividing in 2 then in 2 gives a different notation than dividing in 4.
+
+(use-package :om :rq)
+
+(in-package :rq)
+
+;; Error when a schema is empty
+(define-condition schema-is-empty (error)
+ ()
+ (:report (lambda (condition stream)
+ (format stream "Schema is empty !"))))
+
+(defun schema-resolution (schema)
+ "resolution of the schema, ie least common multiple of the numbers of subdivisions for each possible succession of subdivisions"
+ (labels ((vreso (vschema) ;when there are successives subdivisions (v for vertical, successive subdivision are represented vertically)
+ (cond ((null vschema) 1)
+ ((not (listp vschema)) vschema)
+ (t (reduce #'* (mapcar #'reso vschema)))))
+ (reso (hschema) ;when there are different choices of subdivisions (choice is represented horizontally)
+ (if (listp hschema)
+ (reduce #'lcm (mapcar #'vreso hschema))
+ hschema)))
+ (vreso schema)))
+
+(defun schema-top (schema)
+ "gives the next possible subdivisions (there can be repetitions)"
+ (labels ((vtop (vschema)
+ (cond ((null vschema) nil)
+ ((not (listp vschema)) vschema)
+ (t (htop (first vschema)))))
+ (htop (hschema)
+ (if (listp hschema)
+ (mapcar #'vtop hschema)
+ (vtop hschema))))
+ (flatten (vtop schema))))
+
+;; to flatten nested lists
+(defun flatten (structure)
+ (cond ((null structure) nil)
+ ((atom structure) (list structure))
+ (t (mapcan #'flatten structure))))
+
+(defun schema-pop (val schema)
+ "gives the next schema, given we have subdivided the current node in val. val has to be one of the values given by schema-top"
+ (labels ((vpop (vschema)
+ (cond ((null vschema) nil)
+ ((not (listp vschema)) (equalp val vschema))
+ ((listp vschema) (let ((result (hpop (first vschema))))
+ (if result
+ (append (list result) (rest vschema))
+ nil)))
+ (t nil)))
+ (hpop (hschema)
+ (cond ((null hschema) nil)
+ ((not (listp hschema)) (equalp val hschema))
+ (t (remove nil (mapcar #'vpop hschema)))))
+ (remove-t-nil-recursively (x)
+ (if (listp x)
+ (remove nil (mapcar #'remove-t-nil-recursively
+ (remove nil (remove t x))))
+ x)))
+ (remove-t-nil-recursively (vpop schema))))
diff --git a/src/algorithm/tatum-seg-algorithm.lisp b/src/algorithm/tatum-seg-algorithm.lisp
new file mode 100644
index 0000000..0b93453
--- /dev/null
+++ b/src/algorithm/tatum-seg-algorithm.lisp
@@ -0,0 +1,93 @@
+(in-package :om)
+
+
+;;;============================
+;;; ALGORITHM FOR SEGMENTATION IN CONSTANT-TATUM REGIONS
+;;;
+;;; Algorithm based on A. C. Yang, E. Chew, A. Volk : "A Dynamic Programming Approach to Adaptative Tatum Assignment for Rhythm Transcription"
+;;; Note that the pseudo-code given in the above paper is false (indexes do not match), but the principle is correct.
+;;; Moreover, a customizable "new segment penalty" has been added in order to prevent the algorithm from placing a new segmentation mark at each note.
+
+
+(defpackage "CTSeg"
+ (:nicknames :cts)
+ (:use "COMMON-LISP" "CL-USER" "OM-API" "LISPWORKS" "OM-LISP")
+ (:import-from "CL-USER")
+ (:export #:segmentation)
+ )
+
+(in-package :cts)
+
+(defun e (ioil p)
+ "Computes the remainder squared error for the given IOI list and the given tatum p"
+
+ (reduce #'(lambda (x y) (+ (* y y) x)) (mapcar #'(lambda (x) (- (/ x (float p)) (round (/ x (float p))))) ioil) :initial-value 0)
+
+)
+
+
+(defun err (ioilist i &optional (range '(40 100)))
+ "Returns the value of the minimum RSE for the sublist of indexes between i and N and the corresponding value of tatum p"
+ (let ((ioil (subseq ioilist i))
+ (errors)
+ (minimum))
+
+ (setq errors (loop for p from (car range) to (cadr range) collect
+ (e ioil p)))
+ (setq minimum (reduce #'min errors))
+ (values minimum (+ (position minimum errors :from-end t) 40))
+))
+
+
+(defun opt (ioilist optlist k)
+ "Returns the weight and the index of the previous segmentation mark that gives the best weight"
+ (let* ((errorlist (make-list k))
+ (Tlist (make-list k))
+ (minimum)
+ (index))
+
+ (loop for i from 0 to (1- k) do
+ (multiple-value-bind (error tatum) (err ioilist i)
+ (setf (nth i errorlist) (+ (nth i optlist) error)
+ (nth i Tlist) tatum)
+ ))
+ (setq minimum (reduce #'min errorlist))
+ (setq index (position minimum errorlist))
+ (values minimum index (nth index Tlist))
+
+))
+
+(defun backtrace (Slist Tlist &optional Sbuff Tbuff)
+ (if Slist
+ (let ((S (car (last Slist))))
+ (backtrace (subseq Slist 0 S) (subseq Tlist 0 S) (append (list S) Sbuff) (append (last Tlist) Tbuff))
+ )
+
+ (values Sbuff Tbuff)))
+
+
+(defun segmentation (onsets &optional (penalty 5))
+ "Given a list of onsets (in ms), returns a list of segmentation marks (in ms) segmenting the input in constant-tatum regions."
+ (let* ((ioilist (mapcar #'- (subseq onsets 1) onsets))
+ (N (length onsets))
+ (optlist (make-list N :initial-element 0 ))
+ (Slist (make-list (1- N) :initial-element 0))
+ (Tlist (make-list (1- N) :initial-element 0))
+ (pen (* 0.01 penalty))
+ )
+
+ (loop for k from 1 to (1- N) do
+ (multiple-value-bind (OPT S Tatum) (opt (subseq ioilist 0 k) optlist k)
+ (setf (nth k optlist) (+ OPT pen))
+ (setf (nth (1- k) Slist) S)
+ (setf (nth (1- k) Tlist) Tatum)
+
+ ))
+
+ (multiple-value-bind (Ss Ts) (backtrace Slist Tlist) ;we discard the tatum list, as we do not use it further
+ (loop for S in Ss collect
+ (nth S onsets)))
+
+))
+
+
diff --git a/src/algorithm/tempo-smoothing.lisp b/src/algorithm/tempo-smoothing.lisp
new file mode 100644
index 0000000..5a23798
--- /dev/null
+++ b/src/algorithm/tempo-smoothing.lisp
@@ -0,0 +1,148 @@
+
+
+;;;============================
+;;; ALGORITHM FOR TEMPO SMOOTHING
+;;;
+;;; Dynamic-programming segmentation algorithm
+;;; Inspired by the segmentation algorithm described in : A. C. Yang, E. Chew, A. Volk : "A Dynamic Programming Approach to Adaptative Tatum Assignment for Rhythm Transcription" (see also tatum-seg-algorithm.lisp)
+;;; Also includes a new-tempo penalty (tempo jump penalty)
+;;; The "ERR" function is replaced by a Viterbi-like best-path algorithm
+;;; The "ERR" function finds the series of tempo that minimizes the variations between successive tempi, and the weights of the corresponding transcriptions.
+;;; The balance between tempo variations and weights is made by the alpha parameter
+
+
+
+(defpackage "TempSmooth"
+ (:nicknames :ts)
+ (:use "COMMON-LISP" "CL-USER" "OM-API" "LISPWORKS" "OM-LISP")
+ (:import-from "CL-USER")
+ (:export #:tempo-smooth)
+ )
+
+(in-package :ts)
+
+
+;------- Functions to calculate the best sequence of tempi in a sublist ------;
+
+(defun dist (tempo1 tempo2 &optional (type :rse))
+ "Computes the distance between two tempi"
+ (let ((diff (- tempo2 tempo1)))
+ (case type
+ (:rse (* diff diff))
+ (:abs (abs diff))
+ (:alg diff)
+ )))
+
+(defun dists (tempo ltempo &optional (type :rse))
+ "Returns a list holding the distances between TEMPO and each tempo in LTEMPO"
+ (loop for tempo2 in ltempo
+ collect (dist tempo tempo2 type)))
+
+(defun min-argmin (list &optional (min most-positive-fixnum) (min-index 0) (cur-index 0))
+ "Returns the min (in absolute value) and the argmin of a list"
+ (if list
+ (if (< (abs (car list)) (abs min))
+ (min-argmin (rest list) (car list) cur-index (1+ cur-index))
+ (min-argmin (rest list) min min-index (1+ cur-index)))
+ (values min min-index))
+)
+
+
+(defun viterbi-backtrace (T1 &optional indexes tempi)
+ (let* ((new (nth (car indexes) (car T1)))
+ (new-index (second new))
+ (new-tempo (third new)))
+
+ (if new-index
+ (viterbi-backtrace (rest T1) (append (list new-index) indexes) (append (list new-tempo) tempi))
+ (values indexes (append (list new-tempo) tempi))))
+)
+
+(defun tempo-viterbi (ltempi lweights alpha &optional (type :rse))
+ "Computes the sequence of tempi that minimises the weight (compromise between the weight of the solution and the tempi difference among segments)"
+ (let ((T1 (make-list (length ltempi))))
+ ;T1 holds the cumulated values. It has the same length as ltempi.
+ ;Its i-th element is a list of same length as (nth i ltempi)
+ ;Each element of this list is a triplet (min argmin tempo)
+
+ ;initialization
+ (setf (first T1) (loop for weight in (first lweights)
+ for tempo in (first ltempi)
+ collect (list (* (- 1 alpha) weight) nil tempo)))
+
+ ;iteration
+ (loop for tempi in (rest ltempi)
+ for weights in (rest lweights)
+ for i = 1 then (1+ i)
+ do
+ (setf (nth i T1)
+ (let* ((prev (nth (1- i) T1))
+ (prev-vals (mapcar #'first prev))
+ (prev-tempi (mapcar #'third prev)))
+ (loop for tempo in tempi
+ for weight in weights
+ collect
+ (multiple-value-bind (val index) (min-argmin (om::om+ prev-vals
+ ;(om::om* (dists tempo prev-tempi type) weight)))
+ (om::om+ (om::om* alpha (dists tempo prev-tempi type)) (* 2 (- 1 alpha) weight))))
+ (list val index tempo))))))
+
+ ;backtrace
+ (let* ((last-vals (mapcar #'first (car (last T1))))
+ (min-val (reduce #'min (mapcar #'abs last-vals)))
+ (last-index (position min-val last-vals)))
+ (multiple-value-bind (indexes tempi)
+ (viterbi-backtrace (reverse T1) (list last-index))
+ (values min-val indexes tempi)
+ ))
+))
+
+
+;-------- General algorithm --------;
+
+(defun opt (ltempi lweights optlist k alpha type)
+ "Returns the weight and the index of the previous segmentation mark that gives the best weight"
+ (let* ((errorlist (make-list k))
+ (Tlist (make-list k))
+ (minimum)
+ (index))
+
+ (loop for i from 0 to (1- k) do
+ (multiple-value-bind (error index-list) (tempo-viterbi (subseq ltempi i) (subseq lweights i) alpha type)
+ (setf (nth i errorlist) (+ (nth i optlist) error)
+ (nth i Tlist) index-list)
+ ))
+ (setq minimum (reduce #'min errorlist))
+ (setq index (position minimum errorlist))
+ (values minimum index (nth index Tlist))
+))
+
+(defun backtrace (Slist Tlist &optional Sbuff Tbuff)
+ (if Slist
+ (let ((S (car (last Slist))))
+ (backtrace (subseq Slist 0 S) (subseq Tlist 0 S) (append (list S) Sbuff) (append (last Tlist) Tbuff))
+ )
+
+ (values Sbuff Tbuff)))
+
+(defun tempo-smooth (ltempi lweights &key (alpha 0.5) (type :abs) (penalty 5))
+ "Returns a list of indexes that optimises the variations of tempo between each measure"
+ (let* ((N (length ltempi))
+ (optlist (make-list (1+ N) :initial-element 0 ))
+ (Slist (make-list N :initial-element 0))
+ (Tlist (make-list N :initial-element 0)))
+ (loop for k from 1 to N do
+ (multiple-value-bind (OPT S index-list) (opt (subseq ltempi 0 k) (subseq lweights 0 k) optlist k alpha type)
+ (setf (nth k optlist) (+ OPT penalty))
+ (setf (nth (1- k) Slist) S)
+ (setf (nth (1- k) Tlist) index-list)
+ ))
+ (multiple-value-bind (Ss Ts) (backtrace Slist Tlist) ;we discard the segmentation points list, as we do not use it further (we return the indexes of the solution to keep for each segment)
+ (let ((ks (reduce #'append Ts)))
+ (values ks
+ (loop for k in ks
+ for tempi in ltempi
+ collect (nth k tempi))))
+
+)))
+
diff --git a/src/gui/analysis/k-best-analysis.lisp b/src/gui/analysis/k-best-analysis.lisp
new file mode 100644
index 0000000..b82cdd0
--- /dev/null
+++ b/src/gui/analysis/k-best-analysis.lisp
@@ -0,0 +1,252 @@
+;;;;
+
+(in-package :om)
+
+
+
+;;; Segments = time marker, until next one
+(defclass! k-best-analysis (abstract-analysis)
+ ((segpen :accessor segpen :initarg :segpen :initform 5) ;penalty given to the creation of a new segment in the segmentation algorithm
+ (warning-p :accessor warning-p :initarg :warning-p :initform t))); to display the long segment warning, or not.
+
+;A k-best analysis is only allowed with a quand-chod-seq (ie in the context of a RQ system)
+(defmethod compatible-analysis-p ((analyse k-best-analysis) (object rq::quant-chord-seq)) t)
+(defmethod compatible-analysis-p ((analyse k-best-analysis) (object t)) nil)
+
+(defmethod default-segment-class ((self k-best-analysis)) 'marker-segment)
+
+(defmethod compute-segments-p ((self k-best-analysis)) t)
+(defmethod analyse-segments-p ((self k-best-analysis)) t)
+(defmethod compute+analyse-segments-p ((self k-best-analysis)) nil)
+
+(defmethod analysis-init ((self k-best-analysis) object)
+ (unless (analysis-segments self)
+ (setf (analysis-segments self)
+ (list (make-instance 'marker-segment :mrk-time 0))))
+ (call-next-method))
+
+(defmethod analysis-init-segment ((self k-best-analysis) segment)
+ (unless (segment-data segment)
+ (setf (segment-data segment) (make-instance 'rq::k-best-data)))
+ (when (previous-segment segment)
+ (progn
+ (setf (rq::updateflag (segment-data (previous-segment segment))) nil)
+ (compute-and-set-slur self segment))))
+
+(defmethod delete-from-analysis ((self k-best-analysis) segment)
+ (when (previous-segment segment)
+ (setf (rq::updateflag (segment-data (previous-segment segment))) nil))
+ (call-next-method))
+
+(defmethod compute-analysis-segments ((self k-best-analysis) (object chord-seq))
+ "Computes the segmentation marks using a constant tatum segmentation algorithm"
+ (let ((lonsets (lonset object))
+ marks)
+ (setq marks (cts::segmentation lonsets (segpen self)))
+ (loop for mark in marks collect
+ (make-instance 'marker-segment :mrk-time mark))
+))
+
+(defmethod analyse-one-segment ((self k-best-analysis) (segment segment) (object t))
+ "Runs the analysis on one segment. Computes a k-best structure."
+ (let* ((temp-chord-seq (select object (segment-begin segment) (min (segment-end segment) (get-obj-dur object))))
+ (onsets (print (lonset temp-chord-seq)))
+ (durs (print (ldur temp-chord-seq)))
+ (k-best-data (or (segment-data segment)
+ (setf (segment-data segment) (make-instance 'rq::k-best-data))))
+ (schema (or (rq::schema k-best-data) '(( ((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))))
+ (tempo (rq::tempo k-best-data))
+ (tempomerge (rq::tempomerge k-best-data))
+ (warning (warning-p self))
+ out)
+ ;Warning when the segment is long (computations may take a long time)
+ (when (or (< (- (segment-end segment) (segment-begin segment)) 5000) (if warning (om-y-or-n-dialog (format nil "The segment starting at ~d, ending at ~d seems long, computations might take a long time. Continue anyway ?" (segment-begin segment) (segment-end segment))) t))
+
+ ;If each segment corresponds to a beat, we compute the tempo value from the segment length
+ (if (rq::segments=beats k-best-data)
+ (let ((tempo (round (/ (* 60000 (rq::n-beats-per-seg k-best-data)) (- (segment-end segment) (segment-begin segment))))))
+ (setf out (rq::k-best-segment-quantify-automaton-with-tempo onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) tempo (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data))))
+
+ ;Otherwise, use the tempo parameter
+ ;No tempo specified, try tempi between 40 and 200 bpm
+ (cond ((null tempo)
+ (if tempomerge
+ ;Solutions ranked across all tempi (one ktable for all)
+ (setf out (rq::k-best-segment-quantify-automaton onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data)))
+ ;Solutions ranked independently for each tempo (one ktable per tempo)
+ (setf out (rq::k-best-segment-quantify-automatons onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data)))))
+ ;One single tempo specified
+ ((numberp tempo)
+ (setf out (rq::k-best-segment-quantify-automaton-with-tempo onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) (rq::tempo k-best-data) (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data))))
+ ;A range of tempi (in the form of a 2 elements list) is specified
+ (t
+ (if tempomerge
+ ;Solutions ranked across all tempi (one ktable for all)
+ (setf out (rq::k-best-segment-quantify-automaton onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data) (first tempo) (second tempo)))
+ ;Solutions ranked independently for each tempo (one ktable per tempo)
+ (setf out (rq::k-best-segment-quantify-automatons onsets durs (rq::n-solution k-best-data) schema (- (segment-end segment) (segment-begin segment)) (rq::precision k-best-data) (rq::gracepen k-best-data) (rq::slur k-best-data) (first tempo) (second tempo)))))))
+ (setf (rq::updateflag k-best-data) t)
+ out)))
+
+(defmethod handle-segment-doubleclick ((self k-best-analysis) segment panel pos)
+ (rq::k-best-data-window (or (segment-data segment)
+ (setf (segment-data segment) (make-instance 'rq::k-best-data))))
+ (update-panel panel))
+
+(defmethod draw-segment-data ((self k-best-analysis) segment view)
+ (when (segment-data segment)
+ (let ((x1 (time-to-pixels view (segment-begin segment)))
+ (x2 (time-to-pixels view (segment-end segment)))
+ (qs (rq::parent (analysis-object self)))
+ (segment-index (position segment (analysis-segments self) :test 'equalp))
+ (color (if (rq::updateflag (segment-data segment))
+ (color segment)
+ *om-gray-color*)))
+
+ ;Display k-best parameters
+ (om-with-fg-color view
+ color
+ (om-with-font *om-default-font1*
+ (om-draw-string x1 (- (h view) 115) (format nil "t=~D" (segment-begin segment)))
+ (om-draw-string x1 (- (h view) 105) (format nil "Slur=~D" (rq::slur (segment-data segment))))
+
+ (om-draw-string x1 (- (h view) 85) (format nil "Tempo: ~A" (rq::tempo (segment-data segment))))
+ (om-draw-string x1 (- (h view) 75) (format nil "Nb. solutions : ~A" (rq::n-solution (segment-data segment))))
+ (om-draw-string x1 (- (h view) 65) (format nil "Precision: ~A" (rq::precision (segment-data segment))))
+ (om-draw-string x1 (- (h view) 55) (format nil "Grace pen. : ~A" (rq::gracepen (segment-data segment))))
+
+ ;DISPLAY THE GRID
+ (if (and (numberp (rq::tempo (segment-data segment)))
+ (equal (type-of rq::*clicked-panel*) 'rq::quant-chord-seq-panel))
+
+ ;When a tempo is specified, and the chord-seq panel is the last clicked, display the beats corresponding to the selected tempo.
+ ;Otherwise, display the grid
+ (let (tempo)
+ (if (numberp (rq::tempo (segment-data segment)))
+ (setq tempo (rq::tempo (segment-data segment)))
+ (let* ((mp (rq::wp qs))
+ (current-poly (nth segment-index (rq::polys mp))))
+ (when current-poly
+ (let ((select-voice (nth (nth segment-index (rq::selections mp)) (voices current-poly))))
+ (setq tempo (second (first (tempo select-voice))))))))
+ ;Draw the beats
+ (let* ((segment-dur (- (segment-end segment) (segment-begin segment)))
+ (temps (* (/ 60 tempo) 1000))
+ (nb-temps (ceiling segment-dur temps)))
+
+ (om-draw-line x1 (- (h view) 130) x2 (- (h view) 130))
+ (loop for i from 1 to nb-temps
+ for time = (segment-begin segment) then (+ time temps) do
+ (om-draw-string (time-to-pixels view time) (- (h view) 130) (format nil "~A" i))
+ (om-with-dashline '(2 2)
+ (om-draw-line (time-to-pixels view time) (- (h view) 130)
+ (time-to-pixels view time) 0)))))
+
+ ;To draw the recursive grid corresponding to the current solution
+ ;Also highlights the selected segment.
+ (when (rq::pulse-flag (rq::chord-seq qs))
+ (let ((segment-dur (- (segment-end segment) (segment-begin segment)))
+ (grid (rq::grid (segment-data segment)))
+ (init-depth 1)
+ (select (selection? (panel (rq::voice-editor (rq::editor qs))))))
+ (when (= (length grid) 1)
+ (setq grid (car grid) ;we remove top level of grid when there is only one beat in the subdivision so that the grid matches the displayed rectangle
+ init-depth 2)) ;we compensate the top level in the grid
+ (labels ((draw-grid (grid path &optional (depth 1) (begin (segment-begin segment)) (dur segment-dur) (current-path '(0)))
+ (if (listp grid)
+ (let ((n (length grid)))
+ (loop for i from 0 to (1- n)
+ for time = begin then (+ time (round dur n))
+ do
+ (progn
+ (if (= depth 1)
+ (progn
+ (om-with-dashline '(2 2)
+ (om-draw-line (time-to-pixels view time) (- (h view) 130)
+ (time-to-pixels view time) 0))
+ (om-draw-string (time-to-pixels view time) (- (h view) 130) (format nil "~A" (1+ i))))
+ (unless (= time begin)
+ (om-with-dashline '(2 2)
+ (om-draw-line (time-to-pixels view time) (- (h view) 130)
+ (time-to-pixels view time) (+ (- (h view) 190) (* 10 (min depth 5)) )))))
+ (draw-grid (nth i grid) path (1+ depth) time (round dur n) (append current-path (list i)) )))))
+ (when (and path (equalp path current-path) (equalp (rq::voice-mode (rq::editor qs)) :edit))
+ (draw-h-rectangle (list (time-to-pixels view begin) 20 (+ (time-to-pixels view (+ begin dur)) 1) 95) :fill t :color *om-black-color*))
+ ))
+ (if (or (null select) (not (= segment-index (or (car (rq::get-cons-list (car select))) 0))))
+ (draw-grid grid nil init-depth)
+ (draw-grid grid (cdr (rq::get-cons-list (car select))) init-depth))
+ ))))))
+ ;Display "Merge tempi" when the tempomerge option is selected
+ (when (rq::tempomerge (segment-data segment))
+ (om-with-fg-color view color
+ (om-with-font *om-default-font1b*
+ (om-draw-string x1 (- (h view) 45) "Merge tempi"))))
+ ;Highlight the segment correcponding to the current poly
+ (when (= segment-index (rq::current-poly (rq::wp qs)))
+ (draw-h-rectangle (list x1 20 x2 95) :fill t :color color)))))
+
+(defmethod shorten-string (string &optional (n-caracters 5))
+ "A function to shorten the long strings"
+ (if (> (length string) n-caracters)
+ (concatenate 'string (subseq string 0 (1+ n-caracters)) "...")
+ string)
+)
+
+(defmethod analysis-key-event ((self k-best-analysis) panel char)
+ "Key handler : up-down to change tempo, left-right to change position"
+ (case char
+ (:om-key-up (selected-segment-change-tempo self 1))
+ (:om-key-down (selected-segment-change-tempo self -1))
+ (:om-key-left (selected-segment-change-mrk-time self -5))
+ (:om-key-right (selected-segment-change-mrk-time self 5))
+ (otherwise (call-next-method))))
+
+
+(defmethod compute-and-set-slur ((analyse k-best-analysis) segment)
+ "Computes and sets the slur for a segment (the amount by which the last chord of the previous segment overlaps the segmentation mark)
+When the segment is placed on a chord, the slur is nil (even if a previous chord overlaps)"
+ (let (previous-begin
+ previous-end)
+ (if (previous-segment segment)
+ (setq previous-begin (segment-begin (previous-segment segment))
+ previous-end (segment-end (previous-segment segment)))
+ (setq previous-begin 0
+ previous-end (segment-begin segment)))
+
+ (let* ((chords (analysis-object analyse))
+ (onsets (lonset chords))
+ (durs (ldur chords))
+ (on-dur-previous (loop for on in onsets for dur in durs when (and (>= on previous-begin) (< on previous-end)) collect (list on dur) ))
+ (first-onset (find-if #'(lambda (x) (>= x previous-end)) onsets )))
+
+ (if (equalp first-onset previous-end)
+ (setf (rq::slur (segment-data segment)) nil)
+ (if on-dur-previous
+ (let ((overlap (- (+ (caar (last on-dur-previous)) (car (second (car (last on-dur-previous))))) (segment-begin segment))))
+ (if (> overlap 0) ;when the last note of the previous segment ends in the current segment
+ (setf (rq::slur (segment-data segment)) overlap)
+ (setf (rq::slur (segment-data segment)) nil)))
+ (setf (rq::slur (segment-data segment)) nil))))))
+
+(defmethod selected-segment-change-tempo ((self k-best-analysis) delta)
+ "Adds DELTA to the tempo of the selected segments"
+ (when (selected-segments self)
+ (loop for segment in (selected-segments self) do
+ ;Only when the tempo is a number
+ (unless (listp (rq::tempo (segment-data segment)))
+ (setf (rq::tempo (segment-data segment)) (+ (rq::tempo (segment-data segment)) delta))
+ (setf (rq::updateflag (segment-data segment)) nil)))))
+
+(defmethod selected-segment-change-mrk-time ((self k-best-analysis) delta)
+ "Moves the segmentation mark of DELTA ms"
+ (when (selected-segments self)
+ (loop for segment in (selected-segments self) do
+ (progn
+ (setf (mrk-time segment) (max (+ (mrk-time segment) delta) 0))
+ (compute-and-set-slur self segment)
+ (setf (rq::updateflag (segment-data segment)) nil)
+ (when (previous-segment segment)
+ (setf (rq::updateflag (segment-data (previous-segment segment))) nil))))))
+
+
diff --git a/src/gui/analysis/k-best-data.lisp b/src/gui/analysis/k-best-data.lisp
new file mode 100644
index 0000000..3e558a9
--- /dev/null
+++ b/src/gui/analysis/k-best-data.lisp
@@ -0,0 +1,58 @@
+(in-package :rq)
+
+;;; Data used by the k-best algorithm. Is an attribute to each segment.
+
+(defclass! k-best-data ()
+ ((tempo :accessor tempo :initarg :tempo :initform nil) ; can be either a 2-elements list (tempo range), a number (goal value), or nil (default tempo range)
+ (tempomerge :accessor tempomerge :initarg :tempomerge :initform t) ; when nil, the solutions are ranked for each tempo independently. when t, the ranking is global, on all possible tempi.
+ (schema :accessor schema :initarg :schema :initform '(( ((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)) )) ) ; subdivision schema
+ (n-solution :accessor n-solution :initarg :n-solution :initform 10) ; number of solutions computed for each hashtable
+ (precision :accessor precision :initarg :precision :initform 0.5)
+ (gracepen :accessor gracepen :initarg :gracepen :initform 2) ;penalty given to the gracenotes
+ (segments=beats :accessor segments=beats :initarg :segments=beats :initform nil) ;true when each segment corresponds to a beat
+ (n-beats-per-seg :accessor n-beats-per-seg :initarg :n-beats-per-seg :initform 1) ;number of beats per segments (only used when segments=beats is true).
+ (updateflag :accessor updateflag :initarg :updateflag :initform nil) ;true iff the k-best structure is up-to-date
+ (slur :accessor slur :initarg :slur :initform nil ) ;slur is nil if no note in the previous segment overlaps with the current segment. otherwise, it is by how much the previous segment overlaps (in ms)
+ (grid :accessor grid :initarg :grid-poly :initform nil))) ;quantification grid, to be displayed
+
+(defmethod k-best-data-equal ((data1 k-best-data) (data2 k-best-data))
+ "True iff DATA1 and DATA2 have the same parameters"
+ (and (equalp (tempo data1) (tempo data2))
+ (equalp (tempomerge data1) (tempomerge data2))
+ (equalp (schema data1) (schema data2))
+ (equalp (n-solution data1) (n-solution data2))
+ (equalp (precision data1) (precision data2))
+ (equalp (gracepen data1) (gracepen data2))
+ (equalp (segments=beats data1) (segments=beats data2))
+ (if (segments=beats data1)
+ (equalp (n-beats-per-seg data1) (n-beats-per-seg data2))
+ t))
+)
+
+(defmethod k-best-data-copy ((data k-best-data))
+ (make-instance 'k-best-data
+ :tempo (tempo data)
+ :tempomerge (tempomerge data)
+ :schema (schema data)
+ :n-solution (n-solution data)
+ :precision (precision data)
+ :updateflag (updateflag data)
+ :slur (slur data)
+ :grid (grid data)
+ :segments=beats (segments=beats data)
+ :n-beats-per-seg (n-beats-per-seg data))
+)
+
+(defmethod om::omng-save ((self k-best-data) &optional values?)
+ `(make-instance 'k-best-data
+ :tempo ',(tempo self)
+ :tempomerge ',(tempomerge self)
+ :schema ',(schema self)
+ :n-solution ,(n-solution self)
+ :precision ,(precision self)
+ :gracepen ,(gracepen self)
+ :updateflag ,(updateflag self)
+ :slur ,(slur self)
+ :grid ',(grid self)
+ :segments=beats ,(segments=beats self)
+ :n-beats-per-seg ,(n-beats-per-seg self)))
diff --git a/src/gui/box/quant-box.lisp b/src/gui/box/quant-box.lisp
new file mode 100644
index 0000000..a00015e
--- /dev/null
+++ b/src/gui/box/quant-box.lisp
@@ -0,0 +1,27 @@
+
+(in-package :om)
+
+;;; Quant box
+;;; A new class of box has been implemented to allow special treatments
+;;; - Closing the GUI before evaluating the box
+;;; - Setting the right scroll position to display the selected segments/solutions when opening the GUI
+
+
+
+(defclass quant-box (OMBoxEditCall) ())
+
+(defmethod get-type-of-ed-box ((self rq::rq)) 'quant-box)
+
+(defmethod omng-box-value :before ((self quant-box) &optional (numout 0))
+ "To close the editor bevore re-evaluating the box"
+ (when (and (editorframe self) (not (equal (allow-lock self) "x")))
+ (om-close-window (om-view-window (editorframe self)))))
+
+
+
+(defmethod OpenObjectEditor :after ((self quant-box))
+ "To focus on the selected segment, measure and poly in the three panels when opening the editor"
+ (let ((quant-editor (editorframe self)))
+ (rq::update-scroll (rq::poly-editor quant-editor))
+ (rq::focus-view (rq::chord-seq-editor quant-editor) (rq::current-poly (rq::wp (object quant-editor))))
+ (rq::focus-view (rq::voice-editor quant-editor) (rq::current-poly (rq::wp (object quant-editor))))))
diff --git a/src/gui/choice-table.lisp b/src/gui/choice-table.lisp
new file mode 100644
index 0000000..4d9ae03
--- /dev/null
+++ b/src/gui/choice-table.lisp
@@ -0,0 +1,226 @@
+(in-package :rq)
+
+
+;------------ CHOICE-TABLE -------------;
+;The choice-table stores the modified version of the chosen transcription (the one displayed in the bottom panel).
+;
+;It is a compact version of the global hashtable found in the k-best structures (same keys),
+;but with less entries, and instead of an "entry" structure, each entry is a list :
+;(selected-run weight-of-selected-run ll-align rr-align)
+;It holds only one solution, that is the selected solution, instead of the whole best-list.
+;
+;It also stores the list of modifications done by the user manually.
+;Each modification is a list of 2 elements : the first is the tree to be replaced, the second is the cons-container-path where it has to be replaced
+;Each time a modification is done manually by the user, the modification is added to the list.
+;All the previous modifications that are erased by the new one are removed from the list.
+
+
+(defclass! choice-table ()
+ ((table :accessor table :initarg :table :initform nil)
+ (modified :accessor modified :initarg :modified :initform nil) ;true iff the table has been modified (ie the solution has been edited)
+ (user-edit :accessor user-edit :initard :user-edit :initform nil))) ;nil if the tree was not edited by the user, only by exploring the choice-table. If the user edited it, it stores the sub-tree along with the cons-container-path at which it has to be replaced.
+
+
+
+
+
+(defmethod add-choice ((choice choice-table) ktable input path k &optional (flag nil))
+ "Adds recursively the Kth best run in KTABLE at PATH to the choice-table CHOICE"
+ (multiple-value-bind (run weight ll rr) (rq-best ktable input path k flag)
+ (setf (gethash path (table choice)) (list run weight ll rr))
+ (when run
+ (let ((r (length run)))
+ (loop for i from 1 to r do
+ (add-choice choice ktable input (path-addi path r i) (car (nth (1- i) run)) (cdr (nth (1- i) run)) ))))))
+
+
+(defmethod set-weight ((choice choice-table) path weight)
+ "Sets the weight of entry PATH in CHOICE"
+ (setf (second (gethash path (table choice))) weight)
+)
+
+(defmethod set-aligns ((choice choice-table) path ll rr)
+ "Sets the aligns lists (list of indexes of inputs aligned to the left and to the right) of entry PATH in CHOICE"
+ (setf (third (gethash path (table choice))) ll
+ (fourth (gethash path (table choice))) rr))
+
+
+(defmethod make-tree-from-choice-table ((choice choice-table) input slur gracenote render)
+ "Builds an OM rhythm tree from one choice table, taking into account the user-edit modifications."
+ (let (out)
+ (setq out (rq-to-omtree choice input 1 nil slur gracenote))
+
+ ;Apply the modifications done by the user
+ (when (user-edit choice)
+ (loop for edit in (user-edit choice) do
+ ;when there is only 1 beat in the measure, the first level of the tree is removed
+ ;so we have to adapt the cons-container-path consequently.
+ (if (= 1 (length (rq-best choice input (path-empty input) 1 nil)))
+ (set-subtree-in-place (car out) (cadr edit) (car edit))
+ (set-subtree-in-place (car out) (cadr edit) (cdar edit)))))
+
+ ;Render tree
+ (if render
+ (setq out (rq-remove-top-level out))
+ )
+ out)
+)
+
+(defmethod make-grid (tables ks inputs)
+ "Makes the grids for all the choice-tables and return them in a list"
+ ;This function creates one grid for one table
+ (labels ((grid (table inst path k &optional (length 1) (conslist '(0)))
+ (let* ((run (rq-best table inst path k nil))
+ (r (length run)))
+ (if (and run (not (is-in-edited-group conslist table))) ;We do not create the grid for the subtrees that were modified by the user
+ (loop for i from 1 to r collect
+ (grid table inst (path-addi path r i) (car (nth (1- i) run)) (/ length r) (append conslist (list (1- i)))))
+ length))))
+ (loop for table in tables
+ for input in inputs
+ for k in ks
+ collect
+ (let ((grid (grid table input (path-empty input) k)))
+ (if (listp grid)
+ grid
+ (list grid))))))
+
+
+;------------ Functions to replace a subtree by another inside a rhythm tree ------------;
+
+(defun get-subtree (tree conslist)
+ (if (null conslist)
+ tree
+ (if (atom tree)
+ tree
+ (get-subtree (nth (car conslist) (cadr tree)) (cdr conslist))))
+
+
+)
+
+;; Warning : this function works in-place !
+(defun set-subtree-in-place (tree subtree conslist)
+ (if (= (length conslist) 1)
+ (setf (nth (car conslist) (cadr tree)) subtree)
+ (if (atom tree)
+ tree
+ (set-subtree-in-place (nth (car conslist) (cadr tree)) subtree (cdr conslist))))
+
+
+)
+
+(defun set-subtree (tree subtree conslist)
+ (let ((out (copy-tree tree)))
+ (set-subtree-in-place out subtree conslist)
+ out))
+
+
+;---------- Functions relative to the user-edit list ----------;
+
+(defmethod add-change-to-user-edit ((choice choice-table) conslist tree)
+ "Adds a modification to the user-edit list of CHOICE"
+ (let ((user-edit (user-edit choice)))
+ ;remove obsolete changes
+ (setq user-edit
+ (loop for elt in user-edit
+ unless (is-an-ancestor conslist (car elt))
+ collect elt))
+ ;add current change to list
+ (setf (user-edit choice) (append user-edit (list (list conslist tree)))))
+
+)
+
+;true iff cons1 is an ancestor of cons2
+;when conslist1 and conslist2 are equal, returns equal?
+(defmethod is-an-ancestor (conslist1 conslist2 &optional (equal? t))
+ "True iff CONSLIST1 is an ancestor of CONSLIST2. When CONSLIST1 and CONSLIST2 are equal, returns equal?"
+ (if (null conslist1)
+ (if (null conslist2)
+ equal?
+ t)
+ (if (and (car conslist2) (= (car conslist1) (car conslist2)))
+ (is-an-ancestor (cdr conslist1) (cdr conslist2) equal?)
+ nil))
+)
+
+(defmethod remove-descendents-from-user-edit (conslist (choice choice-table) &key ((:equal? eq) t))
+ "Remove obsolete modifications (modifications of descendants of a newly modified group"
+ (remove-if #'(lambda (x) (is-an-ancestor (car x) conslist eq)) (user-edit choice))
+)
+
+
+(defmethod is-in-edited-group (conslist (choice choice-table) &key ((:equal? eq) t))
+ "true iff CONSLIST is a descendent of one of the groups modified by the user. When CONSLIST belongs to the user-edit list, returns equal?"
+ (find-if #'(lambda (x) (is-an-ancestor (car x) conslist eq)) (user-edit choice))
+)
+
+
+
+;------------- Redefinition of the rq functions for the choice-table -----------;
+
+;;; To build the tree using the same rq-to-omtree function, we have to redefine rq-best and align
+
+
+(defmethod rq-best ((ktable choice-table) inst p k flag)
+ (let ((val (gethash p (table ktable))))
+ (values (first val) (second val) (third val) (fourth val))))
+
+(defun choice-inhabited (ktable p)
+ (distance-inhabitedp (weight-dist (second (gethash p (table ktable))))))
+
+(defmethod align ((ktable choice-table) p)
+ (let ((out (gethash p (table ktable))))
+ (values (third out) (fourth out))))
+
+(defmethod notes-align ((ktable choice-table) inst p)
+ (let ((out (gethash p (table ktable))))
+ (values (remove-silences (third out) inst) (remove-silences (fourth out) inst))))
+
+(defmethod get-gracenotes ((choice choice-table) inst k &optional (flag nil) (path (path-empty inst)))
+ (length (nth-value 1 (notes-align choice inst path))))
+
+(defmethod previous-subdiv ((choice choice-table) path)
+ (let* ((val (path-val path))
+ (last-val (car (last val))))
+ (if (= (path-begin path) 0) ;if the current subdivision is the first
+ nil
+ (if (= 1 (cdr last-val))
+ (let* ((father (path-father path)))
+ (previous-subdiv choice father))
+ (path-previous path)))))
+
+(defmethod get-last-input (input path)
+ (let* ((onsets (input-input input))
+ (mask (input-mask input))
+ (begin (path-begin path))
+ (index (position-if #'(lambda (x) (< x begin)) onsets :from-end t)))
+ (if (and index (plusp (aref mask index )))
+ 1
+ 0)))
+
+(defmethod previous-gracenotes (choice input k flag path)
+ (let* ((previous (previous-subdiv choice path)))
+ (if previous
+ (get-gracenotes choice input k flag previous)
+ 0)))
+
+
+;----- Save ------;
+(in-package :om)
+(defmethod om::omng-save ((self rq::choice-table) &optional values?)
+ (let ((choicetable (rq::table self)))
+ `(let* ((choice (make-instance 'rq::choice-table)))
+
+ (setf (rq::table choice) (make-hash-table :test 'equalp))
+
+
+ ,(let ((entries nil))
+
+ (maphash #'(lambda (p e) (setq entries (append entries
+ (list `(gethash ,(om::omng-save p) (rq::table choice)))
+ (list `(list ',(first e) ,(om::omng-save (second e)) ',(third e) ',(fourth e)))))) choicetable)
+ (append (list `setf) entries))
+
+ (setf (rq::modified choice) ,(rq::modified self))
+ (setf (rq::user-edit choice) ',(rq::user-edit self))
+ choice)))
diff --git a/src/gui/editor/multi-poly-editor.lisp b/src/gui/editor/multi-poly-editor.lisp
new file mode 100644
index 0000000..ca68ef7
--- /dev/null
+++ b/src/gui/editor/multi-poly-editor.lisp
@@ -0,0 +1,152 @@
+
+(in-package :rq)
+
+;;; Multi-poly Editor
+;;; All the functions related to the editor in the right panel
+;;; It is built as a poly editor, but the poly displayed can be changed (one of the poly of the polys list of the multi-poly object)
+
+
+
+(defclass! multi-poly-editor (om::polyEditor)
+ ((parent :accessor parent :initval nil)
+ (scroll-pos-list :accessor scroll-pos-list :initval '(0)) ;a list that holds the scroll position for all polys. Initialised with init-scroll-pos-list
+ ))
+
+(defmethod om::get-score-class-panel ((self multi-poly-editor)) 'multi-poly-panel)
+
+
+;; Two functions to save the zoom level for each panel (chord-seq, voice and multi-poly) independently (and not one zoom level for all)
+
+(defmethod om::set-edit-param ((self multi-poly-editor) param newval)
+ "To set a zoom level for the poly panel only"
+ (if (equal param 'om::zoom)
+ (om::set-edit-param (om::ref self) 'poly-zoom newval)
+ (call-next-method)
+))
+
+(defmethod om::get-edit-param ((self multi-poly-editor) param)
+ "To get the zoom level of the poly panel"
+ (if (equal param 'om::zoom)
+ (om::get-edit-param (om::ref self) 'poly-zoom)
+ (call-next-method)
+))
+
+
+;; Key handler for right panel.
+; Left-right : change segment (change displayed poly)
+; Up-down : change selected solution.
+(defmethod om::handle-key-event ((self multi-poly-editor) char)
+ "Handles key events for a `multi-poly-editor'."
+ (cond ((equal char :om-key-right)
+ (change-poly self 1))
+ ((equal char :om-key-left)
+ (change-poly self -1))
+ ((equal char :om-key-up)
+ (let ((mp (wp (om::object (parent self)))))
+ (change-selected-solution self (max (1- (nth (current-poly mp) (selections mp))) 0))))
+ ((equal char :om-key-down)
+ (let ((mp (wp (om::object (parent self)))))
+ (change-selected-solution self (min (1+ (nth (current-poly mp) (selections mp))) (1- (length (om::voices (nth (current-poly mp) (polys mp) ))))))))
+ (t (call-next-method)))
+ )
+
+
+;; Initialises the scroll positions in order for the selected solutions to be displayed when changing poly.
+; The scroll positions are computed from fixed values.
+; It would be better if they were computed from real, on-the-go computed values
+; (the real height of the grap-voice objects inside the grap-poly for exemple)
+; but initialization problems make it difficult.
+(defmethod init-scroll-pos-list ((self multi-poly-editor))
+ "Initialises the scroll position list for all polys"
+ (let* ((qs (om::object (parent self)))
+ (mp (wp qs))
+ (selections (selections mp))
+ (n-sols (get-list-n-solution qs))
+ )
+ (setf (scroll-pos-list self) (loop for select in selections
+ for n-sol in n-sols
+ collect
+ ;;workaround to display the selected voice
+ ;Spacing between 2 voices : 73 ; Spacing between 2 inputs : 22
+ (max 0 (+ -100 (* select 73) (* (floor select n-sol) 22)))
+ )))
+)
+
+(defmethod update-scroll ((self multi-poly-editor))
+ "Scroll the right panel to the correct position (from the scroll-pos-list) to display the selected solution"
+ (init-scroll-pos-list self)
+ (om-set-scroll-position (om::panel self) (om-make-point (om-h-scroll-position (om::panel self)) (nth (current-poly (wp (om::object (parent self)))) (scroll-pos-list self)))))
+
+(defmethod update-title ((self multi-poly-editor))
+ "Displays the selected segment (and the selected voice in this segment) in the title bar of the multi-poly-editor's panel."
+ (let ((mp (wp (om::object (parent self)))))
+ (om::change-text (om::title-bar self)
+ (format nil "SEGMENT ~A - SELEC= ~A"
+ (current-poly mp)
+ (nth (current-poly mp) (selections mp))))))
+
+(defmethod update-poly ((self multi-poly-editor))
+ "To update the poly-panel (redraw the poly, update the title bar)"
+ (let ((mp (wp (om::object (parent self)))))
+ (setf (om::object self) (nth (current-poly mp) (polys mp)))
+ (setf (om::staff-sys (om::panel self)) (om::get-staff-system (om::correct-staff (om::panel self) (om::get-edit-param self 'om::staff))))
+ (let* ((poly (om::object self))
+ (n-solution (or (nth (current-poly mp) (list-n-solution mp)) 1))
+ (ntempo (floor (length (om::voices poly)) n-solution )))
+ (om::score-system-space (om::panel self) (loop for i from 1 to ntempo append (append (make-list (1- n-solution) :initial-element 2) (list 3)))))
+ (update-title self)
+ (om::update-panel (om::panel self))
+))
+
+(defmethod change-poly ((self multi-poly-editor) increment)
+ "Swiches the displayed poly to another (current + increment). Also focuses the view on the selected voice, and stores the previous scroll position."
+ (let ((mp (wp (om::object (parent self))))
+ (panel (om::panel self)))
+ (when (> (length (polys mp)) 1)
+ ;each time the poly is changed, we store the current scroll position in the scroll-pos-list to retrieve it when combing back to that poly
+ (setf (nth (current-poly mp) (scroll-pos-list self)) (om-v-scroll-position panel))
+ (setf (current-poly mp) (mod (+ (current-poly mp) increment) (length (polys mp))))
+ (update-poly self)
+ (om::update-subviews (parent self))
+ (focus-view (chord-seq-editor (parent self)) (current-poly mp))
+ (focus-view (voice-editor (parent self)) (current-poly mp))
+ ;The scroll position is retrieved from the list.
+ (om-set-scroll-position panel (om-make-point (om-h-scroll-position panel) (nth (current-poly mp) (scroll-pos-list self))))
+ )))
+
+(defmethod change-selected-solution ((self multi-poly-editor) selected)
+ "Changes the selected solution in the current poly. Also updates it in the solution (bottom panel)"
+ (let* ((qs (om::object (parent self)))
+ (mp (wp qs))
+ (mes (current-poly mp)))
+ ;Dialog box to ask for confirmation : when the selected solution is changed, it is directly replaced in the bottom panel
+ ;and thus, all the modifications done on the corresponding measure are lost.
+ (when (and (nth mes (choices (solution qs)))
+ (or (not (modified (nth mes (choices (solution qs)))))
+ (om-y-or-n-dialog "The modifications done on this segment will be lost. Continue ?" :default-button :yes)))
+ (setf (nth mes (selections mp)) selected)
+ (update-title self)
+ (update-ks-indexes (solution qs) mp)
+ (init-one-choice (solution qs) mes)
+ (set-tree (solution qs) (update-tree (solution qs) (not (editflag (solution qs)))))
+ (update-grids (solution qs))
+ (om::update-subviews (parent self))
+ (focus-view self mp))))
+
+
+;Focus view only works when changing the selected solution
+;When changing poly, initialization problems in the positions of the voices causes it not to work (always scrolls back to top)
+;When changing poly, the scroll-pos-list is used instead.
+(defmethod focus-view ((self multi-poly-editor) (wp quant-multi-poly))
+ "Makes the scroll follow the selection."
+ (let* ((panel (om::panel self))
+ (selected-index (nth (current-poly wp) (selections wp)))
+ (voices (om::inside (om::graphic-obj panel)))
+ (selected-voice (nth selected-index voices))
+ (v-scroll (om-v-scroll-position panel))
+ (h-scroll (om-h-scroll-position panel)))
+ (cond ((< (second (om::rectangle selected-voice)) v-scroll)
+ (om-set-scroll-position panel (om-make-point h-scroll (- (second (om::rectangle selected-voice)) 30))))
+ ((> (fourth (om::rectangle selected-voice)) (+ v-scroll (om::h panel)))
+ (om-set-scroll-position panel (om-make-point h-scroll (+ (- (fourth (om::rectangle selected-voice)) (om::h panel)) 30)))))))
+
diff --git a/src/gui/editor/quant-chord-seq-editor.lisp b/src/gui/editor/quant-chord-seq-editor.lisp
new file mode 100644
index 0000000..02fbca6
--- /dev/null
+++ b/src/gui/editor/quant-chord-seq-editor.lisp
@@ -0,0 +1,61 @@
+(in-package :rq)
+
+;;; Quant-chord-seq Editor
+;;; All the functions related to the editor in the top panel
+
+(defclass! quant-chord-seq-editor (om::ChordSeqEditor)
+ ((parent :accessor parent :initval nil)))
+
+(defmethod om::get-score-class-panel ((self quant-chord-seq-editor)) 'quant-chord-seq-panel)
+
+;; Two functions to save the zoom level for each panel (chord-seq, voice and multi-poly) independently (and not one zoom level for all)
+
+(defmethod om::set-edit-param ((self quant-chord-seq-editor) param newval)
+ "To set a zoom level for the chord-seq panel only"
+ (if (equal param 'om::zoom)
+ (om::set-edit-param (om::ref self) 'chord-seq-zoom newval)
+ (call-next-method)
+))
+
+(defmethod om::get-edit-param ((self quant-chord-seq-editor) param)
+ "To get the zoom level of the chord-seq panel"
+ (if (equal param 'om::zoom)
+ (om::get-edit-param (om::ref self) 'chord-seq-zoom)
+ (call-next-method)
+))
+
+;; Key handler for top panel.
+; q : to quantify the selected segments
+(defmethod om::handle-key-event ((self quant-chord-seq-editor) char)
+ "Handles key events for a `quant-chord-seq-editor'."
+ (cond ((equal char #\q) ;To quantify only the selected segments
+ (when (om::selected-segments (get-k-best-analysis (om::object self)))
+ (let* ((k-best-analysis (get-k-best-analysis (om::object self)))
+ (select-segment (om::selected-segments k-best-analysis))
+ (indexes (mapcar #'(lambda (segment) (position segment (analysis-segments k-best-analysis))) select-segment))
+ (qs (om::object (parent self))))
+ (mapcar #'compute-one-k-best (make-list (length select-segment) :initial-element qs) select-segment)
+ (mapcar #'replace-one-poly (make-list (length select-segment) :initial-element qs) indexes)
+ (update-ks-indexes (solution qs) (wp qs))
+ (update-scroll (poly-editor (parent self)))
+ (mapcar #'init-one-choice (make-list (length select-segment) :initial-element (solution qs)) indexes)
+ (set-tree (solution qs) (update-tree (solution qs) (not (editflag (solution qs)))))
+ (update-poly (parent self))
+ (om-invalidate-view (om::panel self))
+ )))
+ (t (call-next-method))))
+
+(defmethod focus-view ((self quant-chord-seq-editor) n)
+ "To make the scroll of the chord-seq panel go to the Nth segment"
+ (let* ((panel (om::panel self))
+ (v-scroll (om-v-scroll-position panel))
+ (h-scroll (om-h-scroll-position panel))
+ (chord-seq (om::object self))
+ (segments (analysis-segments (get-k-best-analysis (om::object self))))
+ (current-segment (nth n segments))
+ (begin (om::time-to-pixels panel (om::segment-begin current-segment)))
+ (end (om::time-to-pixels panel (om::segment-end current-segment))))
+ (cond ((< begin (+ h-scroll 50))
+ (om-set-scroll-position panel (om-make-point (max (- begin 150) 0) v-scroll)))
+ ((> end (+ h-scroll (om::w panel)))
+ (om-set-scroll-position panel (om-make-point (+ (- end (om::w panel)) 250) v-scroll))))))
diff --git a/src/gui/editor/quant-editor.lisp b/src/gui/editor/quant-editor.lisp
new file mode 100644
index 0000000..d82b789
--- /dev/null
+++ b/src/gui/editor/quant-editor.lisp
@@ -0,0 +1,270 @@
+
+
+(in-package :rq)
+
+;;;; Quant-editor
+;;; The general editor for a quant-system
+;;; Holds the 3 sub-editors : chord-seq, voice and poly
+
+(defmethod om::class-has-editor-p ((self rq)) t)
+(defmethod om::get-editor-class ((self rq)) 'quant-editor)
+(defmethod om::default-edition-params ((self rq))
+ (list (cons 'om::winsize (or (om::get-win-ed-size self) (om-make-point 370 280)))
+ (cons 'om::winpos (or (om::get-win-ed-pos self) (om-make-point 400 20)))
+ ;initialize the 3 zoom levels for all 3 sub-editors
+ (cons 'chord-seq-zoom 1)
+ (cons 'voice-zoom 1)
+ (cons 'poly-zoom 1)))
+
+(defclass quant-editor (om::editorview)
+ ((chord-seq-editor :accessor chord-seq-editor :initform nil)
+ (voice-editor :accessor voice-editor :initform nil)
+ (poly-editor :accessor poly-editor :initform nil)
+ (buttons :accessor buttons :initform nil)
+ (voice-mode :accessor voice-mode :initarg :voice-mode :initform :edit)
+ (display-mode :accessor display-mode :initarg :display-mode :initform :close)
+ ))
+
+
+(defmethod om::initialize-instance ((self quant-editor) &rest args)
+ (call-next-method)
+ (om-set-bg-color self (om-make-color 0.4 0.4 0.42))
+ (setf (editor (om::object self)) self)
+
+ ;Chord-seq
+ (setf (chord-seq-editor self)
+ (om-make-view 'quant-chord-seq-editor :owner self :object (chord-seq (om::object self)) :ref (om::ref self)
+ :position (om-make-point 10 10) :size (om-make-point 500 300)))
+ (setf (parent (om::object (chord-seq-editor self))) (om::object self))
+ (setf (parent (chord-seq-editor self)) self)
+ (setf (om::score-mode (om::panel (chord-seq-editor self))) 3) ;to be in "segmentation mode" when opening the editor
+ (om-invalidate-view (om::title-bar (chord-seq-editor self)))
+
+ ;Voice
+ (setf (voice-editor self)
+ (om::om-make-view 'quant-voice-editor :owner self :object (solution (om::object self)) :ref (om::ref self)
+ :position (om::om-make-point 10 370) :size (om::om-make-point 500 220)))
+ (setf (om::score-mode (om::panel (voice-editor self))) 0)
+ (setf (parent (voice-editor self)) self)
+
+ ;Poly
+ (setf (poly-editor self)
+ (om::om-make-view 'multi-poly-editor :object (nth (current-poly (wp (om::object self))) (polys (wp (om::object self))))
+ :owner self :ref (om::ref self)
+ :position (om::om-make-point 510 10) :size (om::om-make-point 500 530)))
+ (setf (parent (poly-editor self)) self)
+ (setf (om::score-mode (om::panel (poly-editor self))) 0)
+ (update-poly self)
+ (update-title (poly-editor self))
+
+ (setf (display-mode self) (display-mode (om::object self)))
+
+ (let ((fgc #-linux *om-white-color* #+linux *om-black-color*))
+ (setf (buttons self) (list
+ (om-make-dialog-item 'om-button (om-make-point (- (om::w (om::window self)) 130) 325) (om-make-point 100 20) "Parameters"
+ :di-action #'(lambda (b)
+ (progn
+ (set-global-k-best-parameters (om::object self))
+ (om-invalidate-view (om::panel (chord-seq-editor self)))
+ )))
+
+ (om-make-dialog-item 'om-radio-button (om-make-point (- (om::w (om::window self)) 340) 317) (om-make-point 120 20) "Edit" :font *om-default-font1b* :fg-color fgc
+ :checked-p (editflag (om::object (voice-editor self)))
+ :di-action #'(lambda (b)
+ (edit-mode-quant-voice self)))
+ (om-make-dialog-item 'om-radio-button (om-make-point (- (om::w (om::window self)) 340) 337) (om-make-point 120 20) "Render" :font *om-default-font1b* :fg-color fgc
+ :checked-p (not (editflag (om::object (voice-editor self))))
+ :di-action #'(lambda (b)
+ (render-mode-quant-voice self)))
+ (om-make-dialog-item 'om-check-box
+ (om-make-point (- (om::w (om::window self)) 260) 310) (om-make-point 120 20)
+ "Color mode" :font *om-default-font1b* :fg-color fgc
+ :checked-p (color-flag (om::object self))
+ :di-action #'(lambda (b)
+ (setf (color-flag (om::object self)) (not (color-flag (om::object self)))
+ (colorflag (solution (om::object self))) (not (colorflag (solution (om::object self)))))
+ (setf (om::selected-p b) (color-flag (om::object self)))
+ (om::update-subviews self)))
+ (om-make-dialog-item 'om-check-box
+ (om-make-point (- (om::w (om::window self)) 260) 330) (om-make-point 120 20)
+ "Show pulses" :font *om-default-font1b* :fg-color fgc
+ :checked-p (pulse-flag (om::object self))
+ :di-action #'(lambda (b)
+ (setf (pulse-flag (om::object self)) (not (pulse-flag (om::object self)))
+ (pulse-flag (chord-seq (om::object self))) (not (pulse-flag (chord-seq (om::object self)))))
+ (setf (om::selected-p b) (pulse-flag (om::object self)))
+ (om::update-subviews self)))
+ (om-make-dialog-item 'om-check-box
+ (om-make-point (- (om::w (om::window self)) 260) 350) (om-make-point 120 20)
+ "Show solutions" :font *om-default-font1b* :fg-color fgc
+ :checked-p (equal :open (display-mode self))
+ :di-action #'(lambda (b)
+ (if (equal :close (display-mode self))
+ (open-poly-edit self)
+ (close-poly-edit self))
+ (setf (om::selected-p b) (equal :open (display-mode self))))))))
+
+
+ (om-add-subviews self
+ (om-make-dialog-item 'om-button (om-make-point 10 325) (om-make-point 115 20) "Segmentation"
+ :di-action #'(lambda (b)
+ (when (om-y-or-n-dialog "This will delete the current segmentation. Continue ?" :default-button :yes)
+ (om::compute-segments (get-k-best-analysis (chord-seq (om::object self))) (chord-seq (om::object self)))
+ (om-invalidate-view (om::panel (chord-seq-editor self))))))
+
+ (om-make-dialog-item 'om-button (om-make-point 120 325) (om-make-point 100 20) "Quantify"
+ :di-action #'(lambda (b)
+ (when (om-y-or-n-dialog "This will delete the current quantification. Continue ?" :default-button :yes)
+ (if (null (get-k-best-segments (om::object self)))
+ (om-message-dialog "Nothing to analyse. Please segment input.")
+ (progn
+ (compute-k-best (om::object self))
+ (when (not (member nil (k-bests (om::object self))))
+ (setf (wp (om::object self)) (make-working-poly (om::object self)))
+ (update-poly self)
+ (init-solution (om::object self))
+ (update-grids (solution (om::object self)))
+ (om-invalidate-view (om::panel (chord-seq-editor self)))
+ (om::update-panel (om::panel (poly-editor self)))
+ (om::update-panel (om::panel (voice-editor self)))
+ (update-poly self)
+ (update-scroll (poly-editor self))))))))
+
+ (om-make-dialog-item 'om-button (om-make-point 215 325) (om-make-point 120 20) "Tempo-smooth"
+ :di-action #'(lambda (b)
+ (setf (selections (wp (om::object self))) (get-smoothed-selections (om::object self)))
+ (update-poly self)
+ (init-solution (om::object self))
+ (update-grids (solution (om::object self)))
+ (update-scroll (poly-editor self))))
+
+ (first (buttons self))
+ (second (buttons self))
+ (third (buttons self))
+ (fourth (buttons self))
+ (fifth (buttons self))
+ (sixth (buttons self))
+ )
+ self)
+
+(defmethod update-poly ((self quant-editor))
+ "To update the poly-panel (redraw the poly, update the title bar)"
+ (update-poly (poly-editor self))
+ )
+
+
+(defmethod om::update-subviews ((self quant-editor))
+ "Handles subviews resizing (when the right panel is diplayed or hidden)"
+ (cond ((equal (display-mode self) :open)
+ (let ((middle (round (- (om::w self) 20) 2)))
+ (om-set-view-size (chord-seq-editor self) (om-make-point middle (om::h (chord-seq-editor self))))
+ (om-set-view-size (voice-editor self) (om-make-point middle (- (om::h self) (om::h (chord-seq-editor self)) 80)))
+ (om-set-view-position (poly-editor self) (om-make-point (+ middle 20) 10))
+ (om-set-view-size (poly-editor self) (om-make-point (- middle 10) (- (om::h self) 20)))
+ (update-buttons self :open)))
+ ((equal (display-mode self) :close)
+ (progn
+ (om-set-view-size (chord-seq-editor self) (om-make-point (- (om::w self) 20) (om::h (chord-seq-editor self))))
+ (om-set-view-size (voice-editor self) (om-make-point (- (om::w self) 20) (- (om::h self) (om::h (chord-seq-editor self)) 80)))
+ (om-set-view-position (poly-editor self) (om-make-point (om::w self) 10 ))
+ (update-buttons self :close)))
+ ((equal (display-mode self) :closing)
+ (progn
+ (om-set-view-position (poly-editor self) (om-make-point (om::x (poly-editor self)) (om::y (poly-editor self))))
+ (om-set-view-size (poly-editor self) (om-make-point (round (- (om::w self) 40) 2) (om::h (poly-editor self))))))
+ ((equal (display-mode self) :opening)
+ (progn
+ (om-set-view-position (poly-editor self) (om-make-point (+ (om::w (chord-seq-editor self)) 20) (om::y (poly-editor self))))
+ (om-set-view-size (poly-editor self) (om-make-point (- (om::w self) 20 (om::x (poly-editor self) ) ) (- (om::h self) 20)))))))
+
+(defmethod update-buttons ((self quant-editor) display-mode)
+ "Updates the position of all the buttons"
+ (let ((middle (round (- (om::w self) 20) 2))
+ (button1 (first (buttons self)))
+ (button2 (second (buttons self)))
+ (button3 (third (buttons self)))
+ (button4 (fourth (buttons self)))
+ (button5 (fifth (buttons self)))
+ (button6 (sixth (buttons self))))
+ (cond ((equal display-mode :open)
+ (let ((middle (round (- (om::w self) 20) 2)))
+ (om-set-view-position button1 (om-make-point (- middle 110) (om::y button1)))
+ (om-set-view-position button2 (om-make-point (- middle 320) (om::y button2)))
+ (om-set-view-position button3 (om-make-point (- middle 320) (om::y button3)))
+ (om-set-view-position button4 (om-make-point (- middle 240) (om::y button4)))
+ (om-set-view-position button5 (om-make-point (- middle 240) (om::y button5)))
+ (om-set-view-position button6 (om-make-point (- middle 240) (om::y button6)))))
+ ((equal display-mode :close)
+ (om-set-view-position button1 (om-make-point (- (om::w self) 130) (om::y button1)))
+ (om-set-view-position button2 (om-make-point (- (om::w self) 340) (om::y button2)))
+ (om-set-view-position button3 (om-make-point (- (om::w self) 340) (om::y button3)))
+ (om-set-view-position button4 (om-make-point (- (om::w self) 260) (om::y button4)))
+ (om-set-view-position button5 (om-make-point (- (om::w self) 260) (om::y button5)))
+ (om-set-view-position button6 (om-make-point (- (om::w self) 260) (om::y button6)))))))
+
+
+(defmethod close-poly-edit ((self quant-editor))
+ "A sequence to close the poly panel"
+ (om::set-edit-param (om::ref self) 'display-mode :close)
+ (setf (display-mode self) :closing)
+ (om::update-subviews self)
+ (om-set-view-size (om::window self) (om-make-point (om-point-h (om::get-win-ed-size (om::object self)) ) (om-point-v (om-view-size (om::window self)))))
+ (setf (display-mode self) :close)
+ (setf (display-mode (om::object self)) :close)
+ (om::update-subviews self))
+
+(defmethod open-poly-edit ((self quant-editor))
+ "A sequence to open the poly panel"
+ (om::set-edit-param (om::ref self) 'display-mode :open)
+ (setf (display-mode self) :opening)
+ (om::update-subviews self)
+ (om-set-view-size (om::window self) (om-make-point (om-point-h (om::get-win-ed-size2 (om::object self)) ) (om-point-v (om-view-size (om::window self)))))
+ (setf (display-mode self) :open)
+ (setf (display-mode (om::object self)) :open)
+ (om::update-subviews self))
+
+;; diplay-mode = :open / :close
+;; => 2 default sizes
+(defmethod om::get-win-ed-size ((self rq) ) (om-make-point 750 590))
+(defmethod om::get-win-ed-size2 ((self rq)) (om-make-point 1500 590))
+
+
+(defmethod render-mode-quant-voice ((self quant-editor))
+ "To set the voice to Render mode"
+ (om::set-edit-param (om::ref self) 'voice-mode :render)
+ (setf (voice-mode self) :render)
+ (set-tree (om::object (voice-editor self)) (update-tree (om::object (voice-editor self)) t))
+ (setf (editflag (om::object (voice-editor self))) nil))
+
+(defmethod edit-mode-quant-voice ((self quant-editor))
+ "To set the voice to Edit mode"
+ (om::set-edit-param (om::ref self) 'voice-mode :edit)
+ (setf (voice-mode self) :edit)
+ (set-tree (om::object (voice-editor self)) (update-tree (om::object (voice-editor self)) nil))
+ (setf (editflag (om::object (voice-editor self))) t))
+
+;;;; Key event handlers:
+(defmethod om::handle-key-event ((self quant-editor) char)
+ "Handles key events for a `quant-editor'. All the key events are redirected to each sub-editor, depending of the last clicked panel."
+ (cond ((equal *clicked-panel* (om::panel (chord-seq-editor self)))
+ (om::handle-key-event (chord-seq-editor self) char))
+ ((equal *clicked-panel* (om::panel (voice-editor self)))
+ (om::handle-key-event (voice-editor self) char))
+ ((equal *clicked-panel* (om::panel (poly-editor self)))
+ (om::handle-key-event (poly-editor self) char))
+ (t (call-next-method))))
+
+
+
+;;; Mouse event handlers:
+(defvar *clicked-panel* nil) ; A hack to catch key events on each editor.
+
+(defmethod om-view-click-handler :before ((self om::scorePanel) where)
+ (setf *clicked-panel* self))
+
+
+
+
+
+
+
diff --git a/src/gui/editor/quant-voice-editor.lisp b/src/gui/editor/quant-voice-editor.lisp
new file mode 100644
index 0000000..47fc9fd
--- /dev/null
+++ b/src/gui/editor/quant-voice-editor.lisp
@@ -0,0 +1,54 @@
+
+(in-package :rq)
+
+;;; Quant-chord-seq Editor
+;;; All the functions related to the editor in the bottom panel
+
+(defclass! quant-voice-editor (om::voiceEditor)
+ ((parent :accessor parent :initval nil)))
+
+(defmethod om::get-score-class-panel ((self quant-voice-editor)) 'quant-voice-panel)
+
+;; Two functions to save the zoom level for each panel (chord-seq, voice and multi-poly) independently (and not one zoom level for all)
+
+(defmethod om::set-edit-param ((self quant-voice-editor) param newval)
+ "To set a zoom level for the voice panel only"
+ (if (equal param 'om::zoom)
+ (om::set-edit-param (om::ref self) 'voice-zoom newval)
+ (call-next-method)
+))
+
+(defmethod om::get-edit-param ((self quant-voice-editor) param)
+ "To get the zoom level of the voice panel"
+ (if (equal param 'om::zoom)
+ (om::get-edit-param (om::ref self) 'voice-zoom)
+ (call-next-method)
+))
+
+
+;; Key handler for top panel.
+; e : to open the dialog box that allows to type manually a subtree
+(defmethod om::handle-key-event ((self quant-voice-editor) char)
+ "Handles key events for a `quant-voice-editor'."
+ (cond ((equal char #\e)
+ (when (om::selection? (om::panel self))
+ (when (open-user-edit-panel (om::panel self) (car (om::selection? (om::panel self))))
+ (set-tree (om::object self) (update-tree (om::object self) (not (editflag (om::object self)))))
+ )))
+ (t (call-next-method))))
+
+
+
+(defmethod focus-view ((self quant-voice-editor) n)
+ "To make the scroll of the voice panel go to the Nth measure"
+ (let* ((panel (om::panel self))
+ (v-scroll (om-v-scroll-position panel))
+ (h-scroll (om-h-scroll-position panel))
+ (measures (om::inside (om::graphic-obj panel)))
+ (current-measure (nth n measures))
+ (begin (first (om::rectangle current-measure)))
+ (end (third (om::rectangle current-measure))))
+ (cond ((< begin (+ h-scroll 50))
+ (om-set-scroll-position panel (om-make-point (max (- begin 150) 0) v-scroll)))
+ ((> end (+ h-scroll (om::w panel) -50))
+ (om-set-scroll-position panel (om-make-point (+ (- end (om::w panel)) 250) v-scroll))))))
diff --git a/src/gui/panel/multi-poly-panel.lisp b/src/gui/panel/multi-poly-panel.lisp
new file mode 100644
index 0000000..49b2664
--- /dev/null
+++ b/src/gui/panel/multi-poly-panel.lisp
@@ -0,0 +1,58 @@
+
+(in-package :rq)
+
+;;; Multi-poly Panel
+;;; All the functions related to the right panel
+
+(defclass multi-poly-panel (om::polyPanel)
+ ())
+
+; When the poly panel is clicked, updates the chord-seq panel in order to update the grid
+; (when a tempo is specified and the chord-seq panel is clicked, display the position of the beats, otherwise, display the quantization grid.)
+(defmethod om-view-click-handler :after ((self multi-poly-panel) where)
+ "Updates the chord-seq panel when the poly panel is clicked"
+ (when (parent (om::editor self))
+ (om::update-panel (om::panel (chord-seq-editor (parent (om::editor self)))))))
+
+;Double-click on a voice to select it
+(defmethod om-view-doubleclick-handler ((self multi-poly-panel) where)
+ "Select a voice when double-clicking it."
+ (when (parent (om::editor self))
+ (let* ((y-click (om-point-y where))
+ (voices (om::inside (om::graphic-obj self)))
+ (y-voices (mapcar #'(lambda (x) (second (om::rectangle x))) voices))
+ (selected (or (position-if #'(lambda (x) (<= x y-click)) y-voices :from-end t) 0)))
+ (change-selected-solution (om::editor self) selected)
+ )))
+
+
+(defmethod om::draw-object :after ((self om::grap-voice) (view multi-poly-panel) x y zoom minx maxx miny maxy slot size linear? staff grille-p chnote)
+ "Draws additional information (distance, number of grace-notes) for a multi-poly panel. Also highlights the selected voice on the current segment."
+ (let* ((mp (wp (om::value (om::ref (om::editor view)))))
+ (poly (om::parent (om::reference self)))
+ (distlist (distances mp))
+ (gracenotes (gracenotes mp))
+ (current-voice (position (om::reference self) (om::voices poly)))
+ (current-dist (nth current-voice (nth (current-poly mp) distlist)))
+ (current-grace (nth current-voice (nth (current-poly mp) gracenotes))))
+
+ ;Display distance
+ (om-with-fg-color view (distance-to-color current-dist)
+ (om-with-font *om-default-font1b*
+ (om-draw-string (+ (om::x view) 50 (om-h-scroll-position view)) (- (second (om::rectangle self)) 5) (format nil "Error = ~A%" current-dist))))
+ ;Display number of gracenotes
+ (unless
+ (or (null current-grace) (zerop current-grace))
+ (om-with-fg-color view *om-gray-color*
+ (om-with-dashline '(2 2)
+ (om-draw-line (+ (third (om::rectangle self)) 40) (- (second (om::rectangle self)) 10)
+ (+ (third (om::rectangle self)) 40) (+ (fourth (om::rectangle self)) 5)))
+ (om-draw-string (+ (third (om::rectangle self)) 50) (+ (second (om::rectangle self)) 25)
+ (make-string current-grace :initial-element #\N))))
+ ;Highlights selected segment
+ (when (= (nth (current-poly mp) (selections mp)) current-voice)
+ (om-with-fg-color view (om-make-color-alpha 0.6 0.4 0.4 0.4)
+ (om-fill-rect (nth 0 (om::rectangle self)) (nth 1 (om::rectangle self))
+ (- (nth 2 (om::rectangle self)) (nth 0 (om::rectangle self)))
+ (- (nth 3 (om::rectangle self)) (nth 1 (om::rectangle self))))))))
+
diff --git a/src/gui/panel/quant-chord-seq-panel.lisp b/src/gui/panel/quant-chord-seq-panel.lisp
new file mode 100644
index 0000000..274ad7b
--- /dev/null
+++ b/src/gui/panel/quant-chord-seq-panel.lisp
@@ -0,0 +1,23 @@
+
+(in-package :rq)
+
+;;; Quant-chord-seq Panel
+;;; All the functions related to the top panel
+;;; No "draw-object" redifinition here, the additional info of the top panel are included in k-best-analysis.lisp (function draw-segment-data)
+
+(defclass! quant-chord-seq-panel (om::ChordSeqPanel) ())
+
+;Double-click on a segment in the top panel to go to that segment in the right panel
+(defmethod om-view-doubleclick-handler ((self quant-chord-seq-panel) where)
+ "When double-clicking on a segment in the chord-seq panel, display this segment in the k-best panel."
+ (when (plusp (om::pixels-to-time self (om-point-x where)))
+ (let* ((time (om::pixels-to-time self (om-point-x where)))
+ (k-best-analysis (get-k-best-analysis (om::object (om::editor self))))
+ (segments (analysis-segments k-best-analysis))
+ (begins (mapcar #'om::segment-begin segments))
+ (selected (position-if #'(lambda (x) (<= x time)) begins :from-end t))
+ (wp (wp (parent (om::object (om::editor self))))))
+ (when selected
+ (change-poly (poly-editor (parent (om::editor self))) (- selected (current-poly wp))))
+ (om-invalidate-view self)))
+ (call-next-method))
diff --git a/src/gui/panel/quant-voice-panel.lisp b/src/gui/panel/quant-voice-panel.lisp
new file mode 100644
index 0000000..c307bd0
--- /dev/null
+++ b/src/gui/panel/quant-voice-panel.lisp
@@ -0,0 +1,202 @@
+(in-package :rq)
+
+;;; Quant-voice Panel
+;;; All the functions related to the bottom panel
+;;; In particular, there are the functions to open the editor dialog (with the list of propositions for a subtree) and the user-edit dialog (to type a subtree)
+
+(defclass! quant-voice-panel (om::voicePanel)
+ ())
+
+;Update the chord-seq view each time the voice-panel is clicked
+;in order to highlight in the top panel the segment that corresponds to the selected subtree.
+(defmethod om-view-click-handler ((self quant-voice-panel) where)
+ "When the voice panel is clicked, updates the chord-seq panel to highlight the current subdivision."
+ (call-next-method)
+ (when (parent (om::editor self))
+ (om::update-panel (om::panel (chord-seq-editor (parent (om::editor self)))))))
+
+;Double click on a measure in the bottom panel to go to that segment in the right panel
+(defmethod om-view-doubleclick-handler ((self quant-voice-panel) where)
+ "When the voice panel is double-clicked, go to this segment in all views."
+ (when (plusp (om::pixels-to-time self (om-point-x where)))
+ (let* ((x-click (om-point-x where))
+ (measures (om::inside (om::graphic-obj self)))
+ (x-list (mapcar #'(lambda (mes) (car (om::rectangle mes))) measures))
+ (selected (position-if #'(lambda (x) (<= x x-click)) x-list :from-end t))
+ (wp (wp (rq (om::object (om::editor self))))))
+ (when selected
+ (change-poly (poly-editor (parent (om::editor self))) (- selected (current-poly wp))))
+ (om-invalidate-view self)))
+ (call-next-method))
+
+
+
+(defmethod om::draw-object :after ((self om::grap-voice) (view quant-voice-panel) x y zoom minx maxx miny maxy slot size linear? staff grille-p chnote)
+ "To draw the additional info in the quant-voice"
+ (let* ((qs (om::value (om::ref (om::editor view))))
+ (current (current-poly (wp qs)))
+ (measures (om::inside self))
+ (current-measure (nth current measures)))
+ ;Draw a rectangle around the selected measure
+ (om-with-fg-color view om::*om-red2-color*
+ (om-draw-rect-outline (nth 0 (om::rectangle current-measure))
+ (- (nth 1 (om::rectangle current-measure)) 10)
+ (- (nth 2 (om::rectangle current-measure)) (nth 0 (om::rectangle current-measure)))
+ (+ (- (nth 3 (om::rectangle current-measure)) (nth 1 (om::rectangle current-measure))) 20)
+ 1))))
+
+;The purpose of the following functions is to open the dialog with the possible transcriptions when a group, a note or a rest is double-clicked
+(defmethod om::obj-for-internal-editor ((self om::group)) (if (equal (type-of (om::get-root-parent self)) 'quant-voice) '(group-selection) nil))
+(defmethod om::obj-for-internal-editor ((self om::chord)) (if (equal (type-of (om::get-root-parent self)) 'quant-voice) '(group-selection) (list 'om::chordEditor "internal chord")))
+(defmethod om::obj-for-internal-editor ((self om::rest)) (if (equal (type-of (om::get-root-parent self)) 'quant-voice) '(group-selection) nil))
+(defmethod om::obj-for-internal-editor ((self om::continuation-chord)) (if (equal (type-of (om::get-root-parent self)) 'quant-voice) '(group-selection) nil))
+
+(defmethod om::handle-internal-open ((self quant-voice-panel) (type (eql 'group-selection)) (obj om::chord) add-info)
+ (choose-and-update-solution self type obj add-info))
+(defmethod om::handle-internal-open ((self quant-voice-panel) (type (eql 'group-selection)) (obj om::group) add-info)
+ (choose-and-update-solution self type obj add-info))
+(defmethod om::handle-internal-open ((self quant-voice-panel) (type (eql 'group-selection)) (obj om::rest) add-info)
+ (choose-and-update-solution self type obj add-info))
+
+;---------- Functions to open the panel with the various propositions of a particular subtree ----------;
+
+(defmethod choose-and-update-solution ((self quant-voice-panel) (type (eql 'group-selection)) obj add-info)
+ "Opens the dialog containing all the possible transcriptions, then updates the choice-table and the voice's tree. Also focuses the view of the chord-seq on the current subdivision"
+ (focus-view (chord-seq-editor (parent (om::editor self))) (or (car (get-cons-list obj)) 0))
+ (let ((dialog-return t))
+ ;as long as the "more" button is pressed, re-open the dialog
+ (loop while (equal dialog-return t) do
+ (setq dialog-return (open-trees-panel self type obj add-info)))
+ ;when a solution has been selected
+ (when (numberp dialog-return)
+ (let ((voice (om::object (om::editor self))))
+ (set-tree-choice obj voice dialog-return)
+ (set-tree voice (update-tree voice (not (editflag voice)))))
+)))
+
+(defmethod open-trees-panel ((self quant-voice-panel) (type (eql 'group-selection)) obj add-info)
+ "Opens the tree panel, that displays the othe solutions for the object OBJ selected"
+
+ (when (editflag (om::object (om::editor self))) ;when edition is allowed
+ (unless (is-in-edited-group obj (om::object (om::editor self)) :equal? nil) ;disable edition when inside a tree that was edited by the user
+ ;(but allow it for the group that was modified)
+ (let* ((voice (om::object (om::editor self)))
+ (gracenotes (get-gracenotes-from-obj obj voice))
+ (colors (get-colors obj voice) )
+ (signature (get-signature-of-group obj voice))
+ (h (max 70 (+ 70 (* 65 (length gracenotes)))))
+ (selection nil)
+ (dialog (om-make-window 'om-dialog
+ :size (om-make-point 260 (min h 550))
+ :window-title "" :owner nil
+ :maximize nil :minimize nil :resizable t
+ :position (om-add-points (om-view-position (om::window self)) (om-mouse-position self))))
+
+ (choice-panel (om-make-view 'om-scroller
+ :scrollbars :v
+ :background :gray
+ :field-size (om-make-point 235 (- h 60))
+ :position (om-make-point 10 5)
+ :size (om-make-point 235 (min (- h 60) 490))))
+
+
+ (morebutton (om-make-dialog-item 'om-button (om-make-point (- (om::w dialog) 90) (- (om::h dialog) 45)) (om-make-point 70 15) "More"
+ :di-action (om-dialog-item-act item
+ (declare (ignore item))
+ (compute-more-solutions voice obj 3)
+ (om-return-from-modal-dialog dialog t)
+ )
+ :focus nil :default-button nil)))
+ (om-set-bg-color choice-panel (om-make-color 0.95 0.95 0.95))
+
+ (multiple-value-bind (trees more?) (get-trees obj voice)
+ (om-add-subviews dialog choice-panel)
+ (apply 'om-add-subviews
+ choice-panel
+ (loop for a-tree in trees
+ for grace in gracenotes
+ for color in colors
+ for i = 0 then (+ i 1) collect
+ (let* ((b-tree (if (numberp a-tree) (list a-tree '(1)) a-tree))
+ (view (om-make-view 'tree-view :position (om-make-point 10 (+ 10 (* i 65)))
+ :size (om-make-point 200 60)
+ :tree (make-instance 'tree-voice
+ :tree (list '? (list (list
+ signature
+ (list (list 1 (cadr b-tree))))))
+ :chords '(6200)
+ :dist (first color)
+ :color (second color))
+ :gracenotes grace
+ :dialog dialog
+ :k i)))
+ view)))
+
+
+ (apply 'om-add-subviews
+ (cons dialog
+ (list
+ morebutton
+ (om-make-dialog-item 'om-button (om-make-point 20 (- (om::h dialog) 45)) (om-make-point 70 15) (om::om-str :cancel)
+ :di-action (om-dialog-item-act item
+ (declare (ignore item))
+ (om-return-from-modal-dialog dialog nil))
+ :focus nil :default-button t)
+ )))
+ (om-enable-dialog-item morebutton more?)
+ (om-modal-dialog dialog))))))
+
+
+;------ Function to open the panel allowing the user to hand-write a subtree ------;
+
+(defmethod open-user-edit-panel ((self quant-voice-panel) obj)
+ "Opens the panel to type in an OM rhythm tree"
+ (when (editflag (om::object (om::editor self)))
+
+ (let* ((voice (om::object (om::editor self)))
+ (win (om-make-window 'om-dialog :position :centered
+ :size (om-make-point 400 150)))
+ (pane (om-make-view 'om-view
+ :size (om-make-point 370 130)
+ :position (om-make-point 10 10)
+ :bg-color *om-white-color*))
+ (cons-list (get-cons-list obj))
+ (current-tree (get-subtree (om::tree voice) cons-list))
+ treetxt)
+ (om-add-subviews pane
+ (om-make-dialog-item 'om-static-text (om-make-point 20 20)
+ (om-make-point 380 40)
+ "Replace selection by the following subtree:"
+ :font *om-default-font2b*)
+
+ (setf treetxt (om-make-dialog-item 'om-editable-text (om-make-point 20 60) (om-make-point 330 13)
+ (format nil "~D" current-tree)
+ :font *om-default-font1*))
+ (om-make-dialog-item 'om-button (om-make-point 100 90)
+ (om-make-point 80 20)
+ "Cancel"
+ :di-action (om-dialog-item-act item
+ (om-return-from-modal-dialog win nil)))
+
+ (om-make-dialog-item 'om-button (om-make-point 200 90)
+ (om-make-point 80 20)
+ "OK"
+ :di-action (om-dialog-item-act item
+ (let ((tree (ignore-errors (read-from-string (om-dialog-item-text treetxt))))
+ (choice (nth (car cons-list) (choices voice)))
+ )
+ (if (tree-equal (om::resolve-? tree) tree) ;if the input tree is a correct rhythm-tree
+ (progn
+ (add-change-to-user-edit choice (cdr cons-list) tree)
+ (setf (modified choice) t)
+ (om-return-from-modal-dialog win t))
+ (error (format nil "Invalid Rhythm Tree : ~A" tree))
+ )))))
+
+ (om-add-subviews win pane)
+ (om-modal-dialog win)
+
+)))
+
+
+
diff --git a/src/gui/panel/tree-view.lisp b/src/gui/panel/tree-view.lisp
new file mode 100644
index 0000000..a1ecead
--- /dev/null
+++ b/src/gui/panel/tree-view.lisp
@@ -0,0 +1,74 @@
+
+(in-package :rq)
+
+
+;------------ TREE VOICE and TREE VIEW -------------;
+; The voices and views used in the internal editor
+; They are created by the function open-tree-panel (cf. quant-voice-panel.lisp)
+
+(defclass tree-voice (voice)
+ ((dist :accessor dist :initarg :dist :initform nil)
+ (color :accessor color :initarg :color :initform nil)))
+
+(defmethod om::get-object-selection-color ((self t) (in tree-voice))
+ (color in)
+)
+
+(defclass tree-view (om-view)
+ ((tree :accessor tree :initarg :tree :initform nil)
+ (gracenotes :accessor gracenotes :initarg :gracenotes :initform nil)
+ (dialog :accessor dialog :initarg :dialog :initform nil) ;tree-views are always created inside a dialog window
+ (k :accessor k :initarg :k :initform nil))) ;index of the proposition in the list
+
+;Double-click on a solution to select it (returns the index of the solution)
+(defmethod om-view-doubleclick-handler ((self tree-view) pos)
+ "When a solution is double-clicked, return from dialog its index"
+ (om-return-from-modal-dialog (dialog self) (k self))
+)
+
+(defmethod om-draw-contents ((self tree-view))
+ "Draws each solution in editor mode"
+ (when (tree self)
+ (let* ((obj (tree self))
+ (sizefont 20)
+ (om::*internal-score-fonts* (om::init-fonts-to-draw sizefont))
+ (om::*draw-mini-pict* t)
+ (staffsys (om::get-staff-system 'om::empty))
+ (scale om::*current-1/2-scale*)
+ (grapobj (om::make-graph-form-obj obj 0 (om::get-miniview-top obj staffsys) (/ sizefont 4) 0 scale nil staffsys t)))
+ (when grapobj
+ (om::space-objects grapobj sizefont)
+ (om::set-graph-rectangles grapobj)
+ (om-with-focused-view self
+ (om-with-line-size 1
+ (om-with-font
+ (om::get-font-to-draw 0)
+ (om::draw-object-ryth (car (om::inside (car (om::inside grapobj)))) self
+ 0 -35 0.8
+ 0 (om::w self) 0 (om::h self)
+ 'om::midic sizefont t staffsys nil)
+
+ ;Add colors
+ (when (color obj)
+ (om::draw-score-selection
+ (car (om::inside (car (om::inside grapobj)))) (list (om::reference (car (om::inside (car (om::inside grapobj)))))) staffsys sizefont))
+
+ ;Draw gracenotes
+ (unless (zerop (gracenotes self))
+ (om-with-fg-color self *om-gray-color*
+ (om-with-dashline '(2 2)
+ (om-draw-line (- (om::w self) 60) (- (om::h self) 10)
+ (- (om::w self) 60) 10))
+
+ (om-draw-string (- (om::w self) 50) 45 (make-string (gracenotes self) :initial-element #\N))))
+
+ ;Display error
+ (om-with-fg-color self (color obj)
+ (om-with-font *om-default-font1b*
+ (om-draw-string 10 10 (format nil "Error = ~A%" (dist obj)))))
+
+
+ )))
+ ))))
+
+
diff --git a/src/gui/quant-chord-seq.lisp b/src/gui/quant-chord-seq.lisp
new file mode 100644
index 0000000..608dd59
--- /dev/null
+++ b/src/gui/quant-chord-seq.lisp
@@ -0,0 +1,52 @@
+(in-package :rq)
+
+;;Quant-chord-seq
+;;special chord-seq to allow different treatments when inside a RQ system
+
+(defclass! quant-chord-seq (chord-seq)
+ ((parent :accessor parent :initval nil)
+ (pulse-flag :accessor pulse-flag :initarg :pulse-flag :initform nil)))
+
+
+(defmethod chord-seq->quant-chord-seq ((chord-seq chord-seq))
+ "Translates a `chord-seq' into a `quant-chord-seq'."
+ ;; ensure input is time-ordered
+ (let ((cs (if (apply #'<= (om::lonset chord-seq))
+ chord-seq
+ (let ((cs (om::clone chord-seq)))
+ (om-beep-msg "rq: re-ordering input chord-seq to ascending time")
+ (setf cs (om::temporal-sort cs))
+ cs))))
+ (make-instance 'quant-chord-seq
+ :lmidic (om::lmidic cs)
+ :lonset (om::lonset cs)
+ :ldur (om::ldur cs)
+ :lvel (om::lvel cs)
+ :loffset (om::loffset cs)
+ :lchan (om::lchan cs)
+ :legato (om::legato cs))))
+
+(defmethod chord-seq->quant-chord-seq ((quant-chord-seq quant-chord-seq))
+ quant-chord-seq)
+
+(defmethod get-segment-chords ((self quant-chord-seq) (segment om::segment))
+ "Returns the list of all the notes (in midic) inside the segment (including the last of the previous segment when it overlaps the current segment)"
+ (let ((begin (om::segment-begin segment))
+ (end (om::segment-end segment))
+ (onsets (om::lonset self))
+ (chords (om::lmidic self))
+ (slur (slur (segment-data segment)))
+ out)
+ (setq out (loop for on in onsets for chord in chords when (and (>= on begin) (< on end)) collect chord ))
+ ;When the last note of the previous segment overlaps the current segment
+ (when slur
+ (let* ((prev-segment (om::previous-segment segment))
+ (prev-chords (get-segment-chords self prev-segment)))
+ (setq out (append (last prev-chords) out ))))
+ out))
+
+(defmethod get-k-best-segment-chords ((self quant-chord-seq))
+ "Gets the chords for each segment, separated in lists"
+ (let* ((k-best-analysis (get-k-best-analysis self))
+ (analysis-segments (analysis-segments k-best-analysis)))
+ (mapcar #'get-segment-chords (make-list (length analysis-segments) :initial-element self) analysis-segments)))
diff --git a/src/gui/quant-multi-poly.lisp b/src/gui/quant-multi-poly.lisp
new file mode 100644
index 0000000..341c39a
--- /dev/null
+++ b/src/gui/quant-multi-poly.lisp
@@ -0,0 +1,41 @@
+
+
+(in-package :rq)
+
+;;;; Quant-multi-poly
+;;;; Contains all the functions relative to the multi-poly object (the "k-best" view of the rq, right panel).
+;; A special 'multi-poly' allowing to choose a current solution for each segment.
+(defclass! quant-multi-poly ()
+ ((polys :accessor polys :initform (list (make-instance 'poly :voices (list (make-instance 'voice :tree '(1 (((4 4) (-1)))))))) :initarg :polys)
+ (current-poly :accessor current-poly :initform 0 :initarg :current-poly) ;; current poly in editor
+ (selections :accessor selections :initform '(0) :initarg :selections) ;;; there is one selected voice for each poly/segment
+ (distances :accessor distances :initform (list (list 0)) :initarg :distances) ;List of list holding the distance value for each proposition (one list of size n-sol) for each segment
+ (gracenotes :accessor gracenotes :initform '((0)) :initarg :gracenotes) ;List of list holding the number of gracenotes at the end of the solution for each proposition (one list of size n-sol) for each segment
+ (list-n-solution :accessor list-n-solution :initform '(1) :initarg :list-n-solution))) ;list holding the n-solution for each poly
+
+(defmethod class-has-editor-p ((self quant-multi-poly)) t)
+(defmethod get-editor-class ((self quant-multi-poly)) 'multi-poly-editor)
+
+;;; NOT USED ANYMORE : TEMPO RECONSTRUCTED FROM CHOICE-TABLES IN VOICE, NOT FROM THE SELECTED TRANSCRIPTIONS.
+(defmethod get-tempo ((self quant-multi-poly))
+ "Returns a list of tempi compatible with a voice corresponding to the tempi of the selected transcriptions."
+ (let* ((selections (selections self))
+ (select-voices (loop for poly in (polys self)
+ for select in selections collect
+ (nth select (om::voices poly))))
+ (tempi (loop for voice in select-voices collect (om::tempo voice)))
+ (tempo1 (car tempi))
+ (prev-temp tempo1)
+ (tempo2 nil)
+ )
+
+ (when (rest tempi)
+ (setq tempo2 (loop for temp in (rest tempi)
+ for i = 1 then (1+ i)
+ unless (equalp prev-temp temp)
+ collect (list (list i 0) (car temp))
+ do (setq prev-temp temp))))
+ (append (list (car tempo1)) (list tempo2))
+ ))
+
+
diff --git a/src/gui/quant-voice.lisp b/src/gui/quant-voice.lisp
new file mode 100644
index 0000000..fa2e93d
--- /dev/null
+++ b/src/gui/quant-voice.lisp
@@ -0,0 +1,360 @@
+(in-package :rq)
+
+;;; Quant-voice
+;;; Contains the functions relative to the editor panel in a rq.
+
+(defclass! quant-voice (voice)
+ ((rq :accessor rq :initform nil) ; Reference to the RQ system it is in
+ (k-bests :accessor k-bests :initform nil ) ;reference to the k-best list of the RQ system (REDUNDANT, TO BE DELETED, SEE UML DIAGRAM)
+ (indexes :accessor indexes :initarg :indexes :initform nil ) ;list of index of automaton (one per segment) in the list of automata
+ (ks :accessor ks :initarg :ks :initform nil ) ;list of ranks (one per segment) of the solution corresponding to the voice chosen
+ (slurs :accessor slurs :initarg :slurs :initform nil ) ;list of slurs for each segment
+ (choices :accessor choices :initarg :choices :initform nil ) ;choices is a list of choice-table (one per segment) holding a hashtable where keys are paths and entries are tuples (runs ll rr)
+ (editflag :accessor editflag :initarg :editflag :initform t )
+ (colorflag :accessor colorflag :initarg :colorflag :initform nil )))
+
+
+
+;; SET-TREE is called each time the voice's tree is modified
+;; the tempo is updated each time
+(defmethod set-tree ((self quant-voice) tree)
+ "This function is called each time the voice's tree is modified. The tempo is updated each time."
+ (let ((voicepanel (om::panel (voice-editor (editor (rq self))))))
+ (setf (om::selection? voicepanel) nil)
+ (initialize-instance self
+ :tree tree :chords (get-chords (chord-seq (rq self)))
+ :tempo (get-tempo self))
+ (update-grids self)
+ (om::update-panel voicepanel)
+ (om-invalidate-view (om::panel (chord-seq-editor (editor (rq self)))))))
+
+(defmethod init-all-choices ((self quant-voice) &optional (nmes nil))
+ "Inits the choices structures for each measure. Basically, it clones in a more compact way what is useful in the ktable corresponding."
+ (let* ((k-bests (k-bests self))
+ (nsegment (length k-bests))
+ (indexes (indexes self))
+ (ks (ks self))
+ (ktables (mapcar #'(lambda (index k-best) (nth index (ktables k-best))) indexes k-bests))
+ (inputs (mapcar #'(lambda (index k-best) (nth index (inputs k-best))) indexes k-bests))
+ (out (loop for i from 1 to nsegment collect (make-instance 'choice-table))))
+ (loop for ktable in ktables
+ for input in inputs
+ for k in ks
+ for choice in out do
+ (setf (table choice) (make-hash-table :test 'equalp))
+ (add-choice choice ktable input (path-empty input) k))
+ (setf (choices self) out)))
+
+(defmethod init-one-choice ((self quant-voice) nmes)
+ "Inits the choice structure for only one measure. Basically, it clones in a more compact way what is useful in the ktable corresponding."
+ (let* ((k-bests (k-bests self))
+ (nsegment (length k-bests))
+ (index (nth nmes (indexes self)))
+ (k (nth nmes (ks self)))
+ (ktable (nth index (ktables (nth nmes k-bests))))
+ (input (nth index (inputs (nth nmes k-bests))))
+ (out (make-instance 'choice-table)))
+ (setf (table out) (make-hash-table :test 'equalp))
+ (add-choice out ktable input (path-empty input) k)
+ (setf (nth nmes (choices self)) out)
+ (update-grids self)))
+
+
+(defmethod update-tree ((self quant-voice) &optional (render nil))
+ "Builds the complete OM rhythm tree from all the choice-tables"
+ (let* ((choices (choices self))
+ (k-bests (k-bests self))
+ (inputs (mapcar #'(lambda (index k-best) (nth index (inputs k-best))) (indexes self) k-bests))
+ (sigs (get-signatures-of-solution self))
+ (gracenotes (append '(0) (loop for choice in choices
+ for input in inputs collect (get-gracenotes choice input 1))))
+ (slurs (slurs self))
+ trees)
+ (if (null k-bests)
+ '(1 (((4 4) (-1))))
+ (progn
+ (setq trees
+ (loop for choice in choices
+ for input in inputs
+ for slur in slurs
+ for gracenote in gracenotes collect (make-tree-from-choice-table choice input slur gracenote render)))
+
+ (setq out (mapcar #'(lambda (sig tree) (append (list sig) (list tree))) sigs trees))
+ (setq out (append (list '?) (list out)))
+ (if render
+ (reducetree out)
+ out)))))
+
+(defmethod get-tempo ((self quant-voice))
+ "Returns a list of tempi compatible with a voice corresponding to the tempi of the selected transcriptions."
+ (let* ((choices (choices self))
+ (k-bests (k-bests self))
+ (inputs (mapcar #'(lambda (index k-best) (nth index (inputs k-best))) (indexes self) k-bests))
+ (sigs (loop for choice in choices
+ for input in inputs
+ for k-best in k-bests
+ collect (get-signature choice input (tempomerge k-best))))
+ (tempi (mapcar #'(lambda (input sig) (round (* (/ 60000 (input-dur input)) (car sig)))) inputs sigs))
+ (tempo1 (list (list 1/4 (car tempi)) nil))
+ (prev-temp (car (car tempo1)))
+ (tempo2 nil)
+ )
+ (if (null k-bests)
+ 60
+ (progn
+ (when (rest tempi)
+ (setq tempo2 (loop for temp in (rest tempi)
+ for i = 1 then (1+ i)
+ unless (equalp prev-temp temp)
+ collect (list (list i 0) (list 1/4 temp))
+ do (setq prev-temp temp))))
+ (append (list (car tempo1)) (list tempo2)))
+ )))
+
+(defmethod update-grids ((self quant-voice))
+ "Updates the grid corresponding to the current tree in the chord-seq panel for each segment"
+ (let* ((choices (choices self))
+ (k-bests (k-bests self))
+ (inputs (mapcar #'(lambda (index k-best) (nth index (inputs k-best))) (indexes self) k-bests))
+ (grids (make-grid choices k-bests inputs))
+ (k-best-analysis (get-k-best-analysis (chord-seq (rq self)))))
+ (loop for segment in (analysis-segments k-best-analysis)
+ for grid in grids
+ do
+ (setf (grid (segment-data segment)) grid))))
+
+
+(defmethod get-cons-list (self)
+ "Returns the cons-list (path in the OM tree) for an object. Handles the case of gracenotes.
+WARNING : due to the handling of the gracenotes, chords (as opposed to single notes) are considered as grace notes."
+
+ (if (and (equal (type-of self) 'chord) (= 1 (length (cadr (om::tree (om::parent self)))))) (reverse (cdr (om::cons-container-path self))) (reverse (om::cons-container-path self))))
+
+
+(defmethod get-trees (self (inside quant-voice))
+ "Gets the list of the best sub-trees for an object (group or chord).
+Second value is true iff more values can be computed"
+ (let* ((k-bests (k-bests inside))
+ (path1 (print (get-cons-list self)))
+ (nmes (or (first path1) 0))
+ (k-best (nth nmes k-bests))
+ (pathflag (print (cons-list->path path1 inside)))
+ (path (car pathflag))
+ (flag (cdr pathflag))
+ (index (nth nmes (indexes inside)))
+ (k (nth nmes (ks inside)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (choice (nth nmes (choices inside)))
+ (entry (gethash path ktable))
+ (nbests (length (entry-bestlist entry nil)))
+ (prev-gracenotes (previous-gracenotes choice input nil nil path ))
+ (prev-input (get-last-input input path)))
+
+ (values (loop for k from 1 to nbests collect
+ (let ((tree (rq-to-omtree ktable input k nil nil prev-gracenotes path prev-input)))
+ (if (equal tree '(-1))
+ (list 1 tree)
+ (reducetree (list 1 tree)))))
+ (null (queue-empty (entry-candidates entry nil))))))
+
+(defmethod get-signature-of-group (self (inside quant-voice))
+ "Gets the signature (ie the length) of the segment corresponding to the group/chord"
+ (let* ((path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (path (car (cons-list->path path1 inside)))
+ (measure-signature (nth nmes (get-signatures inside))))
+ (labels ((subdivide (num denom path)
+ (if (null path)
+ (list num denom)
+ (if (equalp num 1)
+ (subdivide num (* denom (car (car path))) (rest path))
+ (subdivide (/ num (car (car path))) denom (rest path))))))
+ (subdivide (car measure-signature) (second measure-signature) (path-val path)))))
+
+(defmethod get-gracenotes-from-obj (self (inside quant-voice))
+ "Gets a list holding the number of gracenotes (notes aligned to the right) for each proposition for the current segment"
+ (let* ((k-bests (k-bests inside))
+ (path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (k-best (nth nmes k-bests))
+ (pathflag (cons-list->path path1 inside))
+ (path (car pathflag))
+ (flag (cdr pathflag))
+ (index (nth nmes (indexes inside)))
+ (k (nth nmes (ks inside)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (nbests (length (entry-bestlist (gethash path ktable) nil))))
+ (loop for k from 1 to nbests collect
+ (k-best-segment-get-gracenotes ktable input k nil path))))
+
+(defmethod get-colors (self (inside quant-voice))
+ "Gets a list of couples (distance color) for each proposition for the current segment"
+ (let* ((k-bests (k-bests inside))
+ (path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (k-best (nth nmes k-bests))
+ (pathflag (cons-list->path path1 inside))
+ (path (car pathflag))
+ (flag (cdr pathflag))
+ (index (nth nmes (indexes inside)))
+ (k (nth nmes (ks inside)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (nbests (length (entry-bestlist (gethash path ktable) nil))))
+ (loop for k from 1 to nbests collect
+ (let ((dist (/ (round (* 1000 (weight-distance-normalized-by-length (nth-value 1 (rq-best ktable input path k nil)) path))) 10.0))) ;Distance in percets instead of decimal value
+ (list dist (when (colorflag inside) (distance-to-color dist)))))))
+
+(defmethod get-signatures-of-solution ((self quant-voice))
+ "Returns the signatures for each measure in the form of a list"
+ (let* ((choices (choices self))
+ (k-bests (k-bests self))
+ (inputs (mapcar #'(lambda (index k-best) (nth index (inputs k-best))) (indexes self) k-bests)))
+
+ (loop for choice in choices
+ for k-best in k-bests
+ for input in inputs collect
+ (get-signature choice input (tempomerge k-best)))))
+
+
+
+(defmethod compute-more-solutions ((voice quant-voice) self n)
+ "To compute N additional solutions for a subtree"
+ (let* ((k-bests (k-bests voice))
+ (path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (k-best (nth (first path1) k-bests))
+ (pathflag (cons-list->path path1 voice))
+ (path (car pathflag))
+ (flag (cdr pathflag))
+ (index (nth (first path1) (indexes voice)))
+ (k (nth (first path1) (ks voice)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (nbests (length (entry-bestlist (gethash path ktable) flag))))
+ (if (null (path-val path))
+ (rq-best-top ktable input (+ nbests n))
+ (rq-best ktable input path (+ nbests n) flag))))
+
+
+
+
+(defmethod cons-list->path (path1 (voice quant-voice))
+ "Converts from the cons-list representation to a path structure"
+ (let* ((k-bests (k-bests voice))
+ (nmes (or (first path1) 0))
+ (k-best (nth nmes k-bests))
+ (index (nth nmes (indexes voice)))
+ (choice (nth nmes (choices voice)))
+ (k (nth nmes (ks voice)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (path2 (path-empty input))
+ (run (rq-best choice input path2 k nil)))
+ (labels ((build-path (path1 run path2 flag)
+ (if (or (null path1)
+ (null run))
+ (cons path2 flag)
+ (let* ((new-path (path-addi path2 (length run) (1+ (car path1) )))
+ (kflag (nth (car path1) run))
+ (new-k (car kflag))
+ (new-flag (cdr kflag))
+ (new-run (or (rq-best choice input new-path new-k new-flag)
+ (rq-best ktable input new-path new-k new-flag))))
+ (build-path (rest path1) new-run new-path new-flag)))))
+ (if (= (length run) 1)
+ (build-path (cdr path1) run path2 nil)
+ (build-path (cddr path1) run path2 nil)))))
+
+
+(defmethod om::get-object-selection-color ((self t) (in quant-voice))
+ "Gets the color of the object SELF that is currently selected (to display the color of the selected object in the voice panel)"
+ (when (colorflag in)
+ (unless (or (typep self 'quant-voice) (is-in-edited-group self in) (contains-edited-group self in))
+ (let* ((path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (pathflag (cons-list->path path1 in))
+ (path (car pathflag))
+ (choice (nth nmes (choices in))))
+ (distance-to-color (/ (round (* 1000 (weight-distance-normalized-by-length (nth-value 1 (rq-best choice nil path nil nil)) path))) 10.0))))))
+
+
+; Functions relative to user-modified choices (cf quant-voice-panel.lisp)
+(defmethod is-in-edited-group (obj (voice quant-voice) &key ((:equal? eq) t))
+ "true iff obj is inside a group that was edited by the user. When the group is the one that was edited (when it belongs to the user-edit list), returns equal?"
+ (let* ((conslist (get-cons-list obj))
+ (choice (nth (car conslist) (choices voice))))
+ (is-in-edited-group (cdr conslist) choice :equal? eq)
+ )
+)
+
+(defmethod contains-edited-group (obj (voice quant-voice) &key ((:equal? eq) t))
+ "true iff obj contains a group that was edited by the user. When obj is the one that was edited (when it belongs to the user-edit list), returns equal?"
+ (let* ((conslist (get-cons-list obj))
+ (choice (nth (car conslist) (choices voice))))
+ (find-if #'(lambda (x) (is-an-ancestor (cdr conslist) (car x) eq)) (user-edit choice))))
+
+
+
+;;Function called by open-trees-panel (cf quant-voice-panel.lisp)
+(defmethod set-tree-choice (self (voice quant-voice) k)
+ "Replaces the sub-tree of index k in the list into the choice table"
+ (let* ((k-bests (k-bests voice))
+ (path1 (get-cons-list self))
+ (nmes (or (first path1) 0))
+ (k-best (nth nmes k-bests))
+ (pathflag (cons-list->path path1 voice))
+ (path (car pathflag))
+ (flag (cdr pathflag))
+ (index (nth nmes (indexes voice)))
+ (ktable (nth index (ktables k-best)))
+ (input (nth index (inputs k-best)))
+ (choice (nth nmes (choices voice))))
+
+ ;This function recomputes and updates recursively the distance values and the aligns for the choices in the choice-table, from the modified subtree up to the root of the tree
+ (labels ((update-distance (path rest-path-val)
+ (multiple-value-bind (run weight rr ll) (rq-best choice input path 1 nil)
+
+ (if (null rest-path-val)
+ (when run
+ (let ((wl (loop for i from 1 to (length run) collect (nth-value 1 (rq-best choice input (path-addi path (length run) i ) 1 nil))))
+ (new-rr (nth-value 3 (rq-best choice input (path-addi path (length run) (length run)) 1 nil)))
+ (new-ll (nth-value 2 (rq-best choice input (path-addi path (length run) 1) 1 nil)))
+ )
+ (set-weight choice path (weight-addall wl (input-precision input) (input-gracepen input)))
+ (set-aligns choice path new-ll new-rr))
+ )
+ (progn
+ (update-distance (path-add path (car rest-path-val)) (rest rest-path-val) )
+ (let ((wl (loop for i from 1 to (length run) collect (nth-value 1 (rq-best choice input (path-addi path (length run) i) 1 nil))))
+ (new-rr (nth-value 3 (rq-best choice input (path-addi path (length run) (length run)) 1 nil)))
+ (new-ll (nth-value 2 (rq-best choice input (path-addi path (length run) 1) 1 nil))))
+ (set-weight choice path (weight-addall wl (input-precision input) (input-gracepen input)))
+ (set-aligns choice path new-ll new-rr)))))))
+ ;From the selected node down to the leaves, update the runs and distances
+ (add-choice choice ktable input path (1+ k) nil)
+ ;From the selected node up to the root, recompute the distance values and aligns
+ (update-distance (path-empty input) (path-val path) )
+ (setf (modified choice) t)
+ ;Overwrite the user modifications that are invalidated by the current modification
+ (setf (user-edit choice) (remove-descendents-from-user-edit (cdr path1) choice))
+ )))
+
+(in-package :om)
+(defmethod om::omng-save ((self rq::quant-voice) &optional values?)
+ `(let ((qv ,(call-next-method)))
+ (setf (rq::indexes qv) ',(rq::indexes self)
+ (rq::ks qv) ',(rq::ks self)
+ (rq::slurs qv) ',(rq::slurs self)
+ (rq::choices qv) ,(om::omng-save (rq::choices self))
+ (rq::editflag qv) ,(rq::editflag self)
+ (rq::colorflag qv) ,(rq::colorflag self))
+ qv))
+
+
+
+
+
+
diff --git a/src/gui/window/k-best-data-window.lisp b/src/gui/window/k-best-data-window.lisp
new file mode 100644
index 0000000..9a8055f
--- /dev/null
+++ b/src/gui/window/k-best-data-window.lisp
@@ -0,0 +1,232 @@
+(in-package :rq)
+
+;;; This file holds all the functions relative to the various parameters dialog boxes.
+
+(defmethod k-best-data-window ((kdata k-best-data))
+ "Creates a dialog panel to modify the parameters of one segment only (does not include global parameters)"
+ (let ((win (om-make-window 'om-dialog :position :centered
+ :size (om-make-point 500 270))))
+
+ ;create the panel to edit the data
+ (multiple-value-bind (pane tempotxt schematxt n-solution-txt precistxt gracepentxt n-beatstxt)
+ (make-k-best-data-panel kdata)
+
+ ;Add the cancel and OK buttons
+ (om-add-subviews pane
+ (om-make-dialog-item 'om-button (om-make-point (- (om::w pane) 200) (- (om::h pane) 50))
+ (om-make-point 80 20)
+ "Cancel"
+ :di-action (om-dialog-item-act item
+ (om-return-from-modal-dialog win nil)))
+
+ (om-make-dialog-item 'om-button (om-make-point (- (om::w pane) 100) (- (om::h pane) 50))
+ (om-make-point 80 20)
+ "OK"
+ :di-action (om-dialog-item-act item
+ (let ((tempo (ignore-errors (read-from-string (om-dialog-item-text tempotxt))))
+ (n-solution (ignore-errors (read-from-string (om-dialog-item-text n-solution-txt))))
+ (schema (ignore-errors (read-from-string (om-dialog-item-text schematxt))))
+ (precis (ignore-errors (read-from-string (om-dialog-item-text precistxt))))
+ (grace (ignore-errors (read-from-string (om-dialog-item-text gracepentxt))))
+ (n-beats (ignore-errors (read-from-string (om-dialog-item-text n-beatstxt)))))
+ (setf (tempo kdata) tempo
+ (n-solution kdata) n-solution
+ (precision kdata) precis
+ (gracepen kdata) grace
+ (schema kdata) schema
+ (n-beats-per-seg kdata) n-beats)
+ (setf (updateflag kdata) nil)
+ (om-return-from-modal-dialog win t)))))
+ (om-add-subviews win pane)
+ (om-modal-dialog win))))
+
+(defmethod k-best-data-window-global ((kdata k-best-data) (analysis om::k-best-analysis) (rq rq))
+ "Creates a dialog panel to modify the global parameters. Include both segment parameters (to be changed for each segment), and global parameters (segmentation and tempo-smoothing parameters)"
+ (let ((win (om-make-window 'om-dialog :position :centered
+ :size (om-make-point 500 450)))
+ (smooth-paramtxt (om-make-dialog-item 'om-editable-text (om-make-point 190 270) (om-make-point 37 13)
+ (format nil "~D" (smooth-param rq))
+ :font *om-default-font1*))
+ (tempo-jump-pentxt (om-make-dialog-item 'om-editable-text (om-make-point 380 270) (om-make-point 37 13)
+ (format nil "~D" (tempo-jump-pen rq))
+ :font *om-default-font1*))
+ segpentxt
+ (warning (om::warning-p analysis)))
+
+ ;create the panel to edit the data
+ (multiple-value-bind (pane tempotxt schematxt n-solution-txt precistxt gracepentxt n-beatstxt)
+ (make-k-best-data-panel kdata
+ :message "Set global quantification parameters:"
+ :size (om-make-point 470 420))
+
+ (om-add-subviews pane
+ ;Add global parameters :
+
+ ;Add segmentation parameters
+ (om-make-dialog-item 'om-static-text (om-make-point 20 170) (om-make-point 300 20) "Set segmentation parameters:"
+ :font *om-default-font2b*)
+
+ (om-make-dialog-item 'om-static-text (om-make-point 50 200) (om-make-point 190 20) "New-segment penalty"
+ :font *om-default-font1*)
+ (setf segpentxt (om-make-dialog-item 'om-editable-text (om-make-point 190 200) (om-make-point 37 13)
+ (format nil "~D" (om::segpen analysis))
+ :font *om-default-font1*))
+
+ ;Add tempo smoothing parameters
+ (om-make-dialog-item 'om-static-text (om-make-point 20 240) (om-make-point 300 20) "Set tempo smoothing parameters:"
+ :font *om-default-font2b*)
+
+
+ (om-make-dialog-item 'om-static-text (om-make-point 50 270) (om-make-point 180 20) "Smoothing (0.0-1.0)"
+ :font *om-default-font1*)
+ smooth-paramtxt
+ (om-make-dialog-item 'om-static-text (om-make-point 260 270) (om-make-point 180 20) "Tempo jump penalty"
+ :font *om-default-font1*)
+ tempo-jump-pentxt
+
+ ;Add warning parameters
+ (om-make-dialog-item 'om-static-text (om-make-point 20 310) (om-make-point 300 20) "Set warning parameters:"
+ :font *om-default-font2b*)
+
+ (om-make-dialog-item 'om-check-box (om-make-point 50 340) (om-make-point 120 20) "Show warnings "
+ :font *om-default-font1*
+ :checked-p warning
+ :di-action #'(lambda (b)
+ (setf (om::warning-p analysis) (not (om::warning-p analysis)))
+ ))
+
+
+
+ ;Add the cancel and OK buttons
+ (om-make-dialog-item 'om-button (om-make-point (- (om::w pane) 200) (- (om::h pane) 50))
+ (om-make-point 80 20)
+ "Cancel"
+ :di-action (om-dialog-item-act item
+ (om-return-from-modal-dialog win nil)))
+
+ (om-make-dialog-item 'om-button (om-make-point (- (om::w pane) 100) (- (om::h pane) 50))
+ (om-make-point 80 20)
+ "OK"
+ :di-action (om-dialog-item-act item
+ (let ((tempo (ignore-errors (read-from-string (om-dialog-item-text tempotxt))))
+ (n-solution (ignore-errors (read-from-string (om-dialog-item-text n-solution-txt))))
+ (schema (ignore-errors (read-from-string (om-dialog-item-text schematxt))))
+ (precis (ignore-errors (read-from-string (om-dialog-item-text precistxt))))
+ (grace (ignore-errors (read-from-string (om-dialog-item-text gracepentxt))))
+ (segpen (ignore-errors (read-from-string (om-dialog-item-text segpentxt))))
+ (n-beats (ignore-errors (read-from-string (om-dialog-item-text n-beatstxt))))
+ (smooth-param (ignore-errors (read-from-string (om-dialog-item-text smooth-paramtxt))))
+ (tempo-jump-pen (ignore-errors (read-from-string (om-dialog-item-text tempo-jump-pentxt))))
+ )
+ (setf (tempo kdata) tempo
+ (n-solution kdata) n-solution
+ (precision kdata) precis
+ (gracepen kdata) grace
+ (schema kdata) schema
+ (n-beats-per-seg kdata) n-beats)
+ (setf (om::segpen analysis) segpen
+ )
+ (setf (smooth-param rq) smooth-param
+ (tempo-jump-pen rq) tempo-jump-pen)
+ (om-return-from-modal-dialog win t))))
+ )
+
+ (om-add-subviews win pane)
+ (om-modal-dialog win)
+)))
+
+
+(defmethod make-k-best-data-panel ((kdata k-best-data) &key (message nil) (size (om-make-point 470 250)))
+ "Creates a panel to edit all the parameters of a `k-best-data'"
+ (let ((pane (om-make-view 'om-view
+ :size size
+ :position (om-make-point 10 10)
+ :bg-color *om-white-color*))
+ (i 0)
+ tempotxt schematxt n-solution-txt precistxt gracepentxt
+ (tempomerge (tempomerge kdata))
+ (n-beatstxt (om-make-dialog-item 'om-editable-text (om-make-point 380 135) (om-make-point 37 13)
+ (format nil "~D" (n-beats-per-seg kdata))
+ :font *om-default-font1*)))
+ (om-add-subviews pane
+ (om-make-dialog-item 'om-static-text (om-make-point 20 (incf i 16))
+ (om-make-point 380 40)
+ (if message
+ message
+ "Set quantification parameters for selected segment:")
+ :font *om-default-font2b*)
+
+ (om-make-dialog-item 'om-static-text (om-make-point 50 (incf i 30)) (om-make-point 120 20) "Tempi"
+ :font *om-default-font1*)
+ (setf tempotxt (om-make-dialog-item 'om-editable-text (om-make-point 140 i) (om-make-point 37 13)
+ (format nil "~D" (tempo kdata))
+ :font *om-default-font1*))
+
+ (om-make-dialog-item 'om-static-text (om-make-point 260 i) (om-make-point 120 20) "Schema"
+ :font *om-default-font1*)
+ (setf schematxt (om-make-dialog-item 'om-editable-text (om-make-point 330 i) (om-make-point 97 13)
+ (format nil "~D" (schema kdata))
+ :font *om-default-font1*))
+
+ (om-make-dialog-item 'om-static-text (om-make-point 50 (incf i 26)) (om-make-point 120 20) "Nb. solutions"
+ :font *om-default-font1*)
+ (setf n-solution-txt (om-make-dialog-item 'om-editable-text (om-make-point 140 i) (om-make-point 37 13)
+ (format nil "~D" (n-solution kdata))
+ :font *om-default-font1*))
+
+ (om-make-dialog-item 'om-static-text (om-make-point 260 i) (om-make-point 120 20) "Precision (0.0-1.0)"
+ :font *om-default-font1*)
+ (setf precistxt (om-make-dialog-item 'om-editable-text (om-make-point 380 i) (om-make-point 37 13)
+ (format nil "~D" (precision kdata))
+ :font *om-default-font1*))
+
+ (setf tempomergecheck (om-make-dialog-item 'om-check-box (om-make-point 50 (incf i 26)) (om-make-point 120 20) "Merge tempi"
+ :font *om-default-font1*
+ :checked-p tempomerge
+ :di-action #'(lambda (b)
+ (setf (tempomerge kdata) (not (tempomerge kdata)))
+ )))
+
+ (om-make-dialog-item 'om-static-text (om-make-point 260 i) (om-make-point 120 20) "Grace notes penalty"
+ :font *om-default-font1*)
+ (setf gracepentxt (om-make-dialog-item 'om-editable-text (om-make-point 380 i) (om-make-point 37 13)
+ (format nil "~D" (gracepen kdata))
+ :font *om-default-font1*))
+
+ (om-make-dialog-item 'om-check-box (om-make-point 50 135) (om-make-point 140 20) "Segments = beats"
+ :font *om-default-font1*
+ :checked-p (segments=beats kdata)
+ :di-action #'(lambda (b)
+ (setf (segments=beats kdata) (not (segments=beats kdata)))
+ (om-enable-dialog-item n-beatstxt (segments=beats kdata))
+ ))
+
+ (om-make-dialog-item 'om-static-text (om-make-point 260 135) (om-make-point 180 20) "Nb. beats/segment"
+ :font *om-default-font1*)
+ n-beatstxt
+
+ )
+ (om-enable-dialog-item n-beatstxt (segments=beats kdata))
+ (values pane tempotxt schematxt n-solution-txt precistxt gracepentxt n-beatstxt tempomergecheck )))
+
+
+(defmethod set-global-k-best-parameters ((rq rq))
+ "This function creates a global-parameters dialog panel, and once closed, updates all the k-best data for each segment"
+ (let* ((chord-seq (chord-seq rq))
+ (k-best-analysis (get-k-best-analysis chord-seq))
+ (segments (analysis-segments k-best-analysis))
+ (datas (mapcar #'segment-data segments))
+ (new-k-best-data (k-best-data-copy (first datas))))
+ (when (k-best-data-window-global new-k-best-data k-best-analysis rq)
+ (loop for data in datas do
+ (unless (k-best-data-equal new-k-best-data data)
+ (setf (tempo data) (tempo new-k-best-data)
+ (n-solution data) (n-solution new-k-best-data)
+ (schema data) (schema new-k-best-data)
+ (precision data) (precision new-k-best-data)
+ (gracepen data) (gracepen new-k-best-data)
+ (tempomerge data) (tempomerge new-k-best-data))
+ (setf (updateflag data) nil)))
+ )))
+
+
diff --git a/src/rq-class.lisp b/src/rq-class.lisp
new file mode 100644
index 0000000..dc073c0
--- /dev/null
+++ b/src/rq-class.lisp
@@ -0,0 +1,367 @@
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;; RQ-CLASS.LISP
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+; This file contains all the functions relative to the RQ class,
+; the main class to operate the transcription system.
+;
+; The main functions are :
+; - compute-k-best : to run the algorithm on all segments
+; (also compute-one-k-best to run it on one segment only)
+; - make-working-poly : to build the multi-poly object holding all the
+; possible transcriptions for each segment
+; (also replace-one-poly to recompute one poly only)
+; - init-solution : to init a solution from the choices made in the poly panel
+;
+;
+
+
+(in-package :rq)
+
+(om::defclass* rq ()
+ ((chord-seq :accessor chord-seq :initform nil :initarg :chord-seq :documentation "chord-seq to quantify")
+ (marks :accessor marks :initform '(0) :initarg :marks :documentation "list of segmentation marks")
+ (solution :accessor solution :initform nil :documentation "the current solution")
+ (wp :accessor wp :initform (make-instance 'quant-multi-poly) :documentation "working multi-poly (to browse the automaton)")
+ (k-bests :accessor k-bests :initform nil) ;holds all the k-best objects (one per segment)
+ (parent :accessor parent :initform nil) ;always nil, added to prevent some bugs
+ (editor :accessor editor :initform nil) ;reference to the editor (user interface)
+ ;Display parameters
+ (display-mode :accessor display-mode :initform :close) ;open or close, depending on wether the right panel is open or not
+ (color-flag :accessor color-flag :initform nil) ;true when in "Color mode" (displays the distance with colors)
+ (pulse-flag :accessor pulse-flag :initform nil) ;true when "Show pulses" is ticked (to display the quantization grid used)
+ ;Tempo-smoothing parameters
+ (smooth-param :accessor smooth-param :initform 0.5) ;to balance between the smoothness of tempo and the weight of the solutions
+ (tempo-jump-pen :accessor tempo-jump-pen :initform 5) ; to penalize tempo jumps
+ )
+ (:icon 252)
+ (:documentation "
+RQ - Rhythm Quantification
+
+
+Inputs :
+ : a chord-seq object to quantify
+ : a list of instants of segmentation (in milliseconds)
+
+Double-click to open the quantification interface.
+
+To retrieve the quantified output, use the function get-voice
+
+For instructions, tutorials and information : http://repmus.ircam.fr/cao/rq
+
+"))
+
+
+(defmethod initialize-instance :after ((self rq) &rest args)
+ "Constructor for a `rq'."
+ ;; Initializing the input CHORD-SEQ and making it a `quant-chord-seq':
+ (if (chord-seq self)
+ (setf (chord-seq self) (chord-seq->quant-chord-seq (chord-seq self)))
+ (setf (chord-seq self) (make-instance 'quant-chord-seq)))
+ ;; PARENT
+ (setf (parent (chord-seq self)) self)
+ ;; Creating a new `k-best-analysis', with segment defined by the input MARKS
+ ;; Do nothing if there already is a k-best analysis in the input chord-seq
+ (unless (get-k-best-analysis (chord-seq self))
+ (if (marks self)
+ (om::add-object-analysis (chord-seq self)
+ (make-instance 'om::k-best-analysis :analysis-segments
+ (loop for mark in (marks self)
+ when (>= mark 0)
+ collect (make-instance 'om::marker-segment :mrk-time mark))))
+ (om::add-object-analysis (chord-seq self) (make-instance 'om::k-best-analysis))))
+ ;; SOLUTION
+ (setf (solution self) (make-instance 'quant-voice :tree '(1 (((4 4) (-1))))))
+ (setf (rq (solution self)) self)
+ )
+
+
+(defmethod compute-k-best ((self rq) &optional (warning t warning-supplied-p))
+ "Runs the `k-best-analysis'"
+ (let* ((k-best-analysis (get-k-best-analysis (chord-seq self)))
+ (old-warning (if (om::warning-p k-best-analysis) t nil)));a trick to get a copy of (warning-p k-best-abalysis)
+ ;Small hack : when warning is supplied, you want the analysis to use this argument.
+ ;To do so, you set the value of (warning-p (editor self)) as you want, and you set it back as it was before afterwards
+ (when warning-supplied-p
+ (setf (om::warning-p k-best-analysis) warning))
+ (setf (k-bests self) (loop for segment in (analysis-segments k-best-analysis)
+ collect (om::analyse-one-segment k-best-analysis segment (chord-seq self))))
+ (setf (k-bests (solution self)) (k-bests self))
+ (setf (rq (solution self)) self)
+ (when warning-supplied-p
+ (setf (om::warning-p k-best-analysis) old-warning))))
+
+
+(defmethod get-k-best-analysis ((self chord-seq))
+ (car (remove nil (loop for an in (om::analysis self)
+ when (equal (type-of an) 'om::k-best-analysis)
+ collect an))))
+
+;;; Output functions:
+
+(defmethod get-chord-seq ((self rq))
+ (chord-seq self))
+
+
+(om::defmethod! get-voice ((rq rq) &optional (render t))
+ :initvals '(nil t)
+ :indoc '("rq" "render")
+ :icon '(252)
+ :doc "Returns a voice corresponding to the chosen transcription in the rq"
+
+ (make-instance 'voice
+ :tree (update-tree (solution rq) render)
+ :chords (get-chords (chord-seq rq))
+ :tempo (get-tempo (solution rq))))
+
+
+(om::defmethod! get-k-best-list ((self rq) &optional poly-indexes voice-indexes)
+ :initvals '(nil nil nil)
+ :indoc '("rq" "indexes of polys" "indexes of the voices")
+ :icon '(252)
+ :doc "Returns a list of transcriptions in the form of a list of polys/a poly.
+If no optional arguments are provided, the function returns a list of all the polys in the k-best panel (one for each segment)
+
+If the argument is a number, the function returns the corresponding poly.
+If the argument is a list, the function returns a list of polys corresponding to the indexes provided.
+
+If the argument is a number, the function returns the corresponding voice (a list of voices when is a list).
+If the argument is a list, the function returns a poly containing only the corresponding voices (a list of polys when is a list).
+If the argument is a list of lists, the function returns a list of poly containing the corresponding voices for each sublist. When a sublist is nil, all the voices are included.
+"
+
+(let ((polys (polys (wp self))))
+ (cond ((null poly-indexes)
+ polys)
+
+ ((numberp poly-indexes)
+ (cond ((null voice-indexes)
+ (nth poly-indexes polys))
+
+ ((numberp voice-indexes)
+ (nth voice-indexes (om::voices (nth poly-indexes polys))))
+
+ ((and (listp voice-indexes) (numberp (car voice-indexes)))
+ (let ((current-poly (nth poly-indexes polys)))
+ (make-instance 'poly :voices (loop for index in voice-indexes collect
+ (nth index (om::voices current-poly))))))
+ ((and (listp voice-indexes) (listp (car voice-indexes)))
+ (let ((current-poly (nth poly-indexes polys)))
+ (make-instance 'poly :voices (loop for index in (car voice-indexes) collect
+ (nth index (om::voices current-poly))))))
+ (t nil)
+ ))
+
+ ((listp poly-indexes)
+ (cond ((null voice-indexes)
+ (loop for index in poly-indexes collect (nth index polys)))
+
+ ((numberp voice-indexes)
+ (loop for index in poly-indexes collect (nth voice-indexes (om::voices (nth index polys)))))
+
+ ((and (listp voice-indexes) (numberp (car voice-indexes)))
+ (loop for poly-index in poly-indexes collect
+ (let ((current-poly (nth poly-index polys)))
+ (make-instance 'poly :voices (loop for index in voice-indexes collect
+ (nth index (om::voices current-poly)))))))
+
+ ((and (listp voice-indexes) (listp (car voice-indexes)))
+ (loop for poly-index in poly-indexes
+ for lvoice-index in voice-indexes collect
+ (let ((current-poly (nth poly-index polys)))
+ (if lvoice-index
+ (make-instance 'poly :voices (loop for index in lvoice-index collect
+ (nth index (om::voices current-poly))))
+ current-poly)))))))
+))
+
+;;; Computation functions:
+
+(defmethod compute-one-k-best ((self rq) (segment om::segment))
+ "Computes a k-best structure for one segment. Works only if the k-bests already have been computed once."
+ (let* ((k-best-analysis (get-k-best-analysis (chord-seq self)))
+ (k-best-segments (analysis-segments k-best-analysis))
+ (segment-index (position segment k-best-segments)))
+ (setf (nth segment-index (k-bests self)) (om::analyse-one-segment k-best-analysis segment (chord-seq self)))
+ (setf (k-bests (solution self)) (k-bests self))
+ (setf (rq (solution self)) self)
+ ))
+
+(defmethod init-solution ((self rq))
+ "Initializes the solution from the chosen transcriptions."
+ (let ((mp (wp self)))
+ (update-ks-indexes (solution self) mp)
+ (setf (rq (solution self)) self)
+ (setf (slurs (solution self)) (get-slurs self))
+ (init-all-choices (solution self))
+ (set-tree (solution self) (update-tree (solution self) (not (editflag (solution self)))))))
+
+;;
+(defmethod get-list-n-solution ((self rq))
+ (mapcar #'(lambda (segment) (n-solution (segment-data segment))) (get-k-best-segments self)))
+
+;;
+(defmethod update-ks-indexes ((voice quant-voice) (wp quant-multi-poly))
+ "Updates in the voice the indexes and ks of the chosen transcriptions"
+ (let* ((selections (selections wp))
+ (index-k (get-indexes-of-solutions (rq voice) selections)))
+ (setf (indexes voice) (mapcar #'first index-k))
+ (setf (ks voice) (mapcar #'second index-k))))
+
+
+
+;;
+(defmethod get-k-best-segments ((self rq))
+ (analysis-segments (get-k-best-analysis (chord-seq self))))
+
+(defmethod get-k-best-analysis ((self rq))
+ (get-k-best-analysis (chord-seq self)))
+
+;;
+(defmethod get-indexes-of-solutions ((self rq) selections)
+ "Computes for each segment the indexes (in the list of inputs)
+and ks (for the corresponding input) of the chosen transcriptions"
+ (let ((list-n-solution (get-list-n-solution self)))
+ (loop for select in selections
+ for n-solution in list-n-solution
+ collect (list (floor select n-solution) (1+ (rem select n-solution))))))
+
+;;
+(defmethod get-slurs ((self rq))
+ (mapcar #'(lambda (segment) (slur (segment-data segment))) (get-k-best-segments self)))
+
+
+(defmethod get-smoothed-selections ((self rq))
+ "To run the tempo smoothing algorithm.
+Returns a list of selections (one for each segment, corresponds to the index of the selected transcription)"
+ (let* ((wp (wp self))
+ (polys (polys wp))
+ (k-bests (k-bests self))
+ (ltempi nil)
+ (lweights nil)
+ (lks nil)
+ (indexes)
+ )
+
+ (loop for k-best in k-bests
+ do
+ (multiple-value-bind (tempi weights ks) (get-tempi-weigths-ks k-best)
+ (setq ltempi (append ltempi (list tempi))
+ lweights (append lweights (list weights))
+ lks (append lks (list ks)))))
+
+ (setq indexes (ts::tempo-smooth ltempi lweights
+ :alpha (smooth-param self)
+ :penalty (tempo-jump-pen self)))
+
+ (loop for index in indexes
+ for ks in lks
+ collect (nth index ks))
+
+))
+
+
+
+;------ Poly functions ------;
+
+;;; To build a poly from the automaton:
+;;
+(defmethod make-working-poly ((self rq))
+ "Make the working poly with all the transcriptions for all segments from the k-bests structures"
+ (let* ((k-bests (k-bests self))
+ (segment-chords (get-k-best-segment-chords (chord-seq self)))
+ (wp (make-instance
+ 'quant-multi-poly
+ :current-poly 0)))
+ (setf (polys wp) (loop for k-best in k-bests
+ for chords in segment-chords collect
+ (make-one-poly k-best chords)))
+ ;(setf (selections wp) (get-smoothed-selections self))
+ (setf (selections wp) (make-list (length k-bests) :initial-element 0))
+ (setf (distances wp) (get-distances k-bests))
+ (setf (gracenotes wp) (mapcar #'(lambda (x) (reduce #'append x)) (mapcar #'gracenotes k-bests )))
+ (setf (list-n-solution wp) (get-list-n-solution self)) wp))
+
+;;
+(defmethod replace-one-poly ((self rq) index)
+ "Recomputes one single poly (works only if there is already an existing working poly)"
+ (let* ((k-bests (k-bests self))
+ (k-best (nth index k-bests))
+ (segment (nth index (get-k-best-segments self)))
+ (wp (wp self))
+ (chords (get-segment-chords (chord-seq self) segment)))
+ (setf (nth index (polys wp)) (make-one-poly k-best chords))
+ (setf (nth index (selections wp)) 0)
+ (setf (distances wp) (get-distances k-bests))
+ (setf (gracenotes wp) (mapcar #'(lambda (x) (reduce #'append x)) (mapcar #'gracenotes k-bests)))
+ (setf (list-n-solution wp) (get-list-n-solution self))))
+
+;;
+(defmethod make-one-poly (k-best chords)
+ (let* ((ktables (ktables k-best))
+ (inputs (inputs k-best))
+ (slur nil)
+ (n-solution (n-solution k-best))
+ (gracenotes (make-list (length inputs) :initial-element (make-list n-solution :initial-element 0))))
+ (k-best-create-poly ktables inputs n-solution slur gracenotes (tempomerge k-best) chords)))
+
+;;;Misc.
+;;
+(defmethod k-best-analysis-update-p ((self rq))
+ "TRUE iff at least one segment is not up to date (ie if we have to quantify again)"
+ (let ((k-best-analysis (get-k-best-analysis (chord-seq self))))
+ (find-if #'(lambda (segment) (null (updateflag (segment-data segment)))) (analysis-segments k-best-analysis))))
+
+(defmethod distance-to-color (dist)
+ "Converts a distance to a RGB color ranging from red (DIST>30) to green (DIST<5)."
+ (cond ((null dist) (om-make-color 0 0 0))
+ ((< dist 0) (om-make-color 0 0 0))
+ ((> dist 30) (om-make-color 1 0 0))
+ ((> dist 25) (om-make-color 1 0.33 0))
+ ((> dist 20) (om-make-color 1 0.67 0))
+ ((> dist 15) (om-make-color 0.90 0.90 0.2))
+ ((> dist 10) (om-make-color 0.66 1 0))
+ ((> dist 5) (om-make-color 0.33 1 0))
+ (t (om-make-color 0 1 0))))
+
+;;; SAVE
+
+(in-package :om)
+
+(defmethod om::omng-save ((self rq::rq) &optional values?)
+ `(let ((qs, (call-next-method)))
+
+ (setf (rq::color-flag qs), (rq::color-flag self))
+ (setf (rq::pulse-flag qs), (rq::pulse-flag self))
+ (setf (rq::display-mode qs), (rq::display-mode self))
+
+ ;K-bests
+ ;Last argument = do not show warnings when loading a patch
+ (rq::compute-k-best qs nil)
+ ;WP
+ (setf (rq::wp qs) (rq::make-working-poly qs))
+ (setf (rq::current-poly (rq::wp qs)) ,(rq::current-poly (rq::wp self))
+ (rq::selections (rq::wp qs)) ',(rq::selections (rq::wp self)))
+ ;Solution
+ (setf (rq::solution qs), (om::omng-save (rq::solution self)))
+ (setf (rq::rq (rq::solution qs)) qs)
+ (setf (rq::k-bests (rq::solution qs)) (rq::k-bests qs))
+ (initialize-instance (rq::solution qs)
+ :tree (tree (rq::solution qs)) :chords (rq::get-chords (rq::chord-seq qs))
+ :tempo (rq::get-tempo (rq::wp qs)))
+ (rq::update-grids (rq::solution qs))
+
+ qs))
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/tests.lisp b/src/tests.lisp
new file mode 100644
index 0000000..4c3b8b4
--- /dev/null
+++ b/src/tests.lisp
@@ -0,0 +1,290 @@
+;;;; Test code chunks found in other source files.
+
+;;; From quant-system.lisp:
+(defun test (&optional (n nil))
+ (if n
+ (print (format nil "test ~d" n))
+ (print "test")))
+
+;;; From k-best-analysis.lisp:
+(defmethod compute-analysis-segments-test (entry)
+ (let* ((lonsets entry)
+ (ldurs (x->dx lonsets))
+ (nb-chords (length lonsets))
+ (marks nil))
+ ;onsets contient les onsets à l'intérieur du segment
+ (labels ((estim-tempo ( dur-segment durs on-segment onsets &optional (ltempo nil))
+ (if (null durs)
+ (let* ((tempo (if (null ltempo) (to-tempo dur-segment) (average ltempo nil))))
+ (setq marks (append marks (list (make-instance 'marker-segment
+ :mrk-time (first on-segment)
+ :color (om-random-color)
+ :segment-data (make-instance 'k-best-data :tempo tempo))))))
+ (let ((new-tempo (to-tempo dur-segment)))
+ (if (null ltempo)
+ ;si début du segment
+ (estim-tempo (append dur-segment (list (first durs))) (rest durs) (append on-segment (list (first onsets))) (rest onsets) (list new-tempo))
+ (let ((old-tempo (average ltempo nil)))
+ (if (> (/ (abs (- new-tempo old-tempo)) old-tempo) 0.1)
+ ;on découpe
+ (progn
+ (setq marks (append marks (list (make-instance 'marker-segment
+ :mrk-time (first on-segment)
+ :color (om-random-color)
+ :segment-data (make-instance 'k-best-data :tempo old-tempo)))))
+ (estim-tempo (list (car (last dur-segment)) (first durs)) (cdr durs) (list (car (last on-segment)) (first onsets)) (cdr onsets)))
+ ;on continue
+ (estim-tempo (append dur-segment (list (first durs))) (rest durs) (append on-segment (list (first onsets))) (rest onsets) (append ltempo (list new-tempo)))))))))
+ (compute-error (dur-segment gcd &optional (error 0))
+ (if (null dur-segment)
+ error
+ (compute-error (rest dur-segment) gcd (+ error (abs (nth-value 1 (round (first dur-segment) gcd)))))))
+ (to-tempo (list)
+ (let* ((P1 (agcd list 0.05))
+ (P2 (agcd (mapcar #'(lambda (x) (/ x P1)) list) 0.2))
+ (P (* P1 (round P2)))
+ (tempo (/ 60000 P)))
+
+ (loop while (> tempo 300)
+ do (setq tempo (/ tempo 2)))
+ tempo)))
+ (estim-tempo (subseq ldurs 0 2) (cddr ldurs) (subseq lonsets 0 2) (cddr lonsets)))))
+
+
+;(compute-analysis-segments-test '(0 110 230 500 600 700 820))
+;(compute-analysis-segments-test '(1619 2207 2430 2670 2875 3134 3628 4129 4614 5043 5200 5466 5693 5926 6182 6695 7195 7616 7753 8222 8447 8714 8942 9213 9700 9950 10195 10413 10672 11162 11393 11655 11876 12095 12212 12652 12888 13121 13364 13648 14148 14372 14599 14830 15097 15571 16072 16577 16976 17216 17446 17700 17942 18216 18697 18949 19203 19426 19605 19747 20202 20433 20686 20920 21180 21645 21885 22129 22368 22646 23108 23359 23609 23858 24169 25244 25976))
+
+(defun draw-grid-test (grid &optional (depth 1) (begin 0) (dur 1000) (current-path nil))
+ (if (listp grid)
+ (let ((n (length grid)))
+ (loop for i from 0 to (1- n)
+ for time = begin then (+ time (round dur n))
+ do
+ (progn
+ (if (= depth 1)
+ (format nil "level 1 : ~d" time)
+ (unless (= time begin)
+ (format nil "level ~d : ~d" depth time)))
+ (draw-grid-test (nth i grid) (1+ depth) time (round dur n) (append current-path (list i))))))
+ (print current-path)))
+
+
+;(draw-grid-test '((1/4 (1/8 1/8)) 1/2))
+
+;;; From rq.lisp:
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;; TESTS ;;;;;;;;;;;;;;;;;;;;;;;;;;
+;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
+
+
+;(defun keypath (list schema &optional (path (path-empty *input2*)))
+; (if (null list)
+; path
+; (keypath (cdr list) (cdr schema) (path-addi path (car schema) (car list)))
+;))
+
+;(defun get-entry (list schema)
+; (gethash (keypath list schema))
+;)
+
+
+;(defun test (k flag)
+; (let* ((input (input-make ;'(( ((2 3) (2 3) 2) (5 (2 3) 2)))
+; '(2 2 2)
+; #(0.0 0.45 0.6 0.9 1)
+; #(1 1 1 1 -1)))
+; (ktable (init (transitions input)))
+; (p (path-empty input)))
+
+; (values (rq-best ktable input p k flag) (rq-to-omtree ktable input k flag))
+
+; )
+;)
+
+;(test 2 nil)
+
+
+
+;;; From subdivision.lisp:
+;; tests
+
+(setq *testschema1* '((((2 5) 2 3) (2 3 2) (3 2 2))) )
+(setq *testschema2* '(((2 2 2) (3 (2 3) (2 3)))) )
+(setq *testschema3* '((2 2) 3 4)) ;schéma mauvais : "2 ou 2, puis 3, puis 4"
+
+
+
+;;; From kbest-segment-quantification.lisp:
+;;;===========
+;;; tests
+;;;===========
+
+;(kbest-segment-cut-measures '(500 2500 5500) '(1000 2000 2000) '(2 4) 60 6750 250)
+
+
+
+;;Seg 1
+;(0 494 995 1480 1884)
+;((485) (214) (168) (404))
+;10
+;((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;(3 4)
+;120.645455
+;1490
+;0.5
+;nil
+;2
+
+
+;;Seg 2
+;(419 576 842 1069 1302 1563)
+;((104 55) (310) (302) (254) (261))
+;10
+;((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;(3 4);;;===========
+;;; tests
+;;;===========
+
+;(kbest-segment-cut-measures '(500 2500 5500) '(1000 2000 2000) '(2 4) 60 6750 250)
+
+
+
+;;Seg 1
+;(0 494 995 1480 1884)
+;((485) (214) (168) (404))
+;10
+;((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;(3 4)
+;120.645455
+;1490
+;0.5
+;nil
+;2
+
+
+;;Seg 2
+;(419 576 842 1069 1302 1563)
+;((104 55) (310) (302) (254) (261))
+;10
+;((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;(3 4)
+;108.86856
+;1557
+;0.5
+;nil
+;394
+
+
+;;Seg chelou
+;OM > (26 500 1001 1143)
+;OM > ((448) (157) (142))
+;OM > 10
+;OM > ((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;OM > (3 4)
+;OM > 119.121445
+;OM > 1495
+;OM > 0.5
+;OM > nil
+;OM > 23
+
+
+
+;(kbest-segment-quantify '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 120.645455 1490 0.5 nil 2)
+
+;(kbest-segment-quantify '(419 576 842 1069 1302 1563) '((104 55) (310) (302) (254) (261)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 108.86856 1557 0.5 nil 394)
+
+;(kbest-segment-quantify '(26 500 1001 1143) '((448) (157) (142)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 119.121445 1495 '0.5 nil 23)
+
+;(kbest-segment-quantify-automata '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 1490 0.5 2)
+
+;(kbest-segment-quantify-automata '(0 806 1625 2417 3208 4208) '((1000) (1000) (1000) (1000) (1000)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 4208 0.5 2)
+
+
+;(kbest-to-poly (kbest-segment-quantify-automatas '(0) nil 1 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 3278 0 991))
+
+
+
+
+;(defun test ()
+
+; (let* ((kbest (kbest-segment-quantify-automatas '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 2590 0.5 2))
+; (ktable (first (ktables kbest)))
+; (input (first (inputs kbest))))
+
+
+; (rq-to-omtree ktable input 1 nil 0 (path-addi (path-empty input) 2 1))
+
+; (let ((qv (make-instance 'om::quant-voice :k-bests kbest)))
+
+; (om::init-choices qv)
+
+
+
+;)))
+
+;(test)
+;108.86856
+;1557
+;0.5
+;nil
+;394
+
+
+;;Seg chelou
+;OM > (26 500 1001 1143)
+;OM > ((448) (157) (142))
+;OM > 10
+;OM > ((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13))))
+;OM > (3 4)
+;OM > 119.121445
+;OM > 1495
+;OM > 0.5
+;OM > nil
+;OM > 23
+
+
+
+;(kbest-segment-quantify '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 120.645455 1490 0.5 nil 2)
+
+;(kbest-segment-quantify '(419 576 842 1069 1302 1563) '((104 55) (310) (302) (254) (261)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 108.86856 1557 0.5 nil 394)
+
+;(kbest-segment-quantify '(26 500 1001 1143) '((448) (157) (142)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) '(3 4) 119.121445 1495 '0.5 nil 23)
+
+;(kbest-segment-quantify-automata '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 1490 0.5 2)
+
+;(kbest-segment-quantify-automata '(0 806 1625 2417 3208 4208) '((1000) (1000) (1000) (1000) (1000)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 4208 0.5 2)
+
+
+;(kbest-to-poly (kbest-segment-quantify-automatas '(0) nil 1 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 3278 0 991))
+
+
+
+
+;(defun test ()
+
+; (let* ((kbest (kbest-segment-quantify-automatas '(0 494 995 1480 1884) '((485) (214) (168) (404)) 10 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 2590 0.5 2))
+; (ktable (first (ktables kbest)))
+; (input (first (inputs kbest))))
+
+
+; (rq-to-omtree ktable input 1 nil 0 (path-addi (path-empty input) 2 1))
+
+; (let ((qv (make-instance 'om::quant-voice :automaton kbest)))
+
+; (om::init-choices qv)
+
+
+
+;)))
+
+;(test)
+
+
+
+(defun testsavetable ()
+ (let* ((k-best (rq::k-best-segment-quantify-automatas '(0 1000) '((1000)) 3 '((((2 3) (2 3) 2) (5 (2 3) 2) ((7 11 13)))) 1000 0 nil))
+ (ktable (car (rq::ktables k-best))))
+ (omng-save ktable)))
+
+;(testsavetable)
+;(gethash (path-addi (path-empty (input-make '(2 3 3) #(0 1000) #(1 -1)) ) 2 1) (eval (testsavetable)))