diff --git a/LICENSES/GPL-3.0-only.txt b/LICENSES/GPL-3.0-only.txt
new file mode 100644
index 0000000000000000000000000000000000000000..f6cdd22a6c1fbc887e08a215cb4beb3c47048041
--- /dev/null
+++ b/LICENSES/GPL-3.0-only.txt
@@ -0,0 +1,232 @@
+GNU GENERAL PUBLIC LICENSE
+Version 3, 29 June 2007
+
+Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
+
+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.
+
+     <one line to give the program's name and a brief idea of what it does.>
+     Copyright (C) <year>  <name of author>
+
+     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 <https://www.gnu.org/licenses/>.
+
+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:
+
+     <program>  Copyright (C) <year>  <name of author>
+     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 <https://www.gnu.org/licenses/>.
+
+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 <https://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/LICENSES/MIT.txt b/LICENSES/MIT.txt
deleted file mode 100644
index 2071b23b0e08594ea6bc99ac71129ef992abf498..0000000000000000000000000000000000000000
--- a/LICENSES/MIT.txt
+++ /dev/null
@@ -1,9 +0,0 @@
-MIT License
-
-Copyright (c) <year> <copyright holders>
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/README.md b/README.md
index 9f8a7eedf8e14e2058f6a896c757875425da0b25..f36a4882ee9a1c5ea2956db0f264678e7b73c84c 100644
--- a/README.md
+++ b/README.md
@@ -47,8 +47,12 @@ The RCFS website also includes interactive exercises: [https://rcfs.ch](https://
 | iLQR_bimanual_manipulability | iLQR applied to a planar bimanual robot problem with a cost on tracking a desired manipulability ellipsoid at the center of mass (batch formulation) | ✅ | ✅ |  |  |
 | iLQR_bicopter | iLQR applied to a bicopter problem (batch formulation) | ✅ | ✅ | ✅ |  |
 | iLQR_car | iLQR applied to a car parking problem (batch formulation) | ✅ | ✅ | ✅ |  |
-| ergodic_control_HEDAC | 2D ergodic control formulated as Heat Equation Driven Area Coverage (HEDAC) objective |  | ✅ |  |  |
-| ergodic_control_SMC | 2D ergodic control formulated as Spectral Multiscale Coverage (SMC) objective | ✅ | ✅ |  |  |
+| ergodic_control_HEDAC_1D | 1D ergodic control formulated as Heat Equation Driven Area Coverage (HEDAC) |  | ✅ |  |  |
+| ergodic_control_HEDAC_2D | 2D ergodic control formulated as Heat Equation Driven Area Coverage (HEDAC) |  | ✅ |  |  |
+| ergodic_control_SMC_1D | 1D ergodic control formulated as Spectral Multiscale Coverage (SMC) | ✅ | ✅ |  |  |
+| ergodic_control_SMC_2D | 2D ergodic control formulated as Spectral Multiscale Coverage (SMC) | ✅ | ✅ |  |  |
+| ergodic_control_SMC_DDP_1D | 1D trajectory optimization for ergodic control problem  | ✅ | ✅ |  |  |
+| ergodic_control_SMC_DDP_2D | 2D trajectory optimization for ergodic control problem  | ✅ | ✅ |  |  |
 
 
 ### Maintenance, contributors and licensing
@@ -59,5 +63,5 @@ Contributors: Sylvain Calinon, Philip Abbet, Jérémy Maceiras, Hakan Girgin, Ju
 
 Copyright (c) 2024 Idiap Research Institute, https://idiap.ch
 
-RCFS is licensed under the MIT License.
+RCFS is licensed under the GPLv3 License.
 
diff --git a/cpp/header.txt b/cpp/header.txt
index 3659078ec4123049f597136151b7f2a7ef32f04e..35538a171b5fc459c4a7bda7a9c92d61abe5942d 100644
--- a/cpp/header.txt
+++ b/cpp/header.txt
@@ -6,5 +6,5 @@ Written by John Doe <john.doe@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
diff --git a/cpp/src/IK_manipulator.cpp b/cpp/src/IK_manipulator.cpp
index e65067982a2b8de4cbe2874e7e4dc786255d00eb..5e9f35b90340419ad3c06b0bb24c20109dfe1668 100644
--- a/cpp/src/IK_manipulator.cpp
+++ b/cpp/src/IK_manipulator.cpp
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <iostream>
diff --git a/cpp/src/LQT.cpp b/cpp/src/LQT.cpp
index aa49a84f78a906c87a29cc2767ae068dea9e990d..99c1f5d50160b788d88997dded59688234d86a43 100644
--- a/cpp/src/LQT.cpp
+++ b/cpp/src/LQT.cpp
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <Eigen/Dense>
diff --git a/cpp/src/iLQR_bicopter.cpp b/cpp/src/iLQR_bicopter.cpp
index 64a74217fd83efed6105ff050c3e3976bab43628..d42612dcf8c0946443cf91b50a0fb1458c9f2df8 100644
--- a/cpp/src/iLQR_bicopter.cpp
+++ b/cpp/src/iLQR_bicopter.cpp
@@ -6,7 +6,7 @@ Written by Julius Jankowski <julius.jankowski@idiap.ch>,
 Jérémy Maceiras <jeremy.maceiras@idiap.ch> and Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <iostream>
diff --git a/cpp/src/iLQR_bimanual.cpp b/cpp/src/iLQR_bimanual.cpp
index 5c9a67d8c54dc7a44b3846ea37eff8f9d26414f9..cae43762994828aff84c240dfdf5f3e2ab18cb11 100644
--- a/cpp/src/iLQR_bimanual.cpp
+++ b/cpp/src/iLQR_bimanual.cpp
@@ -7,7 +7,7 @@ Written by Adi Niederberger <aniederberger@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <iostream>
diff --git a/cpp/src/iLQR_car.cpp b/cpp/src/iLQR_car.cpp
index e70be61f9ce7cdbdab74ef9dea01cd9ddea4aaad..2d6205ba39f1393ba158d2aebda818fe67adbb51 100644
--- a/cpp/src/iLQR_car.cpp
+++ b/cpp/src/iLQR_car.cpp
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <iostream>
diff --git a/cpp/src/iLQR_manipulator.cpp b/cpp/src/iLQR_manipulator.cpp
index 51de2163673e23e8f67a934f0822c3be5871e53d..cb1d5354175113a014ee11add3eee1bf77ba79ed 100644
--- a/cpp/src/iLQR_manipulator.cpp
+++ b/cpp/src/iLQR_manipulator.cpp
@@ -6,7 +6,7 @@ Written by Tobias Löw <tobias.low@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <GL/glut.h>
diff --git a/cpp/src/iLQR_manipulator_obstacle.cpp b/cpp/src/iLQR_manipulator_obstacle.cpp
index 6500df60adbc25b2657e37b30038cc30ae838867..5c4f4d52cd9d038b713e3ebcafcde706a3ac9a81 100644
--- a/cpp/src/iLQR_manipulator_obstacle.cpp
+++ b/cpp/src/iLQR_manipulator_obstacle.cpp
@@ -6,7 +6,7 @@ Written by Tobias Löw <tobias.low@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <GL/glut.h>
diff --git a/cpp/src/iLQR_obstacle_GPIS.cpp b/cpp/src/iLQR_obstacle_GPIS.cpp
index 6d3fae77c720b49694575cd72b2c0b0a825c0436..435427d6dc45b37b46c74e486cb269d161118abe 100644
--- a/cpp/src/iLQR_obstacle_GPIS.cpp
+++ b/cpp/src/iLQR_obstacle_GPIS.cpp
@@ -7,7 +7,7 @@ Written by Léane Donzé <leane.donze@epfl.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 */
 
 #include <Eigen/Core>
diff --git a/doc/bib_rcfs.bib b/doc/bib_rcfs.bib
index 6c22d51fb002a0706c997950f617d2768866f9b4..7c8e2c4fa943dd5d18c720d96cdb543b1271d0e0 100644
--- a/doc/bib_rcfs.bib
+++ b/doc/bib_rcfs.bib
@@ -68,7 +68,7 @@
   year = {1988}
 }
 
-%MP
+%MP + ergodic control
 @incollection{Calinon19MM,
 	author="Calinon, S.",
 	title="Mixture Models for the Analysis, Edition, and Synthesis of Continuous Time Series",
@@ -80,6 +80,18 @@
 	doi="10.1007/978-3-030-23876-6\_3"
 }
 
+%Ergodic control
+@article{Shetty21TRO,
+	author="Shetty, S. and Silv\'erio, J. and Calinon, S.",
+	title="Ergodic Exploration using Tensor Train: Applications in Insertion Tasks",
+	year="2022",
+	journal="{IEEE} Trans.\ on Robotics",
+	volume="38",
+	number="2",
+	pages="906--921",
+	doi="10.1109/TRO.2021.3087317"
+}
+
 %iLQR
 @inproceedings{Li04,
 	author="Li, W. and Todorov, E.",
@@ -236,3 +248,4 @@
   pages = {3789--3799},
   year = {2020}
 }
+
diff --git a/doc/images/SDF_coordSys01.png b/doc/images/SDF_coordSys01.png
index bf2c12797d0da985fbaa44bcaf9a7946b88be8fb..49c979644378965375373f19d0b476fbac619eb5 100644
Binary files a/doc/images/SDF_coordSys01.png and b/doc/images/SDF_coordSys01.png differ
diff --git a/doc/images/SMC-room001.jpg b/doc/images/SMC-room001.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..bba49afd2a8f36d9bcba5f9df2e10b0699ae3ad4
Binary files /dev/null and b/doc/images/SMC-room001.jpg differ
diff --git a/doc/images/SMC-room001c.jpg b/doc/images/SMC-room001c.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..7a7f6f83ef611d031ae762f2a0c06eef9a6cfba8
Binary files /dev/null and b/doc/images/SMC-room001c.jpg differ
diff --git a/doc/images/SMC-room002.jpg b/doc/images/SMC-room002.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..b2a855cf4b98275e35eab85b421311ea5ad64db7
Binary files /dev/null and b/doc/images/SMC-room002.jpg differ
diff --git a/doc/images/SMC-room002c.jpg b/doc/images/SMC-room002c.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..6fb87436010edac5935f9a22cc31b6b9e22ff0fa
Binary files /dev/null and b/doc/images/SMC-room002c.jpg differ
diff --git a/doc/images/basisFcts2D01.png b/doc/images/basisFcts2D01.png
new file mode 100644
index 0000000000000000000000000000000000000000..0d1c8a095442a378d1ce4eee3fab1014e7631359
Binary files /dev/null and b/doc/images/basisFcts2D01.png differ
diff --git a/doc/images/emoji-title.pdf b/doc/images/emoji-title.pdf
new file mode 100644
index 0000000000000000000000000000000000000000..22660f4077c926159ed82034af9cb4b7496b103a
Binary files /dev/null and b/doc/images/emoji-title.pdf differ
diff --git a/doc/images/ergodicControl-fromCrudetoPrecise01.jpg b/doc/images/ergodicControl-fromCrudetoPrecise01.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..0f67c875f160f9ac79cc62e5560c3e287441d920
Binary files /dev/null and b/doc/images/ergodicControl-fromCrudetoPrecise01.jpg differ
diff --git a/doc/images/ergodicControl_DDP_1D01.png b/doc/images/ergodicControl_DDP_1D01.png
new file mode 100644
index 0000000000000000000000000000000000000000..fd9f4ead76127f36eff5823ea1cb056ffd2721fe
Binary files /dev/null and b/doc/images/ergodicControl_DDP_1D01.png differ
diff --git a/doc/images/ergodicControl_DDP_2D01.png b/doc/images/ergodicControl_DDP_2D01.png
new file mode 100644
index 0000000000000000000000000000000000000000..b5d971ddcb4396337beac47a084f44545ea6e10d
Binary files /dev/null and b/doc/images/ergodicControl_DDP_2D01.png differ
diff --git a/doc/images/ergodicVsPatternedSearch01.jpg b/doc/images/ergodicVsPatternedSearch01.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..4b704766251175a7abd75b9dde4429bf23fc2ea5
Binary files /dev/null and b/doc/images/ergodicVsPatternedSearch01.jpg differ
diff --git a/doc/images/f_ee01.png b/doc/images/f_ee01.png
index 89d70336229a315f739ceb16126c5551354a40dc..8b4792a35fd7da2b67870c24df5b58633e8acfa9 100755
Binary files a/doc/images/f_ee01.png and b/doc/images/f_ee01.png differ
diff --git a/doc/images/gradientDescent1D01.png b/doc/images/gradientDescent1D01.png
new file mode 100755
index 0000000000000000000000000000000000000000..d80bd7ad70a7bf073b664cbe92341d39a116ed4f
Binary files /dev/null and b/doc/images/gradientDescent1D01.png differ
diff --git a/doc/images/gradientDescent_vs_NewtonMethod01.jpg b/doc/images/gradientDescent_vs_NewtonMethod01.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..8b8bd582068516c0db73405c2852cab9a00a3a20
Binary files /dev/null and b/doc/images/gradientDescent_vs_NewtonMethod01.jpg differ
diff --git a/doc/images/iLQR_curvature01.png b/doc/images/iLQR_curvature01.png
new file mode 100644
index 0000000000000000000000000000000000000000..f96c0df1e4a6a93b6a84e67ac5e0959c9b2b88a1
Binary files /dev/null and b/doc/images/iLQR_curvature01.png differ
diff --git a/doc/images/iLQR_distMaintain01.png b/doc/images/iLQR_distMaintain01.png
new file mode 100644
index 0000000000000000000000000000000000000000..2302e21a6dac2b791c138faf75633d348bc33808
Binary files /dev/null and b/doc/images/iLQR_distMaintain01.png differ
diff --git a/doc/images/iLQR_distMaintain02.png b/doc/images/iLQR_distMaintain02.png
new file mode 100644
index 0000000000000000000000000000000000000000..c59b7a74b07de158109177d8e29c492c821c20f8
Binary files /dev/null and b/doc/images/iLQR_distMaintain02.png differ
diff --git a/doc/images/iLQR_objectBoundaries01.jpg b/doc/images/iLQR_objectBoundaries01.jpg
index ebb873de036a708b16c9905c6a7a532556c59024..f8b031f7ac6ed1ba32e400470684ef7ee89ba3fe 100644
Binary files a/doc/images/iLQR_objectBoundaries01.jpg and b/doc/images/iLQR_objectBoundaries01.jpg differ
diff --git a/doc/images/intrinsicGeom_vs_extrinsicGeom01.jpg b/doc/images/intrinsicGeom_vs_extrinsicGeom01.jpg
new file mode 100644
index 0000000000000000000000000000000000000000..317a53d258c6d514cfbf6bf69813d9f4d6b50f01
Binary files /dev/null and b/doc/images/intrinsicGeom_vs_extrinsicGeom01.jpg differ
diff --git a/doc/images/kinEnergyGeodesics01.png b/doc/images/kinEnergyGeodesics01.png
new file mode 100644
index 0000000000000000000000000000000000000000..30e987960d2d9279512cca0ee432f7106cc36af0
Binary files /dev/null and b/doc/images/kinEnergyGeodesics01.png differ
diff --git a/doc/images/linesearch01.png b/doc/images/linesearch01.png
new file mode 100755
index 0000000000000000000000000000000000000000..fdf393dac704c49eaad214a8fda6f0d98f4d0eb9
Binary files /dev/null and b/doc/images/linesearch01.png differ
diff --git a/doc/images/nonhomogeneousManifolds01.png b/doc/images/nonhomogeneousManifolds01.png
deleted file mode 100644
index 6be727a8722d947226eb21f7e4bbffacbb489ea4..0000000000000000000000000000000000000000
Binary files a/doc/images/nonhomogeneousManifolds01.png and /dev/null differ
diff --git a/doc/images/obstacleGeodesics01.png b/doc/images/obstacleGeodesics01.png
new file mode 100644
index 0000000000000000000000000000000000000000..c3e8188411b9c552b664bc0861159f401ce31a16
Binary files /dev/null and b/doc/images/obstacleGeodesics01.png differ
diff --git a/doc/images/transformations01.jpg b/doc/images/transformations01.jpg
index c493bfb2f2bdf3233b1687cb1c678f3157dbcc0c..787ee1b128f376838fe23408e489eca0c1491109 100644
Binary files a/doc/images/transformations01.jpg and b/doc/images/transformations01.jpg differ
diff --git a/doc/rcfs.pdf b/doc/rcfs.pdf
index 5dacccf432c45e75e648fac6c741678ed6647ca2..6b5784de458bf1cd3ea1f5bb7cc255dcb2c33552 100644
Binary files a/doc/rcfs.pdf and b/doc/rcfs.pdf differ
diff --git a/doc/rcfs.tex b/doc/rcfs.tex
index 2b0c11e8f4d4878a5fc1554d39c8c73047d4fdf0..abda8708533461647d05bc376ed73787f7e3e2dc 100644
--- a/doc/rcfs.tex
+++ b/doc/rcfs.tex
@@ -1,6 +1,9 @@
+%requires compilation with lualatex
 \documentclass[10pt,a4paper]{article} %twocolumn
 \usepackage{graphicx,amsmath,amssymb,bm,xcolor,soul,nicefrac,listings,algorithm2e,dsfont,caption,subcaption,wrapfig,sidecap} 
 \usepackage[hidelinks]{hyperref}
+\usepackage[makeroom]{cancel}
+\usepackage[export]{adjustbox} %for valign in figures
 
 %pseudocode
 \newcommand\mycommfont[1]{\footnotesize\ttfamily\textcolor{lightgray}{#1}}
@@ -74,7 +77,7 @@ innerleftmargin=0.3em,innerrightmargin=0.3em,innertopmargin=0.3em,innerbottommar
 \newcommand{\tmin}{{\scriptscriptstyle\min}}
 \newcommand{\tmax}{{\scriptscriptstyle\max}}
 %\newcommand{\filename}[1]{{\raggedleft\colorbox{rr2}{{\color{white}\texttt{#1}}}\\[2mm]}}
-\newcommand{\filename}[1]{\colorbox{rr2}{\color{white}\texttt{#1}}}
+\newcommand{\filename}[1]{\colorbox{rr2}{\color{white}\texttt{#1}}}%{\emojifont🦉}
 \newcommand{\new}{{\!\scriptscriptstyle\mathrm{new}}}
 
 %\usepackage{hyperref}
@@ -96,7 +99,13 @@ innerleftmargin=0.3em,innerrightmargin=0.3em,innertopmargin=0.3em,innerbottommar
 %    urlcolor=black
 %}
 
-\title{\huge Learning and Optimization in Robotics\\[4mm]\emph{Lecture notes}}
+%\usepackage{fontspec}
+%\newfontfamily\emojifont[Renderer=HarfBuzz]{NotoColorEmoji.ttf} %,SizeFeatures={Size=20}
+%%-> requires compilation with lualatex
+
+\title{\huge A Math Cookbook for Robot Manipulation\\\includegraphics{images/emoji-title.pdf}}
+%{\emojifont🔢🧑‍🍳🦾} 
+%Learning and Optimization in Robotics\\[4mm]\emph{Lecture notes}
 %A practical guide to learning and control problems in robotics\\solved with second-order optimization
 \author{Sylvain Calinon, Idiap Research Institute}
 \date{}
@@ -113,49 +122,69 @@ innerleftmargin=0.3em,innerrightmargin=0.3em,innertopmargin=0.3em,innerbottommar
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Introduction}
 
-This technical report presents several learning and optimal control techniques in robotics in the form of simple toy problems that can be easily coded. It comes as part of \textbf{Robotics Codes From Scratch (RCFS)}, a website containing interactive sandbox examples and exercises, together with a set of standalone source code examples gathered in a git repository, which can be accessed at:
+This cookbook presents learning and optimal control recipes for robotics (essentially for robot manipulators), complemented by simple toy problems that can be easily coded. It accompanies \textbf{Robotics Codes From Scratch (RCFS)}, a website containing interactive sandbox examples and exercises, together with a set of standalone source code examples gathered in a git repository, which can be accessed at:
 \begin{center}
 \url{https://rcfs.ch}
 %\url{https://gitlab.idiap.ch/rli/robotics-codes-from-scratch}
 \end{center}%\\
 
-Each section in this report lists the corresponding source codes in Python and Matlab (ensuring full compatibility with GNU Octave), as well as in C++ and Julia for some of the principal examples, which can be accessed at:
+Each section in this document lists the corresponding source codes in Python and Matlab (ensuring full compatibility with GNU Octave), as well as in C++ and Julia for some of the principal examples, which can be accessed at:
 \begin{center}
 \url{https://gitlab.idiap.ch/rli/robotics-codes-from-scratch}
 \end{center}
 
+
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Quadratic costs minimization as a product of Gaussians (PoG)}\label{sec:PoG}
 
+\begin{figure}[ht]
+\centering
+\includegraphics[width=.8\columnwidth]{images/PoG01.png}
+\caption{\footnotesize
+Quadratic costs minimization as a product of Gaussians (PoG).
+}
+\label{fig:PoG}
+\end{figure}
+
 The solution of a quadratic cost function can be viewed probabilistically as corresponding to a Gaussian distribution. Indeed, given a precision matrix $\bm{W}$, the quadratic cost
 \begin{align}
 	c(\bm{x}) &= (\bm{x}-\bm{\mu})^\trsp \bm{W} (\bm{x}-\bm{\mu}),\\
 	&= \|\bm{x}-\bm{\mu}\|_{\bm{W}}^2,
 	\label{eq:quadratic}
 \end{align}
-has an optimal solution $\bm{x}^* = \bm{\mu}$. This solution does not contain much information about the cost function itself. Alternatively, we can view $\bm{x}$ as a random variable with a Gaussian distribution, i.e., $p(\bm{x}) = \mathcal{N}(\bm{\mu}, \bm{\Sigma})$ where $\bm{\mu}$ and $\bm{\Sigma}=\bm{W}^{-1}$ are the mean vector and covariance matrix of the Gaussian, respectively. The negative log-likelihood of this Gaussian distribution is equivalent to \eqref{eq:quadratic} up to a constant factor. According to $p(\bm{x})$, $\bm{x}$ has the highest probability at $\bar{\bm{x}}$, and $\bm{\Sigma}$ gives the directional information on how this probability changes as we move away from $\bm{\mu}$. The point having the lowest cost in \eqref{eq:quadratic} is therefore associated with the point having the highest probability. 
+has an optimal solution $\bm{x}^* = \bm{\mu}$. This solution does not contain much information about the cost function itself. Alternatively, we can view $\bm{x}$ as a random variable with a Gaussian distribution, i.e., $p(\bm{x}) = \mathcal{N}(\bm{\mu}, \bm{\Sigma})$, where $\bm{\mu}$ and $\bm{\Sigma}=\bm{W}^{-1}$ are the mean vector and covariance matrix of the Gaussian, respectively. The negative log-likelihood of this Gaussian distribution is equivalent to \eqref{eq:quadratic} up to a constant factor. According to $p(\bm{x})$, $\bm{x}$ has the highest probability at $\bar{\bm{x}}$, and $\bm{\Sigma}$ gives the directional information on how this probability changes as we move away from $\bm{\mu}$. The point having the lowest cost in \eqref{eq:quadratic} is therefore associated with the point having the highest probability. 
 
 Similarly, the solution of a cost function composed of several quadratic terms 
 \begin{equation}
 	\bm{\hat{\mu}} = \arg\min_{\bm{x}} \sum_{k=1}^K {(\bm{x} - \bm{\mu}_k)}^\trsp \bm{W}_k (\bm{x} - \bm{\mu}_k)
 \label{eq:quad_costs_multiple}
 \end{equation}
-can be seen as a product of Gaussians $\prod_{k=1}^K\mathcal{N}(\bm{\mu}_k,\bm{W}_k^{-1})$, with centers $\bm{\mu}_k$ and covariance matrices $\bm{W}_k^{-1}$. The Gaussian $\mathcal{N}(\bm{\hat{\mu}},\bm{\hat{W}}^{-1})$ resulting from this product has parameters
+can be seen as a product of Gaussians $\prod_{k=1}^K\mathcal{N}(\bm{\mu}_k,\bm{W}_k^{-1})$, with centers $\bm{\mu}_k$ and covariance matrices $\bm{\Sigma}_k=\bm{W}_k^{-1}$. The Gaussian $\mathcal{N}(\bm{\hat{\mu}},\bm{\hat{W}}^{-1})$ resulting from this product has parameters
 \begin{equation*}
 	\bm{\hat{\mu}} = {\left(\sum_{k=1}^K \bm{W}_k\right)}^{\!-1} \left(\sum_{k=1}^K\bm{W}_k \bm{\mu}_k \right), \quad 
 	\bm{\hat{W}} = \sum_{k=1}^K \bm{W}_k.
 \end{equation*}
 
-$\bm{\hat{\mu}}$ and $\bm{\hat{W}}$ are the same as the solution of~\eqref{eq:quad_costs_multiple} and its Hessian, respectively. Viewing the quadratic cost probabilistically can capture more information about the cost function in the form of the covariance matrix $\bm{\hat{W}}^{-1}$. 
+$\bm{\hat{\mu}}$ and $\bm{\hat{W}}$ are the same as the solution of~\eqref{eq:quad_costs_multiple} and its Hessian, respectively. Viewing the quadratic cost probabilistically can capture more information about the cost function in the form of the covariance matrix $\bm{\hat{\Sigma}}= \bm{\hat{W}}^{-1}$. 
 
-\begin{figure}
-\centering
-\includegraphics[width=.8\columnwidth]{images/PoG01.png}
-\caption{\footnotesize
-Quadratic costs minimization as a product of Gaussians (PoG).
-}
-\label{fig:PoG}
-\end{figure}
+There are also computation alternatives in case of Gaussians close to singularity. To be numerically more robust when computing the product of two Gaussians $\mathcal{N}(\bm{\mu}_1, \bm{\Sigma}_1)$ and $\mathcal{N}(\bm{\mu}_2, \bm{\Sigma}_2)$, the Gaussian $\mathcal{N}(\bm{\hat{\mu}}, \bm{\hat{\Sigma}})$ resulting from the product can indeed be computed with 
+\begin{equation*}
+	\bm{\hat{\mu}} = \bm{\Sigma}_2 {\left(\bm{\Sigma}_1+\bm{\Sigma}_2\right)}^{-1} \bm{\mu}_1 + 
+	\bm{\Sigma}_1 {\left(\bm{\Sigma}_1+\bm{\Sigma}_2\right)}^{-1} \bm{\mu}_2 , \quad 
+	\bm{\hat{\Sigma}} = \bm{\Sigma}_1 {\left(\bm{\Sigma}_1+\bm{\Sigma}_2\right)}^{-1} \bm{\Sigma}_2,
+\end{equation*}
+by exploiting the fact that $\bm{\Sigma}_1\bm{\Sigma}_1^{-1}\!=\!\bm{I}$ and $\bm{\Sigma}_2^{-1}\bm{\Sigma}_2\!=\!\bm{I}$, we can observe that 
+\begin{align*}
+	\bm{W}_1+\bm{W}_2 &= \bm{\Sigma}_2^{-1}+\bm{\Sigma}_1^{-1}\\
+	&= \bm{\Sigma}_2^{-1}\bm{\Sigma}_1\bm{\Sigma}_1^{-1}+\bm{\Sigma}_2^{-1}\bm{\Sigma}_2\bm{\Sigma}_1^{-1}\\
+	&=\bm{\Sigma}_2^{-1} (\bm{\Sigma}_1+\bm{\Sigma}_2) \bm{\Sigma}_1^{-1},
+\end{align*}
+so that 
+\begin{align*}
+\bm{\hat{\Sigma}} &= {(\bm{W}_1+\bm{W}_2)}^{-1} = \bm{\Sigma}_1 {(\bm{\Sigma}_1+\bm{\Sigma}_2)}^{-1} \bm{\Sigma}_2,\\
+\bm{\hat{\mu}} &= {(\bm{W}_1+\bm{W}_2)}^{-1} (\bm{\Sigma}_1^{-1}\bm{\mu}_1+\bm{\Sigma}_2^{-1}\bm{\mu}_2) 
+= \bm{\Sigma}_2 {\left(\bm{\Sigma}_1+\bm{\Sigma}_2\right)}^{-1} \bm{\mu}_1 + \bm{\Sigma}_1 {\left(\bm{\Sigma}_1+\bm{\Sigma}_2\right)}^{-1} \bm{\mu}_2.
+\end{align*}
 
 Figure \ref{fig:PoG} shows an illustration for 2 Gaussians in a 2-dimensional space. It also shows that when one of the Gaussians is singular, the product corresponds to a projection operation, that we for example find in nullspace projections to solve prioritized tasks in robotics. 
 
@@ -177,13 +206,14 @@ Figure \ref{fig:PoG} shows an illustration for 2 Gaussians in a 2-dimensional sp
 %Solving an objective function composed of quadratic terms as a product of Gaussians offers a probabilistic perspective by representing the solution in the form of a distribution. 
 
 \newpage
+
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\section{Newton's method for minimization}\label{sec:Newton}
+\section{Cost function minimization problems}\label{sec:Newton}
 
-\begin{wrapfigure}{r}{.28\textwidth}
+\begin{wrapfigure}{r}{.24\textwidth}
 %\vspace{-20pt}
 \centering
-\includegraphics[width=.26\textwidth]{images/NewtonMethod1D_problem01.png}
+\includegraphics[width=.23\textwidth]{images/NewtonMethod1D_problem01.png}
 \caption{\footnotesize
 Problem formulation.
 }
@@ -191,19 +221,89 @@ Problem formulation.
 \vspace{20pt}
 \end{wrapfigure}
 
-We would like the find the value of a decision variable $x$ that would give us a cost $c(x)$ that is a small as possible, see Figure \ref{fig:NewtonProblem}. Imagine that we start from an initial guess $x_1$ and that can observe the behavior of this cost function within a very small region around our initial guess. Now let's assume that we can make several consecutive guesses that will each time provide us with similar local information about the behavior of the cost around the points that we guessed. From this information, what point would you select as second guess (see question marks in the figure), based on the information that you obtained from the first guess? There were two relevant information in the small portion of curve that we can observe in the figure to make a smart choice. First, the trend of the curve indicates that the cost seems to decrease if we move on the left side, and increase if we move on the right side. Namely, the slope $c'(x_1)$ of the function $c(x)$ at point $x_1$ is positive. Second, we can observe that the portion of the curve has some curvature that can be also be informative about the way the trend of the curve $c(x)$ will change by moving to the left or to the right. Namely, how much the slope $c'(x_1)$ will change, corresponding to an acceleration $c''(x_1)$ around our first guess $x_1$. This is informative to estimate how much we should move to the left of the first guess to wisely select a second guess. \newline
+We would like the find the value of a decision variable $x$ that would give us a cost $c(x)$ that is a small as possible, see Figure \ref{fig:NewtonProblem}. Imagine that we start from an initial guess $x_1$ and that can observe the behavior of this cost function within a very small region around our initial guess. Now let's assume that we can make several consecutive guesses that will each time provide us with similar local information about the behavior of the cost around the points that we guessed. From this information, what point would you select as second guess (see question marks in the figure), based on the information that you obtained from the first guess? 
 
-\begin{wrapfigure}{r}{.48\textwidth}
-%\vspace{-20pt}
+There were two relevant information in the small portion of curve that we can observe in the figure to make a smart choice. First, the trend of the curve indicates that the cost seems to decrease if we move on the left side, and increase if we move on the right side. Namely, the slope $c'(x_1)$ of the function $c(x)$ at point $x_1$ is positive. Second, we can observe that the portion of the curve has some curvature that can be also be informative about the way the trend of the curve $c(x)$ will change by moving to the left or to the right. Namely, how much the slope $c'(x_1)$ will change, corresponding to an acceleration $c''(x_1)$ around our first guess $x_1$. This is informative to estimate how much we should move to the left of the first guess to wisely select a second guess. \newline
+
+Now that we have this intuition, we can move to a more formal problem formulation. Newton's method attempts to solve $\min_x c(x)$ or $\max_x c(x)$ from an initial guess $x_1$ by using a sequence of \textbf{first-order Taylor approximations} (gradient descent) or \textbf{second-order Taylor approximations} (Newton's method) of $c(x)$ around the iterates. 
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsection{Gradient descent} 
+
+\begin{wrapfigure}{r}{.42\textwidth}
 \centering
-\includegraphics[width=.42\textwidth]{images/NewtonMethod1D01.png}
+\includegraphics[width=.36\textwidth]{images/gradientDescent1D01.png}
 \caption{\footnotesize
-Newton's method for minimization, starting from an initial estimate $x_1$ and converging to a local minimum (red point) after 5 iterations.
+Gradient descent for minimization, starting from an initial estimate $x_1$ and converging to a local minimum (red point) after 8 iterations.
 }
-\label{fig:Newton}
+\label{fig:gradientDescent}
+\vspace{30pt}
 \end{wrapfigure}
 
-Now that we\begin{wrapfigure}{r}{.48\textwidth}
+\begin{algorithm}
+\caption{Backtracking line search method with parameter $\alpha_{\min}$ (presented here for decision variable $\bm{x}$)}
+\label{alg:linesearch}
+$\alpha \gets 1$ \\
+%\While{$c(\bm{\hat{u}}+\alpha\;\Delta\bm{\hat{u}}) > c(\bm{\hat{u}}) \;\textbf{and}\;\; \alpha > \alpha_{\min}$}{
+\While{$c(\bm{x}+\alpha\;\Delta\bm{x}) > c(\bm{x}) \;\textbf{and}\;\; \alpha > \alpha_{\min}$}{
+	$\alpha \gets \frac{\alpha}{2}$
+}
+\end{algorithm}
+
+Figure \ref{fig:gradientDescent} shows how consecutive \textbf{first-order Taylor approximations} of $c(x)$ around the iterates allow to solve a minimization problem.
+
+The first-order Taylor expansion around the point $x_k$ can be expressed as
+\begin{equation*}
+	c(x_k\!+\!\Delta x_k) \approx c(x_k) + c'(x_k) \; \Delta x_k,
+\end{equation*}
+where $c'(x_k)$ is the derivative of $c(x_k)$ at point $x_k$.
+
+By starting from a point $x_k$ at each step $k$, we are interested in applying a correction $\Delta x_k$ that would decrease the cost $c(x_k)$. 
+If the cost function follows a linear trend at point $x_k$ with a slope defined by its gradient $c'(x_k)$, one direction would increase the cost while the other would decrease it. Thus, by applying a correction $\Delta x_k = -\alpha c'(x_k)$,  where $\alpha$ is a positive scaling factor, we go down the slope estimated at $x_k$. 
+
+The scaling factor $\alpha$ can be either constant or variable. If $\alpha$ is too large, there is the risk that our local linear approximation is not valid anymore when we move far away from $x_k$. If it is too small, the iterative algorithm will require many iteration steps to converge to a local minimum of the cost function. 
+
+In practice, a simple backtracking line search procedure can be considered with Algorithm \ref{alg:linesearch}, by considering a small value for $\alpha_{\min}$, see Figure \ref{fig:linesearch}. For more elaborated methods, see Ch.~3 of \cite{Nocedal06}. 
+
+\newpage
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsubsection*{Multidimensional case}
+
+\begin{wrapfigure}{r}{.24\textwidth}
+\centering
+\includegraphics[width=.22\textwidth]{images/linesearch01.png}
+\caption{\footnotesize
+backtracking line search to scale the update vector $\Delta x_k$ until the update decreases the cost. In this example, by starting with $\alpha=1$ and by iteratively dividing $\alpha$ by two, the procedure provides a scaling factor $\alpha=0.25$.    
+}
+\label{fig:linesearch}
+\vspace{20pt}
+\end{wrapfigure}
+
+For functions that depend on multiple variables stored as multidimensional vectors $\bm{x}$, the cost function $c(\bm{x})$ can similarly be approximated by a first-order Taylor expansion around the point $\bm{x}_k$ with
+%\begin{equation*}
+%	c(\bm{x}_k\!+\!\Delta\bm{x}_k) \approx c(\bm{x}_k) + \Delta\bm{x}_k^\trsp \, \frac{\partial c}{\partial\bm{x}}\Big|_{\bm{x}_k}, 
+%\end{equation*}
+%which can also be rewritten in vector form as
+\begin{equation*}
+	c(\bm{x}_k\!+\!\Delta\bm{x}_k) \approx c(\bm{x}_k) + {\bm{g}(\bm{x}_k)}^\trsp \Delta\bm{x}_k,
+\end{equation*}
+with gradient vector
+\begin{equation*}
+	\bm{g}(\bm{x}_k) = \frac{\partial c}{\partial\bm{x}}\Big|_{\bm{x}_k}.
+\end{equation*}
+
+By starting from an initial estimate $\bm{x}_1$ and by recursively refining the current estimate by following the gradient, we obtain at each iteration $k$ the recursion
+\begin{equation*}
+	\bm{x}_{k+1} = \bm{x}_k - \alpha \bm{g}(\bm{x}_k).
+\end{equation*}
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsection{Newton's method}
+
+\begin{wrapfigure}{r}{.46\textwidth}
 %\vspace{-20pt}
 \centering
 \includegraphics[width=.42\textwidth]{images/NewtonMethod1D01.png}
@@ -211,7 +311,9 @@ Now that we\begin{wrapfigure}{r}{.48\textwidth}
 Newton's method for minimization, starting from an initial estimate $x_1$ and converging to a local minimum (red point) after 5 iterations.
 }
 \label{fig:Newton}
-\end{wrapfigure} have this intuition, we can move to a more formal problem formulation. Newton's method attempts to solve $\min_x c(x)$ or $\max_x c(x)$ from an initial guess $x_1$ by using a sequence of \textbf{second-order Taylor approximations} of $c(x)$ around the iterates, see Fig.~\ref{fig:Newton}. 
+\end{wrapfigure}
+
+Figure \ref{fig:Newton} shows how consecutive \textbf{second-order Taylor approximations} of $c(x)$ around the iterates allow to solve a minimization problem.
 
 The second-order Taylor expansion around the point $x_k$ can be expressed as
 \begin{equation}
@@ -222,20 +324,9 @@ where $c'(x_k)$ and $c''(x_k)$ are the first and second derivatives at point $x_
 
 We are interested in solving minimization problems with this approximation. If the second derivative $c''(x_k)$ is positive, the quadratic approximation is a convex function of $\Delta x_k$, and its minimum can be found by setting the derivative to zero.
 
-\newpage
-
-\begin{wrapfigure}{r}{.28\textwidth}
-\vspace{-20pt}
-\includegraphics[width=.26\textwidth]{images/optim_principle01.png}
-\caption{\footnotesize
-Finding local optima by localizing the points whose derivatives are zero (horizontal slopes).
-}
-\label{fig:optimPrinciple}
-\end{wrapfigure}
+Indeed, to find the local optima of a function, we can localize the points whose derivatives are zero (horizontal slopes), see Figure \ref{fig:optimPrinciple} for an illustration.
 
-To find the local optima of a function, we can localize the points whose derivatives are zero, see Figure \ref{fig:optimPrinciple} for an illustration.
-
-Thus, by differentiating \eqref{eq:Taylor_1D} w.r.t.\ $\Delta x_k$ and equating to zero, we obtain 
+By differentiating \eqref{eq:Taylor_1D} w.r.t.\ $\Delta x_k$ and equating to zero, we then obtain 
 \begin{equation*}
 	c'(x_k) + c''(x_k) \, \Delta x_k = 0,
 \end{equation*}
@@ -245,29 +336,40 @@ meaning that the minimum is given by
 \end{equation*} 
 which corresponds to the offset to apply to $x_k$ to minimize the second-order polynomial approximation of the cost at this point.
 
-\begin{wrapfigure}{r}{.28\textwidth}
+\begin{wrapfigure}{r}{.32\textwidth}
 %\vspace{-20pt}
 \centering
-\includegraphics[width=.26\textwidth]{images/NewtonMethod_negativeHessian01.png}
+\includegraphics[width=.24\textwidth]{images/optim_principle01.png}
 \caption{\footnotesize
-Newton update that would be achieved when the second derivative is negative.
+Finding local optima.
 }
-\label{fig:NewtonNegativeHessian}
-%\vspace{-20pt}
+\label{fig:optimPrinciple}
 \end{wrapfigure}
 
-It is important that $c''(x_k)$ is positive if we want to find local minima, see Figure \ref{fig:NewtonNegativeHessian} for an illustration. 
-
-
 By starting from an initial estimate $x_1$ and by recursively refining the current estimate by computing the offset that would minimize the polynomial approximation of the cost at the current estimate, we obtain at each iteration $k$ the recursion
 \begin{equation}
 	x_{k+1} = x_k - \frac{c'(x_k)}{c''(x_k)}.
 	\label{eq:Taylor_1D_update}
 \end{equation}
 
+\begin{wrapfigure}{r}{.42\textwidth}
+%\vspace{-20pt}
+\centering
+\includegraphics[width=.26\textwidth]{images/NewtonMethod_negativeHessian01.png}
+\caption{\footnotesize
+Newton update that would be achieved when the second derivative is negative.
+}
+\label{fig:NewtonNegativeHessian}
+%\vspace{-20pt}
+\end{wrapfigure}
+
+It is important that at each iteration, $c''(x_k)$ is positive, as we want to find local minima, see Figure \ref{fig:NewtonNegativeHessian} for an illustration. If $c''(x_k)$ is negative or too close to 0, it is in practice replaced by as small positive value in \eqref{eq:Taylor_1D_update}.
+
 The geometric interpretation of Newton's method is that at each iteration, it amounts to the fitting of a paraboloid to the surface of $c(x)$ at $x_k$, having the same slopes and curvature as the surface at that point, and then proceeding to the maximum or minimum of that paraboloid. Note that if $c(x)$ is a quadratic function, then the exact extremum is found in one step, which corresponds to the resolution of a least-squares problem. 
 %Note also that Newton's method is often modified to include a step size (e.g., estimated with line search).
 
+Similarly as for gradient descent, in practice, a simple backtracking line search procedure can also be considered with Algorithm \ref{alg:linesearch}.
+
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsubsection*{Multidimensional case}
@@ -329,45 +431,111 @@ By starting from an initial estimate $\bm{x}_1$ and by recursively refining the
 	\label{eq:Taylor_nD_update}
 \end{equation}
 
+In practice, we need to verify if the Hessian matrix $\bm{H}(\bm{x}_k)$ is positive definite at each iteration step.
+
+\begin{figure}
+\centering
+\includegraphics[width=.6\columnwidth]{images/gradientDescent_vs_NewtonMethod01.jpg}
+\caption{\footnotesize
+Convergence of gradient descent and Newton's method to solve minimization problems.
+}
+\label{fig:gradientDescent_vs_NewtonMethod}
+\end{figure}
+
+Figure \ref{fig:gradientDescent_vs_NewtonMethod} shows the iteration steps taken by gradient descent and Newton's method to solve two minimization problems. The minimization problem in the first row is a quadratic cost function, where Newton's method converges in one iteration, while gradient descent requires multiple oscillatory steps to reach the minimum.
+
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsection{Gauss--Newton algorithm}\label{sec:GaussNewton}
 %https://en.wikipedia.org/wiki/Gauss%E2%80%93Newton_algorithm (section Derivation from Newton's method)
 %http://homepages.laas.fr/nmansard/teach/robotics2015/textbook_draft.pdf
 
-The Gauss--Newton algorithm is a special case of Newton's method in which the cost is quadratic (sum of squared function values), with $c(\bm{x})=\sum_{i=1}^R r_i^2(\bm{x})=\bm{r}^\trsp\bm{r}=\|r\|^2$, where $\bm{r}$ are residual vectors. We neglect in this case the second-order derivative terms of the Hessian. The gradient and Hessian can in this case be computed with 
+The Gauss--Newton algorithm is a special case of Newton's method in which the cost is quadratic (sum of squared function values), with the scalar cost $c(\bm{x})=\|\bm{f}(\bm{x})\|^2=\bm{f}(\bm{x})^\trsp\bm{f}(\bm{x})=\sum_{i=1}^R f_i^2(\bm{x})$, where $\bm{f}(\bm{x})\in\mathbb{R}^R$ is a residual vector. By neglecting the second-order derivative terms, the gradient and Hessian can be computed with 
 \begin{equation*}
-	\bm{g} = 2 \bm{J}_{\bm{r}}^\trsp \bm{r} ,\quad 
-	\bm{H} \approx 2 \bm{J}_{\bm{r}}^\trsp \bm{J}_{\bm{r}},
+	\bm{g}(\bm{x}) = 2 \bm{J}(\bm{x})^\trsp \bm{f}(\bm{x}) ,\quad 
+	\bm{H}(\bm{x}) \approx 2 \bm{J}(\bm{x})^\trsp \bm{J}(\bm{x}),
 \end{equation*}
-where $\bm{J}_{\bm{r}}\in\mathbb{R}^{R\times D}$ is the Jacobian matrix of $\bm{r}\in\mathbb{R}^R$. This definition of the Hessian matrix makes it positive definite, which is useful to solve minimization problems as for well conditioned Jacobian matrices, we do not need to verify the positive definiteness of the Hessian matrix at each iteration.
+where $\bm{J}(\bm{x})\in\mathbb{R}^{R\times D}$ is the Jacobian matrix of $\bm{f}(\bm{x})$. This definition of the Hessian matrix makes it positive definite, which is useful to solve minimization problems as for well conditioned Jacobian matrices, we do not need to verify the positive definiteness of the Hessian matrix at each iteration.
 
 The update rule in \eqref{eq:Taylor_nD_update} then becomes
 \begin{align}
-	\bm{x}_{k+1} &= \bm{x}_k - {\big(\bm{J}_{\bm{r}}^\trsp(\bm{x}_k) \bm{J}_{\bm{r}}(\bm{x}_k)\big)}^{-1} \, 
-	\bm{J}_{\bm{r}}^\trsp(\bm{x}_k) \, \bm{r}(\bm{x}_k) \\
-	&= \bm{x}_k - \bm{J}_{\bm{r}}^\psin(\bm{x}_k) \, \bm{r}(\bm{x}_k),
+	\bm{x}_{k+1} &= \bm{x}_k - {\big(\bm{J}^\trsp(\bm{x}_k) \bm{J}(\bm{x}_k)\big)}^{-1} \, 
+	\bm{J}^\trsp(\bm{x}_k) \, \bm{f}(\bm{x}_k) \nonumber\\
+	&= \bm{x}_k - \bm{J}^\psin(\bm{x}_k) \, \bm{f}(\bm{x}_k),
 	\label{eq:GaussNewtonUpdate}
 \end{align}
-where $\bm{J}_{\bm{r}}^\psin$ denotes the pseudoinverse of $\bm{J}_{\bm{r}}$.
+where $\bm{J}^\psin$ denotes the pseudoinverse of $\bm{J}$.
+
+For comparison, the corresponding gradient descent problem would be computed as
+\begin{equation*}
+	\bm{x}_{k+1} = \bm{x}_k - \, \bm{J}^\trsp(\bm{x}_k) \, \bm{f}(\bm{x}_k). 
+\end{equation*}
+
+Thus, for costs that can be expressed as $c(\bm{x})=\bm{f}(\bm{x})^\trsp\bm{f}(\bm{x})$, the difference between first order or second order optimization is that the latter transforms the gradient of the former by the inverse of the Hessian matrix $\bm{H}(\bm{x}_k)=\bm{J}^\trsp(\bm{x}_k) \bm{J}(\bm{x}_k)$. Another way to described this difference is to explain the former as an approximation of the latter with an Hessian matrix defined as identity (i.e., $\bm{H}=\bm{I}$). 
 
-The Gauss--Newton algorithm is the workhorse of many robotics problems, including inverse kinematics and optimal control, as we will see in the next sections.
+The Gauss--Newton algorithm is the workhorse of many robotics problems, including inverse kinematics and optimal control, as we will see later in the document.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsection{Least squares}\label{sec:LS}
 
+We show in this section the direct link between Gauss--Newton algorithm and least squares. Extensions of least square are also presented here, which can also directly be used for optimization problems.
+
 When the cost $c(\bm{x})$ is a quadratic function w.r.t.\ $\bm{x}$, the optimization problem can be solved directly, without requiring iterative steps. Indeed, for any matrix $\bm{A}$ and vector $\bm{b}$, we can see that if
-\begin{equation*}
-	c(\bm{x}) = (\bm{A}\bm{x}-\bm{b})^\trsp (\bm{A}\bm{x}-\bm{b}),
-\end{equation*}
-derivating $c(\bm{x})$ w.r.t.\ $\bm{x}$ and equating to zero yields
-\begin{equation*}
+\begin{equation}
+	c(\bm{x}) = \|\bm{A}\bm{x}-\bm{b}\|^2 = (\bm{A}\bm{x}-\bm{b})^\trsp (\bm{A}\bm{x}-\bm{b}),
+	\label{eq:costquadratic}
+\end{equation}
+deriving $c(\bm{x})$ w.r.t.\ $\bm{x}$ and equating to zero yields
+\begin{equation}
 	\bm{A}\bm{x} - \bm{b} = \bm{0} 
-	\iff \bm{x} = \bm{A}^\psin\bm{b},
-\end{equation*}
+	\iff \bm{x} = (\bm{A}^\trsp \bm{A})^{-1} \bm{A}^\trsp \bm{b} = \bm{A}^\psin \bm{b},
+	\label{eq:costquadraticsolution}
+\end{equation}
 which corresponds to the standard analytic least squares estimate. We will see later in the inverse kinematics section that for the complete solution can also include a nullspace structure. 
 
+In contrast to the Gauss--Newton algorithm presented in Section \ref{sec:GaussNewton}, the optimization problem in \eqref{eq:costquadratic}, described by a quadratic cost on the decision variable $\bm{x}$, admits the solution \eqref{eq:costquadraticsolution} that can be computed directly without relying on an iterative procedure. We can observe that if we follow the Gauss--Newton procedure, the residual vector corresponding to the cost \eqref{eq:costquadratic} is $\bm{f}=\bm{A}\bm{x}-\bm{b}$ and its Jacobian matrix is $\bm{J}=\bm{A}$. By starting from an initial estimate $\bm{x}_0$, the Gauss--Newton update in \eqref{eq:GaussNewtonUpdate} then takes the form
+\begin{align*}
+	\bm{x}_{k+1} &= \bm{x}_k - \bm{A}^\psin (\bm{A}\bm{x}_k-\bm{b})\\
+	&= \bm{x}_k - (\bm{A}^\trsp \bm{A})^{-1} \bm{A}^\trsp (\bm{A}\bm{x}_k-\bm{b})\\
+	&= \bm{x}_k - \cancel{(\bm{A}^\trsp \bm{A})^{-1}} \cancel{(\bm{A}^\trsp\bm{A})} \bm{x}_k + \bm{A}^\psin \bm{b}\\
+	&= \bm{A}^\psin \bm{b},
+\end{align*}
+which converges in a single iteration, independently of the initial guess $\bm{x}_0$. Indeed, a cost that takes a quadratic form with respect to the decision variable can be soled in batch form (least squares solution), which will be a useful property that we will exploit later in the context of linear quadratic controllers.
+
+A \textbf{ridge regression} problem can similarly be defined as
+\begin{align}
+	\bm{\hat{x}} &= \arg\min_{\bm{x}} \; \|\bm{A}\bm{x}-\bm{b}\|^2 + \alpha \|\bm{x}\|^2 \nonumber\\
+	&= (\bm{A}^\trsp \bm{A} + \alpha\bm{I})^{-1} \bm{A}^\trsp \bm{b}, \label{eq:regLS}
+\end{align}
+which is also called \textbf{penalized least squares}, \textbf{robust regression}, \textbf{damped least squares} or \textbf{Tikhonov regularization}. In \eqref{eq:regLS}, $\bm{I}$ denotes an identity matrix (diagonal matrix with 1 as elements in the diagonal). $\alpha$ is typically a small scalar value acting as a regularization term when inverting the matrix $\bm{A}^\trsp \bm{A}$. 
+
+The cost can also be weighted by a matrix $\bm{W}$, providing the \textbf{weighted least squares} solution
+\begin{align}
+	\bm{\hat{x}} &= \arg\min_{\bm{x}} \; \|\bm{A}\bm{x}-\bm{b}\|^2_{\bm{W}} \nonumber\\
+	&= \arg\min_{\bm{x}} \; (\bm{A}\bm{x}-\bm{b})^\trsp \bm{W} (\bm{A}\bm{x}-\bm{b}) \nonumber\\
+	&= (\bm{A}^\trsp \bm{W} \bm{A})^{-1} \bm{A}^\trsp \bm{W} \bm{b}. \label{eq:WLS}
+\end{align}
+
+By combining \eqref{eq:regLS} and \eqref{eq:WLS}, a \textbf{weighted ridge regression} problem can be defined as
+\begin{align}
+	\bm{\hat{x}} &= \arg\min_{\bm{x}} \; \|\bm{A}\bm{x}-\bm{b}\|^2_{\bm{W}} + \alpha \|\bm{x}\|^2 \nonumber\\
+	&= (\bm{A}^\trsp \bm{W} \bm{A} + \alpha\bm{I})^{-1} \bm{A}^\trsp \bm{W} \bm{b}. \label{eq:regWLS}
+\end{align}
+
+If the matrices and vectors in \eqref{eq:regWLS} have the structure
+\begin{equation*}
+	\bm{W}=\begin{bmatrix}\bm{W}_{1}&\bm{0}\\\bm{0}&\bm{W}_{2}\end{bmatrix},\quad 
+	\bm{A}=\begin{bmatrix}\bm{A}_{1}\\\bm{A}_{2}\end{bmatrix},\quad
+	\bm{b}=\begin{bmatrix}\bm{b}_{1}\\\bm{b}_{2}\end{bmatrix},
+\end{equation*}
+we can consider an optimization problem using only the first part of the matrices, yielding the estimate
+\begin{align}
+	\bm{\hat{x}} &= \arg\min_{\bm{x}} \; \|\bm{A}_1\bm{x}-\bm{b}_1\|^2_{\bm{W}_1} + \alpha \|\bm{x}\|^2 \nonumber\\
+	&= (\bm{A}_1^\trsp \bm{W}_1 \bm{A}_1 + \alpha\bm{I})^{-1} \bm{A}_1^\trsp \bm{W}_1 \bm{b}_1. \label{eq:regWLS1}
+\end{align}
+which is the same as the result of computing \eqref{eq:regWLS} with $\bm{W}_2=\bm{0}$.
+
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsection{Least squares with constraints}\label{sec:LSconstraints}
@@ -408,6 +576,7 @@ minimizes the constrained cost. The first part of this augmented state then give
 
 
 \newpage
+
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Forward kinematics (FK) for a planar robot manipulator}\label{sec:FK}
 \begin{flushright}
@@ -436,7 +605,7 @@ Forward kinematics for a planar robot with two links.
 
 The \emph{forward kinematics} (FK) function of a planar robot manipulator is defined as
 \begin{align*}
-	\bm{f} &= \begin{bmatrix} \bm{\ell}^\trsp \cos(\bm{L}\bm{x}) \\ \bm{\ell}^\trsp \sin(\bm{L}\bm{x}) \\ \bm{1}^\trsp \bm{x} \end{bmatrix} \\
+	\bm{f}^\tp{ee} &= \begin{bmatrix} \bm{\ell}^\trsp \cos(\bm{L}\bm{x}) \\ \bm{\ell}^\trsp \sin(\bm{L}\bm{x}) \\ \bm{1}^\trsp \bm{x} \end{bmatrix} \\
 	&= \begin{bmatrix} 
 	\ell_1 \!\cos(x_1) \!+\! \ell_2 \!\cos(x_1\!+\!x_2) \!+\! \ell_3 \!\cos(x_1\!+\!x_2\!+\!x_3) \!+\! \ldots\\ 
 	\ell_1 \sin(x_1) \!+\! \ell_2 \!\sin(x_1\!+\!x_2) \!+\! \ell_3 \!\sin(x_1\!+\!x_2\!+\!x_3) \!+\! \ldots\\ 
@@ -447,30 +616,30 @@ The \emph{forward kinematics} (FK) function of a planar robot manipulator is def
 %	f = [model.l * cos(T * x); ...
 %		 model.l * sin(T * x); ...
 %		 mod(sum(x,1)+pi, 2*pi) - pi];
-with $\bm{x}$ the state of the robot (joint angles), $\bm{f}$ the position of the robot endeffector, $\bm{\ell}\,$ a vector of robot links lengths, $\bm{L}$ a lower triangular matrix with unit elements, and $\bm{1}$ a vector of unit elements, see Fig.~\ref{fig:FK}.
+with $\bm{x}$ the state of the robot (joint angles), $\bm{f}^\tp{ee}$ the position of the robot endeffector, $\bm{\ell}\,$ a vector of robot links lengths, $\bm{L}$ a lower triangular matrix with unit elements, and $\bm{1}$ a vector of unit elements, see Fig.~\ref{fig:FK}.
 
 The position and orientation of all articulations can similarly be computed with the forward kinematics function
 \begin{align}
-	\bm{\tilde{f}} &= {\Big[ \bm{L}\; \diag(\bm{\ell}) \cos(\bm{L}\bm{x}) ,\quad \bm{L}\; \diag(\bm{\ell}) \sin(\bm{L}\bm{x}) ,\quad \bm{L} \bm{x} \Big]}^\trsp 
+	\bm{\tilde{f}}^\tp{ee} &= {\Big[ \bm{L}\; \diag(\bm{\ell}) \cos(\bm{L}\bm{x}) ,\quad \bm{L}\; \diag(\bm{\ell}) \sin(\bm{L}\bm{x}) ,\quad \bm{L} \bm{x} \Big]}^\trsp 
 	\nonumber\\
 	&= \begin{bmatrix} 
-	\tilde{f}_{1,1} & \tilde{f}_{1,2} & \tilde{f}_{1,3} & \ldots\\ 
-	\tilde{f}_{2,1} & \tilde{f}_{2,2} & \tilde{f}_{2,3} & \ldots\\ 
-	\tilde{f}_{3,1} & \tilde{f}_{3,2} & \tilde{f}_{3,3} & \ldots\\ 
+	\tilde{f}^\tp{ee}_{1,1} & \tilde{f}^\tp{ee}_{1,2} & \tilde{f}^\tp{ee}_{1,3} & \ldots\\ 
+	\tilde{f}^\tp{ee}_{2,1} & \tilde{f}^\tp{ee}_{2,2} & \tilde{f}^\tp{ee}_{2,3} & \ldots\\ 
+	\tilde{f}^\tp{ee}_{3,1} & \tilde{f}^\tp{ee}_{3,2} & \tilde{f}^\tp{ee}_{3,3} & \ldots\\ 
 	\end{bmatrix} \!\!,
 	\label{eq:FKall}
 \end{align} 
 \begin{alignat*}{3}
-	& \tilde{f}_{1,1} = \ell_1 \!\cos(x_1),\quad &&
-	\tilde{f}_{1,2} = \ell_1 \!\cos(x_1) \!+\! \ell_2 \!\cos(x_1\!+\!x_2),\quad &&
-	\tilde{f}_{1,3} = \ell_1 \!\cos(x_1) \!+\! \ell_2 \!\cos(x_1\!+\!x_2) \!+\! \ell_3 \!\cos(x_1\!+\!x_2\!+\!x_3),\\ 
+	& \tilde{f}^\tp{ee}_{1,1} = \ell_1 \!\cos(x_1),\quad &&
+	\tilde{f}^\tp{ee}_{1,2} = \ell_1 \!\cos(x_1) \!+\! \ell_2 \!\cos(x_1\!+\!x_2),\quad &&
+	\tilde{f}^\tp{ee}_{1,3} = \ell_1 \!\cos(x_1) \!+\! \ell_2 \!\cos(x_1\!+\!x_2) \!+\! \ell_3 \!\cos(x_1\!+\!x_2\!+\!x_3),\\ 
 \text{with}\quad 
-	& \tilde{f}_{2,1} = \ell_1 \sin(x_1), &&
-	\tilde{f}_{2,2} = \ell_1 \sin(x_1) \!+\! \ell_2 \!\sin(x_1\!+\!x_2), &&
-	\tilde{f}_{2,3} = \ell_1 \sin(x_1) \!+\! \ell_2 \!\sin(x_1\!+\!x_2) \!+\! \ell_3 \!\sin(x_1\!+\!x_2\!+\!x_3), \quad\ldots\\ 
-	& \tilde{f}_{3,1} = x_1, &&
-	\tilde{f}_{3,2} = x_1 + x_2, &&
-	\tilde{f}_{3,3} = x_1 + x_2 + x_3.
+	& \tilde{f}^\tp{ee}_{2,1} = \ell_1 \sin(x_1), &&
+	\tilde{f}^\tp{ee}_{2,2} = \ell_1 \sin(x_1) \!+\! \ell_2 \!\sin(x_1\!+\!x_2), &&
+	\tilde{f}^\tp{ee}_{2,3} = \ell_1 \sin(x_1) \!+\! \ell_2 \!\sin(x_1\!+\!x_2) \!+\! \ell_3 \!\sin(x_1\!+\!x_2\!+\!x_3), \quad\ldots\\ 
+	& \tilde{f}^\tp{ee}_{3,1} = x_1, &&
+	\tilde{f}^\tp{ee}_{3,2} = x_1 + x_2, &&
+	\tilde{f}^\tp{ee}_{3,3} = x_1 + x_2 + x_3.
 \end{alignat*}
 
 %\begin{align*}
@@ -506,12 +675,63 @@ f = np.array([L @ np.diag(l) @ np.cos(L @ x), L @ np.diag(l) @ np.sin(L @ x)]) #
 \filename{IK\_manipulator.*}
 \end{flushright}
 
-By differentiating the forward kinematics function, a least norm inverse kinematics solution can be computed with
+\begin{figure}
+\centering
+\includegraphics[width=.5\columnwidth]{images/transformations01.jpg}
+\caption{\footnotesize
+Typical transformations involved in a manipulation task involving a robot, a vision system, a visual marker on the object, and a desired grasping location on the object.  
+}
+\label{fig:transformations}
+\end{figure}
+
+We define a manipulation task involving a set of transformations as in Fig.~\ref{fig:transformations}. By relying on these transformation operators, we will describe all variables in the robot frame of reference (defined by $\bm{0}$, $\bm{e}_1$ and $\bm{e}_2$ in the figure). 
+
+We first define $\bm{f}(\bm{x})$ as the residual vector between a target $\bm{\mu}$ and the endeffector position $\bm{f}^\tp{ee}(\bm{x})$ computed by the forward kinematics function, namely
+\begin{align*}
+	\bm{f}(\bm{x}) &= \bm{f}^\tp{ee}(\bm{x}) - \bm{\mu}. %\\
+	%\bm{J}(\bm{x}_t) &= \bm{J}^\tp{ee}(\bm{x}_t).
+\end{align*}
+
+The \emph{inverse kinematics} (IK) problem consists of finding a robot pose to reach a target with the robot endeffector. The underlying optimization problem consists of minimizing a cost $c(\bm{x})=\|\bm{f}(\bm{x})\|^2=\bm{f}(\bm{x})^\trsp\bm{f}(\bm{x})$, which can be solved iteratively with a Gauss--Newton method.
+
+As seen in Section \ref{sec:GaussNewton}, by differentiating $c(\bm{x})$ with respect to $\bm{x}$ and equating to 0, we get an update rule as in \eqref{eq:Taylor_nD_update}, namely
+\begin{align}
+	\bm{x}_{k+1} &= \bm{x}_k - {\big(\bm{J}^\trsp(\bm{x}_k) \bm{J}(\bm{x}_k)\big)}^{-1} \, 
+	\bm{J}^\trsp(\bm{x}_k) \, \bm{f}(\bm{x}_k) \nonumber\\
+	&= \bm{x}_k - \bm{J}^\psin(\bm{x}_k) \, \big(\bm{f}^\tp{ee}(\bm{x}_k) - \bm{\mu}\big),
+	\label{eq:GaussNewtonUpdateIK}
+\end{align}
+where $\bm{J}\in\mathbb{R}^{R\times D}$ is the Jacobian matrix of $\bm{f}\in\mathbb{R}^R$, and $\bm{J}^\psin$ denotes the pseudoinverse of $\bm{J}$.
+
+For the orientation part of the data (if considered), the residual vector $\bm{f}(\bm{x}) = \bm{f}^\tp{ee}(\bm{x}) - \bm{\mu}$ is replaced by a geodesic residual computed with the logarithmic map $\bm{f}(\bm{x}) = \mathrm{Log}_{\bm{\mu}}\!\big(\bm{f}^\tp{ee}(\bm{x})\big)$, see \cite{Calinon20RAM} for details.
+
+The approach can also be extended to target objects/landmarks with positions $\bm{\mu}$ and rotation matrices $\bm{U}$, as depicted in Fig.~\ref{fig:transformations}. %, whose columns are basis vectors forming a coordinate system
+We can then define an error between the robot endeffector and an object/landmark expressed in the object/landmark coordinate system as 
 \begin{equation}
-	\bm{\dot{\bm{x}}} = \bm{J}^\psin\!(\bm{x}) \; \bm{\dot{f}},
-	\label{eq:IK_LS}
+\begin{aligned}
+	\bm{f}(\bm{x}) &= \bm{U}^\trsp \big(\bm{f}^\tp{ee}(\bm{x}) - \bm{\mu}\big), \\
+	\bm{J}(\bm{x}) &= \bm{U}^\trsp \bm{J}^\tp{ee}(\bm{x}). 
+\end{aligned}
+\label{eq:fJU}
 \end{equation}
-where the Jacobian $\bm{J}(\bm{x})$ corresponding to the endeffector forward kinematics function $\bm{f}(\bm{x})$ can be computed as (with a simplification for the orientation part by ignoring the manifold aspect)
+
+The inverse kinematics update in \eqref{eq:GaussNewtonUpdateIK} can also be used to compute controllers.
+
+For a manipulator controlled by joint angle velocity commands $\bm{u}=\bm{\dot{x}} \approx \frac{\bm{\Delta}\bm{x}}{\Delta t}$, we can for example define a controller
+\begin{equation}
+	\bm{u} = \bm{J}^\psin(\bm{x}) \, (\bm{f}^\tp{ee}(\bm{x}) - \bm{\mu})\frac{\alpha}{\Delta t}, 
+\end{equation}
+where $\alpha$ can typically be set as a small constant value, by taking into account the desired reactivity and the velocity capability of the robot.
+
+%the evolution of the system is described by $\bm{x}_{t+1} = \bm{x}_t + \bm{u}_t \Delta t$.
+
+%By differentiating the forward kinematics function, a least norm inverse kinematics solution can be computed with
+%\begin{equation}
+%	\bm{\dot{\bm{x}}} = \bm{J}^\psin\!(\bm{x}) \; \bm{\dot{f}},
+%	\label{eq:IK_LS}
+%\end{equation}
+
+For the planar robot manipulator example shown in Fig.~\ref{fig:FK}, the Jacobian $\bm{J}(\bm{x})$ of the endeffector forward kinematics function $\bm{f}^\tp{ee}(\bm{x})$ can be computed as %(with a simplification for the orientation part by ignoring the manifold aspect)
 \begin{align*}
 	\bm{J} &= \begin{bmatrix} 
 	-\sin(\bm{L}\bm{x})^\trsp \diag(\bm{\ell}) \bm{L} \\ 
@@ -561,7 +781,6 @@ In Python, this can be coded for the endeffector position part as
 J = np.array([-np.sin(L @ x).T @ np.diag(l) @ L, np.cos(L @ x).T @ np.diag(l) @ L]) #Jacobian (for endeffector)
 \end{lstlisting}
 
-This Jacobian can be used to solve the \emph{inverse kinematics} (IK) problem that consists of finding a robot pose to reach a target with the robot endeffector. The underlying optimization problem consists of minimizing a quadratic cost $c=\|\bm{f}-\bm{\mu}\|^2$, where $\bm{f}$ is the position of the endeffector and $\bm{\mu}$ is a target to reach with this endeffector. An optimization problem with a quadratic cost can be solved iteratively with a Gauss--Newton method, requiring to compute Jacobian pseudoinverses $\bm{J}^\psin$, see Section \ref{sec:GaussNewton} for details.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
@@ -596,26 +815,26 @@ where $\Delta$ is a small value for the approximation of the derivatives.
 \begin{subfigure}[b]{.20\textwidth}
 	\centering
 	\includegraphics[width=.9\textwidth]{images/IK_nullspace01.png}
-	\caption{Moving the first joint as secondary task}
+	\caption{\footnotesize Moving the first joint as secondary task}
 	\label{fig:nullspace1}
 \end{subfigure}
 \hfill
 \begin{subfigure}[b]{.23\textwidth}
 	\centering
 	\includegraphics[width=.9\textwidth]{images/IK_nullspace02.png}
-	\caption{Orientation tracking a as secondary task}
+	\caption{\footnotesize Orientation tracking a as secondary task}
 \end{subfigure}
 \hfill
 \begin{subfigure}[b]{.17\textwidth}
 	\centering
 	\includegraphics[width=.8\textwidth]{images/IK_nullspace03.png}
-	\caption{Position tracking as secondary task}
+	\caption{\footnotesize Position tracking as secondary task}
 \end{subfigure}
 \hfill
 \begin{subfigure}[b]{.34\textwidth}
 	\centering
 	\includegraphics[width=.9\textwidth]{images/IK_nullspace04.png}
-	\caption{Tracking of a moving object with the right hand as secondary task}
+	\caption{\footnotesize Tracking of a moving object with the right hand as secondary task}
 \end{subfigure}
 \caption{\footnotesize
 Examples of nullspace controllers. The red paths represent the trajectories of moving objects that need to be tracked by the robot endeffectors.
@@ -623,7 +842,7 @@ Examples of nullspace controllers. The red paths represent the trajectories of m
 \label{fig:nullspace}
 \end{figure}
 
-In \eqref{eq:IK_LS}, the pseudoinverse provides a single least norm solution. This result can be generalized to obtain all solutions of the linear system with
+In \eqref{eq:GaussNewtonUpdateIK}, the pseudoinverse provides a single least norm solution. This result can be generalized to obtain all solutions of the linear system with
 \begin{equation}
 	\bm{\dot{\bm{x}}} = \bm{J}^\psin\!(\bm{x}) \; \bm{\dot{f}} + \bm{N}\!(\bm{x}) \; \bm{g}(\bm{x}),
 	\label{eq:IK_nullspace}
@@ -904,12 +1123,12 @@ By using basis functions as analytic expressions, the derivatives are easy to co
 \end{equation}
 providing the derivatives of $\bm{\Psi}(\bm{t})$ with respect to $\bm{t}$ expressed as
 \begin{equation}
-	\bm{\nabla}\bm{\Psi}(\bm{t}) = \frac{\partial\bm{\Psi}(\bm{t})}{\partial t_1} \,\otimes\, \frac{\partial\bm{\Psi}(\bm{t})}{\partial t_2},
+	\bm{\nabla}\!\bm{\Psi}(\bm{t}) = \frac{\partial\bm{\Psi}(\bm{t})}{\partial t_1} \,\otimes\, \frac{\partial\bm{\Psi}(\bm{t})}{\partial t_2},
 	\label{eq:dPsi}
 \end{equation}
 which can be used to compute the 2D gradient of the SDF at location $\bm{t}$ with
 \begin{equation}
-	\bm{\nabla}x = \bm{\nabla}\bm{\Psi}(\bm{t}) \, \bm{w}.
+	\bm{\nabla}x = \bm{\nabla}\!\bm{\Psi}(\bm{t}) \, \bm{w}.
 \end{equation}
 
 When using splines of the form $\bm{\phi}(t)=\bm{T}(t)\bm{B}\bm{C}$, the derivatives in \eqref{eq:parialPsi} are simply computed as $\frac{\partial\bm{\phi}(t)}{\partial t}=\frac{\partial\bm{T}(t)}{\partial t} \bm{B}\bm{C}$. For a cubic splines, it corresponds to $\bm{T}(t) = [1,t,t^2,t^3]$ and $\frac{\partial\bm{T}(t)}{\partial t} = [0,1,2t,3t^2]$.\newline
@@ -1009,16 +1228,23 @@ which ensures that $w_4=w_5$ and $w_6=-w_3+2w_5$. These constraints guarantee th
 \subsection{Batch computation of basis functions coefficients}
 \label{sec:batchSDF}
 
-Based on observed data $\bm{x}$, the superposition weights $\bm{w}$ can be estimated as a simple least squares estimate 
+Based on observed data $\bm{x}$, the superposition weights $\bm{\hat{w}}$ can be estimated as a simple least squares estimate 
 \begin{equation}
-	\bm{w} = \bm{\Psi}^\psin \bm{x},
+	\bm{\hat{w}} = \bm{\Psi}^\psin \bm{x} = {(\bm{\Psi}^\trsp\bm{\Psi})}^{-1} \bm{\Psi}^\trsp \bm{x},
 \end{equation}
 or as the regularized version (ridge regression)
 \begin{equation}
-	\bm{w} = {(\bm{\Psi}^\trsp\bm{\Psi} + \lambda\bm{I})}^{-1} \bm{\Psi}^\trsp \bm{x}.
+	\bm{\hat{w}} = {(\bm{\Psi}^\trsp\bm{\Psi} + \lambda\bm{I})}^{-1} \bm{\Psi}^\trsp \bm{x}.
 	\label{eq:ridge}
 \end{equation}
 
+For example, if we want to fit a reference path, which can also be sparse or composed of a set of viapoints, while minimizing velocities (or similarly, any other derivatives, such as computing a minimum jerk trajectories), we can solve
+\begin{align}
+	\bm{\hat{w}} &= \arg\min_{\bm{w}} \frac{1}{2}\|\bm{\Psi}\bm{w} - \bm{x}\|^2 + \frac{\lambda}{2} \|\bm{\nabla}\!\bm{\Psi}\bm{w}\|^2 \\
+	&= {(\bm{\Psi}^\trsp\bm{\Psi} + \lambda\bm{\nabla}\!\bm{\Psi}^\trsp\bm{\nabla}\!\bm{\Psi})}^{-1} \bm{\Psi}^\trsp \bm{x}.
+	\label{eq:ridge2}
+\end{align}
+
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsection{Recursive computation of basis functions coefficients}
@@ -1145,15 +1371,15 @@ The above equations can be used recursively, with $\bm{B}_\new^{-1}$ and $\bm{w}
 
 %By following the notation in Section \ref{sec:GaussNewton}, the above objective can be written as a sum of squared functions that can be solved by Gauss--Newton optimization, with residuals and Jacobians given by
 %\begin{alignat*}{3}
-%	& \bm{r}_1 = \bm{\Psi}\bm{w} - \bm{x}, \qquad
+%	& \bm{f}_1 = \bm{\Psi}\bm{w} - \bm{x}, \qquad
 %	&& \bm{J}_1 = \bm{\Psi}, \\
-%	& \bm{r}_2 = \bm{\nabla}_{\!\bm{t}}\bm{x}^\trsp \, \bm{\nabla}_{\!\bm{t}}\bm{x} - 1, \qquad\qquad 
+%	& \bm{f}_2 = \bm{\nabla}_{\!\bm{t}}\bm{x}^\trsp \, \bm{\nabla}_{\!\bm{t}}\bm{x} - 1, \qquad\qquad 
 %	&& \bm{J}_2 = 2 \, \bm{\nabla}_{\!\bm{t}}\bm{x} \, \bm{\nabla}_{\!\bm{t}}\bm{\Psi},
 %\end{alignat*}
 %which provide at each iteration step $k$ the Gauss--Newton update rule
 %\begin{equation*}
 %	\bm{w}_{k+1} = \bm{w}_k - \alpha {\big( \bm{J}_1^\trsp \bm{J}_1 + \lambda \bm{J}_2^\trsp \bm{J}_2 \big)}^{-1} \, 
-%	\big( \bm{J}_1^\trsp \, \bm{r}_1 + \lambda \bm{J}_2^\trsp \, \bm{r}_2 \big),\\
+%	\big( \bm{J}_1^\trsp \, \bm{f}_1 + \lambda \bm{J}_2^\trsp \, \bm{f}_2 \big),\\
 %\end{equation*}
 %as detailed in Section \ref{sec:GaussNewton}, where the learning rate $\alpha$ can be determined by line search.
 
@@ -1189,13 +1415,13 @@ The first component of the objective in \eqref{eq:wEikonal} is to find a SDF tha
 
 By following the notation in Section \ref{sec:GaussNewton}, the above objective can be written as a sum of squared functions that can be solved by Gauss--Newton optimization, with residuals and Jacobians given by
 \begin{align*}
-	r_{1,m} &= \bm{\Psi}(\bm{t}_m) \, \bm{w} - x_m, 
+	f_{1,m} &= \bm{\Psi}(\bm{t}_m) \, \bm{w} - x_m, 
 	\quad &
 	\bm{J}_{1,m} &= \bm{\Psi}(\bm{t}_m), 
 	\quad &
 	\forall m\in\{1,\ldots,M\}, 
 	\\
-	r_{2,n} &= \bm{\nabla}x_n^\trsp \, \bm{\nabla}x_n - 1, 
+	f_{2,n} &= \bm{\nabla}x_n^\trsp \, \bm{\nabla}x_n - 1, 
 	\quad & 
 	\bm{J}_{2,n} &= 2 \, {\bm{\nabla}x_n}^{\!\trsp} \, \bm{\nabla}\bm{\Psi}(\bm{t}_n), 
 	\quad &
@@ -1205,7 +1431,7 @@ which provide at each iteration step $k$ the Gauss--Newton update rule
 \begin{equation*}
 	\bm{w}_{k+1} \;\leftarrow\; 
 	\bm{w}_k - \alpha {\Bigg( \sum_{m=1}^M \bm{J}_{1,m}^\trsp \bm{J}_{1,m} + \lambda \sum_{n=1}^N \bm{J}_{2,n}^\trsp \bm{J}_{2,n} \Bigg)}^{\!-1} \, 
-	\Bigg( \sum_{m=1}^M \bm{J}_{1,m}^\trsp \, r_{1,m} + \lambda \sum_{n=1}^N \bm{J}_{2,n}^\trsp \, r_{2,n} \bigg),\\
+	\Bigg( \sum_{m=1}^M \bm{J}_{1,m}^\trsp \, f_{1,m} + \lambda \sum_{n=1}^N \bm{J}_{2,n}^\trsp \, f_{2,n} \bigg),\\
 \end{equation*}
 as detailed in Section \ref{sec:GaussNewton}, where the learning rate $\alpha$ can be determined by line search.
 
@@ -1213,7 +1439,7 @@ Note that the above computation can be rewritten with concatenated vectors and m
 \begin{equation*}
 	\bm{w}_{k+1} \;\leftarrow\; 
 	\bm{w}_k - \alpha {\Bigg( \bm{J}_{1}^\trsp \bm{J}_{1} + \lambda \bm{J}_{2}^\trsp \bm{J}_{2} \Bigg)}^{\!-1} \, 
-	\Bigg( \bm{J}_{1}^\trsp \, \bm{r}_{1} + \lambda \bm{J}_{2}^\trsp \, \bm{r}_{2} \bigg).
+	\Bigg( \bm{J}_{1}^\trsp \, \bm{f}_{1} + \lambda \bm{J}_{2}^\trsp \, \bm{f}_{2} \bigg).
 \end{equation*}
 
 Figure \ref{fig:Bezier_2D_eikonal} presents an example in 2D.
@@ -1223,6 +1449,7 @@ Figure \ref{fig:Bezier_2D_eikonal} presents an example in 2D.
 \section{Linear quadratic tracking (LQT)}\label{sec:LQT}
 \begin{flushright}
 \filename{LQT.*}
+\filename{LQT\_nullspace.*}
 \end{flushright}
 
 Linear quadratic tracking (LQT) is a simple form of optimal control that trades off tracking and control costs expressed as quadratic terms over a time horizon, with the evolution of the state described in a linear form. The LQT problem is formulated as the minimization of the cost
@@ -1311,7 +1538,7 @@ The problem is formulated as in \eqref{eq:cBatch}, namely
 	(\bm{\mu}-\bm{x})
 	\;+\;
 	\bm{u}^{\!\trsp} \!\bm{R} \bm{u},
-	\;\text{s.t.}\;
+	\quad\text{s.t.}\quad
 	\bm{x}=\bm{S}_{\bm{x}}\bm{x}_1+\bm{S}_{\bm{u}}\bm{u},
 	\label{eq:cTennis}
 \end{equation}
@@ -2109,15 +2336,6 @@ from $t=2$ to $t=T-1$.
 \filename{iLQR\_manipulator.*}
 \end{flushright}
 
-\begin{algorithm}
-\caption{Backtracking line search method with parameter $\alpha_{\min}$}
-\label{alg:linesearch}
-$\alpha \gets 1$ \\
-\While{$c(\bm{\hat{u}}+\alpha\;\Delta\bm{\hat{u}}) > c(\bm{\hat{u}}) \;\textbf{and}\;\; \alpha > \alpha_{\min}$}{
-	$\alpha \gets \frac{\alpha}{2}$
-}
-\end{algorithm}
-
 \begin{algorithm}
 \caption{Batch formulation of iLQR}
 \label{alg:iLQRbatch}
@@ -2164,7 +2382,7 @@ Initialize all $\bm{\hat{u}}_t$ \\
 Use \eqref{eq:iLQRrecursiveController} and $\bm{d}(\cdot)$ for reproduction \\
 \end{algorithm}
 
-To be more efficient, iLQR most often requires at each iteration to estimate a step size $\alpha$ to scale the control command updates.
+iLQR typically requires to estimate a step size $\alpha$ at each iteration to scale the control command updates.
 For the batch formulation in Section \ref{sec:iLQRbatch}, this can be achieved by setting the update \eqref{eq:du_general} as
 \begin{equation}
 	\bm{\hat{u}} \leftarrow \bm{\hat{u}} + \alpha \; \Delta\bm{\hat{u}},
@@ -2178,14 +2396,15 @@ For the recursive formulation in Section \ref{sec:iLQRrecursive}, this can be ac
 	\label{eq:alpha2}
 \end{equation}
 
-In practice, a simple backtracking line search procedure can be considered with Algorithm \ref{alg:linesearch}, by considering a small value for $\alpha_{\min}$. For more elaborated methods, see Ch.~3 of \cite{Nocedal06}. 
+In practice, a simple backtracking line search procedure can be considered, as shown in Algorithm \ref{alg:linesearch}, by considering a small value for $\alpha_{\min}$. 
 
 The complete iLQR procedures are described in Algorithms \ref{alg:iLQRbatch} and \ref{alg:iLQRrecursive} for the batch and recursive formulations, respectively.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 %\bm in titles and hyperref are incompatible: https://tex.stackexchange.com/questions/174840/bmp-in-the-section-title-or-subsection-title-produces-error
-\subsection{iLQR with quadratic cost on {\boldmath$f(x_t)$}} 
+\section{iLQR with quadratic cost on f(x)} %{\boldmath$f(x_t)$} 
+\label{sec:iLQR_quadraticCost}
 \begin{flushright}
 \filename{iLQR\_manipulator.*}
 \end{flushright}
@@ -2219,9 +2438,14 @@ and Hessian matrices
 \end{equation}
 with $\bm{J}(\bm{x}_t)=\frac{\partial\bm{f}(\bm{x}_t)}{\partial\bm{x}_t}$ a Jacobian matrix. The same results can be used in the recursive formulation in \eqref{eq:qt}.
 
-At a trajectory level, the evolution of the tracking and control weights is represented by $\bm{Q}\!=\!\mathrm{blockdiag}(\bm{Q}_1,\bm{Q}_2,\ldots,\bm{Q}_T)$ and $\bm{R}\!=\!\mathrm{blockdiag}(\bm{R}_{1},\bm{R}_{2},\ldots,\bm{R}_{T-1})$, respectively.  %\in\mathbb{R}^{DCT\times DCT} 
+At a trajectory level, the cost can be written as
+\begin{equation}
+	c(\bm{x},\bm{u}) = \bm{f}(\bm{x})^{\!\trsp} \bm{Q} \bm{f}(\bm{x}) + \bm{u}^\trsp \bm{R} \, \bm{u}, 
+\end{equation}
+where the tracking and control weights are represented by the diagonally concatenated matrices $\bm{Q}\!=\!\mathrm{blockdiag}(\bm{Q}_1,\bm{Q}_2,\ldots,\bm{Q}_T)$ and $\bm{R}\!=\!\mathrm{blockdiag}(\bm{R}_{1},\bm{R}_{2},\ldots,\bm{R}_{T-1})$, respectively.  %\in\mathbb{R}^{DCT\times DCT} 
+In the above, with a slight abuse of notation, we defined $\bm{f}(\bm{x})$ as a vector concatenating the vectors $\bm{f}(\bm{x}_t)$. Similarly, $\bm{J}(\bm{x})$ will represent a block-diagonal concatenation of the Jacobian matrices $\bm{J}(\bm{x}_t)$. 
 
-With a slight abuse of notation, we define $\bm{f}(\bm{x})$ as a vector concatenating the vectors $\bm{f}(\bm{x}_t)$, and $\bm{J}(\bm{x})$ as a block-diagonal concatenation of the Jacobian matrices $\bm{J}(\bm{x}_t)$. The minimization problem \eqref{eq:minu} then becomes
+With this notation, the minimization problem \eqref{eq:minu} then becomes
 \begin{equation}
 	\min_{\Delta\bm{u}} \quad 2 \Delta\bm{x}^{\!\trsp} \bm{J}(\bm{x})^\trsp \bm{Q} \bm{f}(\bm{x}) + 2 \Delta\bm{u}^{\!\trsp} \bm{R} \, \bm{u} \; + 
 	\Delta\bm{x}^{\!\trsp} \bm{J}(\bm{x})^\trsp \bm{Q} \bm{J}(\bm{x}) \Delta\bm{x} + \Delta\bm{u}^{\!\trsp} \bm{R} \Delta\bm{u}, 
@@ -2251,21 +2475,21 @@ In the next sections, we show examples of functions $\bm{f}(\bm{x})$ that can re
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Robot manipulator}
+\subsection{Robot manipulator}
 \begin{flushright}
 \filename{iLQR\_manipulator.*}
 \end{flushright}
 
-\begin{figure}
-\centering
-\includegraphics[width=.7\columnwidth]{images/transformations01.jpg}
-\caption{\footnotesize
-Typical transformations involved in a manipulation task involving a robot, a vision system, a visual marker on the object, and a desired grasping location on the object.  
-}
-\label{fig:transformations}
-\end{figure}
+%\begin{figure}
+%\centering
+%\includegraphics[width=.5\columnwidth]{images/transformations01.jpg}
+%\caption{\footnotesize
+%Typical transformations involved in a manipulation task involving a robot, a vision system, a visual marker on the object, and a desired grasping location on the object.  
+%}
+%\label{fig:transformations}
+%\end{figure}
 
-We define a manipulation task involving a set of transformations as in Fig.~\ref{fig:transformations}. By relying on these transformation operators, we will next describe all variables in the robot frame of reference (defined by $\bm{0}$, $\bm{e}_1$ and $\bm{e}_2$ in the figure). 
+%We define a manipulation task involving a set of transformations as in Fig.~\ref{fig:transformations}. By relying on these transformation operators, we will next describe all variables in the robot frame of reference (defined by $\bm{0}$, $\bm{e}_1$ and $\bm{e}_2$ in the figure). 
 
 For a manipulator controlled by joint angle velocity commands $\bm{u}=\bm{\dot{x}}$, the evolution of the system is described by $\bm{x}_{t+1} = \bm{x}_t + \bm{u}_t \Delta t$, with the Taylor expansion \eqref{eq:DS} simplifying to $\bm{A}_t=\frac{\partial\bm{g}}{\partial\bm{x}_t}=\bm{I}$ and $\bm{B}_t=\frac{\partial\bm{g}}{\partial\bm{u}_t}=\bm{I}\Delta t$. Similarly, a double integrator can alternatively be considered, with acceleration commands $\bm{u}=\bm{\ddot{x}}$ and states composed of both positions and velocities.
 
@@ -2275,20 +2499,8 @@ For a robot manipulator, $\bm{f}(\bm{x}_t)$ in \eqref{eq:du} typically represent
 	\bm{J}(\bm{x}_t) &= \bm{J}^\tp{ee}(\bm{x}_t).
 \end{align*}
 
-For the orientation part of the data (if considered), the Euclidean distance vector $\bm{f}^\tp{ee}(\bm{x}_t) - \bm{\mu}_t$ is replaced by a geodesic distance measure computed with the logarithmic map $\log_{\bm{\mu}_t}\!\big(\bm{f}^\tp{ee}(\bm{x}_t)\big)$, see \cite{Calinon20RAM} for details.
-
-The approach can similarly be extended to target objects/landmarks with positions $\bm{\mu}_t$ and orientation matrices $\bm{U}_t$, whose columns are basis vectors forming a coordinate system, see Fig.~\ref{fig:iLQR_manipulator}. We can then define an error between the robot endeffector and an object/landmark expressed in the object/landmark coordinate system as 
-\begin{equation}
-\begin{aligned}
-	\bm{f}(\bm{x}_t) &= \bm{U}_t^\trsp \big(\bm{f}^\tp{ee}(\bm{x}_t) - \bm{\mu}_t\big), \\
-	\bm{J}(\bm{x}_t) &= \bm{U}_t^\trsp \bm{J}^\tp{ee}(\bm{x}_t). 
-\end{aligned}
-\label{eq:fJU}
-\end{equation}
-
-
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%\subsubsection{Bounded joint space}
+%\subsection{Bounded joint space}
 
 %\begin{figure}
 %\centering
@@ -2310,7 +2522,7 @@ The approach can similarly be extended to target objects/landmarks with position
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Bounded joint space}
+\subsection{Bounded joint space}
 
 %\begin{figure}
 %\centering
@@ -2353,7 +2565,7 @@ We can see with \eqref{eq:dcdx} that for $\bm{Q}=\frac{1}{2}\bm{I}$, if $\bm{x}$
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Bounded task space}
+\subsection{Bounded task space}
 
 The iLQR solution in \eqref{eq:du} can be used to keep the endeffector within a boundary (e.g., endeffector position limits).
 Based on the above definitions, $\bm{f}(\bm{x})$ and $\bm{J}(\bm{x})$ are in this case defined as
@@ -2392,7 +2604,7 @@ see also Fig.~\ref{fig:iLQR_manipulator}.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Initial state optimization}\label{sec:iLQR_initStateOptim}
+\subsection{Initial state optimization}\label{sec:iLQR_initStateOptim}
 \begin{flushright}
 \filename{iLQR\_manipulator\_initStateOptim.*}
 \end{flushright}
@@ -2429,9 +2641,10 @@ where $\bm{\mu}$ is a vector containing the initial elements in $\bm{x}_1$ that
 
 The above approach can for example be used to estimate the optimal placement of a robot manipulator. For a planar robot, this can for example be implemented by defining the kinematic chain starting with two prismatic joints along the two axes directions, providing a way to represent the location of a free floating platform as two additional prismatic joints in the kinematic chain. If we would like the base of the robot to remain static, we can request that these first two prismatic joints will stay still during the motion. By using the above formulation, this can be done by setting arbitrary large control weights for these corresponding joints, see Figure \ref{fig:iLQR_initStateOptim} and the corresponding source code example.
 
+\newpage
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Center of mass}
+\subsection{Center of mass}
 \begin{flushright}
 \filename{iLQR\_manipulator\_CoM.*}
 \end{flushright}
@@ -2487,7 +2700,7 @@ The forward kinematics function $\bm{f}^\tp{CoM}$ can be used in tracking tasks
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Bimanual robot}
+\subsection{Bimanual robot}
 \begin{flushright}
 \filename{iLQR\_bimanual.*}
 \end{flushright}
@@ -2576,7 +2789,7 @@ with the corresponding Jacobian matrix $\bm{J}^\tp{CoM}\in\mathbb{R}^{2\times 5}
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Obstacle avoidance with ellipsoid shapes} %(1-e'*e)'*(1-e'*e) version, where 1-e'*e is a scalar
+\subsection{Obstacle avoidance with ellipsoid shapes} %(1-e'*e)'*(1-e'*e) version, where 1-e'*e is a scalar
 \begin{flushright}
 \filename{iLQR\_obstacle.*}
 \end{flushright}
@@ -2625,12 +2838,23 @@ A similar principle can be applied to robot manipulators by composing forward ki
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Maintaining a desired distance to an object} %(1-e'*e)'*(1-e'*e) version, where 1-e'*e is a scalar
+\subsection{Distance to a target} %(1-e'*e)'*(1-e'*e) version, where 1-e'*e is a scalar
 \begin{flushright}
 \filename{iLQR\_distMaintenance.*}
 \end{flushright}
 
-The obstacle example above can easily be extended to the problem of maintaining a desired distance to an object, which can also typically used with other objectives. We first define a function and a gradient
+\begin{wrapfigure}{r}{.38\textwidth}
+%\vspace{-20pt}
+\centering
+\includegraphics[width=.14\textwidth,valign=c]{images/iLQR_distMaintain01.png}\hspace{6mm}
+\includegraphics[width=.14\textwidth,valign=c]{images/iLQR_distMaintain02.png}
+\caption{\footnotesize
+\emph{Left:} Optimal control problem to generate a motion by considering a point mass starting from an initial point (in black), with a cost asking to reach or maintain a desired distance to a target point (in red). \emph{Right:} Similar problem for a contour to reach/maintain defined as a covariance matrix.
+}
+\label{fig:distMaintain}
+\end{wrapfigure}
+
+The obstacle example above can easily be extended to the problem of reaching/maintaining a desired distance to a target, which can also typically used with other objectives. We first define a function and a gradient
 \begin{equation*} 
 	f^\tp{dist}(d) = 1-d, \quad\quad
 	g^\tp{dist}(d) = -1,
@@ -2642,11 +2866,15 @@ that we exploit to define $\bm{f}(\bm{x}_t)$ and $\bm{J}(\bm{x}_t)$ in \eqref{eq
 	\text{with}\quad e(\bm{x}_t) &= \frac{1}{r^2} {(\bm{x}_t-\bm{\mu})}^\trsp (\bm{x}_t-\bm{\mu}).
 \end{align*}
 
-In the above, $\bm{f}(\bm{x})$ defines a continuous function that is $0$ on a sphere of radius $r$ centered on the object (defined by a center $\bm{\mu}$), and increasing/decreasing when moving away from this surface in one direction or the other. 
+In the above, $\bm{f}(\bm{x})$ defines a continuous function that is $0$ on a sphere of radius $r$ centered on the target (defined by a center $\bm{\mu}$), and increasing/decreasing when moving away from this surface in one direction or the other. 
+
+Similarly, the error can be weighted by a covariance matrix $\bm{\Sigma}$, by using $e(\bm{x}_t) = {(\bm{x}_t-\bm{\mu})}^\trsp \bm{\Sigma}^{-1} (\bm{x}_t-\bm{\mu})$ and $\bm{J}(\bm{x}_t) = -2 {(\bm{x}_t-\bm{\mu})}^\trsp \bm{\Sigma}^{-1}$, which corresponds to the problem of reaching/maintaining the contour of an ellipse.
+
+Figure \ref{fig:distMaintain} presents examples with a point mass.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Manipulability tracking}
+\subsection{Manipulability tracking}
 \begin{flushright}
 \filename{iLQR\_bimanual\_manipulability.*}
 \end{flushright}
@@ -2670,7 +2898,7 @@ The manipulability ellipsoid $\bm{M}(\bm{x}) = \bm{J}(\bm{x}) {\bm{J}(\bm{x})}^\
 
 In \cite{Jaquier21IJRR}, we showed that a geometric cost on manipulability can alternatively be defined with the geodesic distance
 \begin{align}
-	c &= \|\bm{A}\|^2_\text{F}, \quad\text{with}\quad \bm{A} = \log\!\big( \bm{S}^\frac{1}{2} \bm{M}(\bm{x}) \bm{S}^\frac{1}{2} \big), \nonumber\\
+	c &= \|\bm{A}\|^2_\text{F}, \quad\text{with}\quad \bm{A} = \log\!\big( \bm{S}^{-\frac{1}{2}} \bm{M}(\bm{x}) \bm{S}^{-\frac{1}{2}} \big), \nonumber\\
 	\iff\; 
 	c &= \text{trace}(\bm{A}\bm{A}^\trsp)=\sum_i\text{trace}(\bm{A}_i\bm{A}_i^\trsp) = \sum_i\bm{A}_i^\trsp\bm{A}_i 
 	= {\text{vec}(\bm{A})}^\trsp \text{vec}(\bm{A}),
@@ -2689,7 +2917,7 @@ The approach can also be extended to other forms of symmetric positive definite
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsubsection{Decoupling of control commands}
+\subsection{Decoupling of control commands}
 
 \begin{wrapfigure}{r}{.22\textwidth}
 %\vspace{-20pt}
@@ -2709,7 +2937,7 @@ For a 2 DOFs robot controlled at each time step $t$ with two control command $u_
 \end{equation*}
 with corresponding residuals and Jacobian given by 
 \begin{equation*}
-	r_t = u_{1,t} \, u_{2,t},
+	f_t = u_{1,t} \, u_{2,t},
 	\quad
 	\bm{J}_t = \big[ u_{2,t}, \, u_{1,t} \big], 
 	\quad 
@@ -2719,13 +2947,64 @@ with corresponding residuals and Jacobian given by
 The Gauss--Newton update rule in concatenated vector form is given by
 \begin{equation*}
 	\bm{u}_{k+1} \;\leftarrow\; 
-	\bm{u}_k - \alpha \, {\big( \bm{J}^\trsp \bm{J} \big)}^{\!-1} \, \bm{J}^\trsp \, \bm{r},
+	\bm{u}_k - \alpha \, {\big( \bm{J}^\trsp \bm{J} \big)}^{\!-1} \, \bm{J}^\trsp \, \bm{f},
 \end{equation*}
-where $\alpha$ is a line search parameter, $\bm{r}$ is a vector concatenating vertically all residuals $r_t$, and $\bm{J}$ is a Jacobian matrix with $\bm{J}_t$ as block diagonal elements. With some linear algebra machinery, this can also be computed in batch form using $\bm{r} = \bm{u}_1 \odot \bm{u}_2$, and $\bm{J} = (\bm{I}_{T-1} \otimes \bm{1}_{1\times 2}) \; \text{diag}\Big(\big(\bm{I}_{T-1} \otimes (\bm{1}_{2\times 2}-\bm{I}_2)\big)\bm{u} \Big)$, with $\odot$ and $\otimes$ the elementwise product and Kronecker product operators, respectively. 
+where $\alpha$ is a line search parameter, $\bm{f}$ is a vector concatenating vertically all residuals $f_t$, and $\bm{J}$ is a Jacobian matrix with $\bm{J}_t$ as block diagonal elements. With some linear algebra machinery, this can also be computed in batch form using $\bm{f} = \bm{u}_1 \odot \bm{u}_2$, and $\bm{J} = (\bm{I}_{T-1} \otimes \bm{1}_{1\times 2}) \; \text{diag}\Big(\big(\bm{I}_{T-1} \otimes (\bm{1}_{2\times 2}-\bm{I}_2)\big)\bm{u} \Big)$, with $\odot$ and $\otimes$ the elementwise product and Kronecker product operators, respectively. 
 
 Figure \ref{fig:iLQR_decoupling} presents a simple example within a 2D reaching problem with a point mass agent and velocity commands.
 
 
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsection{Curvature}
+
+\begin{wrapfigure}{r}{.38\textwidth}
+%\vspace{-20pt}
+\centering
+\includegraphics[width=.32\textwidth]{images/iLQR_curvature01.png}
+\caption{\footnotesize
+Optimal control problem to generate a motion by considering a point mass starting from an initial point (in black), with a cost asking to pass through a set of viapoints (in red), together with a cost on curvature (black path).
+}
+\label{fig:curvature}
+\end{wrapfigure}
+
+The curvature of a 2-dimensional curve is defined as
+\begin{equation}
+	\kappa = \frac{\dot{\text{x}}_1\ddot{\text{x}}_2-\dot{\text{x}}_2\ddot{\text{x}}_1}
+	{(\dot{\text{x}}_1^2+\dot{\text{x}}_2^2)^\frac{3}{2}}.
+	\label{eq:curvature0}
+\end{equation}
+
+We describe the system state in vector form as
+\begin{equation}
+	\bm{x} = \begin{bmatrix} \mathbf{x} \\ \mathbf{\dot{x}} \\ \mathbf{\ddot{x}} \end{bmatrix}.
+\end{equation}
+
+By defining a set of selection vectors $\bm{s}_{i,j}$ so that $\dot{\text{x}}_1 = \bm{s}_{1,1}^\trsp \bm{x}, \; \dot{\text{x}}_2 = \bm{s}_{1,2}^\trsp \bm{x}, \; \ddot{\text{x}}_1 = \bm{s}_{2,1}^\trsp \bm{x}, \; \ddot{\text{x}}_2 = \bm{s}_{2,2}^\trsp \bm{x}$, we can observe that
+\begin{equation}
+	\dot{\text{x}}_1 \ddot{\text{x}}_2 = (\bm{s}_{1,1}^\trsp \bm{x}) (\bm{s}_{2,2}^\trsp \bm{x}) = \bm{x}^\trsp (\bm{s}_{1,1} \bm{s}_{2,2}^\trsp) \bm{x},
+%	= \bm{x}^\trsp \bm{S}_{1,1}^{2,2} \bm{x},
+\end{equation}
+where $(\bm{s}_{1,1} \bm{s}_{2,2}^\trsp)$ is a selection matrix.
+
+By leveraging this matrix formulation, the curvature in \eqref{eq:curvature0} can be expressed as
+\begin{equation}
+	%\kappa(\bm{x}) = \begin{frac}{\bm{x}^\trsp \bm{S}_A \bm{x}}{(\bm{x}^\trsp \bm{S}_B \bm{x})^{\frac{3}{2}}},
+	\kappa(\bm{x}) = (\bm{x}^\trsp \bm{S}_B \, \bm{x})^{-\frac{3}{2}} \; \bm{x}^\trsp \bm{S}_A \, \bm{x},
+	\label{eq:curvature}
+\end{equation}
+with selection matrices $\bm{S}_A=\bm{s}_{1,1} \bm{s}_{2,2}^\trsp - \bm{s}_{1,2} \bm{s}_{2,1}^\trsp$ and $\bm{S}_B=\bm{s}_{1,1} \bm{s}_{1,1}^\trsp + \bm{s}_{1,2} \bm{s}_{1,2}^\trsp$.
+
+With this formulation, by using the derivative property $(fg)'=f'g+fg'$, and by observing that $\bm{S}_B$ is a symmetric matrix and that $\bm{S}_A$ is an asymmetric matrix, the derivatives of \eqref{eq:curvature0} w.r.t $\bm{x}$ form the Jacobian
+\begin{equation}
+	\bm{J}(\bm{x}) = \frac{\partial \kappa(\bm{x})}{\partial\bm{x}} = 
+	(\bm{x}^\trsp \bm{S}_B \bm{x})^{-\frac{3}{2}} \; (\bm{S}_A+\bm{S}_A^\trsp) \bm{x}  -
+	3 \; (\bm{x}^\trsp \bm{S}_A \, \bm{x}) \; (\bm{x}^\trsp \bm{S}_B \, \bm{x})^{-\frac{5}{2}} \; \bm{S}_B \bm{x}. 
+	\label{eq:diff_curvature}
+\end{equation}
+
+Figure \ref{fig:curvature} presents an example with a point mass.
+
+
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \subsection{iLQR with control primitives}
 \begin{flushright}
@@ -3012,55 +3291,67 @@ which can then be converted to a discrete form with \eqref{eq:AdAc}.
 %	\label{eq:du}
 %\end{equation}
 
+\newpage
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 \section{Ergodic control}\label{sec:ergodicControl}
 
-\begin{center}
-\includegraphics[width=.7\columnwidth]{images/ergodic01.png}
-\end{center}
+Ergodic theory studies the connection between the time-averaged and space-averaged behaviors of a dynamical system. By using it in a search and exploration context, it enables optimal exploration of an information distribution. Exploration problems can be formulated in various ways, see Figures \ref{fig:ergodic_intro}, \ref{fig:ergodic_vs_patterned} and \ref{fig:ergodic_fromCrudetoPrecise}. 
 
-A conventional tracking problem in robotics is characterized by a target to reach, requiring a controller to be computed to reach this target. In \emph{ergodic control}, instead of providing a single target point, a probability distribution is given to the robot, which must cover the distribution in an efficient way. Ergodic control thus consists of moving within a spatial distribution by spending time in each part of the distribution in proportion to its density (namely, ``tracking a distribution'' instead of ``tracking a point''). The resulting controller generates natural exploration behaviors, which can be exploited for active sensing, localization, surveillance, insertion tasks, etc. 
+Research in ergodic control addresses fundamental challenges linking machine learning, optimal control, signal processing and information theory. A conventional tracking problem in robotics is characterized by a target to reach, requiring a controller to be computed to reach this target. In \emph{ergodic control}, instead of providing a single target point, a probability distribution is given to the robot, which must cover the distribution in an efficient way. Ergodic control thus consists of moving within a spatial distribution by spending time in each part of the distribution in proportion to its density. 
+%(namely, ``tracking a distribution'' instead of ``tracking a point''). 
+The term ergodicity corresponds here to the difference between the time-averaged spatial statistics of the agent's trajectory and the target distribution to search in. By minimizing this difference, the resulting controller generates natural exploration behaviors.
 
-In robotics, ergodic control can be exploited in a wide range of problems requiring the automatic exploration of regions of interest. This is particularly helpful when the available sensing information is not accurate enough to fulfill the task with a standard controller, but where this information can still guide the robot towards promising areas. In a collaborative task, it can also be used when the operator's input is not accurate enough to fully reproduce the task, which then requires the robot to explore around the requested input (e.g., a point of interest selected by the operator). For picking and insertion problems, ergodic control can be applied to move around the picking/insertion point, thereby facilitating the prehension/insertion. It can also be employed for active sensing and localization (either detected autonomously, or with help by the operator). Here, the robot can plan movements based on the current information density, and can recompute the commands when new measurements are available (i.e., updating the spatial distribution used as target). 
+In robotics, ergodic control can be exploited in a wide range of problems requiring the automatic exploration of regions of interest, which can be used in a wide range of tasks, including active sensing, localization, surveillance, or insertion (see Figure \ref{fig:ergodic_insertion} for an example). This is particularly helpful when the available sensing information or robot actuators are not accurate enough to fulfill the task with a standard controller (limited vision, soft robotic manipulator, etc.), but where this information can still guide the robot towards promising areas. In a collaborative task, it can also be used when the operator's input is not accurate enough to fully reproduce the task, which then requires the robot to explore around the requested input (e.g., a point of interest selected by the operator). For picking and insertion problems, ergodic control can be applied to move around the picking/insertion point, thereby facilitating the prehension/insertion. It can also be employed for active sensing and localization (either detected autonomously, or with help by the operator). Here, the robot can plan movements based on the current information density, and can recompute the commands when new measurements are available (i.e., updating the spatial distribution used as target). 
 
 Ergodic control is originally formulated as a \emph{spectral multiscale coverage} (SMC) objective \cite{Mathew09}, which we will see next. Other ergodic control techniques have later been proposed, including the \emph{heat equation driven area coverage} (HEDAC) \cite{Ivic17}, which we will also be introduced next.
 
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsection{Spectral multiscale coverage (SMC)}\label{sec:SMC}
-\begin{flushright}
-\filename{ergodic\_control\_SMC.*}
-\end{flushright}
+\subsection{Spectral-based ergodic control (SMC)}\label{sec:SMC}
 
-The underlying objective of \emph{spectral multiscale coverage} (SMC) takes a simple form, corresponding to a tracking problem in the spectral domain (tracking of frequency components) \cite{Mathew09}. The advantage of such a control formulation is that it can be easily combined with other control objectives and constraints.
+The underlying objective of \emph{spectral multiscale coverage} (SMC) takes a simple form, corresponding to a tracking problem in the spectral domain (matching of frequency components) \cite{Mathew09}. The advantage of such a simple control formulation is that it can be easily combined with other control objectives and constraints.
 
-It requires the spatial distribution to be decomposed as Fourier series, with a cost function comparing the spectral decomposition of the robot path with the spectral decomposition of the distribution. The resulting controller allows the robot to explore the given spatial distribution in a natural manner, \textbf{by starting from a crude exploration and by refining the search progressively} (i.e., matching the Fourier coefficients with an increasing importance from low to high frequency components). 
+It requires the spatial distribution to be decomposed as Fourier series, with a cost function comparing the spectral decomposition of the robot path with the spectral decomposition of the distribution, in the form of a weighted distance function with a decreasing weight from low frequency to high frequency components. The resulting controller allows the robot to explore the given spatial distribution in a natural manner, \textbf{by starting from a crude exploration and by refining the search progressively} (i.e., matching the Fourier coefficients with an increasing importance from low to high frequency components). 
 
-%% Fourier basis functions
-We will adopt a notation to make links with the superposition of basis functions seen in Section \ref{sec:basisfcts}. By starting with the unidimensional case, we will consider a signal $g(x)$ varying along a variable $x$, where $x$ will be used as a generic variable that can for example be a time variable or the coordinates of a pixel in an image. The signal $g(x)$ can be approximated as a weighted superposition of basis functions with 
-\begin{align*}
-	g(x) &= \sum_{k=-K\!+\!1}^{K\!-\!1} w_k \, \phi_k(x)\\
-	&= \bm{w}^\trsp \bm{\phi}(x), 
-\end{align*}
-where $\bm{w}$ and $\bm{\phi}(x)$ are vectors formed with the elements of $w_k$ and $\phi_k(x)$, respectively.
-$w_k$ and $\phi_k(x)$ denote the coefficients and basis functions of the Fourier series, with
-\begin{align}
-	\phi_k(x) &= \frac{1}{L} \exp\!\left(-i\frac{2\pi k x}{L}\right)\nonumber\\
-	&= \frac{1}{L} \Bigg(\!\cos\!\left(\frac{2\pi k x}{L}\right) - i \, \sin\!\left(\frac{2\pi k x}{L}\right) \!\Bigg)
-	, \;\forall k\!\in\![-K\!+\!1,\ldots,K\!-\!1],
-	\label{eq:complExp1D}
-\end{align}
-with $i$ the imaginary unit of a complex number ($i^2=-1$).
+\begin{figure}
+\centering{\includegraphics[width=.7\columnwidth]{images/ergodicVsPatternedSearch01.jpg}}
+\caption{\footnotesize 
+Search and exploration problems can be formulated in various ways. Ergodic control can be used in a search problem in which we do not know the duration of the exploration (e.g., we would like to find a hidden target as soon as possible). In contrast to stochastic sampling of a distribution, ergodic control takes into account the cost to move the agent from one point to another. If the search optimization problem is formulated as a coverage problem with fixed duration, the optimal path typically reveals some regular coverage patterns (here, illustrated as spirals, but also called lawnmower strategy). Ergodic control instead generates a more natural search behavior to localize the object to search by starting with a crude coverage of the workspace and by then generating progressively more detailed paths to cover the distribution. This for example resembles the way we would search for keys in a house by starting with a distribution about the locations in the rooms in which we believe the keys could be, and by covering these distribution coarsely as a first pass, followed by progressive refinement about the search with more detailed coverage until the keys are found. Both stochastic samples or patterned search would be very inefficient here! 
+\label{fig:ergodic_intro}
+}
+\end{figure}
+
+\begin{SCfigure}[50]
+\centering
+\begin{tabular}{cc}
+Ergodic search & Patterned search\\
+\includegraphics[width=.24\columnwidth]{images/SMC-room002.jpg} &
+\includegraphics[width=.24\columnwidth]{images/SMC-room001.jpg} \\
+\includegraphics[width=.24\columnwidth]{images/SMC-room002c.jpg} &
+\includegraphics[width=.24\columnwidth]{images/SMC-room001c.jpg}
+\end{tabular}
+\caption{\footnotesize
+Example illustrating the search of a key in a living room, where regions of interest are specified in the form of a distribution over the spatial domain. These regions of interest correspond here to the different tables in the room where it is more likely to find the key. The left and right columns respectively depict an ergodic search and patterned search processes. For a coverage problem in which the duration is given in advance, a patterned search can typically be better suited than an ergodic control search, because the agent will optimize the path to reduce the number of transitions from one area to the other. In contrast, an ergodic control search will typically result in multiple transitions between the different regions of interest. When searching for a key, since we are interested in finding the key as early as possible, we have a problem in which the total search duration cannot be specified in advance. In this problem setting, an ergodic search will be better suited than a patterned search, as it generates a natural way of exploring the environment by first proceeding with a crude search in the whole space and by then progressively fine-tuning the search with additional details until the key is finally found. The bottom row shows an example in which the key location is unknown, with the search process stopping when the key is found. Here, a patterned search would provide an inefficient and unnatural way of scanning the whole environment regularly by looking at all details regions by regions, instead of treating the problem at different scales (i.e., at different spatial frequencies), which is what ergodic exploration provides. 
+}
+\label{fig:ergodic_vs_patterned}
+\end{SCfigure}
+
+\begin{SCfigure}[25]
+\centering{\includegraphics[width=.75\columnwidth]{images/ergodic01.png}}
+\caption{\footnotesize 
+Insertion tasks can be achieved robustly with ergodic control, by not only relying on accurate sensors, but instead using a control strategy to cope with limited or inaccurate sensing information, see \cite{Shetty21TRO} for details. 
+\label{fig:ergodic_insertion}
+}
+\end{SCfigure}
 
-The use of Fourier basis functions provides useful connections between the spatial domain and the frequency domain. Several Fourier series properties can be exploited, notably regarding zero-centered Gaussians, shift, symmetry, and linear combination. 
-These properties are reported in Table \ref{tab:Fourier} for the 1D case.
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsubsection{Unidimensional SMC}\label{sec:SMC1D}
 
-\begin{table*}
+\begin{table}
 \caption{Fourier series properties (1D case).}
 \label{tab:Fourier}
 \begin{mdframed}
-
 \noindent\textbf{Symmetry property:}\\
 If $g(x)$ is real and even, $\phi_k(x)$ in \eqref{eq:complExp1D} is also real and even, simplifying to $\phi_k(x) = \frac{1}{L} \cos\!\left(\frac{2\pi k x}{L}\right)$, which then, in practice, only needs an evaluation on the range $k\!\in\![0,\ldots,K\!-\!1]$, as the basis functions are even. We then have $g(x) = w_0 + \sum_{k=1}^{K\!-\!1} w_k \, 2\cos\!\left(\frac{2\pi k x}{L}\right)$, by exploiting $\cos(0)\!=\!1$.\\[-2mm]
 
@@ -3075,91 +3366,367 @@ If $g_0(x)=\mathcal{N}(x \,|\, 0, \sigma^2)=(2\pi\sigma^2)^{-\frac{1}{2}} \exp(-
 is mirrored to create a real and even periodic function $g(x)$ of period $L\gg\sigma$ (implementation details will follow), the corresponding Fourier series coefficients are of the form $w_k=\exp(-\frac{2\pi^2 k^2 \sigma^2}{L^2})$.\\[-2mm]
 
 \end{mdframed}
-\end{table*}
+\end{table}
+
+%% Fourier basis functions
+We will adopt a notation to make links with the superposition of basis functions seen in Section \ref{sec:basisfcts}. By starting with the unidimensional case (system moving along a line segment), we will consider a signal $g(x)$ varying along a variable $x$, where $x$ will be used as a generic variable that can for example be a time variable or the coordinates of a pixel in an image. The signal $g(x)$ can be approximated as a weighted superposition of basis functions with 
+\begin{equation}
+	g(x) = \sum_{k=-K\!+\!1}^{K\!-\!1} w_k \, \phi_k(x).
+	\label{eq:gx}
+\end{equation}
+
+The use of Fourier basis functions provides useful connections between the spatial domain and the spectral domain, where $w_k$ and $\phi_k(x)$ denote the coefficients and basis functions of the Fourier series. 
+
+For a spatial signal $x$ on the interval $[-\frac{L}{2},\frac{L}{2}]$ of period $L$, the basis functions of the Fourier series with complex exponential functions will be defined as 
+\begin{align}
+	\phi_k(x) &= \frac{1}{2L} \exp\!\left(-i\frac{2\pi k x}{L}\right)\nonumber\\
+	&= \frac{1}{2L} \Bigg(\!\cos\!\left(\frac{2\pi k x}{L}\right) - i \, \sin\!\left(\frac{2\pi k x}{L}\right) \!\Bigg)
+	, \;\forall k\!\in\![-K\!+\!1,\ldots,K\!-\!1],
+	\label{eq:complExp1D}
+\end{align}
+with $i$ the imaginary unit of a complex number ($i^2=-1$).
+
+As detailed in Table \ref{tab:Fourier}, when $g(x)$ is real and even (our case of interest), $\phi_k(x)$ in \eqref{eq:complExp1D} is also real and even, simplifying to $\phi_k(x) = \frac{1}{L} \cos\!\left(\frac{2\pi k x}{L}\right)$, which then, in practice, only needs an evaluation on the range $k\!\in\![0,\ldots,K\!-\!1]$, using
+\begin{equation}
+	\phi_k(x) = \frac{1}{L} \cos\!\left(\frac{2\pi k x}{L}\right) 
+	, \quad\forall k\!\in\![0,\ldots,K-1].
+	\label{eq:complExpND1D}
+\end{equation}
+
+The derivatives of \eqref{eq:complExpND1D} with respect to $x$ are easy to compute, namely
+\begin{equation}
+	\nabla_{\!\!x}\phi_k(x) = - \frac{2\pi k}{L^2} \sin\!\left(\frac{2\pi k x}{L}\right). 
+\end{equation}
+
+Ergodic control aims to build a controller so that the Fourier series coefficients $w_k$ along a trajectory $x(t)$ of duration $t$, defined as
+\begin{equation}
+	w_k = \frac{1}{t} \int_{\tau=0}^t \phi_k\big(x(\tau)\big) \; d\tau,
+	\label{eq:wk1D}
+\end{equation}
+will match the Fourier series coefficients $\hat{w}_k$ on the spatial domain $\mathcal{X}$, defined as
+\begin{align}
+	\hat{w}_k &= \int_{x\in\mathcal{X}} \hat{g}(x) \; \phi_k(x) \; \text{d}x.
+	\label{eq:wkhat1D}
+\end{align}
+
+The discretized version of \eqref{eq:wk1D} for a discrete number of time steps $T$ is
+\begin{equation}
+	w_k = \frac{1}{T} \sum_{s=1}^T \phi_k(x_s), 
+	\label{eq:wk2_1D}
+\end{equation}
+which can be computed recursively by updating $w_k$ at each iteration step. 
+
+Similarly, the discretized version of \eqref{eq:wkhat1D} for a given spatial resolution can for example be computed on a domain $\mathcal{X}$ discretized in $X$ bins as 
+\begin{align}
+	\hat{w}_k &= \sum_{s=1}^{X} \hat{g}(x_s) \; \phi_k(x_s),
+	\label{eq:wkhat2_1D}
+\end{align}
+where $x_s$ splits the domain $\mathcal{X}$ into $X$ regular intervals.
+
+To compute these Fourier series coefficients efficiently, several Fourier series properties can be exploited, including general property such as symmetry, shift, and linear combination, as well as more specific property in the special case when the spatial distribution takes the form of a mixture of Gaussians. These properties are reported in Table \ref{tab:Fourier} for the 1D case.
+
+Well-known applications of Fourier basis functions in the context of time series include speech processing and the analysis of periodic motions such as gaits. 
+In ergodic control, the aim is instead to find a series of control commands $u(t)$ so that the retrieved trajectory $x(t)$ covers a bounded space $\mathcal{X}$ in proportion of a desired spatial distribution $\hat{g}(x)$. %, see Fig.~\ref{fig:ergodic_SMC}-\emph{(a)}. 
+This can be achieved by defining a metric in the spectral domain, by decomposing in Fourier series coefficients both the desired spatial distribution $\hat{g}(x)$ and the (partially) retrieved trajectory $x(t)$, which can exploit the Fourier series properties presented in Table \ref{tab:Fourier}, which can also be extended to more dimensions.
+
+
+\begin{wrapfigure}{r}{.34\textwidth}
+\centering
+\includegraphics[width=.32\textwidth]{images/ergodicControl-fromCrudetoPrecise01.jpg}
+\caption{\footnotesize
+Although ergodic control with SMC is specified in the spectral domain, it can also be interpreted in the spatial domain as a coverage problem in which both the path of the agent and the targeted distributions are blurred with filters of varying strength. With very strong blurring, the agent can match the desired distribution very quickly (first row). The weaker the filter, the more time the agent will need to cover the path to match the details of the distribution (second and third row). As an optimization problem, the weights $\Lambda_k$ are set to promote a good match of the distributions that are strongly blurred (i.e., low frequency components). When this part of the cost goes to zero, the agent can then progressively refine the path so that less blurred distributions can also be matched (i.e., higher frequency components).
+}
+\label{fig:ergodic_fromCrudetoPrecise}
+%\vspace{-20pt}
+\end{wrapfigure}
+
+The goal of ergodic control is to minimize
+\begin{equation}
+	\epsilon = \frac{1}{2} \sum_{k=0}^{K-1} \Lambda_k \Big( w_k - \hat{w}_k \Big)^{\!2} \label{eq:ergodicerror1D}
+\end{equation}
+where $\Lambda_k$ are weights, $\hat{w}_k$ are the Fourier series coefficients of $\hat{g}(x)$, and $w_k$ are the Fourier series coefficients along the trajectory $x(t)$. $k\in[0,1,\ldots,K\!-\!1]$ is a set of $K$ index vectors. 
+In \eqref{eq:ergodicerror1D}, the weights
+\begin{equation}
+	\Lambda_k = \left(1+ k^2\right)^{\!-1}
+\end{equation}
+assign more importance on matching low frequency components (related to a metric for Sobolev spaces of negative order). %negative Sobolev norm
+
+Practically, the controller will mainly focus on the lowest frequency components at the beginning as these components have a large effect on the cost due to the large weights. When the errors become zero for these components, the controller can then try to progressively reduce higher frequency components.
+
+%% Ergodic controller
+Ergodic control is then set as the constrained problem of computing a control command $\hat{u}(t)$ at each time step $t$ with 
+\begin{equation}
+	\hat{u}(t) = \arg\min_{u(t)}\; \epsilon\big(x(t\!+\!\Delta t)\big), 
+	\quad \text{s.t.} \quad
+	\dot{x}(t) = f\big(x(t),u(t)\big),\quad \|u(t)\| \leqslant u^{\max},
+	\label{eq:objFct1D}
+\end{equation}
+where the simple system $u(t)=\dot{x}(t)$ is considered (control with velocity commands), and where the error term is approximated with the Taylor series
+\begin{equation}
+	\epsilon\big(x(t\!+\!\Delta t)\big) \;\approx\; \epsilon\big(x(t)\big) \;+\; \dot{\epsilon}\big(x(t)\big) \Delta t 
+	\;+\; \frac{1}{2} \ddot{\epsilon}\big(x(t)\big) {\Delta t}^2.
+	\label{eq:etpp1D}
+\end{equation}
+
+By using \eqref{eq:ergodicerror1D}, \eqref{eq:wk1D}, \eqref{eq:complExpND1D} and the chain rule $\frac{\partial f}{\partial t}=\frac{\partial f}{\partial x} \frac{\partial x}{\partial t}$, the Taylor series is composed of the control term $u(t)$ and $\nabla_{\!\!x} \phi_k\big(x(t)\big)\in\mathbb{R}$, the gradient of $\phi_k\big(x(t)\big)$ with respect to $x(t)$.
+Solving the constrained objective in \eqref{eq:objFct} then results in the analytical solution (see \cite{Mathew09} for the complete derivation)
+\begin{equation}
+	u(t) = \tilde{u}(t)\frac{u^{\max}}{\|\tilde{u}(t)\|} = \text{sign}\big(u(t)\big) u^{\max},
+	\quad\mathrm{with}\quad
+	\tilde{u}(t) = -\sum_{k=0}^{K-1} \Lambda_{k} \big( w_k - \hat{w}_k \big) \nabla_{\!\!x}\phi_k\big(x(t)\big) \nonumber\\
+\end{equation}
+
+It is important to emphasize that the implementation of this controller does not rely on any random number generation: this search behavior is instead deterministic.
+\\[2mm]
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\noindent\textbf{Computation in vector form}
+\begin{flushright}
+\filename{ergodic\_control\_SMC\_1D.*}
+\end{flushright}
+
+
+%\begin{SCfigure}[50]
+%\centering
+%\includegraphics[width=.6\textwidth]{images/ergodicControl-fromCrudetoPrecise01.jpg}
+%\caption{\footnotesize
+%Although ergodic control with SMC is specified in the spectral domain, it can also be interpreted in the spatial domain as a coverage problem in which both the path of the agent and the targeted distributions are blurred with filters of varying strength. With very strong blurring, the agent can match the desired distribution very quickly (first row). The weaker the filter, the more time the agent will need to cover the path to match the details of the distribution (second and third row). As an optimization problem, the weights $\Lambda_k$ are set to promote a good match of the distributions that are strongly blurred (i.e., low frequency components). When this part of the cost goes to zero, the agent can then progressively refine the path so that less blurred distributions can also be matched (i.e., higher frequency components).
+%}
+%\label{fig:ergodic_fromCrudetoPrecise}
+%\end{SCfigure}
+
+\noindent The superposition of basis functions in \eqref{eq:gx} can be rewritten as
+\begin{equation}
+	g(x) = \bm{w}^\trsp \bm{\phi}(x), 
+\end{equation}
+where $\bm{w}$ and $\bm{\phi}(x)$ are vectors formed with the $K$ elements of $w_k$ and $\phi_k(x)$, respectively.
+
+The goal of ergodic control in \eqref{eq:ergodicerror1D} is to minimize
+\begin{equation}
+	\epsilon = \frac{1}{2} {\Big( \bm{w} - \bm{\hat{w}} \Big)}^{\!\trsp} \bm{\Lambda} \, \Big( \bm{w} - \bm{\hat{w}} \Big),
+\end{equation}
+where $\bm{\hat{w}}$ is a vector formed with the $K$ elements $\hat{w}_k$, and $\bm{\Lambda}$ is a weighting matrix formed with the $K$ diagonal elements $\Lambda_k$.
+
+By defining $\bm{\phi}(x_s)$ as the vector concatenating the $K$ elements $\phi_k(x_s)$, \eqref{eq:wk2_1D} can be rewritten in a vector form as 
+\begin{equation}
+	\bm{w} = \frac{1}{T}\sum_{s=1}^T\bm{\phi}(x_s).
+	\label{eq:wk3_1D}
+\end{equation}
+
+With some abuse of notation, by defining a vector $\bm{\tilde{v}}={[0,\ldots,K\!-\!1]}^\trsp$, we can conveniently compute
+\begin{align}
+	\bm{\phi}(x) &= \frac{1}{L} \cos(\bm{v} x), \\
+	\nabla_{\!\!x}\bm{\phi}(x) &= - \frac{\bm{v}}{L} \sin(\bm{v} x), \quad\text{with}\quad \bm{v}=\frac{2\pi\bm{\tilde{v}}}{L},
+	\label{eq:complExpND2_1D}
+\end{align}
+where $\bm{\nabla}_{\!\!x}\bm{\phi}(x)$ is a vector formed by the $K$ elements $\nabla_{\!\!x} \phi_k(x)$, yielding the controller
+\begin{equation}
+	u(t) = - {\bm{\nabla}_{\!\!x}\bm{\phi}(x)}^\trsp \; \bm{\Lambda} \, \big( \bm{w} - \bm{\hat{w}} \big).
+\end{equation}
+%\\[2mm]
+
+Figure \ref{fig:ergodic_fromCrudetoPrecise} shows how this controller can be interpreted in the spatial domain.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\noindent\textbf{Planning formulation of unidimensional SMC with iLQR}
+%\label{sec:iLQR_SMC_1D}
+\begin{flushright}
+\filename{ergodic\_control\_SMC\_DDP\_1D.*}
+\end{flushright}
+
+\begin{figure}
+\centering{\includegraphics[width=.6\columnwidth]{images/ergodicControl_DDP_1D01.png}}
+\caption{\footnotesize 
+Unidimensional SMC problem computed with iLQR. A series of control commands is used as initial guess (see timeline plot in gray on the bottom-left), which is then iteratively refined by iLQR (see timeline plot in black on the bottom-left). The top plots shows the reference distribution (in red) and the reconstructed distributions (in gray for initial guess and black after iLQR), in both spatial domain (top-left) and spectral domain (top-right).
+\label{fig:ergodic_DDP_1D}
+}
+\end{figure}
+
+\noindent By exploiting the results of Section \ref{sec:iLQR_quadraticCost}, the batch formulation of iLQR consists of minimizing the cost
+\begin{equation}
+	c(\bm{x},\bm{u}) = \bm{f}(\bm{x})^{\!\trsp} \bm{Q} \bm{f}(\bm{x}) + \bm{u}^\trsp \bm{R} \, \bm{u}, 
+	\label{eq:c_iLQR_SMC}
+\end{equation}
+with $\bm{Q} = \bm{\Lambda}$ and $\bm{f}(\bm{x}) = \bm{w}(\bm{x}) - \bm{\hat{w}}$, with
+\begin{equation}
+	\bm{w}(\bm{x}) = \frac{1}{T} \sum_{s=1}^T \bm{\phi}(\bm{x}_s), 
+	\label{eq:wk3}
+\end{equation}
+
+By starting from an initial guess, the iterative updates of \eqref{eq:c_iLQR_SMC} are given by
+\begin{equation}
+	\Delta\bm{\hat{u}} \!=\! {\Big(\bm{S}_{\bm{u}}^\trsp \bm{J}(\bm{x})^\trsp \bm{Q} \bm{J}(\bm{x}) \bm{S}_{\bm{u}} \!+\! \bm{R}\Big)}^{\!\!-1} 
+	\Big(- \bm{S}_{\bm{u}}^\trsp \bm{J}(\bm{x})^\trsp \bm{Q} \bm{f}(\bm{x}) - \bm{R} \, \bm{u} \Big),
+	\label{eq:du_iLQR_SMC}
+\end{equation}
+with $\bm{J}(\bm{x})=\frac{\partial\bm{f}(\bm{x})}{\partial\bm{x}}$ a Jacobian matrix given by
+\begin{equation}
+	\bm{J}(\bm{x}) = \frac{1}{T} %\sum_{s=1}^T \nabla_{\!\!x}\bm{\phi}(x_s).
+	\begin{bmatrix} 
+	\nabla_{\!\!x}\bm{\phi}(x_1), \nabla_{\!\!x}\bm{\phi}(x_2), \ldots \nabla_{\!\!x}\bm{\phi}(x_T)
+	\end{bmatrix}.
+\end{equation}
+
+Figure \ref{fig:ergodic_DDP_1D} presents the output of the accompanying source codes.
+
+
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+\subsubsection{Multidimensional SMC}\label{sec:SMCnD}
+\begin{flushright}
+\filename{ergodic\_control\_SMC\_2D.*}\\
+\filename{ergodic\_control\_SMC\_DDP\_2D.*}
+\end{flushright}
+
+\begin{figure}
+\centering{\includegraphics[width=.5\columnwidth]{images/basisFcts2D01.png}}
+\caption{\footnotesize 
+Decomposition of the spatial distribution using Fourier basis functions.
+\label{fig:ergodic_decomposition}
+}
+\end{figure}
 
 \begin{figure}
 \centering{\includegraphics[width=.7\columnwidth]{images/ergodicControl02.png}}
-\caption{
+\caption{\footnotesize 
 2D ergodic control based on SMC used to generate search behaviors.
 \emph{(a)} shows the spatial distribution $\hat{g}(\bm{x})$ that the agent has to explore, encoded here as a mixture of two Gaussians (gray colormap in left graph). The right graphs show the corresponding Fourier series coefficients $\hat{w}_{\bm{k}}$ in the frequency domain ($K=9$ coefficients per dimension). \emph{(b)} shows the evolution of the reconstructed spatial distribution $g(\bm{x})$ (left graph) and the computation of the next control command $\bm{u}$ (red arrow) after $T/10$ iterations. The corresponding Fourier series coefficients $w_{\bm{k}}$ are shown in the right graph. \emph{(c)} shows that after $T$ iterations, the agent covers the space in proportion to the desired spatial distribution, with a good match of coefficients in the frequency domain (we can see that $\hat{w}_{\bm{k}}$ and $w_{\bm{k}}$ are nearly the same). \emph{(d)} shows how a periodic signal $\hat{g}(\bm{x})$ (with range $[-L/2,L/2]$ for each dimension) can be constructed from an initial mixture of two Gaussians $\hat{g}_0(\bm{x})$ (red area). The constructed signal $\hat{g}(\bm{x})$ is composed of eight Gaussians in this 2D example, by mirroring the Gaussians along horizontal and vertical axes to construct an even signal of period $L$. \emph{(e)} depicts the first few basis functions of the Fourier series for the first four coefficients in each dimension, represented as a 2D colormap corresponding to periodic signals of different frequencies along two axes.
 \label{fig:ergodic_SMC}
 }
 \end{figure}
 
-Well-known applications of Fourier basis functions in the context of time series include speech processing and the analysis of periodic motions such as gaits. 
+\begin{figure}
+\centering{\includegraphics[width=.7\columnwidth]{images/ergodicControl_DDP_2D01.png}}
+\caption{\footnotesize 
+Bidimensional SMC problem computed with iLQR.
+\label{fig:ergodic_DDP_2D}
+}
+\end{figure}
+
+For the multidimensional case, we will define $\mathcal{K}$ as a set of index vectors %in $\mathbb{N}^D$ 
+covering a $D$-dimensional array $\bm{k}=\bm{r}\times\bm{r}\times\cdots\times\bm{r}$, with $\bm{r}=[0,1,\ldots,K\!-\!1]$ and $K$ the resolution of the array. For example, with $D=2$ and $K=2$, we will have $\mathcal{K}=\big\{\left[\begin{smallmatrix}0\\0\end{smallmatrix}\right],\left[\begin{smallmatrix}0\\1\end{smallmatrix}\right],\left[\begin{smallmatrix}1\\0\end{smallmatrix}\right],\left[\begin{smallmatrix}1\\1\end{smallmatrix}\right]\big\}$.
+
+Similarly as the unidimensional case, we will build a controller so that the Fourier series coefficients $w_{\bm{k}}$ along a trajectory $\bm{x}(t)$ of duration $t$, defined as
+\begin{equation}
+	w_{\bm{k}} = \frac{1}{t} \int_{\tau=0}^t \phi_{\bm{k}}\big(\bm{x}(\tau)\big) \; d\tau,
+	\label{eq:wk}
+\end{equation}
+will match the Fourier series coefficients $\hat{w}_{\bm{k}}$ on the spatial domain $\mathcal{X}$, defined as
+\begin{align}
+	\hat{w}_{\bm{k}} &= \int_{\bm{x}\in\mathcal{X}} \hat{g}(\bm{x}) \; \phi_{\bm{k}}(\bm{x}) \; \text{d}\bm{x}.
+	\label{eq:wkhat}
+\end{align}
+
+The discretized version of \eqref{eq:wk} for a discrete number of time steps $T$ is
+\begin{equation}
+	w_{\bm{k}} = \frac{1}{T} \sum_{s=1}^T \phi_{\bm{k}}(\bm{x}_s), 
+	\label{eq:wk2}
+\end{equation}
+or equivalently in vector form $\bm{w} = \frac{1}{T}\sum_{s=1}^T\bm{\phi}(\bm{x}_s)$, which can be computed recursively by updating $\bm{w}$ at each iteration step.
+
+Similarly, the discretized version of \eqref{eq:wkhat} for a given spatial resolution can for example be computed on a domain $[0,1]$ discretized in $X$ bins for each dimension as 
+\begin{align}
+	\hat{w}_{\bm{k}} &= \sum_{s_1=1}^{X} \sum_{s_2=1}^{X} \cdots \sum_{s_d=0}^{X} \hat{g}(\bm{x}_{\bm{s}}) \; \phi_{\bm{k}}(\bm{x}_{\bm{s}}),
+	\label{eq:wkhat2}
+\end{align}
+where each dimension $i$ of $\bm{x}$ is given by index $s_i$ splitting each domain dimension into $X$ equal bins.
 
-In ergodic control, the aim is to find a series of control commands $\bm{u}(t)$ so that the retrieved trajectory $\bm{x}(t)\in\mathbb{R}^D$ covers a bounded space $\mathcal{X}$ in proportion of a desired spatial distribution $\hat{g}(\bm{x})$, see Fig.~\ref{fig:ergodic_SMC}-\emph{(a)}. This can be achieved by defining a metric in the spectral domain, by decomposing in Fourier series coefficients both the desired spatial distribution $\hat{g}(\bm{x})$ and the (partially) retrieved trajectory $\bm{x}(t)$.
 The goal of ergodic control is to minimize
 \begin{align}
 	\epsilon &= \frac{1}{2} \sum_{{\bm{k}}\in\mathcal{K}} \Lambda_{\bm{k}} \Big( w_{\bm{k}} - \hat{w}_{\bm{k}} \Big)^{\!2} \label{eq:ergodicerror}\\
 	&= \frac{1}{2} {\Big( \bm{w} - \bm{\hat{w}} \Big)}^{\!\trsp} \bm{\Lambda} \, \Big( \bm{w} - \bm{\hat{w}} \Big),
 \end{align}
-where $\Lambda_{\bm{k}}$ are weights, $\hat{w}_{\bm{k}}$ are the Fourier series coefficients of $\hat{g}(\bm{x})$, and $w_{\bm{k}}$ are the Fourier series coefficients along the trajectory $\bm{x}(t)$. $\mathcal{K}$ is a set of index vectors in $\mathbb{N}^D$ covering the $D$-dimensional array $\bm{k}=\bm{r}\times\bm{r}\times\cdots\times\bm{r}$, with $\bm{r}=[0,1,\ldots,K\!-\!1]$ and $K$ the resolution of the array.\footnote{For $D=2$ and $K=2$, we have $\mathcal{K}=\big\{\left[\begin{smallmatrix}0\\0\end{smallmatrix}\right],\left[\begin{smallmatrix}0\\1\end{smallmatrix}\right],\left[\begin{smallmatrix}1\\0\end{smallmatrix}\right],\left[\begin{smallmatrix}1\\1\end{smallmatrix}\right]\big\}$.}
+where $\Lambda_{\bm{k}}$ are weights, $\hat{w}_{\bm{k}}$ are the Fourier series coefficients of $\hat{g}(\bm{x})$, and $w_{\bm{k}}$ are the Fourier series coefficients along the trajectory $\bm{x}(t)$. 
 $\bm{w}\in\mathbb{R}^{K^D}$ and $\bm{\hat{w}}\in\mathbb{R}^{K^D}$ are vectors composed of elements $w_{\bm{k}}$ and $\hat{w}_{\bm{k}}$, respectively. $\bm{\Lambda}\in\mathbb{R}^{K^D\times K^D}$ is a diagonal weighting matrix with elements $\Lambda_{\bm{k}}$.
 In \eqref{eq:ergodicerror}, the weights
 \begin{equation}
 	\Lambda_{\bm{k}} = \left(1+ \|\bm{k}\|^2\right)^{\!-\frac{D+1}{2}}
 \end{equation}
 assign more importance on matching low frequency components (related to a metric for Sobolev spaces of negative order). %negative Sobolev norm
-The Fourier series coefficients $w_{\bm{k}}$ along a trajectory $\bm{x}(t)$ of continuous duration $t$ are defined as
-\begin{equation}
-	w_{\bm{k}} = \frac{1}{t} \int_{\tau=0}^t \phi_{\bm{k}}\big(\bm{x}(\tau)\big) \; d\tau,
-	\label{eq:ck}
-\end{equation}
-whose discretized version can be computed recursively at each discrete time step $t$ to build
-\begin{equation}
-	w_{\bm{k}} = \frac{1}{t} \sum_{s=1}^t \phi_{\bm{k}}(\bm{x}_s), 
-\end{equation}
-or equivalently in vector form $\bm{w} = \frac{1}{t}\sum_{s=1}^t\bm{\phi}(\bm{x}_s)$. 
+
+Practically, the controller will mainly focus on the lowest frequency components at the beginning as these components have a large effect on the cost due to the large weights. When the errors become zero for these components, the controller can then try to progressively reduce higher frequency components.
 
 For a spatial signal $\bm{x}\in\mathbb{R}^D$, where $x_d$ is on the interval $[-\frac{L}{2},\frac{L}{2}]$ of period $L$, $\forall d\!\in\!\{1,\ldots,D\}$, the basis functions of the Fourier series with complex exponential functions are defined as (see Fig.~\ref{fig:ergodic_SMC}-\emph{(e)})
-\begin{align}
-	\phi_{\bm{k}}(\bm{x}) &= \frac{1}{L^D} \prod_{d=1}^D \exp\!\left(-i\frac{2\pi k_d x_d}{L}\right)\nonumber\\
-	&= \frac{1}{L^D} \prod_{d=1}^D \cos\!\left(\frac{2\pi k_d x_d}{L}\right) - i \, \sin\!\left(\frac{2\pi k_d x_d}{L}\right)
+\begin{equation}
+	\phi_{\bm{k}}(\bm{x}) = \frac{1}{L^D} \prod_{d=1}^D \cos\!\left(\frac{2\pi k_d x_d}{L}\right)
 	, \quad\forall\bm{k}\!\in\!\mathcal{K}.
 	\label{eq:complExpND}
+\end{equation}
+
+By concatenating the $K^D$ index vectors $\bm{k}\!\in\!\mathcal{K}$ into a matrix $\bm{\tilde{V}}\in\mathbb{R}^{D\times K^D}$, we can conveniently compute $\bm{\phi}(\bm{x})$ as the vector concatenating all $K^D$ elements $\phi_{\bm{k}}(\bm{x}), \, \forall\bm{k}\!\in\!\mathcal{K}$, namely
+\begin{align}
+	\bm{\phi}(\bm{x}) &= \frac{1}{L^D} \bigodot_{d=1}^D \cos(\bm{V}_d x_d) \\
+	&= \frac{1}{L^D} \cos(\bm{V}_1 x_1) \odot \cos(\bm{V}_2 x_2) \odot \cdots \odot \cos(\bm{V}_D x_D),
+	\quad\text{with}\quad \bm{V}=\frac{2\pi \bm{\tilde{V}}}{L},
+	\label{eq:complExpND2}
+\end{align}
+where $\odot$ the elementwise/Hadamard product operator.
+
+The derivatives of the vector $\bm{\phi}(\bm{x})$ with respect to $\bm{x}$ are given by the matrix $\nabla_{\!\!\bm{x}}\bm{\phi}(\bm{x})$ of size $K^D \times D$ by concatenating horizontally the $D$ vectors
+\begin{align}
+	\nabla_{\!\!\bm{x}}\bm{\phi}_{d}(\bm{x}) &= -\frac{1}{L^D} \, \bm{V}_d \odot \sin(\bm{V}_d x_d) \bigodot_{i\neq d} \cos(\bm{V}_i x_i) \\
+	&= -\frac{1}{L^D} \, \bm{V}_d \odot \cos(\bm{V}_1 x_1) \odot \cdots \odot \cos(\bm{V}_{d-1} x_{d-1}) \odot \sin(\bm{V}_d x_d) \odot \cos(\bm{V}_{d+1} x_{d+1}) \odot \cdots \odot \cos(\bm{V}_D x_D).
+	\label{eq:diffComplExpND2}
+\end{align}
+
+For the specific example of a 2D space, \eqref{eq:complExpND2} and \eqref{eq:diffComplExpND2} yield 
+\begin{align}
+	\bm{\phi}(\bm{x}) &= \frac{1}{L^2} \cos(\bm{V}_1 x_1) \odot \cos(\bm{V}_2 x_2), \\
+	\nabla_{\!\!\bm{x}}\bm{\phi}(\bm{x}) &= 
+	\begin{bmatrix}
+		-\frac{1}{L} \, \bm{V}_1 \odot \sin(\bm{V}_1 x_1) \odot \cos(\bm{V}_2 x_2) &
+		-\frac{1}{L} \, \bm{V}_2 \odot \cos(\bm{V}_1 x_1) \odot \sin(\bm{V}_2 x_2)
+	\end{bmatrix}.
+	\label{eq:ComplExpND2_2D}
 \end{align}
 
 %% Ergodic controller
-Ergodic control is then set as the constrained problem of computing a control command $\bm{\hat{u}}(t)$ at each time step $t$ with 
+Ergodic control is set as the constrained problem of computing a control command $\bm{\hat{u}}(t)$ at each time step $t$ with 
 \begin{equation}
 	\bm{\hat{u}}(t) = \arg\min_{\bm{u}(t)}\; \epsilon\big(\bm{x}(t\!+\!\Delta t)\big), 
 	\quad \text{s.t.} \quad
 	\bm{\dot{x}}(t) = f\big(\bm{x}(t),\bm{u}(t)\big),\quad \|\bm{u}(t)\| \leqslant u^{\max},
 	\label{eq:objFct}
 \end{equation}
-where the simple system $\bm{\dot{x}}(t)=\bm{u}(t)$ is considered (control with velocity commands), and where the error term is approximated with the Taylor series
+where the simple system $\bm{u}(t)=\bm{\dot{x}}(t)$ is considered (control with velocity commands), and where the error term is approximated with the Taylor series
 \begin{equation}
 	\epsilon\big(\bm{x}(t\!+\!\Delta t)\big) \;\approx\; \epsilon\big(\bm{x}(t)\big) \;+\; \dot{\epsilon}\big(\bm{x}(t)\big) \Delta t 
 	\;+\; \frac{1}{2} \ddot{\epsilon}\big(\bm{x}(t)\big) {\Delta t}^2.
 	\label{eq:etpp}
 \end{equation}
-By using \eqref{eq:ergodicerror}, \eqref{eq:ck}, \eqref{eq:complExpND} and the chain rule $\frac{\partial f}{\partial t}=\frac{\partial f}{\partial \bm{x}} \frac{\partial \bm{x}}{\partial t}$, the Taylor series
+
+By using \eqref{eq:ergodicerror}, \eqref{eq:wk}, \eqref{eq:complExpND} and the chain rule $\frac{\partial f}{\partial t}=\frac{\partial f}{\partial \bm{x}} \frac{\partial \bm{x}}{\partial t}$, the Taylor series
 is composed of the control term $\bm{u}(t)$ and $\nabla_{\!\!\bm{x}} \phi_{\bm{k}}\big(\bm{x}(t)\big)\in\mathbb{R}^{1\times D}$, the gradient of $\phi_{\bm{k}}\big(\bm{x}(t)\big)$ with respect to $\bm{x}(t)$.
 Solving the constrained objective in \eqref{eq:objFct} then results in the analytical solution (see \cite{Mathew09} for the complete derivation)
-\begin{align}
-	\bm{u} = \bm{\tilde{u}}(t)\frac{u^{\max}}{\|\bm{\tilde{u}}(t)\|},
+\begin{equation}
+	\bm{u}(t) = \bm{\tilde{u}}(t)\frac{u^{\max}}{\|\bm{\tilde{u}}(t)\|},
 	\quad\mathrm{with}\quad
-	\bm{\tilde{u}} &= -\sum_{{\bm{k}}\in\mathcal{K}} \Lambda_{\bm{k}} \big( w_{\bm{k}} - \hat{w}_{\bm{k}} \big) 
-	{\nabla_{\!\!\bm{x}} \phi_{\bm{k}}\big(\bm{x}(t)\big)}^\trsp\nonumber\\
-	&= -\bm{\nabla}_{\!\!\bm{x}}\bm{\phi}\big(\bm{x}(t)\big) \; \bm{\Lambda} \, \big( \bm{w} - \bm{\hat{w}} \big),
-\end{align}
-where $\bm{\nabla}_{\!\!\bm{x}}\bm{\phi}\big(\bm{x}(t)\big)\in\mathbb{R}^{D\times K^D}$ is a concatenation of the vectors $\nabla_{\!\!\bm{x}} \phi_{\bm{k}}\big(\bm{x}(t)\big)$.   
+	\bm{\tilde{u}}(t) = -{\nabla_{\!\!\bm{x}} \bm{\phi}(\bm{x})}^\trsp \, \bm{\Lambda} \, \big( \bm{w} - \bm{\hat{w}} \big).
+	%&= -\sum_{{\bm{k}}\in\mathcal{K}} {\nabla_{\!\!\bm{x}} \phi_{\bm{k}}(\bm{x})}^\trsp \, \Lambda_{\bm{k}} \, \big( w_{\bm{k}} - \hat{w}_{\bm{k}} \big) \nonumber\\
+\end{equation}
+
+Figures \ref{fig:ergodic_decomposition} and \ref{fig:ergodic_SMC} show a 2D example of ergodic control to create a motion approximating the distribution given by a mixture of two Gaussians. A remarkable characteristic of such approach is that the controller produces natural exploration behaviors without relying on stochastic noise in the formulation, see Fig.~\ref{fig:ergodic_SMC}-\emph{(c)}. In the limit case, if the distribution $g(\bm{x})$ is a single Gaussian with a very small isotropic covariance, the controller results in a conventional target reaching behavior.
+
+Figure \ref{fig:ergodic_DDP_2D} presents the output of the accompanying source codes, where the initial guess is computed by standard SMC (myopic), whose resulting control command trajectory is then refined with iLQR (SMC as a planning problem).
 
-Figure \ref{fig:ergodic_SMC} shows a 2D example of ergodic control to create a motion approximating the distribution given by a mixture of two Gaussians. A remarkable characteristic of such approach is that the controller produces natural exploration behaviors (see Fig.~\ref{fig:ergodic_SMC}-\emph{(c)}) without relying on stochastic noise in the formulation. In the limit case, if the distribution $g(\bm{x})$ is a single Gaussian with a very small isotropic covariance, the controller results in a standard tracking behavior.
 
 %The downside of the original ergodic control approach is that it does not scale well to problems requiring exploration in search space of more than two dimensions. In particular, the original approach would be too slow to consider full distributions in 6D spaces, which would be ideally required. Indeed, both position and orientation of endeffector(s) matter in most robot problems, including manipulation, insertion, welding, or the use of tools at the robot endeffectors. 
 %In \cite{Shetty21TRO}, we demonstrated that the original problem formulation can be conserved \textbf{by efficiently compressing the Fourier series decomposition with tensor train (TT) factorization}. The proposed solution is efficient both computationally and storage-wise, hence making it suitable for online implementations, as well as to tackle robot learning problems with a low quantity of training data. The above figure shows an overview of an insertion experiment conducted with the Siemens gears benchmark requiring full 6D endeffector poses. Further work is required to extend the approach to online active sensing applications in which the distributions can change based on the data collected by ergodic control. 
 
-\newpage
+%\newpage
+
+
+
 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-\subsection{Heat equation driven area coverage (HEDAC)}\label{sec:HEDAC}
+\subsection{Diffusion-based ergodic control (HEDAC)}\label{sec:HEDAC}
 \begin{flushright}
-\filename{ergodic\_control\_HEDAC.*}
+\filename{ergodic\_control\_HEDAC\_1D.*}\\
+\filename{ergodic\_control\_HEDAC\_2D.*}
 \end{flushright}
 
-Heat equation driven area coverage (HEDAC) is an area coverage method that can be used with multiple agents and a possibly changing reference distribution \cite{Ivic17}. 
+Heat equation driven area coverage (HEDAC) is another area coverage method that relies on diffusion processes instead of spectral analysis \cite{Ivic17}. 
 
 The coverage density currently covered by the agent(s) is defined as the convolution of an instantaneous action and the trajectory, which results in a field occupying the space around the path of the agent. A radial basis function can for example be used as the instantaneous action. 
 
@@ -3390,8 +3957,8 @@ A smooth $d$-dimensional manifold $\mathcal{M}$ is a topological space that loca
 
 \begin{figure}
 \centering
-\includegraphics[width=\textwidth]{images/manifold-mappingAndTransportFcts01.png}
-\caption{
+\includegraphics[width=.7\columnwidth]{images/manifold-mappingAndTransportFcts01.png}
+\caption{\footnotesize 
 Applications in robotics using Riemannian manifolds rely on two well-known principles of Riemannian geometry: exponential/logarithmic mapping (\emph{left}) and parallel transport (\emph{right}), which are depicted here on a $\mathcal{S}^2$ manifold embedded in $\mathbb{R}^3$. 
 \emph{Left:} Bidirectional mappings between tangent space and manifold. \emph{Right:} Parallel transport of a vector along a geodesic (see main text for details).
 } 
@@ -3477,7 +4044,7 @@ For a set of $N$ datapoints, this geometric mean corresponds to the minimization
 \begin{equation*}
 	\min_{\bm{\mu}} \sum_{n=1}^N {\text{Log}_{\bm{\mu}}\!(\bm{x}_n)}^\trsp \; \text{Log}_{\bm{\mu}}\!(\bm{x}_n),
 \end{equation*}
-which can be solved by a simple and fast Gauss-Newton iterative algorithm. The algorithm starts from an initial estimate on the manifold and an associated tangent space. The datapoints $\{\bm{x}_n\}_{n=1}^N$ are projected in this tangent space to compute a direction vector, which provides an updated estimate of the mean. This process is repeated by iterating
+which can be solved by a simple and fast Gauss--Newton iterative algorithm. The algorithm starts from an initial estimate on the manifold and an associated tangent space. The datapoints $\{\bm{x}_n\}_{n=1}^N$ are projected in this tangent space to compute a direction vector, which provides an updated estimate of the mean. This process is repeated by iterating
 \begin{equation*}
 	\bm{u} = \frac{1}{N} \sum_{n=1}^N \text{Log}_{\bm{\mu}}\!(\bm{x}_n),
 	\qquad
@@ -3496,7 +4063,7 @@ This distribution can for example be used in a control problem to represent a re
 \begin{figure*}
 \centering
 \includegraphics[width=\textwidth]{images/manifold-S-SPD-H01.png}
-\caption{
+\caption{\footnotesize 
 Examples of manifolds relevant for robotics. 
 %$\mathcal{S}^3$ can be used to represent the orientation of robot endeffectors (unit quaternions). 
 %$\mathcal{S}^6_{++}$ can be used to represent manipulability ellipsoids (manipulability capability in translation and rotation), corresponding to a symmetric positive definite (SPD) matrix manifold. $\mathcal{H}^d$ can be used to represent trees, graphs and roadmaps. $\mathcal{G}^{d,p}$ can be used to represent subspaces (planes, nullspaces, projection operators). 
@@ -3546,23 +4113,31 @@ The parallel transport of $\bm{V}\in\mathcal{T}_{\bm{X}}\mathcal{S}_{++}^d$ to $
 
 \begin{figure*}
 \centering
+\includegraphics[width=.7\columnwidth]{images/intrinsicGeom_vs_extrinsicGeom01.jpg}
+\caption{\footnotesize 
+Intrinsic geometry defined by a Riemannian metric, with two examples of corresponding extrinsic geometries (here, embedded in a 3D space).   
+} 
+\label{fig:intrinsicGeom_vs_extrinsicGeom}
+\end{figure*}
+
+\begin{figure*}
+\centering
+\includegraphics[height=52mm]{images/kinEnergyGeodesics01.png}
 \includegraphics[height=52mm]{images/SDF_coordSys01.png}
-\includegraphics[height=54mm]{images/nonhomogeneousManifolds01.png}
-\caption{
-\emph{Left:} Transformation of a scalar signed distance field (SDF) and associated derivatives to a smoothly varying coordinate system to facilitate teleoperation. This coordinate system is shape-centric (both user-centric and object-centric), in the sense that it is oriented toward the surface normal while ensuring smoothness (by constructing the SDF as piecewise polynomials). In this example, the commands to approach the surface and move along the surface at a desired distance then corresponds to piecewise constant commands (see control command profiles in the graph inset). 
-\emph{Center:} This coordinate system can also be used to define a cost function with a quadratic error defined by a covariance matrix. This matrix can be shaped by the distance, to provide a Riemannian metric that smoothly distorts distances when being close to objects, users and obstacles (represented as covariance ellipses in the figure). This can be used in control and planning to define geodesic paths based on this metric. This will generate paths that naturally curve around obstacles when the obstacles are close (see the two point-to-point trajectories in green, either far from the obstacle or close to the obstacle). 
-\emph{Right:} The metric can also be weighted by other precision matrices, including stiffness ellipsoids, manipulability ellipsoids and mass inertia matrices. Inertia matrices are used in the figure to generate movements from one joint configuration to another while minimizing kinetic energy (in solid lines). The movement in dashed lines show the baseline movements that would be produced by ignoring inertia (corresponding to linear interpolation between the two poses). 
+\includegraphics[height=54mm]{images/obstacleGeodesics01.png}
+\caption{\footnotesize 
+\emph{Left:} A typical example of smoothly varying metric in robotics is when the weight matrix is a mass inertia matrix so that inertia is taken into account to  generate a movement from a starting joint configuration to a target joint configuration while minimizing kinetic energy (see geodesics in solid lines). In the figure, inverse weight matrices are depicted to visualize locally the equidistant points (w.r.t the metric) that the system can reach as ellipsoids.
+The movement in dashed lines show the baseline movements that would be produced by ignoring inertia (corresponding to linear interpolation between the two poses). The metric can similarly be weighted by other precision matrices, including stiffness and manipulability ellipsoids. 
+\emph{Center:} Transformation of a scalar signed distance field (SDF), as in Figure \ref{fig:Bezier_1D2D3D01}, and its associated derivatives to a smoothly varying coordinate system to facilitate teleoperation. This coordinate system is shape-centric (both user-centric and object-centric), in the sense that it is oriented toward the surface normal while ensuring smoothness (by constructing the SDF as piecewise polynomials). In this example, the commands to approach the surface and move along the surface at a desired distance then corresponds to piecewise constant commands (see control command profiles in the graph inset). 
+\emph{Right:} This coordinate system can be used to define a cost function with a quadratic error defined by a covariance matrix. This matrix can be shaped by the distance, to provide a Riemannian metric that smoothly distorts distances when being close to objects, users and obstacles (represented as covariance ellipses in the figure). This can be used in control and planning to define geodesic paths based on this metric. This will generate paths that naturally curve around obstacles when the obstacles are close (see the two point-to-point trajectories in green, either far from the obstacle or close to the obstacle). The figure inset shows that the metric can also be interpreted as a surface lying in a higher dimensional space (here, in 3D), where the geodesics then correspond to the shortest Euclidean path on this surface. It is relevant to note here that we don't need to know about this corresponding embedding, which is for some problems hard to construct), and that we instead only need the metric to compute geodesics on the Riemannian manifold.   
 } 
 \label{fig:nonhomogeneousManifolds}
 \end{figure*}
 %\emph{Left:} Metric field constructed from a signed distance field, which allow to generate paths that naturally curve around obstacles when the obstacles are close. \emph{Right:} Metric field provided by inertia matrices to generate movements from one joint configuration to another while minimizing kinetic energy (in solid lines). The movement in dashed lines show the baseline movements that would be produced by ignoring inertia (corresponding to linear interpolation between the two robot poses).
 
-%
-
-
-Manifolds with nonconstant curvature can also be employed, such as spaces endowed with a metric, characterized by a weighting matrix used to compute distances. Many problems in robotics can be formulated with such a smoothly varying matrix $\bm{M}$ that measures the distance between two points $\bm{x}_1$ and $\bm{x}_2$ as a quadratic error term $c=(\bm{x}_1\!-\!\bm{x}_2)^\trsp\bm{M}(\bm{x}_1\!-\!\bm{x}_2)$, forming a Riemannian metric that describes the underlying manifold (with non-homogeneous curvature). This weighting matrix can for example represent levels of kinetic energy or stiffness gains to model varying impedance behaviors. Computation is often more costly for these manifolds with nonconstant curvature, because it typically requires iterative algorithms instead of the direct analytic expressions typically provided by homogeneous manifolds. 
+Manifolds with nonconstant curvature can also be employed, such as spaces endowed with a metric, characterized by a weighting matrix used to compute distances. Many problems in robotics can be formulated with such a smoothly varying matrix $\bm{G}(\bm{x})$ that can for example be used to evaluate displacements $\Delta\bm{x}$ as a quadratic error term $c(\Delta\bm{x})=\Delta\bm{x}^\trsp\bm{G}(\bm{x})\Delta\bm{x}$, forming a Riemannian metric that describes the underlying manifold (with non-homogeneous curvature). This weighting matrix can for example represent levels of kinetic energy or stiffness gains to model varying impedance behaviors. Computation is often more costly for these manifolds with nonconstant curvature, because it typically requires iterative algorithms instead of the direct analytic expressions typically provided by homogeneous manifolds. 
 
-Figure \ref{fig:nonhomogeneousManifolds} presents two robotics examples exploiting non-homogeneous Riemannian manifolds.
+Figures \ref{fig:intrinsicGeom_vs_extrinsicGeom} and \ref{fig:nonhomogeneousManifolds} presents examples exploiting non-homogeneous Riemannian manifolds.
 
 
 \newpage
diff --git a/julia/IK.jl b/julia/IK.jl
index 44441b0d845d8509254ec7b5821b1eb82b682714..0032bf315511cba64263e4413df5950b03860239 100644
--- a/julia/IK.jl
+++ b/julia/IK.jl
@@ -4,7 +4,7 @@
 ## Written by Sylvain Calinon <https://calinon.ch>
 ## 
 ## This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-## License: MIT
+## License: GPL-3.0-only
 
 using LinearAlgebra,Plots
 
diff --git a/julia/iLQR_manipulator.jl b/julia/iLQR_manipulator.jl
index 82f906965d6d0ea70f898c51999bed879d67e9e9..1825710f0f034078628bd70b9773e2f510ef165d 100644
--- a/julia/iLQR_manipulator.jl
+++ b/julia/iLQR_manipulator.jl
@@ -5,7 +5,7 @@
 ## Sylvain Calinon <https://calinon.ch>
 ## 
 ## This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-## License: MIT
+## License: GPL-3.0-only
 
 using LinearAlgebra #,Plots
 using Parameters
diff --git a/matlab/FD.m b/matlab/FD.m
index 2974df685d0967de0084fa2d634a8c93a139e25e..614d8605f5b6bd9d6b6fd6b866569dcd7896bc38 100644
--- a/matlab/FD.m
+++ b/matlab/FD.m
@@ -5,7 +5,7 @@
 %% Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function FD
 
diff --git a/matlab/IK_manipulator.m b/matlab/IK_manipulator.m
index 2554d91603f476cb61fe262194f3e62dc64d75ce..db97e5173f69e6cf5ebad9f13d72a26b8eb64f6b 100644
--- a/matlab/IK_manipulator.m
+++ b/matlab/IK_manipulator.m
@@ -4,9 +4,9 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
-function IK
+function IK_manipulator
 
 %% Parameters
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
diff --git a/matlab/IK_nullspace.m b/matlab/IK_nullspace.m
index 125d08e67cdda4d3da0c8f4971b79c781ee1eeaf..4e2a478b4d5b715e470126dc3c81e082f110b8fd 100644
--- a/matlab/IK_nullspace.m
+++ b/matlab/IK_nullspace.m
@@ -6,7 +6,7 @@
 %% Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function IK_nullspace
 
diff --git a/matlab/IK_num.m b/matlab/IK_num.m
index 9c1f6f1a1c134361a10cbab9891ed55e639460cc..4eb551973cbd214c4d4cdadcd714c8c5e060d161 100644
--- a/matlab/IK_num.m
+++ b/matlab/IK_num.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function IK_num
 
diff --git a/matlab/LQR_infHor.m b/matlab/LQR_infHor.m
index b980493f61e05f728c032743a48bdb1e2e00c386..6604df34f29a7895993116cd5d8cc1f324f0158a 100644
--- a/matlab/LQR_infHor.m
+++ b/matlab/LQR_infHor.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQR_infHor
 
diff --git a/matlab/LQT.m b/matlab/LQT.m
index 000c73cb3d664e0f85840f70252e4b36c0fe191a..8f56e6e67b2cf7f418c5a59bd816184b4f9fb79c 100644
--- a/matlab/LQT.m
+++ b/matlab/LQT.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT
 
@@ -16,7 +16,7 @@ param.nbVarPos = 2; %Dimension of position data (here: x1,x2)
 param.nbDeriv = 2; %Number of static and dynamic features (nbDeriv=2 for [x,dx] and u=ddx)
 param.nbVar = param.nbVarPos * param.nbDeriv; %Dimension of state vector
 param.dt = 1E-2; %Time step duration
-param.r = 1E-12; %Control cost in LQR (for other cases)
+param.r = 1E-8; %Control cost in LQR (for other cases)
 
 %Task setting (viapoints passing)
 Mu = [rand(param.nbVarPos, param.nbPoints) - 0.5; zeros(param.nbVar-param.nbVarPos, param.nbPoints)]; %Viapoints
@@ -25,8 +25,11 @@ Mu = [rand(param.nbVarPos, param.nbPoints) - 0.5; zeros(param.nbVar-param.nbVarP
 Q = kron(eye(param.nbPoints), diag([ones(1,param.nbVarPos) * 1E0, zeros(1,param.nbVar-param.nbVarPos)])); %Precision matrix (for position only)
 
 R = speye((param.nbData-1)*param.nbVarPos) * param.r; %Standard control weight matrix (at trajectory level)
+
+%Control weight matrix as transition matrix to encourage smoothness 
+%(using this weight matrix with nbDeriv=1 gives the same result as a standard diagonal control weight matrix with nbDeriv=2)
 %e = ones(param.nbData-1,1) * param.r;
-%R = kron(spdiags([-e 2*e -e], -1:1, param.nbData-1, param.nbData-1), speye(param.nbVarPos)); %Control weight matrix as transition matrix to encourage smoothness
+%R = kron(spdiags([-e 2*e -e], -1:1, param.nbData-1, param.nbData-1), speye(param.nbVarPos)); 
 
 %Time occurrence of viapoints
 tl = linspace(1, param.nbData, param.nbPoints+1);
diff --git a/matlab/LQT_CP.m b/matlab/LQT_CP.m
index b088538505564bfbabf5fad653b8c0f202706b99..9dac5cd88232cd87943ad42032969616bf6aa7c5 100644
--- a/matlab/LQT_CP.m
+++ b/matlab/LQT_CP.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_CP
 
diff --git a/matlab/LQT_CP_DMP.m b/matlab/LQT_CP_DMP.m
index 1866455c5140bf46e75a5ef91e8e9a9549ed22c1..4610d22f8d08002c6480eeb549c00c97cc7d66a5 100644
--- a/matlab/LQT_CP_DMP.m
+++ b/matlab/LQT_CP_DMP.m
@@ -6,7 +6,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_CP_DMP
 
diff --git a/matlab/LQT_nullspace.m b/matlab/LQT_nullspace.m
index c98be1e621c7ee3805e6e966b4fc0c11e7ff18ea..30621ad62f2c4d90f2d4b87b577b70df179b6313 100644
--- a/matlab/LQT_nullspace.m
+++ b/matlab/LQT_nullspace.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_nullspace
 
diff --git a/matlab/LQT_recursive.m b/matlab/LQT_recursive.m
index 9f2ef3e4c22bd8dc0103dfca06e537f48c179c0f..0eaf800a7b0322f61190bc2a7de9458b66dbf516 100644
--- a/matlab/LQT_recursive.m
+++ b/matlab/LQT_recursive.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_recursive
 
diff --git a/matlab/LQT_recursive_LS.m b/matlab/LQT_recursive_LS.m
index ebd8993fcef9b2eaec1d0bd14ef46f8d99b952c5..10aa4230c2aec5d8e23e6d59bc6939a24ef584b9 100644
--- a/matlab/LQT_recursive_LS.m
+++ b/matlab/LQT_recursive_LS.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_recursive_LS
 
diff --git a/matlab/LQT_recursive_LS_multiAgents.m b/matlab/LQT_recursive_LS_multiAgents.m
index 914fa47372dc070295b6d4d18d8e57311ec6acb0..b0d53f684d4b5da277c8c86e674144852bf6719b 100644
--- a/matlab/LQT_recursive_LS_multiAgents.m
+++ b/matlab/LQT_recursive_LS_multiAgents.m
@@ -7,7 +7,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_recursive_LS_multiAgents
 
diff --git a/matlab/LQT_tennisServe.m b/matlab/LQT_tennisServe.m
index 5c2a51a1a61fcdcd2db4786d5b9dd4ed16723a61..de716b29eaf60ae8d36739099aebb463cdb78f4b 100644
--- a/matlab/LQT_tennisServe.m
+++ b/matlab/LQT_tennisServe.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function LQT_tennisServe
 
diff --git a/matlab/MP.m b/matlab/MP.m
index 8ae061501e2b95899104541f6131699f941d4bfe..8d83b5d9e3fe3b40c0b6dfe9f91caeeb8b3286fc 100644
--- a/matlab/MP.m
+++ b/matlab/MP.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function MP
 
diff --git a/matlab/ergodic_control_SMC.m b/matlab/ergodic_control_SMC_2D.m
similarity index 65%
rename from matlab/ergodic_control_SMC.m
rename to matlab/ergodic_control_SMC_2D.m
index 00b6b06522209fea5f3f33d104fb55c0c7df3eab..4dd7ff8dcc2c3864282570e897187d0250abb591 100644
--- a/matlab/ergodic_control_SMC.m
+++ b/matlab/ergodic_control_SMC_2D.m
@@ -1,4 +1,4 @@
-function ergodic_control_SMC
+function ergodic_control_SMC_2D
 %% 2D ergodic control formulated as Spectral Multiscale Coverage (SMC) objective,
 %% with a spatial distribution described as a mixture of Gaussians.
 %% 
@@ -6,22 +6,23 @@ function ergodic_control_SMC
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://rcfs.ch>
-%% License: MIT
+%% License: GPL-3.0-only
 
 
 %% Parameters
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 nbData = 200; %Number of datapoints
-nbFct = 10; %Number of basis functions along x and y
+nbFct = 8; %Number of basis functions along x and y
 nbVar = 2; %Dimension of datapoint
 nbGaussian = 2; %Number of Gaussians to represent the spatial distribution
-nbRes = 100;
+nbRes = 40;
 sp = (nbVar + 1) / 2; %Sobolev norm parameter
 dt = 1E-2; %Time step
 xlim = [0; 1]; %Domain limit for each dimension (considered to be 1 for each dimension in this implementation)
 L = (xlim(2) - xlim(1)) * 2; %Size of [-xlim(2),xlim(2)]
 om = 2 * pi / L; %om parameter
-u_max = 1E1; %Maximum speed allowed 
+u_max = 4E0; %Maximum speed allowed 
+u_norm_reg = 1E-3; %Regularizer to avoid numerical issues when speed is close to zero
 
 %Desired spatial distribution represented as a mixture of Gaussians (GMM)
 Mu(:,1) = [.5; .7]; 
@@ -29,7 +30,7 @@ Sigma(:,:,1) = [.3;.1]*[.3;.1]' *5E-1 + eye(nbVar)*5E-3; %eye(nbVar).*1E-2;
 Mu(:,2) =  [.6; .3]; 
 Sigma(:,:,2) = [.1;.2]*[.1;.2]' *3E-1 + eye(nbVar)*1E-2;
 
-Alpha = ones(1,nbGaussian) / nbGaussian; %Mixing coefficients
+Priors = ones(1,nbGaussian) / nbGaussian; %Mixing coefficients
 
 
 %% Compute Fourier series coefficients phi_k of desired spatial distribution
@@ -49,7 +50,7 @@ for j=1:nbGaussian
 	for n=1:size(op,2)
 		MuTmp = diag(op(:,n)) * Mu(:,j); %Eq.(20)
 		SigmaTmp = diag(op(:,n)) * Sigma(:,:,j) * diag(op(:,n))'; %Eq.(20)
-		w_hat = w_hat + Alpha(j) * cos(kk' * MuTmp) .* exp(diag(-.5 * kk' * SigmaTmp * kk)); %Eq.(21)
+		w_hat = w_hat + Priors(j) * cos(kk' * MuTmp) .* exp(diag(-.5 * kk' * SigmaTmp * kk)); %Eq.(21)
 	end
 end
 w_hat = w_hat / L^nbVar / size(op,2);
@@ -59,8 +60,9 @@ w_hat = w_hat / L^nbVar / size(op,2);
 % xm1d = linspace(xlim(1), xlim(2), nbRes); %Spatial range for 1D
 % [xm(1,:,:), xm(2,:,:)] = ndgrid(xm1d, xm1d); %Spatial range
 % g = zeros(1,nbRes^nbVar);
-% for k=1:nbStates
-% 	g = g + Priors(k) * mvnpdf(xm(:,:)', Mu(:,k)', Sigma(:,:,k))'; %Spatial distribution
+% for k=1:nbGaussian
+%	%Spatial distribution (you can call pkg('load','statistics') in octave if the package is missing)
+% 	g = g + Priors(k) * mvnpdf(xm(:,:)', Mu(:,k)', Sigma(:,:,k))'; 
 % end
 % phi_inv = cos(KX(1,:)' * xm(1,:) * om) .* cos(KX(2,:)' * xm(2,:) * om) / L^nbVar / nbRes^nbVar;
 % w_hat = phi_inv * g'; %Fourier coefficients of spatial distribution
@@ -68,7 +70,7 @@ w_hat = w_hat / L^nbVar / size(op,2);
 %Fourier basis functions (for a discretized map)
 xm1d = linspace(xlim(1), xlim(2), nbRes); %Spatial range for 1D
 [xm(1,:,:), xm(2,:,:)] = ndgrid(xm1d, xm1d); %Spatial range
-phim = cos(KX(1,:)' * xm(1,:) .* om) .* cos(KX(2,:)' * xm(2,:) * om) * 2^nbVar; %Fourier basis functions
+phim = cos(KX(1,:)' * xm(1,:) * om) .* cos(KX(2,:)' * xm(2,:) * om) * 2^nbVar; %Fourier basis functions
 
 [xx, yy] = ndgrid(1:nbFct, 1:nbFct);
 hk = [1; 2*ones(nbFct-1,1)];
@@ -81,53 +83,63 @@ g = w_hat' * phim;
 
 %% Ergodic control 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-x = [.1; .3]; %Initial position
+x = [.1; .1]; %Initial position
 wt = zeros(nbFct^nbVar, 1);
 for t=1:nbData
 	r.x(:,t) = x; %Log data
 	
 	%Fourier basis functions and derivatives for each dimension (only cosine part on [0,L/2] is computed since the signal is even and real by construction) 
-	phi1 = cos(x * rg * om); %Eq.(18)
-	dphi1 = -sin(x * rg * om) .* repmat(rg,nbVar,1) * om;
+	phi1 = cos(x * rg*om) / L; 
+	dphi1 = -sin(x * rg*om) .* repmat(rg*om,nbVar,1) / L;
 	
-	dphi = [dphi1(1,xx) .* phi1(2,yy); phi1(1,xx) .* dphi1(2,yy)]; %Gradient of basis functions
-	wt = wt + (phi1(1,xx) .* phi1(2,yy))' / L^nbVar;	%wt./t are the Fourier series coefficients along trajectory (Eq.(17))
+	phi = (phi1(1,xx) .* phi1(2,yy))';
+	dphi = [dphi1(1,xx) .* phi1(2,yy); phi1(1,xx) .* dphi1(2,yy)]'; %Gradient of basis functions
+	wt = wt + phi;	 
+	w = wt / t; %w are the Fourier series coefficients along trajectory
 
 	%Controller with constrained velocity norm
-	u = -dphi * (Lambda .* (wt/t - w_hat)); %Eq.(24)
-	u = u * u_max / (norm(u)+1E-1); %Velocity command
-	
+	u = -dphi' * diag(Lambda) * (w - w_hat); 
+	u = u * u_max / (norm(u) + u_norm_reg); %Velocity command
 	x = x + u * dt; %Update of position
-	r.g(:,t) = (wt/t)' * phim; %Reconstructed spatial distribution (for visualization)
-	r.w(:,t) = wt/t; %Fourier coefficients along trajectory (for visualization)
-% 	r.e(t) = sum(sum((wt./t - w_hat).^2 .* Lambda)); %Reconstruction error evaluation
+	
+	r.g(:,t) = phim' * w; %Reconstructed spatial distribution (for visualization)
+	r.w(:,t) = w; %Fourier coefficients along trajectory (for visualization)
+% 	r.e(t) = sum(sum((w-w_hat).^2 .* Lambda)); %Reconstruction error evaluation
 end
 
 % Plot 
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 h = figure('position',[10,10,1800,600]); 
-colormap(repmat(linspace(1,.4,64),3,1)');
 
 %x
-subplot(1,3,1); hold on; axis off; title('Path generated by ergodic control','fontsize',20);
+ax(1) = subplot(1,3,1); hold on; axis off; title('Path generated by ergodic control','fontsize',20);
+clrmp = repmat(linspace(1,.4,64),3,1)';
+clrmp(:,1) = linspace(1,.8,64);
+colormap(ax(1), clrmp);
 G = reshape(g,[nbRes,nbRes]); % original spatial distribution
 % G = reshape(r.g(:,end),[nbRes,nbRes]); % reconstructed spatial distribution
-G([1,end],:) = max(g); %Add vertical image borders
-G(:,[1,end]) = max(g); %Add horizontal image borders
+%G([1,end],:) = max(g); %Add vertical image borders
+%G(:,[1,end]) = max(g); %Add horizontal image borders
 surface(squeeze(xm(1,:,:)), squeeze(xm(2,:,:)), zeros([nbRes,nbRes]), G, 'FaceColor','interp','EdgeColor','interp');
 % surface(squeeze(xm(1,:,:)), squeeze(xm(2,:,:)), zeros([nbRes,nbRes]), reshape(r.g(:,end),[nbRes,nbRes]), 'FaceColor','interp','EdgeColor','interp');
 plot(r.x(1,:), r.x(2,:), '-','linewidth',1,'color',[0 0 0]);
 plot(r.x(1,1), r.x(2,1), '.','markersize',15,'color',[0 0 0]);
 axis([xlim(1),xlim(2),xlim(1),xlim(2)]); axis equal;
 
-%w
-subplot(1,3,2); hold on; axis off; title('Reproduced weights','fontsize',20);
-imagesc(reshape(wt./t,[nbFct,nbFct]));
-axis tight; axis equal; axis ij;
-
 %w_hat
-subplot(1,3,3); hold on; axis off; title('Desired weights','fontsize',20);
+ax(2) = subplot(1,3,2); hold on; axis off; title('Desired Fourier coefficients ŵ','fontsize',20);
+colormap(ax(2), repmat(linspace(1,.4,64),3,1)');
 imagesc(reshape(w_hat,nbFct,nbFct));
+msh = [0,0,1,1,0;0,1,1,0,0]*nbFct+0.5;
+plot(msh(1,:),msh(2,:),'-','linewidth',4,'color',[.8 0 0]);
+axis tight; axis equal; axis ij;
+
+%w
+ax(3) = subplot(1,3,3); hold on; axis off; title('Reproduced Fourier coefficients w','fontsize',20);
+colormap(ax(3), repmat(linspace(1,.4,64),3,1)');
+imagesc(reshape(w,[nbFct,nbFct]));
+msh = [0,0,1,1,0;0,1,1,0,0]*nbFct+0.5;
+plot(msh(1,:),msh(2,:),'-','linewidth',4,'color',[0 0 0]);
 axis tight; axis equal; axis ij;
 
 waitfor(h);
diff --git a/matlab/ergodic_control_SMC_DDP_1D.m b/matlab/ergodic_control_SMC_DDP_1D.m
new file mode 100644
index 0000000000000000000000000000000000000000..970f0e49e7d44ee6156f43fa34b521ff36bd2c03
--- /dev/null
+++ b/matlab/ergodic_control_SMC_DDP_1D.m
@@ -0,0 +1,207 @@
+%% Trajectory optimization for ergodic control problem solved with iLQR
+%% Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch>
+%% Written by Sylvain Calinon <https://calinon.ch>
+%% 
+%% This file is part of RCFS <https://rcfs.ch>
+%% License: GPL-3.0-only
+
+function ergodic_control_SMC_DDP_1D
+
+%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param.nbData = 200; %Number of datapoints in the trajectory
+param.nbVarX = 1; %State space dimension (here: x1)
+param.nbFct = 8; %Number of Fourier basis functions
+param.nbStates = 2; %Number of Gaussians to represent the spatial distribution
+param.nbIter = 500; %Maximum number of iteration for the Gauss-Newton optimization process
+param.dt = 1E-2; %Time step
+param.r = 1E-12; %Control weight term
+
+param.xlim = [0; 1]; %Domain limit 
+param.L = (param.xlim(2) - param.xlim(1)) * 2; %Size of [-param.xlim(2),param.xlim(2)]
+param.om = 2 * pi / param.L; %omega
+param.rg = [0:param.nbFct-1]';
+param.kk = param.rg .* param.om;
+param.Lambda = (param.rg.^2 + 1).^-1; %Weighting vector 
+
+%Desired spatial distribution represented as a mixture of Gaussians
+param.Mu(:,1) = 0.7 *1; % Mean Gaussian 1
+param.Sigma(:,1) = 0.003; % STD Gaussian 1
+param.Mu(:,2) = 0.5; % Mean Gaussian 2
+param.Sigma(:,2) = 0.01; % STD Gaussian 2
+
+Priors = ones(1,param.nbStates) ./ param.nbStates; %Mixing coefficients
+
+%Transfer matrices (for linear system as single integrator)
+Su = [zeros(param.nbVarX, param.nbVarX*(param.nbData-1)); tril(kron(ones(param.nbData-1), eye(param.nbVarX)*param.dt))];
+Sx = kron(ones(param.nbData,1), eye(param.nbVarX));
+
+Q = diag(param.Lambda); %Precision matrix
+R = speye((param.nbData-1)*param.nbVarX) * param.r; %Control weight matrix (at trajectory level)
+
+
+%% Compute Fourier series coefficients w_hat of desired spatial distribution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%Explicit description of w_hat by exploiting the Fourier transform properties of Gaussians (optimized version by exploiting symmetries)
+w_hat = zeros(param.nbFct,1);
+for j=1:param.nbStates
+	w_hat = w_hat + Priors(j) .* cos(param.kk .* param.Mu(:,j)) .* exp(-.5 .* param.kk.^2 .* param.Sigma(:,j)); 
+end
+w_hat = w_hat ./ param.L;
+
+%Fourier basis functions (only used for display as a discretized map)
+nbRes = 200;
+xm = linspace(param.xlim(1), param.xlim(2), nbRes); %Spatial range
+phim = cos(param.kk * xm) .* 2; %Fourier basis functions
+phim(2:end,:) = phim(2:end,:) .* 2;
+
+%Desired spatial distribution 
+g = phim' * w_hat;
+
+
+%%% Myopic ergodic control (for initialization)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%u_max = 4E0; %Maximum speed allowed 
+%xt = 0.6; %Initial position
+%wt = zeros(param.nbFct, 1);
+%u = zeros(param.nbVarX*(param.nbData-1),1); %Initial control commands
+%for t=1:param.nbData-1
+%	%Fourier basis functions and derivatives for each dimension (only cosine part on [0,L/2] is computed since the signal is even and real by construction) 
+%	phi = cos(xt * param.kk) / param.L; 
+%	dphi = -sin(xt * param.kk) .* param.kk / param.L;
+
+%	wt = wt + phi;
+%	w = wt / t; %w are the Fourier series coefficients along trajectory 
+
+%%	%Controller with ridge regression formulation
+%%	u(t) = -dphi' * diag(param.Lambda) * (w - w_hat) * t * 1E0; %Velocity command
+%	
+%	%Controller with constrained velocity norm
+%	u(t) = -dphi' * diag(param.Lambda) * (w - w_hat); 
+%	u(t) = sign(u(t)) * u_max; %Velocity command
+%		
+%	xt = xt + u(t) * param.dt; %Update of position
+%end
+
+
+%% Ergodic control as trajectory planning problem
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+u = zeros(param.nbVarX*(param.nbData-1),1); %Initial control commands
+u = cos(linspace(0, 4*pi, param.nbData-1))' * 0.4; %Initial control commands
+#u = u + randn(param.nbVarX*(param.nbData-1),1) * 1E0;
+
+x0 = 0.6; %Initial position
+for n=1:param.nbIter
+	x = Sx * x0 + Su * u; %System evolution
+	
+	[w, J] = f_ergodic(x, param); %Fourier series coefficients and Jacobian
+	f = w - w_hat; %Residuals
+	
+	du = (Su' * J' * Q * J * Su + R) \ (-Su' * J' * Q * f - u * param.r); %Gauss-Newton update	
+	
+	cost0 = f' * Q * f + norm(u)^2 * param.r; %Cost
+	
+	%Log data
+	r.x(:,n) = x; %Save trajectory in state space
+	r.w(:,n) = w; %Save Fourier coefficients along trajectory
+	r.g(:,n) = phim' * w; %Save reconstructed spatial distribution (for visualization)
+	r.e(n) = cost0; %Save reconstruction error 
+	
+	%Estimate step size with backtracking line search method
+	alpha = 1;
+	while 1
+		utmp = u + du * alpha;
+		xtmp = Sx * x0 + Su * utmp; %System evolution
+		wtmp = f_ergodic(xtmp, param); %Fourier series coefficients and Jacobian
+		ftmp = wtmp - w_hat; %Residuals
+		cost = ftmp' * Q * ftmp + norm(utmp)^2 * param.r; %Cost
+		if cost < cost0 || alpha < 1E-3
+			break;
+		end
+		alpha = alpha * 0.5;
+	end
+
+	u = u + du * alpha; %Update control commands
+	
+	if norm(du * alpha) < 1E-1
+		break; %Stop iLQR when solution is reached
+	end
+end
+disp(['iLQR converged in ' num2str(n) ' iterations.']);
+
+
+%% Plot (static)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%s = param.nbData; %Reconstruction at time step s
+%T = param.nbData; %Size of time window
+hf = figure('position',[10,10,2200,1200],'color',[1 1 1]); 
+
+%Plot distribution
+subplot(3,2,1); hold on; 
+h(1) = plot(xm, g, '-','linewidth',6,'color',[1 .6 .6]);
+h(2) = plot(xm, r.g(:,1), '-','linewidth',2,'color',[.7 .7 .7]);
+h(3) = plot(xm, r.g(:,end), '-','linewidth',2,'color',[0 0 0]);
+% plot(xm, (r.g(:,s)-r.g(:,s-1)).*1E2, '-','linewiparam.dth',3,'color',[0 0 .8]); %Plot increment (scaled)
+legend(h,{'Desired','Initial','Final'},'fontsize',18,'location','northwest');
+axis([param.xlim', -.3, max(g)*1.2]);
+set(gca,'xtick',[],'ytick',[],'linewidth',2);
+xlabel('x','fontsize',28); 
+ylabel('Spatial distribution g(x)','fontsize',28);  
+
+%Plot signal
+subplot(3,2,[3,5]); hold on; box on;
+for n=1:10:size(r.x,2)
+	plot(r.x(:,n), 1:param.nbData, '-','linewidth',3,'color',[.9 .9 .9]*(1-n/param.nbIter));
+end
+plot(r.x(:,end), 1:param.nbData, '-','linewidth',3,'color',[0 0 0]);
+plot(r.x(end,end), param.nbData, '.','markersize',28,'color',[0 0 0]);
+axis([param.xlim', 1, param.nbData]);
+set(gca,'linewidth',2,'xtick',[],'ytick',[1,param.nbData],'yticklabel',{'t-T','t'},'fontsize',24);
+xlabel('x','fontsize',28);  
+
+%Plot Fourier coefficients
+subplot(3,2,2); hold on; 
+plot(param.rg, zeros(param.nbFct,1), '-','linewidth',1,'color',[0 0 0]);
+plot(param.rg, w_hat, '.','markersize',28,'color',[1 .6 .6]);
+for n=1:param.nbFct
+	plot([param.rg(n), param.rg(n)], [0, w_hat(n)], '-','linewidth',6,'color',[1 .6 .6]);
+end
+plot(param.rg, r.w(:,end), '.','markersize',18,'color',[0 0 0]);
+for n=1:param.nbFct
+	plot([param.rg(n), param.rg(n)], [0, r.w(n,end)], '-','linewidth',2,'color',[0 0 0]);
+end
+% plot(rg, (r.w(:,s)-r.w(:,s-1)).*1E2, 'o','linewiparam.dth',2,'markersize',7,'color',[0 0 .8]); %Plot increment (scaled)
+axis([0, param.nbFct-1, min(w_hat)-5E-2, max(w_hat)+5E-2]);
+set(gca,'xtick',[0:param.nbFct-1],'ytick',[],'linewidth',2,'fontsize',20);
+xlabel('k','fontsize',28);
+ylabel('Fourier coefficients w_k','fontsize',28); 
+
+%Plot Lambda_k
+subplot(3,2,4); hold on; 
+plot(param.rg, param.Lambda, '-','linewidth',2,'color',[0 0 0]);
+plot(param.rg, param.Lambda, '.','markersize',18,'color',[0 0 0]);
+axis([0, param.nbFct-1, min(param.Lambda)-5E-2, max(param.Lambda)+5E-2]);
+set(gca,'xtick',[0:param.nbFct-1],'ytick',[0,1],'linewidth',2,'fontsize',20);
+xlabel('k','fontsize',28);
+ylabel('\Lambda_k','fontsize',28);
+
+%Plot error
+subplot(3,2,6); hold on; 
+plot(r.e(1:end),'-','linewidth',2,'color',[0 0 0]);
+axis([1, length(r.e), 0, max(r.e)]);
+set(gca,'linewidth',2,'fontsize',20);
+xlabel('n','fontsize',28);   
+ylabel('Cost \epsilon','fontsize',28);   
+
+waitfor(hf);
+close all;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+% Fourier series coefficients and Jacobian
+function [w, J] = f_ergodic(x, param)
+	phi = cos(x * param.kk') / param.L; %Fourier basis functions
+	dphi = -sin(x * param.kk') .* repmat(param.kk',param.nbData,1) / param.L; %Gradient of Fourier basis functions
+	w = sum(phi)' / param.nbData; %Fourier coefficients along trajectory
+	J = dphi' / param.nbData; %Jacobian
+end
diff --git a/matlab/ergodic_control_SMC_DDP_2D.m b/matlab/ergodic_control_SMC_DDP_2D.m
new file mode 100644
index 0000000000000000000000000000000000000000..baba4a89772a5a301826d59c8b3f541eb205db30
--- /dev/null
+++ b/matlab/ergodic_control_SMC_DDP_2D.m
@@ -0,0 +1,221 @@
+%% Trajectory optimization for ergodic control problem solved with iLQR
+%% Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch>
+%% Written by Sylvain Calinon <https://calinon.ch>
+%% 
+%% This file is part of RCFS <https://rcfs.ch>
+%% License: GPL-3.0-only
+
+function ergodic_control_SMC_DDP_2D
+
+%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param.nbData = 200; %Number of datapoints in the trajectory
+param.nbVarX = 2; %State space dimension (here: x1,x2)
+param.nbFct = 8; %Number of Fourier basis functions
+param.nbStates = 2; %Number of Gaussians to represent the spatial distribution
+param.nbIter = 50; %Maximum number of iteration for the Gauss-Newton optimization process
+param.dt = 1E-2; %Time step
+param.r = 1E-8; %Control weight term
+
+param.xlim = [0; 1]; %Domain limit 
+param.L = (param.xlim(2) - param.xlim(1)) * 2; %Size of [-param.xlim(2),param.xlim(2)]
+param.om = 2 * pi / param.L; %omega
+param.rg = [0:param.nbFct-1]';
+param.kk1 = param.rg * param.om; %for 1D
+
+[xx, yy] = ndgrid(1:param.nbFct, 1:param.nbFct);
+[KX(1,:,:), KX(2,:,:)] = ndgrid(param.rg, param.rg);
+sp = (param.nbVarX + 1) / 2; %Sobolev norm parameter
+param.Lambda = (KX(1,:).^2 + KX(2,:).^2 + 1)'.^-sp; %Weighting vector 
+
+%Enumerate symmetry operations for 2D signal ([-1,-1],[-1,1],[1,-1] and [1,1]), and removing redundant ones -> keeping ([-1,-1],[-1,1])
+op = hadamard(2^(param.nbVarX-1));
+op = op(1:param.nbVarX,:);
+param.kk = KX(:,:) * param.om; %for 2D
+
+%Desired spatial distribution represented as a mixture of Gaussians
+param.Mu(:,1) = [.5; .7]; 
+param.Sigma(:,:,1) = [.3;.1]*[.3;.1]' *5E-1 + eye(param.nbVarX)*5E-3; 
+param.Mu(:,2) =  [.6; .3]; 
+param.Sigma(:,:,2) = [.1;.2]*[.1;.2]' *3E-1 + eye(param.nbVarX)*1E-2; 
+Priors = ones(1,param.nbStates) ./ param.nbStates; %Mixing coefficients
+
+%Transfer matrices (for linear system as single integrator)
+Su = [zeros(param.nbVarX, param.nbVarX*(param.nbData-1)); tril(kron(ones(param.nbData-1), eye(param.nbVarX)*param.dt))];
+Sx = kron(ones(param.nbData,1), eye(param.nbVarX));
+
+Q = diag(param.Lambda); %Precision matrix
+R = speye((param.nbData-1)*param.nbVarX) * param.r; %Control weight matrix (at trajectory level)
+
+
+%% Compute Fourier series coefficients phi_k of desired spatial distribution
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%Compute phi_k by exploiting the Fourier transform properties of Gaussians (optimized version by exploiting symmetries)
+w_hat = zeros(param.nbFct^param.nbVarX, 1);
+for j=1:param.nbStates
+	for n=1:size(op,2)
+		MuTmp = diag(op(:,n)) * param.Mu(:,j); 
+		SigmaTmp = diag(op(:,n)) * param.Sigma(:,:,j) * diag(op(:,n))';
+		w_hat = w_hat + Priors(j) .* cos(param.kk' * MuTmp) .* exp(diag(-.5 * param.kk' * SigmaTmp * param.kk));
+	end
+end
+w_hat = w_hat / param.L^param.nbVarX / size(op,2);
+
+%Fourier basis functions (for the display of a discretized map)
+nbRes = 40;
+xm1d = linspace(param.xlim(1), param.xlim(2), nbRes); %Spatial range for 1D
+[xm(1,:,:), xm(2,:,:)] = ndgrid(xm1d, xm1d); %Spatial range
+phim = cos(KX(1,:)' * xm(1,:) * param.om) .* cos(KX(2,:)' * xm(2,:) * param.om) * 2^param.nbVarX; %Fourier basis functions
+hk = [1; 2*ones(param.nbFct-1,1)];
+HK = hk(xx(:)) .* hk(yy(:)); 
+phim = phim .* repmat(HK,[1,nbRes^param.nbVarX]);
+
+%Desired spatial distribution 
+g = w_hat' * phim;
+
+
+%% Myopic ergodic control (for initialization)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+u_max = 4E0; %Maximum speed allowed 
+u_norm_reg = 1E-3;
+xt = [0.1; 0.1]; %Initial position
+wt = zeros(param.nbFct^param.nbVarX, 1);
+u = zeros(param.nbVarX, param.nbData-1); %Initial control commands
+for t=1:param.nbData-1
+	%Fourier basis functions and derivatives for each dimension 
+	phi1 = cos(xt * param.kk1') / param.L; %In 1D
+	dphi1 = -sin(xt * param.kk1') .* repmat(param.kk1',param.nbVarX,1) / param.L; %In 1D
+	
+	phi = (phi1(1,xx) .* phi1(2,yy))'; %Fourier basis functions
+	dphi = [dphi1(1,xx) .* phi1(2,yy); phi1(1,xx) .* dphi1(2,yy)]'; %Gradient of Fourier basis functions
+	
+	wt = wt + phi;
+	w = wt / t; %w are the Fourier series coefficients along trajectory 
+
+%	%Controller with ridge regression formulation
+%	u(t) = -dphi' * diag(param.Lambda) * (w - w_hat) * t * 1E0; %Velocity command
+	
+	%Controller with constrained velocity norm
+	u(:,t) = -dphi' * diag(param.Lambda) * (w - w_hat); 
+	u(:,t) = u(:,t) * u_max / (norm(u(:,t)) + u_norm_reg); %Velocity command
+		
+	xt = xt + u(:,t) * param.dt; %Update of position
+end
+u = u(:);
+
+
+%% Ergodic control as trajectory planning problem
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x0 = [0.1; 0.1];
+%u = zeros(param.nbVarX*(param.nbData-1),1); %Initial control commands
+%u(1:2:end) = sin(linspace(0, 3.5*pi, param.nbData-1)) * 8E-2 + 2E-2; %Initial control commands
+%u(2:2:end) = sin(linspace(0, 2*pi, param.nbData-1)) * 6E-2 + 4E-2; %Initial control commands
+%u = u + randn(param.nbVarX*(param.nbData-1),1) * 1E0;
+
+for n=1:param.nbIter
+	x = Sx * x0 + Su * u; %System evolution
+	
+	[w, J] = f_ergodic(x, param); %Fourier series coefficients and Jacobian
+	f = w - w_hat; %Residuals
+	
+	du = (Su' * J' * Q * J * Su + R) \ (-Su' * J' * Q * f - u * param.r); %Gauss-Newton update	
+	
+	cost0 = f' * Q * f + norm(u)^2 * param.r; %Cost
+	
+	%Log data
+	r.x(:,n) = x; %Save trajectory in state space
+	r.w(:,n) = w; %Save Fourier coefficients along trajectory
+	r.g(:,n) = w' * phim; %Save reconstructed spatial distribution (for visualization)
+	r.e(n) = cost0; %Save reconstruction error 
+	
+	%Estimate step size with backtracking line search method
+	alpha = 1;
+	while 1
+		utmp = u + du * alpha;
+		xtmp = Sx * x0 + Su * utmp; %System evolution
+		wtmp = f_ergodic(xtmp, param); %Fourier series coefficients and Jacobian
+		ftmp = wtmp - w_hat; %Residuals
+		cost = ftmp' * Q * ftmp + norm(utmp)^2 * param.r; %Cost
+		if cost < cost0 || alpha < 1E-3
+			break;
+		end
+		alpha = alpha * 0.5;
+	end
+
+	u = u + du * alpha; %Update control commands
+	
+	if norm(du * alpha) < 1E0
+		break; %Stop iLQR when solution is reached
+	end
+end
+disp(['iLQR converged in ' num2str(n) ' iterations.']);
+
+
+%% Plot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+hf = figure('position',[10,10,2600,800]); 
+
+%x
+ax(1) = subplot(1,4,1); hold on; axis off; title('Spatial distribution g(x)','fontsize',20);
+clrmp = repmat(linspace(1,.4,64),3,1)';
+clrmp(:,1) = linspace(1,.8,64);
+colormap(ax(1), clrmp);
+surface(squeeze(xm(1,:,:)), squeeze(xm(2,:,:)), zeros([nbRes,nbRes]), reshape(g,[nbRes,nbRes]), 'FaceColor','interp','EdgeColor','interp');
+h(1) = plot(-1,-1,'-','color',[.8 0 0]);
+h(2) = plot(r.x(1:2:end,1), r.x(2:2:end,1), '-','linewidth',2,'color',[.7 .7 .7]);
+h(3) = plot(r.x(1:2:end,end), r.x(2:2:end,end), '-','linewidth',2,'color',[0 0 0]);
+plot(r.x(1,end), r.x(2,end), '.','markersize',15,'color',[0 0 0]);
+axis equal; axis([param.xlim(1),param.xlim(2),param.xlim(1),param.xlim(2)]); 
+legend(h,{'Desired','Initial','Final'},'fontsize',18,'location','northwest');
+
+%w_hat
+ax(2) = subplot(1,4,2); hold on; axis off; title('Desired Fourier coefficients ŵ','fontsize',20);
+colormap(ax(2), repmat(linspace(1,.4,64),3,1)');
+imagesc(reshape(w_hat,param.nbFct,param.nbFct));
+msh = [0,0,1,1,0;0,1,1,0,0]*param.nbFct+0.5;
+plot(msh(1,:),msh(2,:),'-','linewidth',4,'color',[.8 0 0]);
+axis tight; axis equal; axis ij;
+
+%w
+ax(3) = subplot(1,4,3); hold on; axis off; title('Reproduced Fourier coefficients w','fontsize',20);
+colormap(ax(3), repmat(linspace(1,.4,64),3,1)');
+imagesc(reshape(w,[param.nbFct,param.nbFct]));
+plot(msh(1,:),msh(2,:),'-','linewidth',4,'color',[0 0 0]);
+axis tight; axis equal; axis ij;
+
+%Plot error
+subplot(1,4,4); hold on; 
+plot(r.e,'k-');
+axis([1, length(r.e), 0, max(r.e)]);
+xlabel('n','fontsize',28);   
+ylabel('Cost \epsilon','fontsize',28); 
+
+waitfor(hf);
+close all;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+% Fourier series coefficients and Jacobian
+function [w, J] = f_ergodic(x, param)
+	[xx, yy] = ndgrid(1:param.nbFct, 1:param.nbFct);
+	
+	phi1 = [];
+	phi1(:,:,1) = cos(x(1:2:end) * param.kk1') / param.L; %Fourier basis functions
+	phi1(:,:,2) = cos(x(2:2:end) * param.kk1') / param.L; %Fourier basis functions
+	
+	dphi1 = [];
+	dphi1(:,:,1) = -sin(x(1:2:end) * param.kk1') .* repmat(param.kk1',param.nbData,1) / param.L; %Gradient of Fourier basis functions
+	dphi1(:,:,2) = -sin(x(2:2:end) * param.kk1') .* repmat(param.kk1',param.nbData,1) / param.L; %Gradient of Fourier basis functions
+	
+	phi = phi1(:,xx,1) .* phi1(:,yy,2); %Fourier basis functions
+	dphi(1:2:param.nbData*param.nbVarX,:) = dphi1(:,xx,1) .* phi1(:,yy,2); %Gradient of Fourier basis functions
+	dphi(2:2:param.nbData*param.nbVarX,:) = phi1(:,xx,1) .* dphi1(:,yy,2); %Gradient of Fourier basis functions
+	
+%	%Alternative computation of phi (slower)
+%	phi1(:,:,1) = cos(x(1:2:end) * param.kk(1,:)) / param.L; %Fourier basis functions
+%	phi1(:,:,2) = cos(x(2:2:end) * param.kk(2,:)) / param.L; %Fourier basis functions
+%	phi = reshape(phi1(:,:,1) .* phi1(:,:,2), [param.nbData, param.nbFct^param.nbVarX]); %Fourier basis functions
+	
+	w = sum(phi)' / param.nbData; %Fourier coefficients along trajectory
+	J = dphi' / param.nbData; %Jacobian
+end
diff --git a/matlab/iLQR_bicopter.m b/matlab/iLQR_bicopter.m
index 3f50147b19494d0620aca3aa948beec1941d3be9..005e6310a66043c4072eddb7c1a64e22c366884a 100644
--- a/matlab/iLQR_bicopter.m
+++ b/matlab/iLQR_bicopter.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_bicopter
 
diff --git a/matlab/iLQR_bimanual.m b/matlab/iLQR_bimanual.m
index 07604db0375e9edc2d2b63411721319a7316a185..9ec63e82f57580fb512cf1d6bb05ae1d86fce930 100644
--- a/matlab/iLQR_bimanual.m
+++ b/matlab/iLQR_bimanual.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_bimanual
 
diff --git a/matlab/iLQR_bimanual_manipulability.m b/matlab/iLQR_bimanual_manipulability.m
index 1ed2a19fb4b8940d4eb3110d28bf9ebb8868a59d..5b6507ee84c4164f82f6049b394d3a8f124662fc 100644
--- a/matlab/iLQR_bimanual_manipulability.m
+++ b/matlab/iLQR_bimanual_manipulability.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_bimanual_manipulability
 
diff --git a/matlab/iLQR_car.m b/matlab/iLQR_car.m
index 5b9a51a7a9d937f0d7b8b9706bbfaf0285f3e787..ca61eeee8f3261a958d064dad748bc5a14497ae5 100644
--- a/matlab/iLQR_car.m
+++ b/matlab/iLQR_car.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_car
 
diff --git a/matlab/iLQR_curvature.m b/matlab/iLQR_curvature.m
new file mode 100644
index 0000000000000000000000000000000000000000..eb08c07a56a6f3f24b8be3a3142e04c0fb7cda2a
--- /dev/null
+++ b/matlab/iLQR_curvature.m
@@ -0,0 +1,234 @@
+%% Viapoint task for a point-mass system with a cost on curvature
+%% 
+%% Copyright (c) 2024 Idiap Research Institute <https://www.idiap.ch/>
+%% Written by Sylvain Calinon <https://calinon.ch>
+%% 
+%% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+%% License: GPL-3.0-only
+
+function iLQR_curvature
+
+%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param.dt = 1E-2; %Time step size
+param.nbData = 100; %Number of datapoints
+param.nbPoints = 3; %Number of viapoints
+param.nbMinIter = 5; %Minimum number of iterations for iLQR
+param.nbMaxIter = 20; %Maximum number of iterations for iLQR
+param.nbVarPos = 2; %Dimension of position data
+param.nbDeriv = 3; %Number of static and dynamic features (nbDeriv=2 for [x,dx] and u=ddx)
+param.nbVarX = param.nbVarPos * param.nbDeriv; %State space dimension
+param.q = 1E1; %Tracking weight 
+param.qc = 1E-6; %Curvature weight 
+param.r = 1E-9; %Control weight 
+
+idp = [0:param.nbPoints-1]*param.nbVarX + [1:param.nbVarPos]';
+idv = [0:param.nbPoints-1]*param.nbVarX + [param.nbVarPos+1:2*param.nbVarPos]';
+
+%Viapoints
+param.Mu = zeros(param.nbVarX*param.nbPoints,1); 
+%param.Mu(idp(:)) = rand(param.nbVarPos*param.nbPoints,1); 
+param.Mu(idp(:)) = [[1; 1]; [0.5; 0.2]; [0.8; 2]];
+
+%Control weight matrix (at trajectory level)
+R = speye((param.nbData-1) * param.nbVarPos) * param.r; 
+
+%Time occurrence of viapoints
+tl = linspace(1, param.nbData, param.nbPoints+1);
+tl = round(tl(2:end));
+idx = (tl - 1) * param.nbVarX + [1:param.nbVarX]';
+%idPos = (tl - 1) * param.nbVarX + [1:param.nbVarPos]';
+%idVel = (tl - 1) * param.nbVarX + [param.nbVarPos+1:2*param.nbVarPos]';
+
+%Dynamical System settings (discrete version)
+A1d = zeros(param.nbDeriv);
+for i=0:param.nbDeriv-1
+	A1d = A1d + diag(ones(param.nbDeriv-i,1),i) * param.dt^i * 1/factorial(i); %Discrete 1D
+end
+B1d = zeros(param.nbDeriv,1); 
+for i=1:param.nbDeriv
+	B1d(param.nbDeriv-i+1) = param.dt^i * 1/factorial(i); %Discrete 1D
+end
+A = repmat(kron(A1d, eye(param.nbVarPos)), [1 1 param.nbData-1]); %Discrete nD
+B = repmat(kron(B1d, eye(param.nbVarPos)), [1 1 param.nbData-1]); %Discrete nD
+
+[Su0, Sx0] = transferMatrices(A, B); %Constant Su and Sx for the proposed system
+Su = Su0(idx,:);
+
+
+%% Constraining the position of two consecutive keypoints to be same and crossing at given angle -> forming a loop
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%param.Q = eye(param.nbPoints*param.nbVarX);
+
+%Only cares about position part of the state variable
+param.Q = diag(kron(ones(param.nbPoints,1), [ones(param.nbVarPos,1); zeros(param.nbVarX-param.nbVarPos,1)])); 
+
+param.Mu(idp(:,2)) = param.Mu(idp(:,1)); %Viapoints 1 and 2 form the loop
+
+a = pi/2; %desired crossing angle
+V = [cos(a) -sin(a); sin(a) cos(a)]; %rotation matrix
+
+%Impose cost on crossing angle
+param.Q(idv(:,1), idv(:,1)) = eye(param.nbVarPos)*1E0;
+param.Q(idv(:,2), idv(:,2)) = eye(param.nbVarPos)*1E0;
+param.Q(idv(:,1), idv(:,2)) = V; %-eye(nbVarPos)*1E0;
+param.Q(idv(:,2), idv(:,1)) = V'; %-eye(nbVarPos)*1E0;
+
+
+%% iLQR without curvature cost (for initialization)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+x0 = zeros(param.nbVarX,1); %Initial state
+u = zeros(param.nbVarPos*(param.nbData-1), 1); %Initial commands
+
+for n=1:param.nbMaxIter
+	x = reshape(Su0 * u + Sx0 * x0, param.nbVarX, param.nbData); %System evolution
+	[f, J] = f_reach(x(:,tl), param); %Residuals and Jacobians (viapoints tracking objective)
+	du = (Su' * J' * param.Q * J * Su + R) \ (-Su' * J' * param.Q * f - u * param.r); %Update
+	
+	%Estimate step size with backtracking line search method
+	alpha = 1;
+	cost0 = costFct(f, 0, u, param); %Cost
+	while 1
+		utmp = u + du * alpha;
+		xtmp = reshape(Su0 * utmp + Sx0 * x0, param.nbVarX, param.nbData);
+		ftmp = f_reach(xtmp(:,tl), param); %Residuals (viapoints tracking objective)
+		cost = costFct(ftmp, 0, utmp, param); %Cost
+		if cost < cost0 || alpha < 1E-3
+			break;
+		end
+		alpha = alpha * 0.5;
+	end
+	u = u + du * alpha;
+	
+	r(n).x = x; %Log data
+	
+	if norm(du * alpha) < 5E-2 && n>param.nbMinIter
+		break; %Stop iLQR when solution is reached
+	end
+end
+disp(['iLQR converged in ' num2str(n) ' iterations.']);
+
+x1 = x; %Log data
+fc = f_curvature(x, param); %Residuals and Jacobians (motion objective)
+norm(fc(:))^2
+
+
+%% iLQR with curvature cost
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+%x0 = zeros(param.nbVarX,1); %Initial state
+%u = zeros(param.nbVarPos*(param.nbData-1), 1); %Initial commands
+
+for n=1:param.nbMaxIter
+	x = reshape(Su0 * u + Sx0 * x0, param.nbVarX, param.nbData); %System evolution
+	[f, J] = f_reach(x(:,tl), param); %Residuals and Jacobians (viapoints tracking objective)
+	[fc, Jc] = f_curvature(x, param); %Residuals and Jacobians (curvature objective)
+	du = (Su' * J' * param.Q * J * Su + Su0' * Jc' * Jc * Su0 * param.qc + R) \ ...
+	    (-Su' * J' * param.Q * f - Su0' * Jc' * fc(:) * param.qc - u * param.r); %Update
+	
+	%Estimate step size with backtracking line search method
+	alpha = 1;
+	cost0 = costFct(f, fc, u, param); %Cost
+	while 1
+		utmp = u + du * alpha;
+		xtmp = reshape(Su0 * utmp + Sx0 * x0, param.nbVarX, param.nbData);
+		ftmp = f_reach(xtmp(:,tl), param); %Residuals (viapoints tracking objective)
+		fctmp = f_curvature(xtmp, param); %Residuals (curvature objective)
+		cost = costFct(ftmp, fctmp, utmp, param); %Cost
+		if cost < cost0 || alpha < 1E-3
+			break;
+		end
+		alpha = alpha * 0.5;
+	end
+	u = u + du * alpha;
+		
+	if norm(du * alpha) < 5E-2 && n>param.nbMinIter
+		break; %Stop iLQR when solution is reached
+	end
+end
+disp(['iLQR converged in ' num2str(n) ' iterations.']);
+norm(fc(:))^2
+
+
+%% Plot state space
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+h = figure('position',[10,10,600,600],'color',[1,1,1]); hold on; axis off;
+hl(1) = plot(x1(1,:), x1(2,:), '-','linewidth',4,'color',[.7 .7 .7]);
+hl(2) = plot(x(1,:), x(2,:), '-','linewidth',4,'color',[0 0 0]);
+%hl(3) = 
+plot(x(1,1), x(2,1), '.','markersize',30,'color',[0 0 0]);
+%Display curvature information
+%for t=1:param.nbData
+%	v = [x(4,t); -x(3,t)]; %Normal to curve
+%	r = 1 / (fc(t)+1E-12);
+%	 
+%	if abs(r)>1E-2 && abs(r)<0.5
+%		v = -r * v / norm(v);
+%		plot([x(1,t), x(1,t)+v(1)], [x(2,t), x(2,t)+v(2)], '-','color',[0 .6 0]);
+%	end
+%end
+plot(param.Mu(idp(1,:)), param.Mu(idp(2,:)), '.','markersize',30,'color',[.8 0 0]);
+axis equal; 
+legend(hl,{'Without cost on curvature','With cost on curvature'}, 'fontsize',20,'location','southeast'); %,'Viapoints'
+%print('-dpng','graphs/iLQR_curvature01.png');
+
+waitfor(h);
+close all;
+end 
+
+%%%%%%%%%%%%%%%%%%%%%%
+function [Su, Sx] = transferMatrices(A, B)
+	[nbVarX, nbVarU, nbData] = size(B);
+	nbData = nbData+1;
+	Sx = kron(ones(nbData,1), speye(nbVarX)); 
+	Su = sparse(zeros(nbVarX*(nbData-1), nbVarU*(nbData-1)));
+	for t=1:nbData-1
+		id1 = (t-1)*nbVarX+1:t*nbVarX;
+		id2 = t*nbVarX+1:(t+1)*nbVarX;
+		id3 = (t-1)*nbVarU+1:t*nbVarU;
+		Sx(id2,:) = squeeze(A(:,:,t)) * Sx(id1,:);
+		Su(id2,:) = squeeze(A(:,:,t)) * Su(id1,:);	
+		Su(id2,id3) = B(:,:,t);	
+	end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Cost function
+function c = costFct(f, fc, u, param)
+%	c = norm(f(:))^2 * param.q + norm(fc(:))^2 * param.qc + norm(u)^2 * param.r;
+	c = f(:)' * param.Q * f(:) + norm(fc(:))^2 * param.qc + norm(u)^2 * param.r;
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Residuals f and Jacobians J for a viapoints reaching task with point mass system
+function [f, J] = f_reach(x, param)
+	f = x(:) - param.Mu; %Residuals
+	J = eye(param.nbVarX * size(x,2)); %Jacobian
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Residuals f and Jacobians J for curvature minimization over path
+function [f, J] = f_curvature(x, param)
+%	dx = x(:,2:end) - x(:,1:end-1);
+%	l = sum(dx.^2,1).^.5; %Segment lengths
+%	dx0 = dx ./ l; %Unit direction vectors
+%	theta = acos(dx0(:,2:end)' * dx0(:,1:end-1)); %Angles
+
+	ddx = x(2*param.nbVarPos+1:3*param.nbVarPos,:); %Second derivative
+	dx = x(param.nbVarPos+1:2*param.nbVarPos,:); %First derivative
+	dxn = sum(dx.^2,1).^(3/2);
+	f = (dx(1,:) .* ddx(2,:) - dx(2,:) .* ddx(1,:)) ./ (dxn + 1E-8); %Curvature
+	
+	s11 = zeros(param.nbVarX,1); s11(3) = 1; %Selection vector
+	s12 = zeros(param.nbVarX,1); s12(4) = 1; %Selection vector
+	s21 = zeros(param.nbVarX,1); s21(5) = 1; %Selection vector
+	s22 = zeros(param.nbVarX,1); s22(6) = 1; %Selection vector
+	Sa = s11 * s22' - s12 * s21'; %Selection matrix for numerator
+	Sb = s11 * s11' + s12 * s12'; %Selection matrix for denominator
+	J = [];
+	for t=1:param.nbData
+		a = x(:,t)' * Sa * x(:,t);
+		b = x(:,t)' * Sb * x(:,t) + 1E-8; 
+		Jtmp = b^(-3/2) * (Sa + Sa') * x(:,t) - 3 * a * b^(-5/2) * Sb * x(:,t);
+		J = blkdiag(J, Jtmp');
+	end
+end
diff --git a/matlab/iLQR_distMaintenance.m b/matlab/iLQR_distMaintenance.m
index 6c01e1582ffb4b38443d088d4c542e4ddcfc5858..1db55be76006b282ea7554eb057e59276d666a89 100644
--- a/matlab/iLQR_distMaintenance.m
+++ b/matlab/iLQR_distMaintenance.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_distMaintenance
 
@@ -17,9 +17,14 @@ param.nbIter = 100; %Maximum number of iterations for iLQR
 param.nbVarX = 2; %State space dimension (x1,x2)
 param.nbVarU = 2; %Control space dimension (dx1,dx2)
 param.Mu = [1.0; 0.3]; %Object location
-param.dist = .4; %Distance to maintain
+
+%param.dist = .4; %Distance to maintain
+%param.Sigma = eye(param.nbVarX) * param.dist^2; %Covariance matrix
+vtmp = [.8; .8]; %Main axis of covariance matrix
+param.Sigma = vtmp * vtmp' + eye(2) * 2E-2; %Covariance matrix
+
 param.q = 1E0; %Distance maintenance weight term
-param.r = 1E-3; %Control weight term
+param.r = 1E-6; %Control weight term
 
 R = speye((param.nbData-1) * param.nbVarU) * param.r; %Control weight matrix (at trajectory level)
 
@@ -63,13 +68,17 @@ disp(['iLQR converged in ' num2str(n) ' iterations.']);
 
 %% Plot state space
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-al = linspace(-pi, pi, 50);
 h = figure('position',[10,10,800,800],'color',[1,1,1]); hold on; axis off;
-msh = param.dist * [cos(al); sin(al)] + repmat(param.Mu(1:2), 1, 50);
+al = linspace(-pi, pi, 50);
+%msh = param.dist * [cos(al); sin(al)] + repmat(param.Mu(1:2), 1, 50);
+[V,D] = eig(param.Sigma);
+msh = V * D.^.5 * [cos(al); sin(al)] + repmat(param.Mu(1:2), 1, 50);
 patch(msh(1,:), msh(2,:), [1 .8 .8],'linewidth',2,'edgecolor',[.8 .4 .4]);
+
 plot(param.Mu(1), param.Mu(2), '.','markersize',25,'color',[.8 0 0]);
 plot(x(1,:), x(2,:), '-','linewidth',2,'color',[0 0 0]);
-plot(x(1,[1,end]), x(2,[1,end]), '.','markersize',25,'color',[0 0 0]);
+plot(x(1,1), x(2,1), '.','markersize',25,'color',[0 0 0]);
+plot(x(1,end), x(2,end), '.','markersize',25,'color',[0 .6 0]);
 axis equal; 
 
 waitfor(h);
@@ -79,8 +88,11 @@ end
 %Residuals f and Jacobians J for maintaining a desired distance to an object (fast version with computation in matrix form)
 function [f, J] = f_dist(x, param)
 	e = x - repmat(param.Mu(1:2), 1, param.nbData);
-	f = 1 - sum(e.^2, 1)' / param.dist^2; %Residuals
-	Jtmp = repmat(-e'/param.dist^2, 1, param.nbData); 
+%	f = 1 - sum(e.^2, 1)' / param.dist^2; %Residuals
+%	Jtmp = repmat(-e'/param.dist^2, 1, param.nbData);
+	f = 1 - sum(e .* (param.Sigma\e), 1)';
+	Jtmp = repmat(-param.Sigma\e, param.nbData,1 )'; 
+	
 	J = Jtmp .* kron(eye(param.nbData), ones(1,param.nbVarU)); %Jacobians 
 end
 
diff --git a/matlab/iLQR_manipulator.m b/matlab/iLQR_manipulator.m
index 405109825c42b00f2d1778d10e54f62e97241864..47c5bc9629b6a37f83e34f261cb59a6911a3b575 100644
--- a/matlab/iLQR_manipulator.m
+++ b/matlab/iLQR_manipulator.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://rcfs.ch>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator
 
@@ -66,7 +66,7 @@ for n=1:param.nbIter
 		end
 		alpha = alpha * 0.5;
 	end
-	u = u + du * alpha;
+	u = u + du * alpha; %Update
 	
 	if norm(du * alpha) < 1E-2
 		break; %Stop iLQR when solution is reached
diff --git a/matlab/iLQR_manipulator3D.m b/matlab/iLQR_manipulator3D.m
index e27729ea9dc4c6e9f6bc8e10bbdabc49279bc95b..a14ac70c78d66bd987a3e879499de5b998fa8d9b 100644
--- a/matlab/iLQR_manipulator3D.m
+++ b/matlab/iLQR_manipulator3D.m
@@ -4,7 +4,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://rcfs.ch>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator3D
 
@@ -33,8 +33,9 @@ param.dh.d = [0.333, 0, 0.316, 0, 0.384, 0, 0, 0.107]; %Offset along previous z
 param.dh.r = [0, 0, 0, 0.0825, -0.0825, 0, 0.088, 0]; %Length of the common normal 
 
 %Weight matrices for iLQR cost
-Q = speye((param.nbVarF-1) * param.nbPoints) * param.q; %Precision matrix
-%Q = kron(eye(param.nbPoints), diag([0, 0, 0, 1E0, 1E0, 1E0])); %Precision matrix (by removing position constraint)
+%Qr = speye((param.nbVarF-1) * param.nbPoints) * param.q; %Precision matrix in relative coordinate frame (tool frame)
+%Qr = kron(eye(param.nbPoints), diag([0, 0, 0, 1E0, 1E0, 1E0])); %Precision matrix in relative coordinate frame (tool frame), by removing position constraint
+Qr = kron(eye(param.nbPoints), diag([1, 1, 1, 1, 1, 0])) * param.q; %Precision matrix in relative coordinate frame (tool frame), by removing orientation constraint on 3rd axis
 
 R = speye(param.nbVarU * (param.nbData-1)) * param.r; %Control weight matrix (at trajectory level)
 
@@ -82,6 +83,13 @@ Su = Su0(idx,:);
 for n=1:param.nbIter	
 	x = reshape(Su0 * u + Sx0 * x0, param.nbVarX, param.nbData); %System evolution
 	[f, J] = f_reach(x(:,tl), param);
+	Ra = [];
+	for m=1:param.nbPoints
+		Rtmp = q2R(param.Mu(4:end,m)); %Orientation matrix for target
+		Ra = blkdiag(Ra, blkdiag(eye(3),Rtmp)); %Transformation matrix with both translation and rotation 
+	end
+	Q = Ra * Qr * Ra'; %Precision matrix in absolute coordinate frame (base frame)
+
 	du = (Su' * J' * Q * J * Su + R) \ (-Su' * J' * Q * f(:) - u * param.r); %Gauss-Newton update
 	
 	%Estimate step size with backtracking line search method
diff --git a/matlab/iLQR_manipulator_CP.m b/matlab/iLQR_manipulator_CP.m
index f71fb65828338827990a664280ea33d46a63cc6d..36a3106be21b9bb44bb1602121288bbb8b856eb8 100644
--- a/matlab/iLQR_manipulator_CP.m
+++ b/matlab/iLQR_manipulator_CP.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_CP
 
diff --git a/matlab/iLQR_manipulator_CoM.m b/matlab/iLQR_manipulator_CoM.m
index d1189d588820911c69c76f8e88f66bbb09da8b4f..6d1791be44cabf6e98b29571ce4c4b32b2221472 100644
--- a/matlab/iLQR_manipulator_CoM.m
+++ b/matlab/iLQR_manipulator_CoM.m
@@ -6,7 +6,7 @@
 %% Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_CoM
 
diff --git a/matlab/iLQR_manipulator_boundary.m b/matlab/iLQR_manipulator_boundary.m
new file mode 100644
index 0000000000000000000000000000000000000000..1b449e66933bf0cb281c6e2ec352a01d93945ea0
--- /dev/null
+++ b/matlab/iLQR_manipulator_boundary.m
@@ -0,0 +1,214 @@
+%% iLQR applied to a planar manipulator for a viapoints task with bounding box on x (or u)
+%% 
+%% Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
+%% Written by Teguh Lembono <teguh.lembono@idiap.ch> and 
+%% Sylvain Calinon <https://calinon.ch>
+%% 
+%% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+%% License: GPL-3.0-only
+
+function iLQR_manipulator_boundary
+
+%% Parameters
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+param.dt = 1E-2; %Time step size
+param.nbData = 100; %Number of datapoints
+param.nbIter = 100; %Maximum number of iterations for iLQR
+param.nbPoints = 2; %Number of viapoints
+param.nbDOFs = 3; % Number of articulated links
+param.nbVarX = 3; %State space dimension (x1,x2,x3)
+param.nbVarU = 3; %Control space dimension (dx1,dx2,dx3)
+param.nbVarF = 2; %Task space dimension (f1,f2)
+param.l = [3, 2, 1]; %Robot links lengths
+param.sz = [.2, .3]; %Size of objects
+param.ulim = [15, 5, 15]; %Control commands range
+param.xlim = [pi*2, pi*2, pi*.05]; %joint angles range
+param.q = 1E0; %Tracking weighting term
+param.rv = 1E3; %Bounding weighting term
+param.r = 1E-4; %Control weighting term
+param.Mu = [[2; 1], [3; 2]]; %Viapoints
+
+Q = speye(param.nbVarF * param.nbPoints) * param.q; %Precision matrix
+R = speye(param.nbVarU * (param.nbData-1)) * param.r; %Control weight matrix (at trajectory level)
+
+%Time occurrence of viapoints
+tl = linspace(1, param.nbData, param.nbPoints+1);
+tl = round(tl(2:end));
+idx = (tl - 1) * param.nbVarX + [1:param.nbVarX]';
+
+
+%% Iterative LQR (iLQR)
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+u = ones(param.nbVarU*(param.nbData-1), 1) * 0; %Initial control commands
+x0 = [3*pi/4; -pi/2; pi/4]; %Initial robot pose 
+
+%Transfer matrices (for linear system as single integrator)
+Su0 = [zeros(param.nbVarX, param.nbVarX*(param.nbData-1)); kron(tril(ones(param.nbData-1)), eye(param.nbVarX)*param.dt)];
+Sx0 = kron(ones(param.nbData,1), eye(param.nbVarX));
+Su = Su0(idx,:);
+
+X0 = reshape(Su0 * u + Sx0 * x0, param.nbVarX, param.nbData);
+for n=1:param.nbIter
+	x = reshape(Su0 * u + Sx0 * x0, param.nbVarX, param.nbData); %System evolution
+	[f, J] = f_reach(x(:,tl), param);
+%	[v, Jv] = u_bound(u, model);
+	[v, Jv, idv] = x_bound(x(:), param);
+	Sv = Su0(idv,:);
+	
+	du = (Su' * J' * Q * J * Su + Sv' * Jv' * Jv * Sv * param.rv + R) \ (-Su' * J' * Q * f(:) - Sv' * Jv' * v * param.rv - u * param.r); %Gradient
+%	du = (Su' * J' * Q * J * Su + Sv' * Sv * param.rv + R) \ (-Su' * J' * Q * f(:) - Sv' * v * param.rv - u * param.r); %Gradient
+
+%	du = (Su' * J' * Q * J * Su + Jv' * Jv * param.rv + R) \ (-Su' * J' * Q * f(:) - Jv' * v * param.rv - u * param.r); %Gradient
+%	du = (Jv' * Su' * J' * Q * J * Su * Jv + Jv' * Jv * param.rv + R) \ (-Jv' * Su' * J' * Q * f(:) - Jv' * v * param.rv - u * param.r); %Gradient
+	
+	%Estimate step size with backtracking line search method
+	alpha = 1;
+	cost0 = f(:)' * Q * f(:) + norm(v)^2 * param.rv + norm(u)^2 * param.r; 
+	while 1
+		utmp = u + du * alpha;
+		xtmp = reshape(Su0 * utmp + Sx0 * x0, param.nbVarX, param.nbData);
+		ftmp = f_reach(xtmp(:,tl), param);
+		%vtmp = u_bound(utmp, param);
+		vtmp = x_bound(xtmp(:), param);
+		cost = ftmp(:)' * Q * ftmp(:) + norm(vtmp)^2 * param.rv + norm(utmp)^2 * param.r; 
+		if cost < cost0 || alpha < 1E-3
+			break;
+		end
+		alpha = alpha * 0.5;
+	end
+	u = u + du * alpha;
+	
+	if norm(du * alpha) < 1E-2
+		break; %Stop iLQR when solution is reached
+	end
+end
+disp(['iLQR converged in ' num2str(n) ' iterations.']);
+
+
+%% Plot state space
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+figure('position',[10,10,800,800],'color',[1,1,1]); hold on; axis off;
+
+ftmp = fkin0(x(:, 1), param);
+plot(ftmp(1,:), ftmp(2,:), '-','linewidth',4,'color',[.8 .8 .8]);
+
+ftmp = fkin0(x(:,tl(1)), param);
+plot(ftmp(1,:), ftmp(2,:), '-','linewidth',4,'color',[.6 .6 .6]);
+
+ftmp = fkin0(x(:,tl(2)), param);
+plot(ftmp(1,:), ftmp(2,:), '-','linewidth',4,'color',[.4 .4 .4]);
+
+colMat = lines(param.nbPoints);
+for t=1:param.nbPoints
+	plot(param.Mu(1,t), param.Mu(2,t), '.','markersize',40,'color',colMat(t,:));
+end
+
+ftmp = fkin(x, param); 
+plot(ftmp(1,:), ftmp(2,:), '-','linewidth',2,'color',[0 0 0]);
+plot(ftmp(1,1), ftmp(2,1), '.','markersize',40,'color',[0 0 0]);
+plot(ftmp(1,tl), ftmp(2,tl), '.','markersize',30,'color',[0 0 0]);
+axis equal;
+
+%% Timeline plot
+%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
+h = figure('position',[950 10 800 800],'color',[1 1 1]);
+%Plot x
+for j=1:param.nbVarX
+	subplot(param.nbVarX, 1, j); grid on; hold on; box on; 
+	plot([1, param.nbData], [param.xlim(j), param.xlim(j)], 'r-');
+	plot([1, param.nbData], -[param.xlim(j), param.xlim(j)], 'r-');
+	plot(X0(j,:), '-','linewidth',3,'color',[.7 .7 .7]);
+    plot(x(j,:), '-','linewidth',3,'color',[0 0 0]);
+	ylabel(['$x_' num2str(j) '$'], 'interpreter','latex','fontsize',26);
+end
+xlabel('$t$', 'interpreter','latex','fontsize',26); 
+
+waitfor(h);
+end 
+
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Forward kinematics (in robot coordinate system)
+function f = fkin(x, param)
+	T = tril(ones(size(x,1)));
+	f = [param.l * cos(T * x); ...
+		 param.l * sin(T * x)]; 
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%%%%%%%%%%%%%%%%%%%%%%
+%Forward kinematics for all robot articulations (in robot coordinate system)
+function f = fkin0(x, param)
+	L = tril(ones(size(x,1)));
+	f = [L * diag(param.l) * cos(L * x), ...
+	     L * diag(param.l) * sin(L * x)]'; 
+	f = [zeros(2,1), f];
+end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Jacobian with analytical computation (for single time step)
+function J = Jkin(x, param)
+	T = tril(ones(size(x,1)));
+	J = [-sin(T * x)' * diag(param.l) * T; ...
+		  cos(T * x)' * diag(param.l) * T]; 
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%
+%%Jacobian with numerical computation (for single time step)
+%function J = jacob0_num(x, param)
+%	e = 1E-6;
+%	J = zeros(param.nbVarF, param.nbVarX);
+%	for n=1:size(x,1)
+%		xtmp = x;
+%		xtmp(n) = xtmp(n) + e;
+%		J(:,n) = (fkine0(xtmp, param) - fkine0(x, param)) / e;
+%	end
+%end
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Cost and gradient for a viapoints reaching task (in object coordinate system)
+function [f, J] = f_reach(x, param)
+ 	f = fkin(x, param) - param.Mu; %Error by ignoring manifold
+	
+	J = []; 
+	for t=1:size(x,2)
+%		f(1:2,t) = param.A(:,:,t)' * f(1:2,t); %Object-centered FK
+		
+		Jtmp = Jkin(x(:,t), param);
+		%Jtmp = jacob0_num(x(:,t), param);
+		
+%		Jtmp(1:2,:) = param.A(:,:,t)' * Jtmp(1:2,:); %Object-centered Jacobian
+		
+%		%Bounding boxes (optional)
+%		for i=1:2
+%			if abs(f(i,t)) < param.sz(i)
+%				f(i,t) = 0;
+%				Jtmp(i,:) = 0;
+%			else
+%				f(i,t) = f(i,t) - sign(f(i,t)) * param.sz(i);
+%			end
+%		end
+		
+		J = blkdiag(J, Jtmp);
+	end
+end
+
+%%%%%%%%%%%%%%%%%%%%%%%
+%%Cost and gradient for boundary on u
+%function [v, Jv, idv] = u_bound(u, param)
+%	v = zeros(param.nbVarU*(param.nbData-1), 1);
+%	ulim = repmat(param.ulim', param.nbData-1, 1);
+%	idv = abs(u) > ulim; %Bounding boxes
+%	Jv = diag(idv);
+%	v(idv) = u(idv) - sign(u(idv)) .* ulim(idv);
+%end	
+
+%%%%%%%%%%%%%%%%%%%%%%
+%Cost and gradient for boundary on x
+function [v, Jv, idv] = x_bound(x, param)
+	%v = zeros(param.nbVarU*param.nbData, 1);
+	xlim = repmat(param.xlim', param.nbData, 1);
+	idv = abs(x) > xlim; %Bounding boxes
+	Jv = eye(sum(idv));
+	v = x(idv) - sign(x(idv)) .* xlim(idv);
+end	
diff --git a/matlab/iLQR_manipulator_dynamics.m b/matlab/iLQR_manipulator_dynamics.m
index 2ae4b1953ea7ebdc16a2f7ddec3fccbb249c7dc0..d15bd3fddd58a31b7bf79510f1b81984307c1abe 100644
--- a/matlab/iLQR_manipulator_dynamics.m
+++ b/matlab/iLQR_manipulator_dynamics.m
@@ -5,7 +5,7 @@
 %% Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://rcfs.ch>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_dynamics
 
diff --git a/matlab/iLQR_manipulator_initStateOptim.m b/matlab/iLQR_manipulator_initStateOptim.m
index eb4a89fa4f9221b60b90d7227cc9911fb6aca75a..313b2f7b65fc5ab5b08e4c6988429d5afe137307 100644
--- a/matlab/iLQR_manipulator_initStateOptim.m
+++ b/matlab/iLQR_manipulator_initStateOptim.m
@@ -6,7 +6,7 @@ function iLQR_manipulator_initStateOptim
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://rcfs.ch>
-%% License: MIT
+%% License: GPL-3.0-only
 
 
 %% Parameters
diff --git a/matlab/iLQR_manipulator_object_affordance.m b/matlab/iLQR_manipulator_object_affordance.m
index 0076c3735e4302f704d974a1336bbb42422b0ed7..0d49f8b97fad475c746eb8d560b4125069c2cb1c 100644
--- a/matlab/iLQR_manipulator_object_affordance.m
+++ b/matlab/iLQR_manipulator_object_affordance.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_object_affordance
 
diff --git a/matlab/iLQR_manipulator_obstacle.m b/matlab/iLQR_manipulator_obstacle.m
index 45aae7ac70e89e07ba38632f09f9a9a91eec2c8e..2db88bbcd7a1a0cd67aa1a7091a9cb96b292eeb8 100644
--- a/matlab/iLQR_manipulator_obstacle.m
+++ b/matlab/iLQR_manipulator_obstacle.m
@@ -6,7 +6,7 @@
 %% Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_obstacle
 
diff --git a/matlab/iLQR_manipulator_recursive.m b/matlab/iLQR_manipulator_recursive.m
index 650978a2f7c0800b7de3bc42c62602c5bc6206cd..544ad1ba75102676f201bda00ee096aacfdfa257 100644
--- a/matlab/iLQR_manipulator_recursive.m
+++ b/matlab/iLQR_manipulator_recursive.m
@@ -5,7 +5,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_manipulator_recursive
 
diff --git a/matlab/iLQR_obstacle.m b/matlab/iLQR_obstacle.m
index d8365c2f36db8106b79c81d4ce141dc0c8e5a1e5..a4e9bafe04c8303595ab33e013ff287cda1dcf15 100644
--- a/matlab/iLQR_obstacle.m
+++ b/matlab/iLQR_obstacle.m
@@ -7,7 +7,7 @@
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 function iLQR_obstacle
 
diff --git a/matlab/spline1D.m b/matlab/spline1D.m
index 4ff515a1c9c81f2d22ae1f249960a77db6a00105..e20e2eee8c1487d2c81bb43c43f9819193567e41 100644
--- a/matlab/spline1D.m
+++ b/matlab/spline1D.m
@@ -5,8 +5,8 @@ function spline1D
 %% Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
-%% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% This file is part of RCFS <https://rcfs.ch/>
+%% License: GPL-3.0-only
 
 
 %% Parameters
@@ -15,7 +15,7 @@ param.nbFct = 4; %Number of basis functions (code valid for param.nbFct>2)
 param.nbSeg = 7; %Number of segments
 param.nbIn = 1; %Dimension of input data (here: time)
 param.nbOut = 1; %Dimension of position data (here: x)
-param.nbDim = param.nbFct*param.nbSeg*20; %Number of datapoints in a trajectory
+param.nbDim = param.nbFct*param.nbSeg*20+1; %Number of datapoints in a trajectory
 
 
 %% Load handwriting data
@@ -40,7 +40,7 @@ param.B = kron(eye(param.nbSeg), param.B0); %Transform to multidimensional basis
 %and the two control points around should be symmetric (w3-2*w5+w6=0, ...)
 if param.nbFct==3
 	C0 = [1; 1; 2]; 
-	param.C = blkdiag(eye(param.nbFct-1));
+	param.C = eye(param.nbFct-1);
 	for n=1:param.nbSeg-1
 		param.C = blkdiag(param.C, C0);
 	end
@@ -70,22 +70,26 @@ end
 param.BC = param.B * param.C;
 
 %Time parameters matrix to compute positions
-t = linspace(0, 1-1/param.nbDim, param.nbDim);
+t = linspace(0, 1, param.nbDim);
 delta_t = t(2) - t(1);
 [Psi, dPsi, phi] = computePsiList(t, param);
 
 
 %% Trajectory encoding and reproduction as movement primitives
 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
-%Batch estimation of superposition weights from permuted data
-wb = Psi \ x0;
-param.Mw = param.BC * wb; %Transformation matrix
+%Batch estimation of superposition weights from reference position profile
+w = Psi \ x0;
+
+%%Batch estimation of superposition weights from reference position profile with additional cost on derivatives
+%w = (Psi'*Psi + dPsi'*dPsi*1E-3) \ Psi' * x0;
+
+param.Mw = param.BC * w; %Transformation matrix
 
 %Reconstruction of trajectories
-xb = Psi * wb; 
-dxb = dPsi * wb;
+x = Psi * w; 
+dx = dPsi * w;
 %Useful only for visualization
-wb_vis = kron(param.C, eye(param.nbOut)) * wb; 
+w_vis = kron(param.C, eye(param.nbOut)) * w; 
 
 
 %% Plots
@@ -95,39 +99,39 @@ set(gca,'linewidth',2);
 clrmap = lines(param.nbFct * param.nbSeg); %Colors for total number of control points 
 
 %Plot reference
-subplot(3,2,1); hold on; title('Reference position'); 
+subplot(3,2,1); hold on; title('Reference position profile (in red)'); 
 plot(t, x0, 'linewidth',4,'color',[.8 .6 .6]);
-plot(t, xb, 'linewidth',4,'color',[.6 .6 .6]);
+plot(t, x, 'linewidth',4,'color',[.6 .6 .6]);
 xlabel('t','fontsize',30); 
 ylabel('x','fontsize',30);
 set(gca,'xtick',[],'ytick',[]);
 
 %Plot derivatives
-subplot(3,2,2); hold on; title('Reference velocity'); 
+subplot(3,2,2); hold on; title('Velocity profile'); 
 plot(t(1:end-1), diff(x0)/delta_t, 'linewidth',8,'color',[.8 .6 .6]);
-plot(t, dxb, 'linewidth',4,'color',[.6 .6 .6]);
+plot(t, dx, 'linewidth',4,'color',[.6 .6 .6]);
 axis tight;
 xlabel('t','fontsize',30); 
 ylabel('dx/dt','fontsize',30);
 set(gca,'xtick',[],'ytick',[]);
 
-subplot(3,2,3); hold on; title('Reconstructed position'); 
+subplot(3,2,3); hold on; title('Reconstructed position profile'); 
 %Plot reconstructed signal
-plot(t, xb, 'linewidth',4,'color',[.6 .6 .6]);
+plot(t, x, 'linewidth',4,'color',[.6 .6 .6]);
 %Plot control points
 tSeg = [];
 for n=1:param.nbSeg
 	tSeg_n = linspace(0, 1/param.nbSeg, param.nbFct) + (n-1)/param.nbSeg;
 	tSeg = [tSeg, tSeg_n];	
 end	
-plot(tSeg, wb_vis, '.', 'markersize',38,'color',[0 0 0]); 
+plot(tSeg, w_vis, '.', 'markersize',38,'color',[0 0 0]); 
 %Plot segments between control points
 for n=1:param.nbSeg
 	id = (n-1)*param.nbFct + [1,2];
-	plot(tSeg(id), wb_vis(id), '-', 'linewidth',2,'color',[0 0 0]);
+	plot(tSeg(id), w_vis(id), '-', 'linewidth',2,'color',[0 0 0]);
 	id = n*param.nbFct + [-1,0];
-	plot(tSeg(id), wb_vis(id), '-', 'linewidth',2,'color',[0 0 0]);
-	plot([tSeg(id(2)), tSeg(id(2))], [min(wb)-2, max(wb)+2], '-', 'linewidth',2,'color',[.8 .8 .8]);
+	plot(tSeg(id), w_vis(id), '-', 'linewidth',2,'color',[0 0 0]);
+	plot([tSeg(id(2)), tSeg(id(2))], [min(w)-2, max(w)+2], '-', 'linewidth',2,'color',[.8 .8 .8]);
 end
 axis tight;
 xlabel('t','fontsize',30); 
@@ -135,13 +139,13 @@ ylabel('x','fontsize',30);
 set(gca,'xtick',[],'ytick',[]);
 
 %Plot reconstructed derivatives
-subplot(3,2,4); hold on; title('Reconstructed velocity'); 
-plot(t, dxb,'linewidth',4,'color',[.6 .6 .6]);
-%plot(t(1:end-1), diff(xb)/delta_t, ':','linewidth',4,'color',[.2 .2 .2]);
+subplot(3,2,4); hold on; title('Reconstructed velocity profile'); 
+plot(t, dx,'linewidth',4,'color',[.6 .6 .6]);
+%plot(t(1:end-1), diff(x)/delta_t, ':','linewidth',4,'color',[.2 .2 .2]);
 %Plot segments between control points
 for n=1:param.nbSeg
 	id = n*param.nbFct + [-1,0];
-	plot([tSeg(id(2)), tSeg(id(2))], [min(dxb)-2, max(dxb)+2], '-', 'linewidth',2,'color',[.8 .8 .8]);
+	plot([tSeg(id(2)), tSeg(id(2))], [min(dx)-2, max(dx)+2], '-', 'linewidth',2,'color',[.8 .8 .8]);
 end
 axis tight;
 xlabel('t','fontsize',30); 
diff --git a/matlab/spline2D.m b/matlab/spline2D.m
index 2c746e967af162c3dbeb1ef803f6cf1e2ffb2325..fe9435bbea28594c4c2ede3842a8e9bdef13bd29 100644
--- a/matlab/spline2D.m
+++ b/matlab/spline2D.m
@@ -6,7 +6,7 @@ function spline2D
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 
 %% Parameters
diff --git a/matlab/spline2D_eikonal.m b/matlab/spline2D_eikonal.m
index 5330fc44d972b8cd5220b4f2af2355a0a1e4fc2f..84f1bd374defeca16919450c160aadbc1a550014 100644
--- a/matlab/spline2D_eikonal.m
+++ b/matlab/spline2D_eikonal.m
@@ -7,7 +7,7 @@ function spline2D_eikonal
 %% Written by Sylvain Calinon <https://calinon.ch>
 %% 
 %% This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-%% License: MIT
+%% License: GPL-3.0-only
 
 
 %% Parameters
diff --git a/python/FD.py b/python/FD.py
index ae094ee348efd2439597b0bf0e15530df95ba926..60adc957963579c3b55a67f9159b8a7ee688f9ab 100644
--- a/python/FD.py
+++ b/python/FD.py
@@ -6,7 +6,7 @@ Written by Amirreza Razmjoo <amirreza.razmjoo@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/GPIS.py b/python/GPIS.py
index 3cc921291c290c8d5bb831d123bd3a3e00511ee4..afbfdc8c8262193559051a9537a35903b3df051f 100644
--- a/python/GPIS.py
+++ b/python/GPIS.py
@@ -6,7 +6,7 @@ Written by Cem Bilaloglu <cem.bilaloglu@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/IK_bimanual.py b/python/IK_bimanual.py
index b5ca0ea42a377218f63c36245cd5f90ca026d11c..f2a02c39f90f7ff2ec845b5776859a25e78109bf 100644
--- a/python/IK_bimanual.py
+++ b/python/IK_bimanual.py
@@ -6,7 +6,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/IK_manipulator.py b/python/IK_manipulator.py
index 9985001dea21284c789fe7829344b96470cbcc99..46710ba811189ed21e0adabd41d8693af4a8ded3 100644
--- a/python/IK_manipulator.py
+++ b/python/IK_manipulator.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -71,9 +71,9 @@ plt.scatter(fh[0], fh[1], color='r', marker='.', s=10**2) #Plot target
 for t in range(param.nbData):
 	f = fkin(x, param) # Forward kinematics (for end-effector)
 	J = Jkin(x, param) # Jacobian (for end-effector)
-#	x += np.linalg.pinv(J) @ (fh - f) * 10 * param.dt # Update state 
-	x += np.linalg.pinv(J) @ logmap(fh, f) * 10 * param.dt # Update state 
-	
+	u = np.linalg.pinv(J) @ logmap(fh, f) * 0.1 / param.dt # Velocity command (u=delta_x/dt)
+	x += u * param.dt # Update state 
+
 	f_rob = fkin0(x, param) # Forward kinematics (for all articulations, including end-effector)
 	plt.plot(f_rob[0,:], f_rob[1,:], color=str(1-t/param.nbData), linewidth=2) # Plot robot
 
diff --git a/python/IK_manipulator3D.py b/python/IK_manipulator3D.py
index ce0274656cc2e0712e4ee42b9e7cbda7a6a52f4b..c5bf862c405e07a4e3d0f835dab77d93d4b16b24 100644
--- a/python/IK_manipulator3D.py
+++ b/python/IK_manipulator3D.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 '''
 import copy
 import numpy as np
@@ -20,9 +20,7 @@ import matplotlib.pyplot as plt
 def f_reach(x, param):
     ftmp, _ = fkin(x, param)
     f = logmap(ftmp, param.Mu)
-    J = np.zeros([param.nbPoints * 6, param.nbPoints * param.nbVarX])
-    for t in range(param.nbPoints):
-        J[t*6:(t+1)*6, t*param.nbVarX:(t+1)*param.nbVarX] = Jkin_num(x[:,t], param)
+    J = Jkin_num(x[:,0], param)
     return f, J
 
 # Forward kinematics for end-effector (from DH parameters)
@@ -119,15 +117,17 @@ def q2R(q):
 
 # Rotation matrix to unit quaternion conversion
 def R2q(R):
-    R = R.T
-    K = np.array([
-            [R[0,0]-R[1,1]-R[2,2], R[1,0]+R[0,1], R[2,0]+R[0,2], R[1,2]-R[2,1]],
-            [R[1,0]+R[0,1], R[1,1]-R[0,0]-R[2,2], R[2,1]+R[1,2], R[2,0]-R[0,2]],
-            [R[2,0]+R[0,2], R[2,1]+R[1,2], R[2,2]-R[0,0]-R[1,1], R[0,1]-R[1,0]],
-            [R[1,2]-R[2,1], R[2,0]-R[0,2], R[0,1]-R[1,0], R[0,0]+R[1,1]+R[2,2]],
-    ]) / 3.0
-    _, V = np.linalg.eig(K)
-    return np.real([V[3, 0], V[0, 0], V[1, 0], V[2, 0]]) # for quaternions as [w,x,y,z]
+	R = R.T
+	K = np.array([
+			[R[0,0]-R[1,1]-R[2,2], R[1,0]+R[0,1], R[2,0]+R[0,2], R[1,2]-R[2,1]],
+			[R[1,0]+R[0,1], R[1,1]-R[0,0]-R[2,2], R[2,1]+R[1,2], R[2,0]-R[0,2]],
+			[R[2,0]+R[0,2], R[2,1]+R[1,2], R[2,2]-R[0,0]-R[1,1], R[0,1]-R[1,0]],
+			[R[1,2]-R[2,1], R[2,0]-R[0,2], R[0,1]-R[1,0], R[0,0]+R[1,1]+R[2,2]],
+	]) / 3.0
+
+	e_val, e_vec = np.linalg.eig(K) # unsorted eigenvalues
+	q = np.real([e_vec[3, np.argmax(e_val)], *e_vec[0:3, np.argmax(e_val)]]) # for quaternions as [w,x,y,z]
+	return q
 
 # Plot coordinate system
 def plotCoordSys(ax, x, R, width=1):
@@ -143,14 +143,13 @@ def plotCoordSys(ax, x, R, width=1):
 
 param = lambda: None # Lazy way to define an empty class in python
 param.nbIter = 50 # Maximum number of iterations for iLQR
-param.nbPoints = 1 # Number of viapoints
 param.nbVarX = 6 # State space dimension (x1,x2,x3)
 param.nbVarU = param.nbVarX # Control space dimension (dx1,dx2,dx3)
 param.nbVarF = 7 # Task space dimension (f1,f2,f3 for position, f4,f5,f6,f7 for unit quaternion)
 
 Rtmp = q2R([np.cos(np.pi/3), np.sin(np.pi/3), 0.0, 0.0])
 param.MuR = np.dstack((Rtmp, Rtmp))
-param.Mu = np.ndarray((param.nbVarF, param.nbPoints))
+param.Mu = np.ndarray((param.nbVarF, 1))
 param.Mu[0:3, 0] = [.2, 0, .2]
 param.Mu[3:7, 0] = R2q(param.MuR[:,:,1])
 
@@ -188,17 +187,13 @@ param.dh.r = [0, 0.2, 0.087, 0, 0, 0, 0] # Length of the common normal
 # Main program
 # ===============================
 
-x0 = np.array([0]*6,dtype=np.float64) # Initial robot pose
-x0 = x0.reshape((-1, 1))
-
+x0 = np.zeros((6,1)) # Initial robot pose
 x = copy.deepcopy(x0)
 
 for i in range(param.nbIter):
     e, J = f_reach(x,param)
     cost = e.T @ e
-    
-    print(f"Iteration: {i}, cost: {cost}")
-
+#    print(f"Iteration: {i}, cost: {cost}")
     J = Jkin_num(x.flatten(),param)
     dx = 0.1 * np.linalg.pinv(J) @ e
     x -= dx
@@ -212,16 +207,17 @@ ax = plt.figure(figsize=(12, 10)).add_subplot(projection='3d')
 ftmp, _ = fkin0(x0.flatten(), param)
 ax.plot(ftmp[0,:], ftmp[1,:], ftmp[2,:], linewidth=4, color=[.8, .8, .8])
 
-ftmp, _ = fkin0(x.flatten(), param)
+ftmp, Rtmp = fkin0(x.flatten(), param)
 ax.plot(ftmp[0,:], ftmp[1,:], ftmp[2,:], linewidth=4, color=[.6, .6, .6])
+plotCoordSys(ax, ftmp[:,-1:], Rtmp[:,:,-1:] * .06, width=2)
 
 # Plot targets
 plotCoordSys(ax, param.Mu, param.MuR * 0.1)
 
 # Set axes limits and labels
-ax.set_xlim(0, 0.8)
-ax.set_ylim(0, 0.8)
-ax.set_zlim(0, 0.8)
+ax.set_xlim(-0.4, 0.4)
+ax.set_ylim(-0.4, 0.4)
+ax.set_zlim(0, 0.6)
 ax.set_xlabel(r'$f_1$')
 ax.set_ylabel(r'$f_2$')
 ax.set_zlabel(r'$f_3$')
diff --git a/python/IK_manipulator_manipulability.py b/python/IK_manipulator_manipulability.py
new file mode 100644
index 0000000000000000000000000000000000000000..ba110964de82621966d665a6aa733d3dadfc7b45
--- /dev/null
+++ b/python/IK_manipulator_manipulability.py
@@ -0,0 +1,387 @@
+'''
+Inverse kinematics with visualization of manipulability
+
+Copyright (c) 2024 Idiap Research Institute <https://www.idiap.ch/>
+Written by Sylvain Calinon <https://calinon.ch>
+
+This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+License: GPLv3
+'''
+
+import numpy as np
+import random
+import matplotlib
+import matplotlib.pyplot as plt
+import math as m
+import scipy
+import scipy.spatial
+
+# Logarithmic map for R^2 x S^1 manifold
+def logmap(f, f0):
+	diff = np.zeros(3)
+	diff[:2] = f[:2] - f0[:2] # Position residual
+	diff[2] = np.imag(np.log(np.exp(f0[-1]*1j).conj().T * np.exp(f[-1]*1j).T)).conj() # Orientation residual
+	return diff
+	
+# Forward kinematics for end-effector (in robot coordinate system)
+def fkin(x, param):
+	L = np.tril(np.ones([param.nbVarX, param.nbVarX]))
+	f = np.stack([
+		param.l @ np.cos(L @ x),
+		param.l @ np.sin(L @ x),
+		np.mod(np.sum(x,0)+np.pi, 2*np.pi) - np.pi
+	]) # f1,f2,f3, where f3 is the orientation (single Euler angle for planar robot)
+	return f
+
+# Forward kinematics for all joints (in robot coordinate system)
+def fkin0(x, param): 
+	L = np.tril(np.ones([param.nbVarX, param.nbVarX]))
+	f = np.vstack([
+		L @ np.diag(param.l) @ np.cos(L @ x),
+		L @ np.diag(param.l) @ np.sin(L @ x)
+	])
+	f = np.hstack([np.zeros([2,1]), f])
+	return f
+
+# Jacobian with analytical computation (for single time step)
+def Jkin(x, param):
+	L = np.tril(np.ones([param.nbVarX, param.nbVarX]))
+	J = np.vstack([
+		-np.sin(L @ x).T @ np.diag(param.l) @ L,
+		 np.cos(L @ x).T @ np.diag(param.l) @ L,
+		 np.ones([1,param.nbVarX])
+	])
+	return J
+
+## Parameters
+# ===============================
+
+param = lambda: None # Lazy way to define an empty class in python
+param.dt = 1e-2 # Time step length
+param.nbData = 50 # Number of datapoints
+param.nbVarX = 3 # State space dimension (x1,x2,x3)
+param.nbVarU = 3 # Control space dimension (dx1,dx2,dx3)
+param.nbVarF = 3 # Objective function dimension (position and orientation of the end-effector)
+param.l = [2, 2, 1] # Robot links lengths
+
+fig, ax = plt.subplots()
+
+
+fh = np.array([3, 1, -np.pi/2]) # Desired target for the end-effector (position and orientation)
+x = -np.ones(param.nbVarX) * np.pi / param.nbVarX # Initial robot pose
+x[0] = x[0] + np.pi 
+
+## Inverse kinematics (IK)
+# ===============================
+
+ax.scatter(fh[0], fh[1], color='r', marker='.', s=10**2) #Plot target
+for t in range(param.nbData):
+	f = fkin(x, param) # Forward kinematics (for end-effector)
+	J = Jkin(x, param) # Jacobian (for end-effector)
+#	x += np.linalg.pinv(J) @ (fh - f) * 10 * param.dt # Update state 
+	x += np.linalg.pinv(J) @ logmap(fh, f) * 10 * param.dt # Update state
+	
+	f_rob = fkin0(x, param) # Forward kinematics (for all articulations, including end-effector)
+	ax.plot(f_rob[0,:], f_rob[1,:], color=str(1-t/param.nbData), linewidth=2) # Plot robot
+	
+
+
+### MANIPULABILITY ###
+	
+J = J[:2,:]
+center = np.array([f[0], f[1]]) # end-effector position
+length, width, height = 1.8,1.5,1 # max joint velocities
+size = np.array([length, width, height])
+refell = 130 * np.identity(2) # reference ellipsoid
+
+# Choice of the Jacobian matrix         
+J1 = False
+J2 = False
+J3 = False
+J4 = False
+diffJac = [J1, J2, J3, J4]
+
+
+# 1. Robot manipulator
+if J1 == True:
+        theta = 5*m.pi/6
+        U = np.array([[m.cos(theta), -m.sin(theta)],[m.sin(theta), m.cos(theta)]])
+        J = U.T @ J
+        print(J)
+
+# 2. Bounded joint-space
+if J2 == True:
+        jminlim = -np.ones(param.nbVarX)
+        jmaxlim = np.ones(param.nbVarX)   
+        J = np.diag(1 - np.heaviside(x - jminlim,0)*np.heaviside(jmaxlim - x, 0))[:2,:]
+        print(J)
+        
+
+# 3. Bounded task-space
+if J3 == True:
+        tminlim = -np.ones(2)
+        tmaxlim = np.ones(2)
+        J = np.diag(1 - np.heaviside(f[:2] - tminlim,0)*np.heaviside(tmaxlim - f[:2], 0)) @ J   
+        print(J)
+
+# 4. Object boundaries
+if J4 == True:
+        theta = m.pi/4
+        U = np.array([[m.cos(theta), -m.sin(theta)],[m.sin(theta), m.cos(theta)]])
+        tminlim = -np.ones(2)
+        tmaxlim = 2*np.ones(2)
+        J = np.diag(1 - np.heaviside(U.T@(f[:2] - fh[:2]) - tminlim,0)*np.heaviside(tmaxlim - (U.T@(f[:2] - fh[:2])), 0)) @ J
+        print(J)
+        
+        
+
+# Boundaries in joint-velocity space
+
+# 1. Rectangular cuboid
+showedges = False    # Shows the mapping of the cube's edges
+
+# 2. Ellipse
+ellBound = True
+
+# 3. Superellipsoid
+superBound = False
+superVolume = False # Returns the fraction of the rectangular cuboid's volume covered by the superellipsoid
+
+
+# 1. Rectangular cuboid
+cube = np.zeros((2 ** param.nbVarX, param.nbVarX))
+vertex = np.zeros(param.nbVarX)
+# These two loops store the numbers 0 to 7 in binary (which can be seen as the coordinates of a cube)
+for count1 in range(2 ** param.nbVarX):
+        for count2 in range(len(bin(count1)) - 2):
+                vertex[-count2-1] = int(str(bin(count1)[-count2-1]))
+        cube[count1] = vertex
+
+# Rescaling so that the center of the cube is located at the origin
+cube = cube * 2 - 1
+
+
+for i in range(len(size)):
+        cube[:,i] = cube[:,i] * size[i]
+
+# Computation of the manipulability polytope
+polytope = np.zeros((2 ** param.nbVarX,2))
+for count in range(2 ** param.nbVarX):
+        polytope[count] = J @ cube[count] + center
+                
+xpoints = polytope[:,0]
+ypoints = polytope[:,1]
+polytope = np.array([xpoints, ypoints]).T
+
+if not any(diffJac) == True:
+        hull = scipy.spatial.ConvexHull(polytope)
+
+        # vertices of the covex hull (might come in handy)
+        vertices = np.zeros((len(hull.vertices),2))
+        for i in range(len(hull.vertices)):
+                vertices[i] = polytope[hull.vertices[i]]
+        cube_norms = np.linalg.norm(vertices, axis = 1)
+                
+        for simplex in hull.simplices:
+                plt.plot(polytope[simplex, 0], polytope[simplex, 1], 'b--')
+        
+
+def norm(vec, coeff, exp):
+        terms = abs(vec/coeff)**exp
+        norm = sum(terms) ** (1/exp)
+        return norm
+
+def sample(npoints, coeff, exp):
+        vecs = np.random.rand(npoints, param.nbVarX) * 2 - 1
+        vecs *= size
+        
+        for count in range(len(vecs)):
+                vecs[count] = vecs[count] / norm(vecs[count], coeff, exp)
+        return vecs
+
+# 2. Ellipsoid
+if ellBound == True:
+        num_iter = 1000
+        # coeff = np.array([1,1,1]) # these are the dimensions of the superellipsoid in joint-velocity space
+        coeff = size # if one wants the superellipsoid to be contained in the cuboid
+        exp = 2
+
+        ell_jvlim = sample(num_iter, coeff, 2)
+        
+        ell_tvlim = np.zeros((num_iter,2))
+
+        for count in range(len(ell_jvlim)):
+                ell_tvlim[count] = J @ ell_jvlim[count] + center
+
+        ell_x, ell_y = ell_tvlim.T
+
+        A = np.diag(coeff ** 2)
+        Q = J @ A @ J.T
+        eigenvals, eigenvecs = np.linalg.eig(Q)
+        
+        # Sort Eigenvalues and EigenVectors
+        idx = eigenvals.argsort()[::-1]   
+        eigenvals = eigenvals[idx]
+        eigenvecs = eigenvecs[idx]
+
+        # the sqrt of the eigenvalues give the length of the semi-axes
+        print(f"Ellipsoid eigenvalues: {eigenvals}")
+        vec1, vec2 = eigenvecs.T
+        vec1 = vec1 * m.sqrt(eigenvals[0]) + center
+        vec2 = vec2 * m.sqrt(eigenvals[1]) + center
+
+
+        if not any(diffJac) == True:
+                polytope = np.array([ell_x, ell_y]).T
+                hull = scipy.spatial.ConvexHull(polytope)
+
+                        # vertices of the covex hull (might come in handy)
+                        #vertex = np.zeros((len(hull.vertices),2))
+                        #for i in range(len(hull.vertices)):
+                        #        vertex[i] = polytope[hull.vertices[i]]
+                        #ax.plot(vertex[:,0], vertex[:,1], "gv")
+               
+                for simplex in hull.simplices:
+
+                    plt.plot(polytope[simplex, 0], polytope[simplex, 1], 'r--')
+
+
+
+# 3. Superellipsoid (rigorously this is not the most general form of a superellipsoid)
+if superBound == True:
+        num_iter = 1000         
+        # coeff = np.array([1,1,1]) # these are the dimensions of the superellipsoid in joint-velocity space
+        coeff = size # if one wants the superellipsoid to be contained in the cuboid
+        exp = 4 # exp = 2 for an ellipse, exp = 4 for squircle, exp --> infty for rectangular cuboid
+
+        if superVolume == True:
+                vol = scipy.special.gamma(1/exp + 1)**param.nbVarX/scipy.special.gamma(param.nbVarX/exp + 1)
+                print(f"fraction of the rectangular cuboid's volume: {vol}")
+
+        jvlim = sample(num_iter, coeff, exp)
+        
+        tvlim = np.zeros((num_iter,2))
+
+        for count in range(len(jvlim)):
+                tvlim[count] = J @ jvlim[count] + center
+                
+
+        xpoints, ypoints = tvlim.T
+
+        # Idea: approximate whatever shape I get with an ellipsoid, so that the reasoning on the eigenvalues apply!
+        # Note: it does not just give the same ellipsoid as if exp = 2
+
+        tvmax = tvlim[np.argmax(np.linalg.norm(tvlim-center, axis = 1))]
+        cov_mat = np.cov(tvlim.T)
+        eigenvals, eigenvecs = np.linalg.eig(cov_mat)
+        idx = eigenvals.argsort()[::-1]   
+        eigenvals = eigenvals[idx]
+        eigenvecs = eigenvecs[:,idx]
+        eigenvecs = eigenvecs * np.sqrt(eigenvals)
+        ratio = np.linalg.norm(tvmax-center)/m.sqrt(eigenvals[0])
+        eigenvecs *= ratio
+
+        vec1, vec2 = eigenvecs.T[0],eigenvecs.T[1]
+
+        '''
+        # Manipulability matrix
+        Q = eigenvecs @ np.array([[eigenvals[0],0],[0,eigenvals[1]]]) @ np.linalg.inv(eigenvecs)
+
+        # Riemannian distance
+        A = np.linalg.inv(scipy.linalg.sqrtm(refell)) @ Q @ np.linalg.inv(scipy.linalg.sqrtm(refell))
+        d = np.linalg.norm(scipy.linalg.logm(A))
+        print(f"Riemannian distance: {d}")
+        '''
+        
+        print(f"Superellipsoid eigenvalues: {(ratio * np.sqrt(eigenvals))**2}")
+
+        phi = np.linspace(0, 2*m.pi,200)
+        x = np.zeros((len(phi),2))
+
+        for i in range(len(phi)):
+                x[i] = center + vec1 * m.cos(phi[i]) + vec2 * m.sin(phi[i])
+
+        super_norms = np.linalg.norm(x,axis = 1)
+        
+        if not any(diffJac) == True:
+                ax.plot(x[:,0], x[:,1], "g1", label = "superellipsoid")
+                vec1 += center
+                vec2 += center
+                ax.plot([center[0], tvmax[0]], [center[1],tvmax[1]]) 
+                ax.plot([center[0], vec1[0]], [center[1],vec1[1]])
+                ax.plot([center[0], vec2[0]], [center[1],vec2[1]])
+
+
+# Plots
+showhull = True # to show the convex hull of the superellipsoid
+showpoints = False # to show the image of all the sampled points
+
+
+if showhull == True and not any(diffJac) == True:
+        polytope = np.array([xpoints, ypoints]).T
+        hull = scipy.spatial.ConvexHull(polytope)
+
+                # vertices of the covex hull (might come in handy)
+                #vertex = np.zeros((len(hull.vertices),2))
+                #for i in range(len(hull.vertices)):
+                #        vertex[i] = polytope[hull.vertices[i]]
+                #ax.plot(vertex[:,0], vertex[:,1], "gv")
+       
+        for simplex in hull.simplices:
+
+            plt.plot(polytope[simplex, 0], polytope[simplex, 1], 'g--')
+                
+if showpoints == True:
+        ax.plot(xpoints, ypoints, "kx")
+
+#fig = plt.figure()
+#ax2 = fig.add_subplot(projection='3d')
+
+#ax2.scatter(cube[:,0], cube[:,1], cube[:,2], c = "blue", label = "rectangular cuboid")
+
+#if ellBound == True:
+#        ax2.scatter(ell_jvlim[:,0], ell_jvlim[:,1], ell_jvlim[:,2], c = "red", label = "ellipsoid")
+#    
+#if superBound == True:
+#        ax2.scatter(jvlim[:,0], jvlim[:,1], jvlim[:,2], c = "green", label = "superellipsoid")
+
+#legend = ax2.legend(loc='upper right')
+
+
+#if showedges == True:
+#        num_points = 50
+#        jvlim, tvlim = np.zeros((num_points,3)), np.zeros((num_points,2))
+#        
+#        edges = np.vstack((np.unique(cube[:,:2], axis = 0), np.unique(cube[:,1:3], axis = 0), np.unique(cube[:,0:3:2], axis = 0)))
+#        for edge in edges[:4]:
+#                for count in range(num_points):
+#                        z = (random.random() * 2 - 1) * height
+#                        jvlim[count] = np.array([edge[0],edge[1],z])
+#                        tvlim[count] = J @ jvlim[count] + center
+#                ax2.scatter(jvlim[:,0], jvlim[:,1], jvlim[:,2], c = "blue")
+#                ax.plot(tvlim[:,0], tvlim[:,1], "bx")
+
+#        for edge in edges[4:8]:
+#                for count in range(num_points):
+#                        x = (random.random() * 2 - 1) * length
+#                        jvlim[count] = np.array([x,edge[0],edge[1]])
+#                        tvlim[count] = J @ jvlim[count] + center
+#                ax2.scatter(jvlim[:,0], jvlim[:,1], jvlim[:,2], c = "red")
+#                ax.plot(tvlim[:,0], tvlim[:,1], "rx")
+#                        
+#        for edge in edges[8:]:
+#                for count in range(num_points):
+#                        y = (random.random() * 2 - 1) * width
+#                        jvlim[count] = np.array([edge[0],y,edge[1]])
+#                        tvlim[count] = J @ jvlim[count] + center
+#                ax2.scatter(jvlim[:,0], jvlim[:,1], jvlim[:,2], c = "green")
+#                ax.plot(tvlim[:,0], tvlim[:,1], "gx")
+#        
+
+
+#ax.axis('off')
+ax.axis('equal')
+#ax2.axis('equal')
+#plt.title(f"Length: {length}, width: {width}, height: {height}, p = {exp}")
+
+plt.show()
diff --git a/python/IK_nullspace.py b/python/IK_nullspace.py
index 913427c0962540de49e6cd5571f6f82a4322df6f..9d764cdf20298bcd627cfe237c6a4d46926dce1b 100644
--- a/python/IK_nullspace.py
+++ b/python/IK_nullspace.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/IK_num.py b/python/IK_num.py
index f493ac48a177e07beddbcddf17b9bbe4d8722302..e11fda6cee94535d2b7f98e8362af725ee14acc7 100644
--- a/python/IK_num.py
+++ b/python/IK_num.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQR_infHor.py b/python/LQR_infHor.py
index 5dc9f38134638bbeb2958ff60c148c0fd7ade861..4ea88c1196d2ec66dfa2095c1a0ca9c950530e68 100644
--- a/python/LQR_infHor.py
+++ b/python/LQR_infHor.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT.py b/python/LQT.py
index ef99ce82f10a31e0f497ef1b247b4426078dd7dd..20f3986c0041ec6fea736efdb2efc0ec7fbe9f1b 100644
--- a/python/LQT.py
+++ b/python/LQT.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_CP.py b/python/LQT_CP.py
index d66dceb589c36c25c3f72db2f7effd2f5daf1b18..2519eb2c7e115a53869b6eeb3d5943c9aac76579 100644
--- a/python/LQT_CP.py
+++ b/python/LQT_CP.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_CP_DMP.py b/python/LQT_CP_DMP.py
index e63e6588ca85aec90553134111fb7d9b3af0eadf..ef969acfc0d2751fb12481b9c8c2e72f860c8bf0 100644
--- a/python/LQT_CP_DMP.py
+++ b/python/LQT_CP_DMP.py
@@ -8,7 +8,7 @@ Written by Boyang Ti <https://www.idiap.ch/~bti/> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import os 
diff --git a/python/LQT_nullspace.py b/python/LQT_nullspace.py
index 6dfb07a05341bed647f913600c96b50846c56593..d5564a99b0ab1548c7bb2ef6411ada346de2b6d0 100644
--- a/python/LQT_nullspace.py
+++ b/python/LQT_nullspace.py
@@ -6,7 +6,7 @@ Written by Hakan Girgin <hakan.girgin@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_recursive.py b/python/LQT_recursive.py
index 0b8e8c97688501c1ca86c43e0a34cd962212c6b0..bb10eedb80bb1ed8e009e77b0410f7a6bc633a70 100644
--- a/python/LQT_recursive.py
+++ b/python/LQT_recursive.py
@@ -6,7 +6,7 @@ Written by Adi Niederberger <aniederberger@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_recursive_LS.py b/python/LQT_recursive_LS.py
index 0ddec6cac0879954630bac89ec5befd031e13678..9e007503268fd38187a3e8a92f8d9d773cf597fc 100644
--- a/python/LQT_recursive_LS.py
+++ b/python/LQT_recursive_LS.py
@@ -6,7 +6,7 @@ Written by Julius Jankowski <julius.jankowski@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_recursive_LS_multiAgents.py b/python/LQT_recursive_LS_multiAgents.py
index 3c0b53bcbb9a92bc07eb1d81765d72e346e77796..24903d71943cfc8031c7545b5a457ff5f300337a 100644
--- a/python/LQT_recursive_LS_multiAgents.py
+++ b/python/LQT_recursive_LS_multiAgents.py
@@ -6,7 +6,7 @@ Written by Julius Jankowski <julius.jankowski@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/LQT_tennisServe.py b/python/LQT_tennisServe.py
index 94f736003aa6fa0797af4c88f43d037a012e68c4..e3eec370d25fa647f25f2a414152938f867715cb 100644
--- a/python/LQT_tennisServe.py
+++ b/python/LQT_tennisServe.py
@@ -6,7 +6,7 @@ Written by Yiming Li <yiming.li@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/MP.py b/python/MP.py
index 15befbeb8c6d45c7f6d63edf8361dc956418694b..9cbdfb6aba22ec90c186d896237095c11510d58d 100644
--- a/python/MP.py
+++ b/python/MP.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/ergodic_control_HEDAC_1D.py b/python/ergodic_control_HEDAC_1D.py
new file mode 100644
index 0000000000000000000000000000000000000000..b280b31fe088b3f913cdd79607eb4b1de3e6696f
--- /dev/null
+++ b/python/ergodic_control_HEDAC_1D.py
@@ -0,0 +1,405 @@
+"""
+1D ergodic control formulated as Heat Equation Driven Area Coverage (HEDAC) objective,
+with a spatial distribution described as a mixture of Gaussians.
+
+Copyright (c) 2023 Idiap Research Institute, https://www.idiap.ch
+Written by Philip Abbet <philip.abbet@idiap.ch> and
+Cem Bilaloglu <cem.bilaloglu@idiap.ch>
+
+This file is part of RCFS <https://rcfs.ch>
+License: GPLv3
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+# Helper class
+# ===============================
+class SecondOrderAgent:
+    """
+    A point mass agent with second order dynamics.
+    """
+    def __init__(
+        self,
+        x,
+        nbDataPoints,
+        max_dx=1,
+        max_ddx=0.2,
+    ):
+        self.x = x  # position
+        # determine which dimesnion we are in from given position
+        self.dx = np.zeros(1)  # velocity
+
+        self.t = 0  # time
+        self.dt = 1  # time step
+        self.nbDatapoints = nbDataPoints
+
+        self.max_dx = max_dx
+        self.max_ddx = max_ddx
+
+        # we will store the actual and desired position
+        # of the agent over the timesteps
+        self.x_arr = np.zeros(self.nbDatapoints)
+
+    def update(self, gradient):
+        """
+        set the acceleration of the agent to clamped gradient
+        compute the position at t+1 based on clamped acceleration
+        and velocity
+        """
+        ddx = gradient # we use gradient of the potential field as acceleration
+        # clamp acceleration if needed
+        if np.linalg.norm(ddx) > self.max_ddx:
+            ddx = self.max_ddx * ddx / np.linalg.norm(ddx)
+
+        # Ensure that we don't go out of limits
+        next_x =  (self.x + self.dt * self.dx + 0.5 * self.dt * self.dt * ddx)[0]
+        if (next_x < 0) or (next_x >= self.nbDatapoints):
+            ddx = -ddx
+            if np.sign(ddx) != np.sign(self.dx):
+                self.dx = -self.dx
+
+        self.x = (self.x + self.dt * self.dx + 0.5 * self.dt * self.dt * ddx)[0]
+        self.x_arr[self.t] = np.copy(self.x)
+        self.t += 1
+
+        self.dx += self.dt * ddx  # compute the velocity
+        # clamp velocity if needed
+        if np.linalg.norm(self.dx) > self.max_dx:
+            self.dx = self.max_dx * self.dx / np.linalg.norm(self.dx)
+
+
+# Helper functions for HEDAC
+# ===============================
+def rbf(mean, x, eps):
+    """
+    Radial basis function w/ Gaussian Kernel
+    """
+    d = x - mean  # radial distance
+    l2_norm_squared = np.dot(d, d)
+    # eps is the shape parameter that can be interpreted as the inverse of the radius
+    return np.exp(-eps * l2_norm_squared)
+
+
+def normalize_mat(mat):
+    return mat / (np.sum(mat) + 1e-10)
+
+
+def calculate_gradient(agent, gradient_in):
+    """
+    Calculate movement direction of the agent by considering the gradient
+    of the temperature field near the agent
+    """
+    # find agent pos on the grid as integer indices
+    adjusted_position = agent.x / param.dx
+    # note x axis corresponds to col and y axis corresponds to row
+    col = int(adjusted_position)
+
+    gradient = 0.0
+    # if agent is inside the grid, interpolate the gradient for agent position
+    if col > 0 and col < param.nbRes - 1:
+        gradient = linear_interpolation(gradient_in, adjusted_position)
+
+    return gradient
+
+
+def clamp_kernel_1d(x, low_lim, high_lim, kernel_size):
+    """
+    A function to calculate the start and end indices
+    of the kernel around the agent that is inside the grid
+    i.e. clamp the kernel by the grid boundaries
+    """
+    start_kernel = low_lim
+    start_grid = x - (kernel_size // 2)
+    num_kernel = kernel_size
+    # bound the agent to be inside the grid
+    if x <= -(kernel_size // 2):
+        x = -(kernel_size // 2) + 1
+    elif x >= high_lim + (kernel_size // 2):
+        x = high_lim + (kernel_size // 2) - 1
+
+    # if agent kernel around the agent is outside the grid,
+    # clamp the kernel by the grid boundaries
+    if start_grid < low_lim:
+        start_kernel = kernel_size // 2 - x - 1
+        num_kernel = kernel_size - start_kernel - 1
+        start_grid = low_lim
+    elif start_grid + kernel_size >= high_lim:
+        num_kernel -= x - (high_lim - num_kernel // 2 - 1)
+    if num_kernel > low_lim:
+        grid_indices = slice(start_grid, start_grid + num_kernel)
+
+    return grid_indices, start_kernel, num_kernel
+
+
+def agent_block(min_val, agent_radius):
+    """
+    A matrix representing the shape of an agent (e.g, RBF with Gaussian kernel). 
+    min_val is the upper bound on the minimum value of the agent block.
+    """
+    eps = 1.0 / agent_radius  # shape parameter of the RBF
+    l2_sqrd = (
+        -np.log(min_val) / eps
+    )  # squared maximum distance from the center of the agent block
+    l2_single = np.sqrt(l2_sqrd)  # maximum distance on a single axis
+    # round to the nearest larger integer
+    if l2_single.is_integer(): 
+        l2_upper = int(l2_single)
+    else:
+        l2_upper = int(l2_single) + 1
+    # agent block is symmetric about the center
+    num_cols = l2_upper * 2 + 1
+    block = np.zeros(num_cols)
+    center = num_cols // 2
+    for j in range(num_cols):
+        block[j] = rbf(j, center, eps)
+    return block
+
+
+def offset(vec, i):
+    """
+    offset a 2D vector by i
+    """
+    cols = vec.shape[0] - 2
+    return vec[1 + i : 1 + i + cols]
+
+
+def border_interpolate(x, length, border_type):
+    """
+    Helper function to interpolate border values based on the border type
+    (gives the functionality of cv2.borderInterpolate function)
+    """
+    if border_type == "reflect101":
+        if x < 0:
+            return -x
+        elif x >= length:
+            return 2 * length - x - 2
+    return x
+
+
+def linear_interpolation(grid, pos):
+    """
+    Linear interpolating function on a 2-D grid
+    """
+    x = int(pos)
+    # find the nearest integers by minding the borders
+    x0 = border_interpolate(x, grid.shape[0], "reflect101")
+    x1 = border_interpolate(x + 1, grid.shape[0], "reflect101")
+    # Distance from lower integers
+    xd = pos - x0
+    # Interpolate on x-axis
+    c = grid[x0] * (1 - xd) + grid[x1] * xd
+    return c
+
+
+def discrete_gmm(param):
+    # Compute Fourier series coefficients w_hat of desired spatial distribution
+    rg = np.arange(param.nbFct, dtype=float).reshape((param.nbFct, 1))
+    kk = rg * param.omega
+
+    # Explicit description of w_hat by exploiting the Fourier transform
+    # properties of Gaussians (optimized version by exploiting symmetries)
+    w_hat = np.zeros((param.nbFct, 1))
+    for j in range(param.nbGaussian):
+        w_hat = w_hat + param.Priors[j] * np.cos(kk * param.Mu[j]) * np.exp(-.5 * kk**2 * param.Sigma[:,:,j])
+
+    w_hat = w_hat / param.L
+
+    # Fourier basis functions (for a discretized map)
+    xm1d = np.linspace(param.xlim[0], param.xlim[1], param.nbRes).reshape((param.nbRes, 1))  # Spatial range
+    ang = rg @ xm1d.T * param.omega
+    phim = np.cos(ang) * 2
+
+    hk = np.concatenate(([1], 2 * np.ones(param.nbFct-1)))
+
+    phim = phim * np.tile(hk, (param.nbRes, 1)).T
+
+    # Desired spatial distribution
+    g = w_hat.T @ phim
+    return g[0,:]
+
+
+# Parameters
+# ===============================
+param = lambda: None # Lazy way to define an empty class in python
+param.nbDataPoints = 2000
+param.min_kernel_val = 1e-8  # upper bound on the minimum value of the kernel
+param.diffusion = 1  # increases global behavior
+param.source_strength = 1  # increases local behavior
+param.obstacle_strength = 0  # increases local behavior
+param.agent_radius = 10  # changes the effect of the agent on the coverage
+param.max_dx = 1 # maximum velocity of the agent
+param.max_ddx = 0.1 # maximum acceleration of the agent
+param.cooling_radius = param.agent_radius  # changes the effect of the agent on local cooling (collision avoidance)
+param.nbAgents = 1
+param.local_cooling = 0  # for multi agent collision avoidance
+param.dx = 1
+
+param.nbRes = 100 # number of grid cells
+
+param.nbGaussian = 2
+
+param.nbFct = 10  # Number of basis functions
+param.xlim = [0, 1]  # Domain limit for each dimension (considered to be 1 for each dimension in this implementation)
+param.L = (param.xlim[1] - param.xlim[0]) * 2  # Size of [-xlim(2),xlim(2)]
+param.omega = 2 * np.pi / param.L
+
+param.alpha = param.diffusion
+
+# Initial points
+param.x0 = np.array([
+    0.1,
+])
+
+# Desired spatial distribution represented as a mixture of Gaussians (GMM)
+# gaussian centers
+param.Mu = np.array([
+    0.7,
+    0.5,
+])
+
+# Gaussian covariances
+param.Sigma = np.ones((1, 1, param.nbGaussian)) * 0.01
+param.Sigma[:,:,1] *= 0.5
+
+# Mixing coefficients
+param.Priors = np.ones(param.nbGaussian) / param.nbGaussian
+
+G = np.zeros(param.nbRes)
+G = discrete_gmm(param)
+G = np.abs(G)  # there is no negative heat
+
+
+# Initialize agents
+# ===============================
+agents = []
+for i in range(param.nbAgents):
+    agent = SecondOrderAgent(x=param.x0[i] * param.nbRes, nbDataPoints=param.nbDataPoints, max_dx=param.max_dx, max_ddx=param.max_ddx)
+    rgb = np.random.uniform(0, 1, 3)
+    agent.color = np.concatenate((rgb, [1.0]))  # append alpha value
+    agents.append(agent)
+
+
+# Initialize heat equation related fields
+# ===============================
+# precompute everything we can before entering the loop
+coverage_arr = np.zeros((param.nbRes, param.nbDataPoints))
+heat_arr = np.zeros((param.nbRes, param.nbDataPoints))
+local_arr = np.zeros((param.nbRes, param.nbDataPoints))
+goal_arr = np.zeros((param.nbRes, param.nbDataPoints))
+
+param.area = param.dx * param.nbRes
+
+goal_density = normalize_mat(G)
+
+coverage_density = np.zeros(param.nbRes)
+heat = np.array(goal_density)
+
+max_diffusion = np.max(param.alpha)
+param.dt = min(
+    1.0, param.dx / (2.0 * max_diffusion)
+)  # for the stability of implicit integration of Heat Equation
+coverage_block = agent_block(param.min_kernel_val, param.agent_radius)
+cooling_block = agent_block(param.min_kernel_val, param.cooling_radius)
+param.kernel_size = coverage_block.shape[0]
+
+
+# HEDAC Loop
+# ===============================
+# do absolute minimum inside the loop for speed
+for t in range(param.nbDataPoints):
+    # cooling of all the agents for a single timestep
+    # this is used for collision avoidance bw/ agents
+    local_cooling = np.zeros(param.nbRes)
+    for agent in agents:
+        # find agent pos on the grid as integer indices
+        p = agent.x
+        adjusted_position = p / param.dx
+        col = int(adjusted_position)
+
+        # each agent has a kernel around it,
+        # clamp the kernel by the grid boundaries
+        col_indices, col_start_kernel, num_kernel_cols = clamp_kernel_1d(
+            col, 0, param.nbRes, param.kernel_size
+        )
+
+        # add the kernel to the coverage density
+        # effect of the agent on the coverage density
+        coverage_density[col_indices] += coverage_block[
+            col_start_kernel : col_start_kernel + num_kernel_cols,
+        ]
+
+        # local cooling is used for collision avoidance between the agents
+        # so it can be disabled for speed if not required
+        # if param.local_cooling != 0:
+        #     local_cooling[col_indices] += cooling_block[
+        #         col_start_kernel : col_start_kernel + num_kernel_cols,
+        #     ]
+        # local_cooling = normalize_mat(local_cooling)
+
+    coverage = normalize_mat(coverage_density)
+
+    # this is the part we introduce exploration problem to the Heat Equation
+    diff = goal_density - coverage
+    sign = np.sign(diff)
+    source = np.maximum(diff, 0) ** 2
+    source = normalize_mat(source) * param.area
+
+    current_heat = np.zeros(param.nbRes)
+
+    # 1-D heat equation (Partial Differential Equation)
+    # At boundary we have Neumann boundary conditions which assumes
+    # that the derivative is zero at the boundary. This is equivalent
+    # to having a zero flux boundary condition or perfect insulation.
+    current_heat[1:-1] = param.dt * (
+        (
+            + param.alpha * offset(heat, 1)
+            + param.alpha * offset(heat, -1)
+            - 2.0 * offset(heat, 0)
+        )
+        / param.dx
+        + param.source_strength * offset(source, 0)
+        - param.local_cooling * offset(local_cooling, 0)
+    ) + offset(heat, 0)
+
+    heat = current_heat.astype(np.float32)
+
+    # Calculate the first derivatives
+    gradient = np.gradient(heat)
+
+    for agent in agents:
+        grad = calculate_gradient(
+            agent,
+            gradient,
+        )
+        agent.update(grad)
+
+    coverage_arr[..., t] = coverage
+    heat_arr[..., t] = heat
+
+
+# Plot
+# ===============================
+fig, ax = plt.subplots(2, 1, figsize=(16, 12))
+plt.subplots_adjust(hspace=0.4)
+
+xx = np.linspace(param.xlim[0], param.xlim[1], param.nbRes)
+ax[0].plot(xx, goal_density, lw=4, c=[1.0, .4, .4])
+ax[0].plot(xx, coverage, c='black')
+
+ax[0].legend(['Desired', 'Reproduced'], fontsize=10,loc='upper left')
+ax[0].set_xlim(param.xlim[0], param.xlim[1])
+ax[0].title.set_text('Distributions')
+ax[0].set_yticks([0])
+
+for agent in agents:
+    lines = ax[1].plot(agent.x_arr[:] / param.nbRes, np.arange(param.nbDataPoints), linestyle="-")
+    ax[1].plot(agent.x_arr[0] / param.nbRes, [0], marker=".", color=lines[0]._color, markersize=10)
+
+ax[1].set_xlim(param.xlim[0], param.xlim[1])
+ax[1].set_ylim(0, param.nbDataPoints)
+ax[1].set_yticks([0, param.nbDataPoints])
+ax[1].set_yticklabels(['$t-T$','$t$'])
+ax[1].title.set_text('Trajectory')
+
+plt.show()
diff --git a/python/ergodic_control_HEDAC.py b/python/ergodic_control_HEDAC_2D.py
similarity index 98%
rename from python/ergodic_control_HEDAC.py
rename to python/ergodic_control_HEDAC_2D.py
index 56073ae2563b32d99c277c5da3ff006c0e8132c9..05ed2bc866a3a62ae85eaede574d119e1fc45ce2 100644
--- a/python/ergodic_control_HEDAC.py
+++ b/python/ergodic_control_HEDAC_2D.py
@@ -6,7 +6,7 @@
     Written by Cem Bilaloglu <cem.bilaloglu@idiap.ch>
 
     This file is part of RCFS <https://rcfs.ch>
-    License: MIT
+    License: GPL-3.0-only
 """
 
 import numpy as np
@@ -242,17 +242,12 @@ def hadamard_matrix(n: int) -> np.ndarray:
     half_size = n // 2
     h_half = hadamard_matrix(half_size)
 
-    # Construct a matrix of ones with size n/2.
-    ones_matrix = np.ones((half_size, half_size), dtype=int)
-
-    # Construct a matrix of minus ones with size n/2.
-    minus_ones_matrix = -1 * ones_matrix
-
     # Combine the four sub-matrices to form a Hadamard matrix of size n.
     h = np.empty((n, n), dtype=int)
-    for i in range(half_size):
-        h[i] = np.concatenate((h_half[i], ones_matrix[i]))
-        h[i + half_size] = np.concatenate((h_half[i], minus_ones_matrix[i]))
+    h[:half_size,:half_size] = h_half
+    h[half_size:,:half_size] = h_half
+    h[:half_size:,half_size:] = h_half
+    h[half_size:,half_size:] = -h_half
 
     return h
 
diff --git a/python/ergodic_control_SMC_1D.py b/python/ergodic_control_SMC_1D.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d899b5d5d7c6cdbee56af87a1e8e5bb981ffcd3
--- /dev/null
+++ b/python/ergodic_control_SMC_1D.py
@@ -0,0 +1,153 @@
+"""
+1D ergodic control formulated as Spectral Multiscale Coverage (SMC) objective,
+with a spatial distribution described as a mixture of Gaussians.
+
+Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch>
+Written by Philip Abbet <philip.abbet@idiap.ch> and
+Sylvain Calinon <https://calinon.ch>
+
+This file is part of RCFS <https://rcfs.ch>
+License: GPL-3.0-only
+"""
+
+import numpy as np
+import matplotlib.pyplot as plt
+
+
+# Parameters
+# ===============================
+nbData = 500  # Number of datapoints
+nbFct = 10  # Number of basis functions
+nbGaussian = 2  # Number of Gaussians to represent the spatial distribution
+dt = 1e-2  # Time step
+xlim = [0, 1] # Domain limit for each dimension (considered to be 1 for each dimension in this implementation)
+L = (xlim[1] - xlim[0]) * 2  # Size of [-xlim(2),xlim(2)]
+om = 2 * np.pi / L # omega
+u_max = 3e-0  # Maximum speed allowed
+u_norm_reg = 1e-3 # Regularizer to avoid numerical issues when speed is close to zero
+
+# Initial point
+x0 = 0.1
+
+# Desired spatial distribution represented as a mixture of Gaussians (GMM)
+# gaussian centers
+Mu = np.array([
+    0.7,
+    0.5,
+])
+
+# Gaussian covariances
+Sigma = np.ones((1, 1, nbGaussian)) * 0.01
+Sigma[:,:,1] *= 0.5
+
+# Mixing coefficients
+Priors = np.ones(nbGaussian) / nbGaussian
+
+
+# Compute Fourier series coefficients w_hat of desired spatial distribution
+# ===============================
+rg = np.arange(nbFct, dtype=float).reshape((nbFct, 1))
+kk = rg * om
+Lambda = (rg**2 + 1) ** -1 # Weighting vector
+
+# Explicit description of w_hat by exploiting the Fourier transform
+# properties of Gaussians (optimized version by exploiting symmetries)
+w_hat = np.zeros((nbFct, 1))
+for j in range(nbGaussian):
+    w_hat = w_hat + Priors[j] * np.cos(kk * Mu[j]) * np.exp(-.5 * kk**2 * Sigma[:,:,j])
+
+w_hat = w_hat / L
+
+
+# Fourier basis functions (for a discretized map)
+# ===============================
+nbRes = 200
+xm = np.linspace(xlim[0], xlim[1], nbRes).reshape((1, nbRes))  # Spatial range for 1D
+phim = np.cos(kk @ xm) * 2  # Fourier basis functions
+phim[1:,:] = phim[1:,:] * 2
+
+# Desired spatial distribution
+g = phim.T @ w_hat
+
+
+# Ergodic control
+# ===============================
+x = x0  # Initial position
+
+wt = np.zeros((nbFct, 1))
+r_x = np.zeros((nbData))
+
+for t in range(nbData):
+    r_x[t] = x
+
+    # Fourier basis functions and derivatives for each dimension
+    # (only cosine part on [0,L/2] is computed since the signal
+    # is even and real by construction)
+    phi = np.cos(x * kk) / L
+
+    # Gradient of basis functions
+    dphi = -np.sin(x * kk) * kk / L
+
+    # w are the Fourier series coefficients along trajectory
+    wt = wt + phi 
+    w = wt / (t+1)
+
+    # Controller with constrained velocity norm
+    u = -dphi.T @ (Lambda * (w - w_hat))
+    u = u * u_max / (np.linalg.norm(u) + u_norm_reg)  # Velocity command
+
+    # Ensure that we don't go out of limits
+    next_x = x + u * dt
+    if (next_x < xlim[0]) or (next_x > xlim[1]):
+        u = -u
+
+    # Update of position
+    x = x + (u * dt)
+
+    # Log data
+    r_x[t] = x
+
+r_g = phim.T @ w
+
+# Plot
+# ===============================
+#def gdf(x, mu, sigma):
+#    return 1. / (np.sqrt(2. * np.pi) * sigma) * np.exp(-np.power((x - mu) / sigma, 2.) / 2)
+
+fig, ax = plt.subplots(4, 1, figsize=(16, 12), gridspec_kw={'height_ratios': [3, 3, 1, 1]})
+plt.subplots_adjust(hspace=0.4)
+
+#xx = xm.reshape((nbRes))
+#for j in range(nbGaussian):
+#    yy = gdf(xx, Mu[j], Sigma[0,0,j] * 4)
+#    ax[0].plot(xx, yy, color="red")
+#    ax[0].fill_between(xx, yy, alpha=0.2, color="red")
+ax[0].plot(xm.T, g, lw=4, c=[1.0, .4, .4])
+ax[0].plot(xm.T, r_g, c="black")
+#ax[0].fill_between(xm.T, g, alpha=0.2, color="red")
+ax[0].legend(['Desired','Reproduced'], fontsize=10,loc='upper left')
+ax[0].set_xlim(xlim[0], xlim[1])
+ax[0].title.set_text('Distributions')
+ax[0].set_yticks([0])
+
+ax[1].plot(r_x[:], np.arange(nbData), linestyle="-", c="black")
+ax[1].plot(r_x[-1], [nbData], marker=".", c="black", markersize=10)
+ax[1].set_xlim(xlim[0], xlim[1])
+ax[1].set_ylim(0, nbData)
+ax[1].set_yticks([0, nbData])
+ax[1].set_yticklabels(['$t-T$','$t$'])
+ax[1].title.set_text('Trajectory')
+#ax[1].set_ylabel('$t$')
+
+ax[2].set_title(r"Desired Fourier coefficients $\hat{w}$")
+ax[2].imshow(np.reshape(w_hat / nbData, [1, nbFct]), cmap="gray_r")
+msh = np.array([[0.0,0.0,nbFct,nbFct,0.0], [0.0,1.0,1.0,0.0,0.0]]) - 0.5
+ax[2].plot(msh[0,:],msh[1,:], linestyle="-", lw=4, c=[0.8, 0, 0])
+ax[2].set_yticks([])
+
+ax[3].set_title(r"Fourier coefficients $w$")
+ax[3].imshow(np.reshape(wt / nbData, [1, nbFct]), cmap="gray_r")
+ax[3].plot(msh[0,:],msh[1,:], linestyle="-", lw=4, c=[0, 0, 0])
+ax[3].set_yticks([])
+
+plt.show()
diff --git a/python/ergodic_control_SMC.py b/python/ergodic_control_SMC_2D.py
similarity index 67%
rename from python/ergodic_control_SMC.py
rename to python/ergodic_control_SMC_2D.py
index a966b119e7d281d896df7df5255ef23f153fb868..5555297fce17881966887ea31d53af7ef494dc89 100644
--- a/python/ergodic_control_SMC.py
+++ b/python/ergodic_control_SMC_2D.py
@@ -3,16 +3,17 @@
 with a spatial distribution described as a mixture of Gaussians.
 
 Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch>
-Written by Cem Bilaloglu <cem.bilaloglu@idiap.ch> and
+Written by Philip Abbet <philip.abbet@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 """
 
 import numpy as np
 #from math import exp
 import matplotlib.pyplot as plt
+from scipy.interpolate import interpn
 
 
 # Helper functions
@@ -35,25 +36,20 @@ def hadamard_matrix(n: int) -> np.ndarray:
     half_size = n // 2
     h_half = hadamard_matrix(half_size)
 
-    # Construct a matrix of ones with size n/2.
-    ones_matrix = np.ones((half_size, half_size), dtype=int)
-
-    # Construct a matrix of minus ones with size n/2.
-    minus_ones_matrix = -1 * ones_matrix
-
     # Combine the four sub-matrices to form a Hadamard matrix of size n.
     h = np.empty((n, n), dtype=int)
-    for i in range(half_size):
-        h[i] = np.concatenate((h_half[i], ones_matrix[i]))
-        h[i + half_size] = np.concatenate((h_half[i], minus_ones_matrix[i]))
+    h[:half_size,:half_size] = h_half
+    h[half_size:,:half_size] = h_half
+    h[:half_size:,half_size:] = h_half
+    h[half_size:,half_size:] = -h_half
 
     return h
 
 
 # Parameters
 # ===============================
-nbData = 200  # Number of datapoints
-nbFct = 10  # Number of basis functions along x and y
+nbData = 500  # Number of datapoints
+nbFct = 8  # Number of basis functions along x and y
 nbVar = 2  # Dimension of datapoints
 # Number of Gaussians to represent the spatial distribution
 nbGaussian = 2
@@ -64,13 +60,12 @@ dt = 1e-2  # Time step
 xlim = [0, 1]
 L = (xlim[1] - xlim[0]) * 2  # Size of [-xlim(2),xlim(2)]
 om = 2 * np.pi / L
-u_max = 1e1  # Maximum speed allowed
+u_max = 3e0  # Maximum speed allowed
+u_norm_reg = 1e-3 # Regularizer to avoid numerical issues when speed is close to zero
+
 
 # Initial point
 x0 = [0.1, 0.3]
-# this is a regularizer to avoid numerical issues
-# when speed is close to zero
-u_norm_reg = 1e-1
 nbRes = 100
 
 # Desired spatial distribution represented as a mixture of Gaussians (GMM)
@@ -102,12 +97,34 @@ Sigma[:, :, 1] = (
 )
 Alpha = np.ones(nbGaussian) / nbGaussian
 
-
-# Compute Fourier series coefficients w_hat of desired spatial distribution
+# Fourier basis functions (for a discretized map)
 # ===============================
 rg = np.arange(0, nbFct, dtype=float)
 KX = np.zeros((nbVar, nbFct, nbFct))
 KX[0, :, :], KX[1, :, :] = np.meshgrid(rg, rg)
+Lambda = np.array(KX[0, :].flatten() ** 2 + KX[1, :].flatten() ** 2 + 1).T ** (-sp)
+
+xm1d = np.linspace(xlim[0], xlim[1], nbRes)  # Spatial range for 1D
+xm = np.zeros((nbGaussian, nbRes, nbRes))  # Spatial range
+xm[0, :, :], xm[1, :, :] = np.meshgrid(xm1d, xm1d)
+# Mind the flatten() !!!
+arg1 = (
+    KX[0, :, :].flatten().T[:, np.newaxis] @ xm[0, :, :].flatten()[:, np.newaxis].T * om
+)
+arg2 = (
+    KX[1, :, :].flatten().T[:, np.newaxis] @ xm[1, :, :].flatten()[:, np.newaxis].T * om
+)
+phim = np.cos(arg1) * np.cos(arg2) * 2 ** (nbVar)  # Fourier basis functions
+
+# Some weird +1, -1 due to 0 index!!!
+xx, yy = np.meshgrid(np.arange(1, nbFct + 1), np.arange(1, nbFct + 1))
+hk = np.concatenate(([1], 2 * np.ones(nbFct)))
+HK = hk[xx.flatten() - 1] * hk[yy.flatten() - 1]
+phim = phim * np.tile(HK, (nbRes**nbVar, 1)).T
+
+
+# Compute Fourier series coefficients w_hat of desired spatial Gaussian distribution
+# ===============================
 # Mind the flatten() !!!
 # Weighting vector (Eq.(16))
 Lambda = np.array(KX[0, :].flatten() ** 2 + KX[1, :].flatten() ** 2 + 1).T ** (-sp)
@@ -128,27 +145,32 @@ for j in range(nbGaussian):
         w_hat = w_hat + Alpha[j] * cos_term * exp_term
 w_hat = w_hat / (L**nbVar) / (op.shape[1])
 
-# Fourier basis functions (for a discretized map)
-# ===============================
-xm1d = np.linspace(xlim[0], xlim[1], nbRes)  # Spatial range for 1D
-xm = np.zeros((nbGaussian, nbRes, nbRes))  # Spatial range
-xm[0, :, :], xm[1, :, :] = np.meshgrid(xm1d, xm1d)
-# Mind the flatten() !!!
-arg1 = (
-    KX[0, :, :].flatten().T[:, np.newaxis] @ xm[0, :, :].flatten()[:, np.newaxis].T * om
-)
-arg2 = (
-    KX[1, :, :].flatten().T[:, np.newaxis] @ xm[1, :, :].flatten()[:, np.newaxis].T * om
-)
-phim = np.cos(arg1) * np.cos(arg2) * 2 ** (nbVar)  # Fourrier basis functions
 
-# Some weird +1, -1 due to 0 index!!!
-xx, yy = np.meshgrid(np.arange(1, nbFct + 1), np.arange(1, nbFct + 1))
-hk = np.concatenate(([1], 2 * np.ones(nbFct)))
-HK = hk[xx.flatten() - 1] * hk[yy.flatten() - 1]
-phim = phim * np.tile(HK, (nbRes**nbVar, 1)).T
-
-# Desired spatial distribution
+# # Uncomment if a non-Gaussian spatial distribution should be used
+# # Here, a 2D array representing the SDF of a joined rectangle and circle
+# # is used as the distribution to target.
+# # ===============================
+# data = np.load('../data/sdf01.npy', allow_pickle=True).item()
+#
+# # Load data, inverse value and threshold to keep only the postive value (inside of SDF)
+# g = (-1.0 * data['y']).reshape((40, 40)) # sdf01 is a 40x40 array
+# g[g<0.0] = 0.0
+#
+# # Rescale distribution to match the defined resolution
+# x = np.linspace(0, 1, g.shape[0])
+# xi = np.linspace(0, 1, nbRes)
+# grid_xx, grid_yy = np.meshgrid(xi, xi, indexing='ij')
+# new_grid = np.stack((grid_xx, grid_yy), axis=-1)
+# g = interpn((x, x), g, new_grid)
+# g = g.reshape((nbRes * nbRes,))
+# g = g * nbRes**nbVar / np.sum(g)
+#
+# # Compute Fourier coefficients
+# phi_inv = np.cos(arg1) * np.cos(arg2) / L**nbVar / nbRes**nbVar
+# w_hat = phi_inv @ g
+
+
+# Compute desired spatial distribution from w_hat
 g = w_hat.T @ phim
 
 # Ergodic control
@@ -161,39 +183,39 @@ r_g = np.zeros((nbRes**nbVar, nbData))
 r_w = np.zeros((nbFct**nbVar, nbData))
 r_e = np.zeros((nbData))
 
-for i in range(nbData):
+for t in range(nbData):
     # Fourier basis functions and derivatives for each dimension
     # (only cosine part on [0,L/2] is computed since the signal
     # is even and real by construction)
-    angle = x[:, np.newaxis] * rg * om
-    phi1 = np.cos(angle)  # Eq.(18)
+    angle = x[:,np.newaxis] * rg * om
+    phi1 = np.cos(angle) / L 
+    dphi1 = -np.sin(angle) * np.tile(rg * om, (nbVar, 1)) / L
 
     # Gradient of basis functions
-    dphi1 = -np.sin(angle) * np.tile(rg, (nbVar, 1)) * om
-    phix = phi1[0, xx - 1].flatten()
-    phiy = phi1[1, yy - 1].flatten()
-    dphix = dphi1[0, xx - 1].flatten()
-    dphiy = dphi1[1, yy - 1].flatten()
+    phix = phi1[0, xx-1].flatten()
+    phiy = phi1[1, yy-1].flatten()
+    dphix = dphi1[0, xx-1].flatten()
+    dphiy = dphi1[1, yy-1].flatten()
 
-    dphi = np.vstack([[dphix * phiy], [phix * dphiy]])
+    dphi = np.vstack([[dphix * phiy], [phix * dphiy]]).T
 
-    # wt./t are the Fourier series coefficients along trajectory
-    # (Eq.(17))
-    wt = wt + (phix * phiy).T / (L**nbVar)
+    # w are the Fourier series coefficients along trajectory
+    wt = wt + (phix * phiy).T
+    w = wt / (t + 1)
 
     # Controller with constrained velocity norm
-    u = -dphi @ (Lambda * (wt / (i + 1) - w_hat))  # Eq.(24)
+    u = -dphi.T @ (Lambda * (w - w_hat)) 
     u = u * u_max / (np.linalg.norm(u) + u_norm_reg)  # Velocity command
 
     x = x + (u * dt)  # Update of position
     # Log data
-    r_x[:, i] = x
+    r_x[:,t] = x
     # Reconstructed spatial distribution (for visualization)
-    r_g[:, i] = (wt / (i + 1)).T @ phim
+    r_g[:,t] = phim.T @ w
     # Fourier coefficients along trajectory (for visualization)
-    r_w[:, i] = wt / (i + 1)
+    r_w[:,t] = w
     # Reconstruction error evaluation
-    r_e[i] = np.sum((wt / (i + 1) - w_hat) ** 2 * Lambda)
+    r_e[t] = np.sum((w - w_hat) ** 2 * Lambda)
 
 # Plot
 # ===============================
@@ -210,13 +232,19 @@ ax[0].contourf(X, Y, G, cmap="gray_r")
 ax[0].plot(r_x[0, :], r_x[1, :], linestyle="-", color="black")
 ax[0].plot(r_x[0, 0], r_x[1, 0], marker=".", color="black", markersize=10)
 ax[0].set_aspect("equal", "box")
+ax[0].set_xticks([])
+ax[0].set_yticks([])
+
+# w_hat
+ax[1].set_title(r"Desired Fourier coefficients $\hat{w}$")
+ax[1].imshow(np.reshape(w_hat, [nbFct, nbFct]).T, cmap="gray_r")
+ax[1].set_xticks([])
+ax[1].set_yticks([])
 
 # w
-ax[1].set_title(r"$w$")
-w = ax[1].imshow(np.reshape(wt / nbData, [nbFct, nbFct]).T, cmap="gray_r")
+ax[2].set_title(r"Reproduced Fourier coefficients $w$")
+ax[2].imshow(np.reshape(wt / nbData, [nbFct, nbFct]).T, cmap="gray_r")
+ax[2].set_xticks([])
+ax[2].set_yticks([])
 
-# w_hat
-ax[2].set_title(r"$\hat{w}$")
-ax[2].imshow(np.reshape(w_hat, [nbFct, nbFct]).T, cmap="gray_r")
-# plt.savefig('ergodic_weight.pdf')
 plt.show()
diff --git a/python/ergodic_control_SMC_DDP_1D.py b/python/ergodic_control_SMC_DDP_1D.py
new file mode 100644
index 0000000000000000000000000000000000000000..31339fa14c29b0080b33c62c4846d4d9963abd85
--- /dev/null
+++ b/python/ergodic_control_SMC_DDP_1D.py
@@ -0,0 +1,180 @@
+'''
+Trajectory optimization for ergodic control problem 
+
+Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
+Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
+Sylvain Calinon <https://calinon.ch>
+
+This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+License: GPL-3.0-only
+'''
+
+import numpy.matlib
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+
+# Helper functions
+# ===============================
+
+# Residuals w and Jacobians J in spectral domain
+def f_ergodic(x, param):
+	phi = np.cos(x @ param.kk.T) / param.L
+	dphi = - np.sin(x @ param.kk.T) * np.matlib.repmat(param.kk.T,param.nbData,1) / param.L
+	w = (np.sum(phi,axis=0) / param.nbData).reshape((param.nbFct,1))
+	J = dphi.T / param.nbData
+	return w, J
+
+## Parameters
+# ===============================
+
+param = lambda: None # Lazy way to define an empty class in python
+param.nbData = 100 # Number of datapoints
+param.nbVarX = 1 # State space dimension
+param.nbFct = 8 # Number of Fourier basis functsions
+param.nbStates = 2 # Number of Gaussians to represent the spatial distribution
+param.nbIter = 500 # Maximum number of iterations for iLQR
+param.dt = 1e-2 # Time step length
+param.r = 1e-12 # Control weight term
+
+param.xlim = [0,1] # Domain limit
+param.L = (param.xlim[1] - param.xlim[0]) * 2 # Size of [-param.xlim(2),param.xlim(2)]
+param.om = 2 * np.pi / param.L # Omega
+param.range = np.arange(param.nbFct)
+param.kk = param.om * param.range.reshape((param.nbFct,1))
+param.Lambda = 1/(param.range**2 + 1) # Weighting factor
+
+# Desired spatial distribution represented as a mixture of Gaussians
+param.Mu = np.array([0.7, 0.5])
+param.Sigma = np.array([0.003,0.01])
+
+logs = lambda: None # Object to store logs
+logs.x = []
+logs.w = []
+logs.g = []
+logs.e = []
+
+Priors = np.ones(param.nbStates) / param.nbStates # Mixing coefficients
+
+# Transfer matrices (for linear system as single integrator)
+Su = np.vstack([
+	np.zeros([param.nbVarX, param.nbVarX*(param.nbData-1)]), 
+	np.tril(np.kron(np.ones([param.nbData-1, param.nbData-1]), np.eye(param.nbVarX) * param.dt))
+]) 
+Sx = np.kron(np.ones(param.nbData), np.eye(param.nbVarX)).T
+
+Q = np.diag(param.Lambda) # Precision matrix
+R = np.eye((param.nbData-1) * param.nbVarX) * param.r # Control weight matrix (at trajectory level)
+
+
+# Compute Fourier series coefficients w_hat of desired spatial distribution
+# =========================================================================
+# Explicit description of w_hat by exploiting the Fourier transform properties of Gaussians (optimized version by exploiting symmetries)
+
+w_hat = np.zeros((param.nbFct,1))
+for i in range(param.nbStates):
+	w_hat = w_hat + Priors[i] * np.cos( param.kk * param.Mu[i] ) * np.exp(-.5*param.kk**2*param.Sigma[i])
+w_hat = w_hat / param.L
+
+# Fourier basis functions (only used for display as a discretized map)
+
+nbRes = 200
+xm = np.linspace(param.xlim[0],param.xlim[1],nbRes).reshape((1,nbRes)) # Spatial range
+phim = np.cos(param.kk @ xm) * 2 # Fourier basis functions
+phim[1:] = phim[1:]*2
+
+# Desired spatial distribution
+g = w_hat.T @ phim
+
+# iLQR
+# ===============================
+
+u = np.zeros(param.nbVarX * (param.nbData-1)).reshape((-1,1)) # Initial control command
+u = (u + np.random.normal(size=(len(u),1))).reshape((-1,1))
+
+x0 = np.array([[0.6]]) # Initial position
+
+for i in range(param.nbIter):
+	x = Su @ u + Sx @ x0 # System evolution
+	w, J = f_ergodic(x, param) # Fourier series coefficients and Jacobian
+	f = w - w_hat # Residual
+
+	du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f - u * param.r) # Gauss-Newton update
+	
+	cost0 = f.T @ Q @ f + np.linalg.norm(u)**2 * param.r # Cost
+	
+	# Log data
+	logs.x += [x] # Save trajectory in state space
+	logs.w += [w] # Save Fourier coefficients along trajectory
+	logs.g += [w.T @ phim] # Save reconstructed spatial distribution (for visualization)
+	logs.e += [cost0.squeeze()] # Save reconstruction error
+
+	# Estimate step size with backtracking line search method
+	alpha = 1
+	while True:
+		utmp = u + du * alpha
+		xtmp = Sx @ x0 + Su @ utmp
+		wtmp, _ = f_ergodic(xtmp,param)
+		ftmp = wtmp - w_hat 
+		cost = ftmp.T @ Q @ ftmp + np.linalg.norm(utmp)**2 * param.r
+		if cost < cost0 or alpha < 1e-3:
+			print("Iteration {}, cost: {}".format(i,cost.squeeze()))
+			break
+		alpha /= 2
+	
+	u = u + du * alpha
+
+	if np.linalg.norm(du * alpha) < 1E-2:
+		break # Stop iLQR iterations when solution is reached
+
+# Plots
+# ===============================
+
+# Plot distribution
+plt.subplot(3,2,1)
+plt.plot(xm.squeeze(),g.squeeze(),label="Desired",color=(1,.6,.6),linewidth=6)
+plt.plot(xm.squeeze(),logs.g[0].squeeze(),label="Initial",color=(.7,.7,.7),linewidth=2)
+plt.plot(xm.squeeze(),logs.g[-1].squeeze(),label="Final",color=(0,0,0),linewidth=2)
+plt.legend()
+plt.xlabel("x",fontsize=16)
+plt.ylabel("g(x)",fontsize=16)
+plt.yticks([])
+plt.xticks([])
+
+# Plot signal
+plt.subplot(3,1,2)
+plt.xlabel("x",fontsize=16)
+plt.yticks([1,param.nbData],["t-T","t"],fontsize=16)
+plt.xticks([])
+for i,x in enumerate(logs.x[::10]):
+	c = [0.9 * (1-(i*10)/len(logs.x))]*3
+	plt.plot(x,range(1,param.nbData+1),color=c)
+plt.plot(logs.x[-1],range(1,param.nbData+1),color=[0,0,0])
+
+# Plot Fourier coefficients
+plt.subplot(3,2,2)
+plt.xlabel("k",fontsize=16)
+plt.ylabel("$W_k$",fontsize=16)
+plt.xticks([0,param.nbFct-1])
+plt.yticks([])
+for i in range(param.nbFct):
+	plt.plot( [param.range[i],param.range[i]], [0,w_hat[i,0]], color = [1,.6,.6], linewidth=6)
+	plt.plot( [param.range[i],param.range[i]], [0,logs.w[-1][i,0]], color = [0,0,0], linewidth=2)
+	plt.scatter([param.range[i]],[logs.w[-1][i,0]],color=[0,0,0],zorder=10)
+plt.plot(param.range,np.zeros(len(param.range)),color=[0,0,0])
+
+# Plot Lambbda_k
+plt.subplot(3,2,5)
+plt.xlabel("k",fontsize=16)
+plt.ylabel("$\Lambda_k$",fontsize=16)
+plt.xticks([0,param.nbFct-1])
+plt.yticks([0,1])
+plt.plot(param.range,param.Lambda,color=[0,0,0],marker='o')
+
+# Plot Epsilon
+plt.subplot(3,2,6)
+plt.xlabel("n",fontsize=16)
+plt.ylabel("$\epsilon$",fontsize=16)
+plt.plot(logs.e,color=[0,0,0])
+
+plt.show()
\ No newline at end of file
diff --git a/python/ergodic_control_SMC_DDP_2D.py b/python/ergodic_control_SMC_DDP_2D.py
new file mode 100644
index 0000000000000000000000000000000000000000..599e455525c7ef317b14c5886a8d51ab6537cd56
--- /dev/null
+++ b/python/ergodic_control_SMC_DDP_2D.py
@@ -0,0 +1,262 @@
+'''
+Trajectory optimization for ergodic control problem 
+
+Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
+Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
+Sylvain Calinon <https://calinon.ch>
+
+This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+License: GPL-3.0-only
+'''
+
+import numpy.matlib
+import numpy as np
+import matplotlib.pyplot as plt
+import matplotlib.patches as patches
+
+# Helper functions
+# ===============================
+
+# Residuals w and Jacobians J in spectral domain
+def f_ergodic(x, param):
+	[xx,yy] = numpy.mgrid[range(param.nbFct),range(param.nbFct)]
+
+	phi1 = np.zeros((param.nbData,param.nbFct,2))
+	dphi1 = np.zeros((param.nbData,param.nbFct,2))
+
+	x1_s = x[0::2]
+	x2_s = x[1::2]
+
+	phi1[:,:,0] = np.cos(x1_s @ param.kk1.T) / param.L
+	dphi1[:,:,0] = - np.sin(x1_s @ param.kk1.T) * np.matlib.repmat(param.kk1.T,param.nbData,1) / param.L
+	
+	phi1[:,:,1] = np.cos(x2_s @ param.kk1.T) / param.L
+	dphi1[:,:,1] = - np.sin(x2_s @ param.kk1.T) * np.matlib.repmat(param.kk1.T,param.nbData,1) / param.L
+
+	phi = phi1[:,xx.flatten(),0] * phi1[:,yy.flatten(),1]
+
+	dphi = np.zeros((param.nbData*param.nbVarX,param.nbFct**2))
+	dphi[0::2,:] = dphi1[:,xx.flatten(),0] * phi1[:,yy.flatten(),1]
+	dphi[1::2,:] = phi1[:,xx.flatten(),0] * dphi1[:,yy.flatten(),1]
+
+	w = (np.sum(phi,axis=0) / param.nbData).reshape((param.nbFct**2,1))
+	J = dphi.T / param.nbData
+	return w, J
+
+# Constructs a Hadamard matrix of size n.
+def hadamard_matrix(n: int) -> np.ndarray:
+    # Base case: A Hadamard matrix of size 1 is just [[1]].
+    if n == 1:
+        return np.array([[1]])
+
+    # Recursively construct a Hadamard matrix of size n/2.
+    half_size = n // 2
+    h_half = hadamard_matrix(half_size)
+
+    # Combine the four sub-matrices to form a Hadamard matrix of size n.
+    h = np.empty((n, n), dtype=int)
+    h[:half_size,:half_size] = h_half
+    h[half_size:,:half_size] = h_half
+    h[:half_size:,half_size:] = h_half
+    h[half_size:,half_size:] = -h_half
+
+    return h
+
+## Parameters
+# ===============================
+
+param = lambda: None # Lazy way to define an empty class in python
+param.nbData = 200 # Number of datapoints
+param.nbVarX = 2 # State space dimension
+param.nbFct = 8 # Number of Fourier basis functsions
+param.nbStates = 2 # Number of Gaussians to represent the spatial distribution
+param.nbIter = 50 # Maximum number of iterations for iLQR
+param.dt = 1e-2 # Time step length
+param.r = 1e-8 # Control weight term
+
+param.xlim = [0,1] # Domain limit
+param.L = (param.xlim[1] - param.xlim[0]) * 2 # Size of [-param.xlim(2),param.xlim(2)]
+param.om = 2 * np.pi / param.L # Omega
+param.range = np.arange(param.nbFct)
+param.kk1 = param.om * param.range.reshape((param.nbFct,1))
+[xx,yy] = numpy.mgrid[range(param.nbFct),range(param.nbFct)]
+sp = (param.nbVarX + 1) / 2 # Sobolev norm parameter
+
+KX = np.zeros((param.nbVarX, param.nbFct, param.nbFct))
+KX[0, :, :], KX[1, :, :] = np.meshgrid(param.range, param.range)
+param.kk = KX.reshape(param.nbVarX, param.nbFct**2) * param.om
+param.Lambda = np.power(xx**2++yy**2+1,-sp).flatten() # Weighting vector
+
+# Enumerate symmetry operations for 2D signal ([-1,-1],[-1,1],[1,-1] and [1,1]), and removing redundant ones -> keeping ([-1,-1],[-1,1])
+op = hadamard_matrix(2**(param.nbVarX-1))
+
+# Desired spatial distribution represented as a mixture of Gaussians
+param.Mu = np.zeros((2,2))
+param.Mu[:,0] = [0.5, 0.7]
+param.Mu[:,1] = [0.6, 0.3]
+
+param.Sigma = np.zeros((2,2,2))
+sigma1_tmp= np.array([[0.3],[0.1]])
+param.Sigma[:,:,0] = sigma1_tmp @ sigma1_tmp.T * 5e-1 + np.identity(param.nbVarX)*5e-3
+sigma2_tmp= np.array([[0.1],[0.2]])
+param.Sigma[:,:,1] = sigma2_tmp @ sigma2_tmp.T * 3e-1 + np.identity(param.nbVarX)*1e-2 
+
+logs = lambda: None # Object to store logs
+logs.x = []
+logs.w = []
+logs.g = []
+logs.e = []
+
+Priors = np.ones(param.nbStates) / param.nbStates # Mixing coefficients
+
+# Transfer matrices (for linear system as single integrator)
+Su = np.vstack([
+	np.zeros([param.nbVarX, param.nbVarX*(param.nbData-1)]), 
+	np.tril(np.kron(np.ones([param.nbData-1, param.nbData-1]), np.eye(param.nbVarX) * param.dt))
+]) 
+Sx = np.kron(np.ones(param.nbData), np.eye(param.nbVarX)).T
+
+Q = np.diag(param.Lambda) # Precision matrix
+R = np.eye((param.nbData-1) * param.nbVarX) * param.r # Control weight matrix (at trajectory level)
+
+
+# Compute Fourier series coefficients w_hat of desired spatial distribution
+# =========================================================================
+# Explicit description of w_hat by exploiting the Fourier transform properties of Gaussians (optimized version by exploiting symmetries)
+
+w_hat = np.zeros(param.nbFct**param.nbVarX)
+for j in range(param.nbStates):
+    for n in range(op.shape[1]):
+        MuTmp = np.diag(op[:, n]) @ param.Mu[:, j]
+        SigmaTmp = np.diag(op[:, n]) @ param.Sigma[:, :, j] @ np.diag(op[:, n]).T
+        cos_term = np.cos(param.kk.T @ MuTmp)
+        exp_term = np.exp(np.diag(-0.5 * param.kk.T @ SigmaTmp @ param.kk))
+        # Eq.(22) where D=1
+        w_hat = w_hat + Priors[j] * cos_term * exp_term
+w_hat = w_hat / (param.L**param.nbVarX) / (op.shape[1])
+w_hat = w_hat.reshape((-1,1))
+
+# Fourier basis functions (only used for display as a discretized map)
+nbRes = 40
+xm1d = np.linspace(param.xlim[0], param.xlim[1], nbRes)  # Spatial range for 1D
+xm = np.zeros((param.nbStates, nbRes, nbRes))  # Spatial range
+xm[0, :, :], xm[1, :, :] = np.meshgrid(xm1d, xm1d)
+phim = np.cos(KX[0,:].flatten().reshape((-1,1)) @ xm[0,:].flatten().reshape((1,-1))*param.om) * np.cos(KX[1,:].flatten().reshape((-1,1)) @ xm[1,:].flatten().reshape((1,-1))*param.om) * 2 ** param.nbVarX
+hk = np.ones((param.nbFct,1)) * 2
+hk[0,0] = 1
+HK = hk[xx.flatten()] * hk[yy.flatten()]
+phim = phim * np.matlib.repmat(HK,1,nbRes**param.nbVarX)
+
+# Desired spatial distribution
+g = w_hat.T @ phim
+
+# Myopic ergodic control (for initialisation)
+# ===============================
+u_max = 4e0 # Maximum speed allowed
+u_norm_reg = 1e-3 
+
+xt = np.array([[0.1],[0.1]]) # Initial position
+wt = np.zeros((param.nbFct**param.nbVarX,1))
+u = np.zeros((param.nbData-1,param.nbVarX)) # Initial control command
+
+for t in range(param.nbData-1):
+	phi1 = np.cos(xt @ param.kk1.T) / param.L # In 1D
+	dphi1 = - np.sin(xt @ param.kk1.T) * np.matlib.repmat(param.kk1.T, param.nbVarX,1) / param.L # in 1D
+
+	phi = (phi1[0,xx.flatten()] * phi1[1,yy.flatten()]).reshape((-1,1)) # Fourier basis function
+	dphi = np.vstack((
+		dphi1[0,xx.flatten()] * phi1[1,yy.flatten()],
+		phi1[0,xx.flatten()] * dphi1[1,yy.flatten()]
+	)) # Gradient of Fourier basis functions
+
+	wt = wt + phi
+	w = wt / (t+1) #w are the Fourier series coefficients along trajectory 
+
+	# Controller with constrained velocity norm
+	u_t = -dphi @ np.diag(param.Lambda) @ (w-w_hat)
+	u_t = u_t * u_max / (np.linalg.norm(u_t)+u_norm_reg) # Velocity command
+	u[t] = u_t.T
+	xt = xt + u_t * param.dt # Update of position
+
+# iLQR
+# ===============================
+
+u = u.reshape((-1,1)) # Initial control command
+#u = (u + np.random.normal(size=(len(u),1))).reshape((-1,1))
+
+x0 = np.array([[0.1],[0.1]]) # Initial position
+
+for i in range(param.nbIter):
+	x = Su @ u + Sx @ x0 # System evolution
+	w, J = f_ergodic(x, param) # Fourier series coefficients and Jacobian
+	f = w - w_hat # Residual
+
+	du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f - u * param.r) # Gauss-Newton update
+	
+	cost0 = f.T @ Q @ f + np.linalg.norm(u)**2 * param.r # Cost
+	
+	# Log data
+	logs.x += [x] # Save trajectory in state space
+	logs.w += [w] # Save Fourier coefficients along trajectory
+	logs.g += [w.T @ phim] # Save reconstructed spatial distribution (for visualization)
+	logs.e += [cost0.squeeze()] # Save reconstruction error
+
+	# Estimate step size with backtracking line search method
+	alpha = 1
+	while True:
+		utmp = u + du * alpha
+		xtmp = Sx @ x0 + Su @ utmp
+		wtmp, _ = f_ergodic(xtmp,param)
+		ftmp = wtmp - w_hat 
+		cost = ftmp.T @ Q @ ftmp + np.linalg.norm(utmp)**2 * param.r
+		if cost < cost0 or alpha < 1e-3:
+			print("Iteration {}, cost: {}".format(i,cost.squeeze()))
+			break
+		alpha /= 2
+	
+	u = u + du * alpha
+
+	if np.linalg.norm(du * alpha) < 1E-2:
+		break # Stop iLQR iterations when solution is reached
+
+# Plots
+# ===============================
+
+plt.figure(figsize=(16,8))
+
+# x
+plt.subplot(2,3,1)
+X = np.squeeze(xm[0, :, :])
+Y = np.squeeze(xm[1, :, :])
+G = np.reshape(g, [nbRes, nbRes])  # original distribution
+G = np.where(G > 0, G, 0)
+plt.contourf(X, Y, G, cmap="gray_r")
+plt.plot(logs.x[0][0::2],logs.x[0][1::2], linestyle="-", color=[.7,.7,.7],label="Initial")
+plt.plot(logs.x[-1][0::2],logs.x[-1][1::2], linestyle="-", color=[0,0,0],label="Final")
+plt.axis("scaled")
+plt.legend()
+plt.title("Spatial distribution g(x)")
+plt.xticks([])
+plt.yticks([])
+
+# w_hat
+plt.subplot(2,3,2)
+plt.title(r"Desired Fourier coefficients $\hat{w}$")
+plt.imshow(np.reshape(w_hat, [param.nbFct, param.nbFct]).T, cmap="gray_r")
+plt.xticks([])
+plt.yticks([])
+
+# w
+plt.subplot(2,3,3)
+plt.title(r"Reproduced Fourier coefficients $w$")
+plt.imshow(np.reshape(logs.w[-1] / param.nbData, [param.nbFct, param.nbFct]).T, cmap="gray_r")
+plt.xticks([])
+plt.yticks([])
+
+# error
+plt.subplot(2,1,2)
+plt.xlabel("n",fontsize=16)
+plt.ylabel("$\epsilon$",fontsize=16)
+plt.plot(logs.e,color=[0,0,0])
+
+plt.show()
\ No newline at end of file
diff --git a/python/header.txt b/python/header.txt
index cb673066025464a4c2f90ccfee38a8f476236310..1f5fc921ec68f2acf2d97af3d9c1a1ff1d549dc0 100644
--- a/python/header.txt
+++ b/python/header.txt
@@ -6,5 +6,5 @@ Written by John Doe <john.doe@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
diff --git a/python/iLQR_bicopter.py b/python/iLQR_bicopter.py
index df043e32ee03f3ea5cfa48839d91acd5e6e83746..0892b93fbacb8d23433604fc82e9d555a207bc7a 100644
--- a/python/iLQR_bicopter.py
+++ b/python/iLQR_bicopter.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -118,8 +118,12 @@ for i in range(param.nbIter):
     
     # Gauss-Newton update
     e = x[:,tl].flatten() - param.Mu 
-    du = np.linalg.inv(Su.T @ Q @ Su + R) @ (-Su.T @ Q @ e - R @ u)
-    
+    du = np.linalg.lstsq(
+		Su.T @ Q @ Su + R,
+		-Su.T @ Q @ e - R @ u,
+		rcond=-1
+	)[0] # Gauss-Newton update
+
     # Estimate step size with backtracking line search method
     alpha = 1
     cost0 = e.T @ Q @ e + u.T @ R @ u
diff --git a/python/iLQR_bimanual.py b/python/iLQR_bimanual.py
index 1202c70f18cbe4e2b1c52cfef1a3d9fe6cfed135..14c5357745183327704b166bd32603560045263a 100644
--- a/python/iLQR_bimanual.py
+++ b/python/iLQR_bimanual.py
@@ -6,7 +6,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -149,10 +149,13 @@ for i in range(param.nbIter):
 #    print(Qc.shape)
 #    print(fc.flatten('F'))
 
-    du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + Su0.T @ Jc.T @ Qc @ Jc @ Su0 + R) @ \
-         (-Su.T @ J.T @ Q @ f.flatten('F') - \
+    du = np.linalg.lstsq(
+		Su.T @ J.T @ Q @ J @ Su + Su0.T @ Jc.T @ Qc @ Jc @ Su0 + R,
+        (-Su.T @ J.T @ Q @ f.flatten('F') - \
          Su0.T @ Jc.T @ Qc @ fc.flatten('F') - \
-         u * param.r)
+         u * param.r),
+        rcond=-1
+	)[0] # Gauss-Newton update
 
     # Estimate step size with line search method
     alpha = 1
diff --git a/python/iLQR_bimanual_manipulability.py b/python/iLQR_bimanual_manipulability.py
index aa9d66a84fe77bc90ccba7cd7260a153cfe0d3dc..7875d096ec9a7924d1de6c75237c99323c36747e 100644
--- a/python/iLQR_bimanual_manipulability.py
+++ b/python/iLQR_bimanual_manipulability.py
@@ -7,7 +7,7 @@ Written by Boyang Ti <https://tiboy.co/> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -157,7 +157,13 @@ for i in range(param.nbIter):
     x = Su0 @ u + Sx0 @ x0  # System evolution
     x = x.reshape([param.nbVarX, param.nbData], order='F')
     f, J = f_manipulability(x[:,tl], param)  # Residuals and Jacobians
-    du = np.linalg.inv(Su.T @ J.T @ J @ Su + R) @ (-Su.T @ J.T @ f.flatten('F') - u * param.r)  # Gauss-Newton update
+
+    du = np.linalg.lstsq(
+		Su.T @ J.T @ J @ Su + R,
+		-Su.T @ J.T @ f.flatten('F') - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update   
+   
     # Estimate step size with backtracking line search method
     alpha = 1
     cost0 = f.flatten('F').T @ f.flatten('F') + np.linalg.norm(u)**2 * param.r  # Cost
diff --git a/python/iLQR_car.py b/python/iLQR_car.py
index ef22a34d3d9397562df2c5d913bb7b3ca5b2a53d..26b4e13d7b16bce246a209521fe7db53a4d08eec 100644
--- a/python/iLQR_car.py
+++ b/python/iLQR_car.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -111,7 +111,11 @@ for i in range(param.nbIter):
     
     # Gauss-Newton update
     e = x[:,tl].flatten('F') - param.Mu.flatten('F') 
-    du = np.linalg.inv(Su.T @ Q @ Su + R) @ (-Su.T @ Q @ e - R @ u)
+    du = np.linalg.lstsq(
+		Su.T @ Q @ Su + R,
+		-Su.T @ Q @ e - R @ u,
+		rcond=-1
+	)[0] # Gauss-Newton update
     
     # Estimate step size with backtracking line search method
     alpha = 1
diff --git a/python/iLQR_distMaintenance.py b/python/iLQR_distMaintenance.py
index 863e91b5243ccbf2b12565de985bc8a7a457af7c..24e31f1373407fd32319db762d226833126aa07a 100644
--- a/python/iLQR_distMaintenance.py
+++ b/python/iLQR_distMaintenance.py
@@ -6,7 +6,7 @@ Written by Maximilien Dufau <maximilien.dufau@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -62,8 +62,12 @@ for i in range( param.nbIter ):
     x = Su @ u + Sx @ x0
     x = x.reshape( ( param.nbVarX, param.nbData ),order="F" )
     f, J = f_dist(x,param)# Avoidance objective
-
-    du = np.linalg.inv(Su.T @ J.T @ J @ Su * param.q + R) @ (-Su.T @ J.T @ f * param.q - u * param.r)
+	
+    du = np.linalg.lstsq(
+		Su.T @ J.T @ J @ Su * param.q + R,
+		-Su.T @ J.T @ f * param.q - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/iLQR_manipulator.py b/python/iLQR_manipulator.py
index d83720f6a4b136c39786081c1f101418a698de0b..759470a21d831a668d738a9f7763237f4b963d8e 100644
--- a/python/iLQR_manipulator.py
+++ b/python/iLQR_manipulator.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -133,7 +133,13 @@ for i in range(param.nbIter):
 	x = Su0 @ u + Sx0 @ x0 # System evolution
 	x = x.reshape([param.nbVarX, param.nbData], order='F')
 	f, J = f_reach(x[:,tl], param) # Residuals and Jacobians
-	du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f.flatten('F') - u * param.r) # Gauss-Newton update
+
+	du = np.linalg.lstsq(
+		Su.T @ J.T @ Q @ J @ Su + R,
+		-Su.T @ J.T @ Q @ f.flatten('F') - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
+
 	# Estimate step size with backtracking line search method
 	alpha = 1
 	cost0 = f.flatten('F').T @ Q @ f.flatten('F') + np.linalg.norm(u)**2 * param.r # Cost
diff --git a/python/iLQR_manipulator3D.py b/python/iLQR_manipulator3D.py
index 00e87a2ed717a314028e04c58a805e0734e60a0c..3c4dbcdeb06cc36fb58cf880f171bd4b5e194f19 100644
--- a/python/iLQR_manipulator3D.py
+++ b/python/iLQR_manipulator3D.py
@@ -7,14 +7,13 @@ Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
 import numpy.matlib
 import matplotlib.pyplot as plt
-import matplotlib.patches as patches
-import math
+
 
 # Helper functions
 # ===============================
@@ -121,8 +120,9 @@ def R2q(R):
 			[R[2,0]+R[0,2], R[2,1]+R[1,2], R[2,2]-R[0,0]-R[1,1], R[0,1]-R[1,0]],
 			[R[1,2]-R[2,1], R[2,0]-R[0,2], R[0,1]-R[1,0], R[0,0]+R[1,1]+R[2,2]],
 	]) / 3.0
-	_, V = np.linalg.eig(K)
-	return np.real([V[3, 0], V[0, 0], V[1, 0], V[2, 0]]) # for quaternions as [w,x,y,z]
+	e_val, e_vec = np.linalg.eig(K) # unsorted eigenvalues
+	q = np.real([e_vec[3, np.argmax(e_val)], *e_vec[0:3, np.argmax(e_val)]]) # for quaternions as [w,x,y,z]
+	return q
 
 # Plot coordinate system
 def plotCoordSys(ax, x, R, width=1):
@@ -144,7 +144,6 @@ param.nbPoints = 2 # Number of viapoints
 param.nbVarX = 7 # State space dimension (x1,x2,x3,...)
 param.nbVarU = param.nbVarX # Control space dimension (dx1,dx2,dx3,...)
 param.nbVarF = 7 # Task space dimension (f1,f2,f3 for position, f4,f5,f6,f7 for unit quaternion)
-param.q = 1e0 # Tracking weighting term
 param.r = 1e-6 # Control weighting term
 
 Rtmp = q2R([np.cos(np.pi/3), np.sin(np.pi/3), 0.0, 0.0])
@@ -170,7 +169,8 @@ param.dh.r = [0, 0, 0, 0.0825, -0.0825, 0, 0.088, 0] # Length of the common norm
 # ===============================
 
 # Precision matrix
-Q = np.eye((param.nbVarF-1) * param.nbPoints) * param.q
+# Q = np.identity((param.nbVarF-1) * param.nbPoints) # Full precision matrix
+Qr = np.diag([1.0,1.0,1.0,1.0,1.0,0.0] * param.nbPoints) # Precision matrix in relative coordinate frame (tool frame) (by removing orientation constraint on 3rd axis)
 
 # Control weight matrix (at trajectory level)
 R = np.eye((param.nbData-1) * param.nbVarU) * param.r
@@ -193,7 +193,7 @@ Su = Su0[idx,:] # We remove the lines that are out of interest
 # ===============================
 
 u = np.zeros((param.nbVarU * (param.nbData-1), 1)) # Initial control command
-x0 = np.array([0, 0, 0, -np.pi/2, -0, np.pi/2, 0]) # Initial robot pose
+x0 = np.array([0, 0, 0, -np.pi/2, 0, np.pi/2, 0]) # Initial robot pose
 
 x0 = x0.reshape((-1, 1))
 
@@ -204,7 +204,24 @@ for i in range(param.nbIter):
 	f, J = f_reach(x[:,tl], param) # Residuals and Jacobians
 	f = f.reshape((-1,1), order='F')
 
-	du = np.linalg.pinv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f - u * param.r) # Gauss-Newton update
+	Ra = np.zeros_like(Qr)
+
+	for j in range(param.nbPoints):
+		Rkp = np.zeros((param.nbVarF-1,param.nbVarF-1)) # Transformation matrix with both translation and rotation
+		Rkp[:3,:3] = np.identity(3) # For translation
+		Rkp[-3:,-3:] = q2R(param.Mu[-4:,j]) # Orientation matrix for target
+
+		nbVarQ = param.nbVarF - 1
+		Ra[j*nbVarQ:(j+1)*nbVarQ,j*nbVarQ:(j+1)*nbVarQ] = Rkp
+
+	Q = Ra @ Qr @ Ra.T # Precision matrix in absolute coordinate frame (base frame)
+	
+	#du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f - u * param.r) # Gauss-Newton update
+	du = np.linalg.lstsq(
+		Su.T @ J.T @ Q @ J @ Su + R,
+		-Su.T @ J.T @ Q @ f - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
 
 	# Estimate step size with backtracking line search method
 	alpha = 1
diff --git a/python/iLQR_manipulator_CP.py b/python/iLQR_manipulator_CP.py
index bd0cdadcce1cf50b3ce23d33bf24de8ee767996b..44afe88d46dc510e5d837f0e5743b3b0d3aa159e 100644
--- a/python/iLQR_manipulator_CP.py
+++ b/python/iLQR_manipulator_CP.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -189,7 +189,11 @@ for i in range( param.nbIter ):
 	x = x.reshape( (  param.nbData , param.nbVarX) )
 
 	f, J = f_reach(param,x[tl])
-	dw = np.linalg.inv(PSI.T @ Su.T @ J.T @ Q @ J @ Su @ PSI + PSI.T @ R @ PSI) @ (-PSI.T @ Su.T @ J.T @ Q @ f.flatten() - PSI.T @ u * param.r)
+	dw = np.linalg.lstsq(
+		PSI.T @ Su.T @ J.T @ Q @ J @ Su @ PSI + PSI.T @ R @ PSI,
+		-PSI.T @ Su.T @ J.T @ Q @ f.flatten() - PSI.T @ u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
 	du = PSI @ dw
 	# Perform line search
 	alpha = 1
diff --git a/python/iLQR_manipulator_CoM.py b/python/iLQR_manipulator_CoM.py
index 56adcd5e3d31288009578c7b8539a411b5bf56af..6114c090730d50ce101493f8dd01cbb7e3911154 100644
--- a/python/iLQR_manipulator_CoM.py
+++ b/python/iLQR_manipulator_CoM.py
@@ -7,7 +7,7 @@ Written by Teng Xue <teng.xue@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -143,8 +143,11 @@ for i in range(param.nbIter):
     x = x.reshape([param.nbVarX, param.nbData], order='F')
     f, J = f_reach(x[:,tl], param)
     fc, Jc = f_reach_CoM(x, param)
-    du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + Su0.T @ Jc.T @ Qc @ Jc @ Su0 + R) @ \
-                      (-Su.T @ J.T @ Q @ f.flatten('F') - Su0.T @ Jc.T @ Qc @ fc.flatten('F') - u * param.r)
+    du = np.linalg.lstsq(
+		Su.T @ J.T @ Q @ J @ Su + Su0.T @ Jc.T @ Qc @ Jc @ Su0 + R,
+		-Su.T @ J.T @ Q @ f.flatten('F') - Su0.T @ Jc.T @ Qc @ fc.flatten('F') - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/iLQR_manipulator_boundary.py b/python/iLQR_manipulator_boundary.py
new file mode 100644
index 0000000000000000000000000000000000000000..40b30adf543df358784d69c35b50bbf59b6a5fd4
--- /dev/null
+++ b/python/iLQR_manipulator_boundary.py
@@ -0,0 +1,218 @@
+"""
+iLQR applied to a planar manipulator for a viapoints task with bounding on x
+
+Copyright (c) 2021 Idiap Research Institute, http://www.idiap.ch/
+Written by Ekansh Sharma <ekanshh.sharma@gmail.com> and
+Sylvain Calinon <https://calinon.ch>
+
+This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
+License: GPL-3.0-only
+"""
+
+import matplotlib.pyplot as plt
+import numpy as np
+
+
+def fkin(x, param):
+    """Forward kinematics for end-effector (in robot coordinate system)"""
+    T = np.tril(np.ones(len(x)))
+    f = np.vstack([param.l @ np.cos(T @ x), param.l @ np.sin(T @ x)])
+    return f
+
+
+def jacob0(x, param):
+    """Jacobian with analytical computation (for single time step)"""
+    T = np.tril(np.ones(len(x)))
+    J = np.array(
+        [
+            -np.sin(T @ x).T @ np.diag((param.l)) @ T,
+            np.cos(T @ x).T @ np.diag(param.l) @ T,
+        ]
+    )
+    return J
+
+
+def f_reach(x, param):
+    """Cost and gradient for a viapoints reaching task (in object coordinate system)"""
+    f = fkin(x, param) - param.Mu
+    J = np.array([])
+    for t in range(x.shape[1]):
+        Jtmp = jacob0(x[:, t], param)
+        if np.any(J):
+            J = np.block(
+                [
+                    [J, np.zeros((J.shape[0], Jtmp.shape[1]))],
+                    [np.zeros((Jtmp.shape[0], J.shape[1])), Jtmp],
+                ]
+            )
+        else:
+            J = Jtmp
+    return f, J
+
+def x_bound(x, param):
+    """Cost and gradient for a viapoints reaching task (in object coordinate system)"""
+    xlim = np.tile(param.xlim.T, (param.nbData))
+    idv = np.abs(x) > xlim
+    Jv = np.eye(np.sum(idv))
+    v = x[idv] - np.sign(x[idv]) * xlim[idv].flatten()
+    return v, Jv, idv
+
+
+def fkin0(x, params):
+    """Compute forward kinematics for all joints (in robot coordinate system)"""
+    L = np.tril(np.ones(len(x)))
+    f = np.vstack(
+        [
+            L @ np.diag(params.l) @ np.cos(L @ x),
+            L @ np.diag(params.l) @ np.sin(L @ x),
+        ]
+    )
+    f = np.hstack((np.zeros((2, 1)), f))
+    return f
+
+## Parameters
+# ===============================
+
+param = lambda: None
+param.dt = 1e-2  # Time step size
+param.nbData = 100  # Number of datapoints
+param.nbIter = 100  # Maximum number of iterations for iLQR
+param.nbPoints = 2  # Number of viapoints
+param.nbVarX = 3  # State space dimension (x1,x2,x3)
+param.nbVarU = 3  # Control space dimension (dx1,dx2,dx3)
+param.nbVarF = 2  # Task space dimension (f1,f2)
+param.l = np.array([3, 2, 1])  # Robot links lengths
+param.xlim = np.array([np.pi * 2, np.pi * 2, np.pi * 0.05])  # joint angles range
+param.q = 1e0  # Tracking weighting term
+param.rv = 1e3  # Bounding weighting term
+param.r = 1e-4  # Control weighting term
+param.Mu = np.array([[2, 3], [1, 2]])  # Viapoints
+
+# Main program
+# ===============================
+
+# Precision matrix
+Q = np.eye(param.nbVarF * param.nbPoints)
+
+# Control weight matrix
+R = np.eye((param.nbData - 1) * param.nbVarU) * param.r
+
+# Time occurrence of viapoints
+tl = np.rint(np.linspace(0, param.nbData - 1, param.nbPoints + 1)[1:]).astype(np.int64)
+idx = np.array([i + np.arange(0, param.nbVarX, 1) for i in (tl * param.nbVarX)])
+idx = idx.flatten()
+
+# Transfer matrices (for linear system as single integrator)
+Su0 = np.vstack(
+    [
+        np.zeros([param.nbVarX, param.nbVarX * (param.nbData - 1)]),
+        np.kron(np.tril(np.ones(param.nbData - 1)), np.eye(param.nbVarX) * param.dt),
+    ]
+)
+Sx0 = np.kron(np.ones(param.nbData), np.eye(param.nbVarX)).T
+Su = Su0[idx, :]  # We remove the lines that are out of interest
+
+# iLQR
+# ===============================
+
+u = np.zeros(param.nbVarU * (param.nbData - 1))  # Initial control command
+x0 = np.array([3 * np.pi / 4, -np.pi / 2, np.pi / 4])  # Initial state
+
+for i in range(param.nbIter):
+    x = Sx0 @ x0 + Su0 @ u  # System evolution
+    x = x.reshape([param.nbVarX, param.nbData], order="F")
+
+    f, J = f_reach(x[:, tl], param)  # Residuals and Jacobians for reaching task
+    x = x.flatten(order="F")
+    v, Jv, idv = x_bound(x, param)  # Residuals and Jacobians for boundary on x
+
+    Sv = Su0[idv, :]
+
+    du = np.linalg.lstsq(
+		Su.T @ J.T @ Q @ J @ Su + Sv.T @ Jv.T @ Jv @ Sv * param.rv + R,
+		-Su.T @ J.T @ Q @ f.flatten("F") - Sv.T @ Jv.T @ v * param.rv - u * param.r,
+		rcond=-1
+	)[0] # Gauss-Newton update
+
+    # Estimate step size with backtracking line search method
+    alpha = 1
+    cost0 = f.flatten("F").T @ Q @ f.flatten("F") + np.linalg.norm(v) ** 2 * param.rv + np.linalg.norm(u) ** 2 * param.r
+    while True:
+        utmp = u + du * alpha
+        xtmp = Su0 @ utmp + Sx0 @ x0  # System evolution
+        xtmp = xtmp.reshape([param.nbVarX, param.nbData], order="F")
+        ftmp, _ = f_reach(xtmp[:, tl], param)  # Residuals
+        xtmp = xtmp.flatten(order="F")
+        vtmp, _, _ = x_bound(xtmp, param)
+        cost = (
+            ftmp.flatten("F").T @ Q @ ftmp.flatten("F")
+            + np.linalg.norm(vtmp) ** 2 * param.rv
+            + np.linalg.norm(utmp) ** 2 * param.r
+        )
+        if cost < cost0 or alpha < 1e-4:
+            print("Iteration {}, cost: {}, alpha: {}".format(i, cost, alpha))
+            break
+        alpha /= 2
+
+    u = u + du * alpha
+
+    if np.linalg.norm(du * alpha) < 1e-2:
+        break  # Stop iLQR iterations when solution is reached
+
+print(f"iLQR converged in {i} iterations")
+
+# Visualize
+x = x.reshape([param.nbVarX, param.nbData], order="F")
+"""Plot robot forward kinematics for initial configuration, via-points, and path."""
+_, ax = plt.subplots(figsize=(12, 8))
+
+fkin00 = fkin0(x0, param)
+ax.plot(fkin00[0, :], fkin00[1, :], color=(0.9, 0.9, 0.9), 
+        linewidth=5,label="Initial Configuration",)
+ax.scatter(fkin00[0, 1:], fkin00[1, 1:], color="skyblue", 
+           marker="o", s=100, zorder=2)
+ax.scatter(fkin00[0, 0], fkin00[1, 0], color="black", 
+           marker="s", s=100, zorder=2)
+
+for i, idx in enumerate(tl):
+    fkin0_i = fkin0(x[:, idx], param)
+    color_factor = len(param.Mu) / (len(param.Mu) - i)
+    ax.plot(fkin0_i[0, :], fkin0_i[1, :], linewidth=5,
+        color=(0.8 / color_factor, 0.8 / color_factor, 0.8 / color_factor),
+        label=f"Via-point {i + 1} Configuration",
+    )
+    ax.scatter(fkin0_i[0, 1:], fkin0_i[1, 1:], color="skyblue", 
+               marker="o", s=100, zorder=2)
+    ax.scatter(fkin0_i[0, 0], fkin0_i[1, 0], color="black", 
+               marker="s", s=100, zorder=2)
+
+ftmp0 = fkin(x, param)
+ax.plot(ftmp0[0, :], ftmp0[1, :], "--", linewidth=1,
+    color="black", label="End-effector trajectory",
+)
+ax.plot(param.Mu[0, 0], param.Mu[1, 0], ".", markersize=10, color="darkred", 
+        label="Via-point 1 Marker",
+)
+ax.plot(param.Mu[0, 1], param.Mu[1, 1], ".", markersize=10,
+    color="purple", label="Via-point 2 Marker",
+)
+
+ax.axis("off")
+ax.set_aspect("equal", adjustable="box")
+ax.legend(loc="upper left", bbox_to_anchor=(1.05, 1), borderaxespad=0.0)
+plt.show()
+
+"""Plot the change of x ( i.e. [x1, x2, x3]) over time"""
+_, axs = plt.subplots(3, 1, figsize=(10, 8))
+
+for i in range(3):
+    axs[i].plot(x[i, :], color="black", label=f"x{i}")
+    axs[i].axhline(y=x0[i], color="blue", linestyle="--", label=f"x{i}_0")
+    axs[i].axhline(y=param.xlim[i], color="red", linestyle="--", label=f"x{i}_lim")
+    axs[i].set_title(f"x{i} vs t")
+    axs[i].set_xlabel("t")
+    axs[i].set_ylabel(f"x{i}")
+    axs[i].legend()
+
+plt.tight_layout()
+plt.show()
diff --git a/python/iLQR_manipulator_dynamics.py b/python/iLQR_manipulator_dynamics.py
index 225c58533ebecda1671da94bf9f277675466b49e..e1cafac82599d91b30b9d0b1b692b1c4cef61cff 100644
--- a/python/iLQR_manipulator_dynamics.py
+++ b/python/iLQR_manipulator_dynamics.py
@@ -6,7 +6,7 @@ Written by Amirreza Razmjoo <amirreza.razmjoo@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -201,7 +201,11 @@ for i in range( param.nbIter ):
     Su = Su0[idx.flatten()]
 
     f, J = f_reach(x[tl,:param.nbVarX],param)
-    du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + R) @ (-Su.T @ J.T @ Q @ f.flatten() - u * param.r) # Gauss-Newton update
+    du = np.linalg.lstsq(
+        Su.T @ J.T @ Q @ J @ Su + R,
+        -Su.T @ J.T @ Q @ f.flatten() - u * param.r,
+        rcond=-1
+    )[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/iLQR_manipulator_initStateOptim.py b/python/iLQR_manipulator_initStateOptim.py
index e19e7ab4f7ae778890ed0c6818470ac7081caae6..b55f910fabc82f174d9628275baf88be37dfb949 100644
--- a/python/iLQR_manipulator_initStateOptim.py
+++ b/python/iLQR_manipulator_initStateOptim.py
@@ -7,7 +7,7 @@ Written by Yan Zhang <yan.zhang@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -118,7 +118,12 @@ for i in range(param.nbIter):
 	x = x.reshape([param.nbVarX, param.nbData], order='F')
 	f, J = f_reach(x[:,tl], param) # Residuals and Jacobians
 	fua = ua - np.concatenate((x0_hat, np.zeros(param.nbVarU * (param.nbData-1)))) # Control command evolution
-	dua = np.linalg.inv(Sa.T @ J.T @ Q @ J @ Sa + Ra) @ (-Sa.T @ J.T @ Q @ f.flatten('F') - Ra @ fua) # Gauss-Newton update
+	dua = np.linalg.lstsq(
+		Sa.T @ J.T @ Q @ J @ Sa + Ra,
+		-Sa.T @ J.T @ Q @ f.flatten('F') - Ra @ fua,
+		rcond=-1
+	)[0] # Gauss-Newton update
+
 	# Estimate step size with backtracking line search method
 	alpha = 1
 	cost0 = f.flatten('F').T @ Q @ f.flatten('F') + fua.T @ Ra @ fua # Cost
diff --git a/python/iLQR_manipulator_object_affordance.py b/python/iLQR_manipulator_object_affordance.py
index f30b1ae13f81cf3e59cdecc158cad8c1d5f5c47d..81fae5461750d2d1d4536e35ada9a435aa21e742 100644
--- a/python/iLQR_manipulator_object_affordance.py
+++ b/python/iLQR_manipulator_object_affordance.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import copy
@@ -150,7 +150,11 @@ for i in range( param.nbIter ):
 
     f, J = f_reach(param,x[tl])
     fc , Jc = f_reach(param,x[tl],False)
-    du = np.linalg.inv(Su.T @ J.T @ Q @ J @ Su + Su.T @ Jc.T @ Qc @ Jc @ Su + R) @ (-Su.T @ J.T @ Q @ f.flatten() - Su.T @ Jc.T @ Qc @ fc.flatten() - u * param.r)
+    du = np.linalg.lstsq(
+        Su.T @ J.T @ Q @ J @ Su + Su.T @ Jc.T @ Qc @ Jc @ Su + R,
+        -Su.T @ J.T @ Q @ f.flatten() - Su.T @ Jc.T @ Qc @ fc.flatten() - u * param.r,
+        rcond=-1
+    )[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/iLQR_manipulator_obstacle.py b/python/iLQR_manipulator_obstacle.py
index 0e673b32808cc2677fe18979b33bc2a3c91270df..2d3218fb733467391236440ff5e75f1add7f59f4 100644
--- a/python/iLQR_manipulator_obstacle.py
+++ b/python/iLQR_manipulator_obstacle.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch>,
 Teguh Lembono <teguh.lembono@idiap.ch> and Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -229,11 +229,18 @@ for i in range( param.nbIter ):
 
     if len(id2) > 0: # Numpy does not allow zero sized array as Indices
         Su2 = Su0[id2.flatten()]
-        du = np.linalg.inv(Su.T @ J.T @ J @ Su * param.Q_track + Su2.T @ J2.T @ J2 @ Su2 * param.Q_avoid + R) @ \
-            (-Su.T @ J.T @ f.flatten() * param.Q_track - Su2.T @ J2.T @ f2.flatten() * param.Q_avoid - u * param.r)
+        du = np.linalg.lstsq(
+            Su.T @ J.T @ J @ Su * param.Q_track + Su2.T @ J2.T @ J2 @ Su2 * param.Q_avoid + R,
+            -Su.T @ J.T @ f.flatten() * param.Q_track - Su2.T @ J2.T @ f2.flatten() * param.Q_avoid - u * param.r,
+            rcond=-1
+        )[0] # Gauss-Newton update
     else: # It means that we have a collision free path
-        du = np.linalg.inv(Su.T @ J.T @ J @ Su * param.Q_track + R) @ \
-            (-Su.T @ J.T @ f.flatten() * param.Q_track - u * param.r)
+        du = np.linalg.lstsq(
+            Su.T @ J.T @ J @ Su * param.Q_track + R,
+            -Su.T @ J.T @ f.flatten() * param.Q_track - u * param.r,
+            rcond=-1
+        )[0] # Gauss-Newton update
+
     # Perform line search
     alpha = 1
     cost0 = np.linalg.norm(f.flatten())**2 * param.Q_track + np.linalg.norm(f2.flatten())**2 * param.Q_avoid + np.linalg.norm(u) * param.r
diff --git a/python/iLQR_manipulator_recursive.py b/python/iLQR_manipulator_recursive.py
index 247e2f251454f13b086f7b2983b5a8169a8b1dd5..0161dd5ba4888a9b629aeffaffd8ec67a5fe392a 100644
--- a/python/iLQR_manipulator_recursive.py
+++ b/python/iLQR_manipulator_recursive.py
@@ -5,7 +5,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/iLQR_obstacle.py b/python/iLQR_obstacle.py
index f321df489e365bcb9dddbaf54ca43134df987742..517c333eefad34cbbc4c492cf6e8fbeadaba5aff 100644
--- a/python/iLQR_obstacle.py
+++ b/python/iLQR_obstacle.py
@@ -6,7 +6,7 @@ Written by Jérémy Maceiras <jeremy.maceiras@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -124,11 +124,17 @@ for i in range( param.nbIter ):
     
     if len(id2) > 0: # Numpy does not allow zero sized array as Indices
         Su2 = Su0[id2.flatten()]
-        du = np.linalg.inv(Su.T @ J.T @ J @ Su * param.Q_track + Su2.T @ J2.T @ J2 @ Su2 * param.Q_avoid + R) @ \
-                (-Su.T @ J.T @ f.flatten() * param.Q_track - Su2.T @ J2.T @ f2.flatten() * param.Q_avoid - u * param.r)
+        du = np.linalg.lstsq(
+           Su.T @ J.T @ J @ Su * param.Q_track + Su2.T @ J2.T @ J2 @ Su2 * param.Q_avoid + R,
+            -Su.T @ J.T @ f.flatten() * param.Q_track - Su2.T @ J2.T @ f2.flatten() * param.Q_avoid - u * param.r,
+            rcond=-1
+        )[0] # Gauss-Newton update
     else: # It means that we have a collision free path
-        du = np.linalg.inv(Su.T @ J.T @ J @ Su * param.Q_track + R) @ \
-                (-Su.T @ J.T @ f.flatten() * param.Q_track - u * param.r)
+        du = np.linalg.lstsq(
+           Su.T @ J.T @ J @ Su * param.Q_track + R,
+            -Su.T @ J.T @ f.flatten() * param.Q_track - u * param.r,
+            rcond=-1
+        )[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/iLQR_obstacle_GPIS.py b/python/iLQR_obstacle_GPIS.py
index ec2f9ba505654ccf10cd8d5b6fdc7e7414c8daa0..8215d9c3f9e9977f13d67a805575859db89a5140 100644
--- a/python/iLQR_obstacle_GPIS.py
+++ b/python/iLQR_obstacle_GPIS.py
@@ -7,7 +7,7 @@ Written by Yan Zhang <yan.zhang@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/iLQR_spacetime.py b/python/iLQR_spacetime.py
index dad6cc1ce8255ba72b49ab17d6d941a4538d9e0f..82b9f19f51c87ca27aa673ade436862e3ddcac4d 100644
--- a/python/iLQR_spacetime.py
+++ b/python/iLQR_spacetime.py
@@ -6,7 +6,7 @@ Written by Yifei Dong <ydong@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
@@ -102,7 +102,12 @@ for i in range(param.nbIter):
     # Increment of control input
     e = x[:, tl] - param.Mu
     e = e.T.reshape((-1, 1))
-    du = np.linalg.inv(Su.T @ Q @ Su + R) @ (-Su.T @ Q @ e - R @ u)
+    
+    du = np.linalg.lstsq(
+        Su.T @ Q @ Su + R,
+        -Su.T @ Q @ e - R @ u,
+        rcond=-1
+    )[0] # Gauss-Newton update
 
     # Perform line search
     alpha = 1
diff --git a/python/impedance_control.py b/python/impedance_control.py
index b97d3bf8ca49d898c40d0f00c244294da0bd7f18..d794b8ae5785c46a12b77c5b4f71aaf71b269222 100644
--- a/python/impedance_control.py
+++ b/python/impedance_control.py
@@ -6,7 +6,7 @@ Written by Sylvain Calinon <https://calinon.ch> and
 Amirreza Razmjoo <amirreza.razmjoo@idiap.ch>
 
 This file is part of RCFS <https://rcfs.ch/>
-License: MIT
+License: GPL-3.0-only
 '''
 
 import numpy as np
diff --git a/python/spline1D.py b/python/spline1D.py
index a60720aacc433064ca873a7e3b7dedcea72c2d31..e6ab9b0a70373c1858bf317d3f02f3592ce15ea1 100644
--- a/python/spline1D.py
+++ b/python/spline1D.py
@@ -5,7 +5,7 @@ Copyright (c) 2024 Idiap Research Institute <https://www.idiap.ch>
 Written by Guillaume Clivaz <guillaume.clivaz@idiap.ch> and Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 """
 
 import numpy as np
diff --git a/python/spline1D_SDF.py b/python/spline1D_SDF.py
index 0da60b99a9669ea0e292145a0fd535b189841720..79ec71a9001c0f8d8047e926483d722c73ae0063 100644
--- a/python/spline1D_SDF.py
+++ b/python/spline1D_SDF.py
@@ -7,7 +7,7 @@ Copyright (c) 2024 Idiap Research Institute <https://www.idiap.ch>
 Written by Guillaume Clivaz <guillaume.clivaz@idiap.ch> and Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://rcfs.ch>
-License: MIT
+License: GPL-3.0-only
 """
 
 import numpy as np
diff --git a/python/spline2D.py b/python/spline2D.py
index 2ff475d48187513e454f42783a7465c361d620cb..2f93ff03734404b1f155ec09bcb3d2a8aee4f64d 100644
--- a/python/spline2D.py
+++ b/python/spline2D.py
@@ -7,7 +7,7 @@ Written by Yiming Li <yiming.li@idiap.ch> and
 Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 """
 
 import numpy as np
diff --git a/python/spline2D_eikonal.py b/python/spline2D_eikonal.py
index 7d1e5c7cfc52ffc341d4a074a91cbc0ed6d3030b..dd4874efc2d38c5e35bdc9e8aca096607fe9269e 100644
--- a/python/spline2D_eikonal.py
+++ b/python/spline2D_eikonal.py
@@ -7,7 +7,7 @@ Copyright (c) 2023 Idiap Research Institute <https://www.idiap.ch/>
 Written by Guillaume Clivaz <guillaume.clivaz@idiap.ch> and Sylvain Calinon <https://calinon.ch>
 
 This file is part of RCFS <https://robotics-codes-from-scratch.github.io/>
-License: MIT
+License: GPL-3.0-only
 """
 
 import numpy as np
@@ -69,7 +69,7 @@ def computePsiList(Tmat, param):
             p1 = np.linspace(0, param.nbFct - 1, param.nbFct)
             p2 = np.linspace(0, param.nbFct - 2, param.nbFct - 1)
             T[d, :] = tt**p1
-            dT[d, 1:] = p1[1:] @ tt**p2 * param.nbSeg
+            dT[d, 1:] = p1[1:] * tt**p2 * param.nbSeg
             idl[:, d] = id.astype("int") * param.nbFct + p1
 
         # Reconstruct Psi for all dimensions