Repository: gaochq/IMU_Attitude_Estimator Branch: master Commit: 2ad6f4fe29da Files: 20 Total size: 133.2 KB Directory structure: gitextract_hjgyys6b/ ├── Allan_Analysis.py ├── CMakeLists.txt ├── DataSets.py ├── LICENSE ├── README.md ├── cmake_modules/ │ ├── FindEigen3.cmake │ └── FindGlog.cmake ├── datasets/ │ └── readme.txt ├── demo/ │ └── Test.cpp ├── include/ │ ├── Convert.h │ ├── EKF_Attitude.h │ ├── ESKF_Attitude.h │ ├── Mahony_Attitude.h │ ├── TypeDefs.h │ ├── matplotlibcpp.h │ └── tic_toc.h └── src/ ├── Convert.cpp ├── EKF_Attitude.cpp ├── ESKF_Attitude.cpp └── Mahony_Attitude.cpp ================================================ FILE CONTENTS ================================================ ================================================ FILE: Allan_Analysis.py ================================================ import numpy as np import matplotlib.pyplot as plt import math import numpy.matlib from scipy.optimize import nnls import scipy.io as sio # data was sampled in 100hz Pts_size = 100 fs = 100 data = np.loadtxt("./datasets/data.dat") data = data[:,2:5]*3600 [N, M] = data.shape n = np.arange(0, math.floor(math.log(N/2, 2))+1) n = 2**n maxN = n[n.size-1] endLogInc = math.log(maxN, 10); m = np.unique(np.ceil(np.logspace(0, endLogInc, Pts_size))).transpose() t0 = 1.0/fs T = m*t0 theta = np.zeros([N, M]) theta[:, 0] = data[:, 0].cumsum()/fs theta[:, 1] = data[:, 1].cumsum()/fs theta[:, 2] = data[:, 2].cumsum()/fs sigma2 = np.zeros([T.size, M]) for i in range(0, m.size): for k in range(0, int(N-2*m[i])): sigma2[i,:] = sigma2[i,:] + (theta[int(k+2*m[i]), :] - 2*theta[int(k+m[i]), :] + theta[k, :])**2 print(i) sigma2[i,:] = sigma2[i,:]/(2*T[i]**2*(N-2*m[i])) sigma2 = np.load("sigma2.dat.npy") T = np.load("T.dat.npy") sigma = np.sqrt(sigma2) print("hello") plt.loglog(T, sigma2) plt.show() for j in range(0,2): avar = sigma(j) P = np.empty((T.size, 5)) P[:, 0] = 3 / T**2 P[:, 1] = 1 / T P[:, 2] = 2 * np.log(2) / np.pi P[:, 3] = T / 3 P[:, 4] = T**2 / 2 P /= avar[:, np.newaxis] b = np.ones(T.size) s = nnls(P, b)[0] params = np.sqrt(s) print(params) ================================================ FILE: CMakeLists.txt ================================================ cmake_minimum_required(VERSION 2.8) project(IMU_Attitude_Estimator) set(CMAKE_BUILD_TYPE Release) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -o3") set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/bin) set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${PROJECT_SOURCE_DIR}/lib) list(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules) find_package(Eigen3 REQUIRED) include_directories(EIGEN3_INCLUDE_DIR) include_directories("/usr/include/eigen3") find_package(Glog REQUIRED) include_directories(${GLOG_INCLUDE_DIRS}) find_package(PythonLibs 2.7) include_directories(${PYTHON_INCLUDE_DIRS}) include_directories(${PROJECT_SOURCE_DIR}/include) add_library(${PROJECT_NAME} SHARED src/Convert.cpp src/EKF_Attitude.cpp src/ESKF_Attitude.cpp src/Mahony_Attitude.cpp) target_link_libraries(${PROJECT_NAME} ${GLOG_LIBRARIES} ${EIGEN3_LIBS} ${PYTHON_LIBRARIES}) add_executable(Demo demo/Test.cpp) target_link_libraries(Demo ${PROJECT_NAME}) ================================================ FILE: DataSets.py ================================================ import numpy as np import scipy.io as sio load_fn = './datasets/NAV.mat' load_Data = sio.loadmat(load_fn) data = load_Data['NAV'] mea = data[:,8:17] euler = data[:,29:32] out = np.hstack((mea, euler)) np.savetxt("data.bin", out, fmt='%f') print out.shape print data ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. [http://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} {fullname} 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 [http://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: IMU_Attitude_Estiamtor Copyright (C) 2018 gaochq 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 [http://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 [http://www.gnu.org/philosophy/why-not-lgpl.html]. ================================================ FILE: README.md ================================================ # IMU_Attitude_Estimator This project is aimed at estimating the attitude of Attitude Heading and Reference System(AHRS). And the project contains three popular attitude estimator algorithms. - Mahony's algorithm - Extend Kalman Filter(EKF) - Error State Kalman Filter(ESKF) ```DataSets.py``` for converting estimator data. ```Allan_Analysis``` for Allan Variance analysis. ### Refrence [1] [Mahony R, Hamel T, Pflimlin J M. Nonlinear complementary filters on the special orthogonal group[J]. IEEE Transactions on automatic control, 2008, 53(5): 1203-1218.](http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=4608934) [2] [Pixhawk state estimation](https://pixhawk.org/_media/firmware/apps/attitude_estimator_ekf/ekf_excerptmasterthesis.pdf) [3] [Solà, Joan. Quaternion kinematics for the error-state Kalman filter[J]. 2017.](http://219.216.82.193/cache/4/03/www.iri.upc.edu/bbcd603c764cd75e76df0968d16bc022/kinematics.pdf) [4] [Trawny N, Roumeliotis S I. Indirect Kalman Filter for 3D Attitude Estimation[J]. 2005.](http://pdfs.semanticscholar.org/2c8e/95bc331024105cbde6f6918cda8493f263c8.pdf) ### Dependencies - Eigen3.2.0 - glog ``` sudo apt-get install libgoogle-glog-dev ``` - [matplotlib-cpp](https://github.com/lava/matplotlib-cpp) ### Simple Test Simple comparision among three methods. And the params of Mahony filter can be further tuned. ================================================ FILE: cmake_modules/FindEigen3.cmake ================================================ # - Try to find Eigen3 lib # # This module supports requiring a minimum version, e.g. you can do # find_package(Eigen3 3.1.2) # to require version 3.1.2 or newer of Eigen3. # # Once done this will define # # EIGEN3_FOUND - system has eigen lib with correct version # EIGEN3_INCLUDE_DIR - the eigen include directory # EIGEN3_VERSION - eigen version # Copyright (c) 2006, 2007 Montel Laurent, # Copyright (c) 2008, 2009 Gael Guennebaud, # Copyright (c) 2009 Benoit Jacob # Redistribution and use is allowed according to the terms of the 2-clause BSD license. if(NOT Eigen3_FIND_VERSION) if(NOT Eigen3_FIND_VERSION_MAJOR) set(Eigen3_FIND_VERSION_MAJOR 2) endif(NOT Eigen3_FIND_VERSION_MAJOR) if(NOT Eigen3_FIND_VERSION_MINOR) set(Eigen3_FIND_VERSION_MINOR 91) endif(NOT Eigen3_FIND_VERSION_MINOR) if(NOT Eigen3_FIND_VERSION_PATCH) set(Eigen3_FIND_VERSION_PATCH 0) endif(NOT Eigen3_FIND_VERSION_PATCH) set(Eigen3_FIND_VERSION "${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}") endif(NOT Eigen3_FIND_VERSION) macro(_eigen3_check_version) file(READ "${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h" _eigen3_version_header) string(REGEX MATCH "define[ \t]+EIGEN_WORLD_VERSION[ \t]+([0-9]+)" _eigen3_world_version_match "${_eigen3_version_header}") set(EIGEN3_WORLD_VERSION "${CMAKE_MATCH_1}") string(REGEX MATCH "define[ \t]+EIGEN_MAJOR_VERSION[ \t]+([0-9]+)" _eigen3_major_version_match "${_eigen3_version_header}") set(EIGEN3_MAJOR_VERSION "${CMAKE_MATCH_1}") string(REGEX MATCH "define[ \t]+EIGEN_MINOR_VERSION[ \t]+([0-9]+)" _eigen3_minor_version_match "${_eigen3_version_header}") set(EIGEN3_MINOR_VERSION "${CMAKE_MATCH_1}") set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION}) if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) set(EIGEN3_VERSION_OK FALSE) else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) set(EIGEN3_VERSION_OK TRUE) endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION}) if(NOT EIGEN3_VERSION_OK) message(STATUS "Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, " "but at least version ${Eigen3_FIND_VERSION} is required") endif(NOT EIGEN3_VERSION_OK) endmacro(_eigen3_check_version) if (EIGEN3_INCLUDE_DIR) # in cache already _eigen3_check_version() set(EIGEN3_FOUND ${EIGEN3_VERSION_OK}) else (EIGEN3_INCLUDE_DIR) # specific additional paths for some OS if (WIN32) set(EIGEN_ADDITIONAL_SEARCH_PATHS ${EIGEN_ADDITIONAL_SEARCH_PATHS} "C:/Program Files/Eigen/include" "C:/Program Files (x86)/Eigen/include") endif(WIN32) find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library PATHS ${CMAKE_INSTALL_PREFIX}/include ${EIGEN_ADDITIONAL_SEARCH_PATHS} ${KDE4_INCLUDE_DIR} PATH_SUFFIXES eigen3 eigen ) if(EIGEN3_INCLUDE_DIR) _eigen3_check_version() endif(EIGEN3_INCLUDE_DIR) include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK) mark_as_advanced(EIGEN3_INCLUDE_DIR) endif(EIGEN3_INCLUDE_DIR) ================================================ FILE: cmake_modules/FindGlog.cmake ================================================ # Ceres Solver - A fast non-linear least squares minimizer # Copyright 2015 Google Inc. All rights reserved. # http://ceres-solver.org/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # * Neither the name of Google Inc. nor the names of its contributors may be # used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # Author: alexs.mac@gmail.com (Alex Stewart) # # FindGlog.cmake - Find Google glog logging library. # # This module defines the following variables: # # GLOG_FOUND: TRUE iff glog is found. # GLOG_INCLUDE_DIRS: Include directories for glog. # GLOG_LIBRARIES: Libraries required to link glog. # # The following variables control the behaviour of this module: # # GLOG_INCLUDE_DIR_HINTS: List of additional directories in which to # search for glog includes, e.g: /timbuktu/include. # GLOG_LIBRARY_DIR_HINTS: List of additional directories in which to # search for glog libraries, e.g: /timbuktu/lib. # # The following variables are also defined by this module, but in line with # CMake recommended FindPackage() module style should NOT be referenced directly # by callers (use the plural variables detailed above instead). These variables # do however affect the behaviour of the module via FIND_[PATH/LIBRARY]() which # are NOT re-called (i.e. search for library is not repeated) if these variables # are set with valid values _in the CMake cache_. This means that if these # variables are set directly in the cache, either by the user in the CMake GUI, # or by the user passing -DVAR=VALUE directives to CMake when called (which # explicitly defines a cache variable), then they will be used verbatim, # bypassing the HINTS variables and other hard-coded search locations. # # GLOG_INCLUDE_DIR: Include directory for glog, not including the # include directory of any dependencies. # GLOG_LIBRARY: glog library, not including the libraries of any # dependencies. # Reset CALLERS_CMAKE_FIND_LIBRARY_PREFIXES to its value when # FindGlog was invoked. macro(GLOG_RESET_FIND_LIBRARY_PREFIX) if (MSVC) set(CMAKE_FIND_LIBRARY_PREFIXES "${CALLERS_CMAKE_FIND_LIBRARY_PREFIXES}") endif (MSVC) endmacro(GLOG_RESET_FIND_LIBRARY_PREFIX) # Called if we failed to find glog or any of it's required dependencies, # unsets all public (designed to be used externally) variables and reports # error message at priority depending upon [REQUIRED/QUIET/] argument. macro(GLOG_REPORT_NOT_FOUND REASON_MSG) unset(GLOG_FOUND) unset(GLOG_INCLUDE_DIRS) unset(GLOG_LIBRARIES) # Make results of search visible in the CMake GUI if glog has not # been found so that user does not have to toggle to advanced view. mark_as_advanced(CLEAR GLOG_INCLUDE_DIR GLOG_LIBRARY) glog_reset_find_library_prefix() # Note _FIND_[REQUIRED/QUIETLY] variables defined by FindPackage() # use the camelcase library name, not uppercase. if (Glog_FIND_QUIETLY) message(STATUS "Failed to find glog - " ${REASON_MSG} ${ARGN}) elseif (Glog_FIND_REQUIRED) message(FATAL_ERROR "Failed to find glog - " ${REASON_MSG} ${ARGN}) else() # Neither QUIETLY nor REQUIRED, use no priority which emits a message # but continues configuration and allows generation. message("-- Failed to find glog - " ${REASON_MSG} ${ARGN}) endif () endmacro(GLOG_REPORT_NOT_FOUND) # Handle possible presence of lib prefix for libraries on MSVC, see # also GLOG_RESET_FIND_LIBRARY_PREFIX(). if (MSVC) # Preserve the caller's original values for CMAKE_FIND_LIBRARY_PREFIXES # s/t we can set it back before returning. set(CALLERS_CMAKE_FIND_LIBRARY_PREFIXES "${CMAKE_FIND_LIBRARY_PREFIXES}") # The empty string in this list is important, it represents the case when # the libraries have no prefix (shared libraries / DLLs). set(CMAKE_FIND_LIBRARY_PREFIXES "lib" "" "${CMAKE_FIND_LIBRARY_PREFIXES}") endif (MSVC) # Search user-installed locations first, so that we prefer user installs # to system installs where both exist. list(APPEND GLOG_CHECK_INCLUDE_DIRS /usr/local/include /usr/local/homebrew/include # Mac OS X /opt/local/var/macports/software # Mac OS X. /opt/local/include /usr/include) # Windows (for C:/Program Files prefix). list(APPEND GLOG_CHECK_PATH_SUFFIXES glog/include glog/Include Glog/include Glog/Include) list(APPEND GLOG_CHECK_LIBRARY_DIRS /usr/local/lib /usr/local/homebrew/lib # Mac OS X. /opt/local/lib /usr/lib) # Windows (for C:/Program Files prefix). list(APPEND GLOG_CHECK_LIBRARY_SUFFIXES glog/lib glog/Lib Glog/lib Glog/Lib) # Search supplied hint directories first if supplied. find_path(GLOG_INCLUDE_DIR NAMES glog/logging.h PATHS ${GLOG_INCLUDE_DIR_HINTS} ${GLOG_CHECK_INCLUDE_DIRS} PATH_SUFFIXES ${GLOG_CHECK_PATH_SUFFIXES}) if (NOT GLOG_INCLUDE_DIR OR NOT EXISTS ${GLOG_INCLUDE_DIR}) glog_report_not_found( "Could not find glog include directory, set GLOG_INCLUDE_DIR " "to directory containing glog/logging.h") endif (NOT GLOG_INCLUDE_DIR OR NOT EXISTS ${GLOG_INCLUDE_DIR}) find_library(GLOG_LIBRARY NAMES glog PATHS ${GLOG_LIBRARY_DIR_HINTS} ${GLOG_CHECK_LIBRARY_DIRS} PATH_SUFFIXES ${GLOG_CHECK_LIBRARY_SUFFIXES}) if (NOT GLOG_LIBRARY OR NOT EXISTS ${GLOG_LIBRARY}) glog_report_not_found( "Could not find glog library, set GLOG_LIBRARY " "to full path to libglog.") endif (NOT GLOG_LIBRARY OR NOT EXISTS ${GLOG_LIBRARY}) # Mark internally as found, then verify. GLOG_REPORT_NOT_FOUND() unsets # if called. set(GLOG_FOUND TRUE) # Glog does not seem to provide any record of the version in its # source tree, thus cannot extract version. # Catch case when caller has set GLOG_INCLUDE_DIR in the cache / GUI and # thus FIND_[PATH/LIBRARY] are not called, but specified locations are # invalid, otherwise we would report the library as found. if (GLOG_INCLUDE_DIR AND NOT EXISTS ${GLOG_INCLUDE_DIR}/glog/logging.h) glog_report_not_found( "Caller defined GLOG_INCLUDE_DIR:" " ${GLOG_INCLUDE_DIR} does not contain glog/logging.h header.") endif (GLOG_INCLUDE_DIR AND NOT EXISTS ${GLOG_INCLUDE_DIR}/glog/logging.h) # TODO: This regex for glog library is pretty primitive, we use lowercase # for comparison to handle Windows using CamelCase library names, could # this check be better? string(TOLOWER "${GLOG_LIBRARY}" LOWERCASE_GLOG_LIBRARY) if (GLOG_LIBRARY AND NOT "${LOWERCASE_GLOG_LIBRARY}" MATCHES ".*glog[^/]*") glog_report_not_found( "Caller defined GLOG_LIBRARY: " "${GLOG_LIBRARY} does not match glog.") endif (GLOG_LIBRARY AND NOT "${LOWERCASE_GLOG_LIBRARY}" MATCHES ".*glog[^/]*") # Set standard CMake FindPackage variables if found. if (GLOG_FOUND) set(GLOG_INCLUDE_DIRS ${GLOG_INCLUDE_DIR}) set(GLOG_LIBRARIES ${GLOG_LIBRARY}) endif (GLOG_FOUND) glog_reset_find_library_prefix() # Handle REQUIRED / QUIET optional arguments. include(FindPackageHandleStandardArgs) find_package_handle_standard_args(Glog DEFAULT_MSG GLOG_INCLUDE_DIRS GLOG_LIBRARIES) # Only mark internal variables as advanced if we found glog, otherwise # leave them visible in the standard GUI for the user to set manually. if (GLOG_FOUND) mark_as_advanced(FORCE GLOG_INCLUDE_DIR GLOG_LIBRARY) endif (GLOG_FOUND) ================================================ FILE: demo/Test.cpp ================================================ #include #include #include "time.h" #include #include #include "Convert.h" #include "EKF_Attitude.h" #include "Mahony_Attitude.h" #include "ESKF_Attitude.h" #include "matplotlibcpp.h" using namespace std; using namespace IMU; namespace plt = matplotlibcpp; int main(int argc, char **argv) { Eigen::MatrixXd data, measurements, groundtruth; data =IMU::readFromfile("./datasets/NAV2_data.bin"); if(data.isZero()) return 0; const int Rows = data.rows() - 1; measurements = data.block(0, 0, Rows, 9); groundtruth = data.block(0, 9, Rows, 3)*180/M_PI; IMU::EKF_Attitude EKF_AHRS(true, 0.02); IMU::Mahony_Attitude Mahony(Eigen::Vector2d(1.0, 0), 0.02); Eigen::Matrix ESKF_InitVec; ESKF_InitVec << 1e-5*Eigen::Vector3d::Ones(), 1e-9*Eigen::Vector3d::Ones(), 1e-3*Eigen::Vector3d::Ones(), 1e-4*Eigen::Vector3d::Ones(); IMU::ESKF_Attitude ESKF_AHRS(ESKF_InitVec, 0.02); unsigned int i = 0; Eigen::MatrixXd Euler(measurements.rows(), 3), Euler1(measurements.rows(), 3), Euler2(measurements.rows(), 3); std::vector Index, Roll, Pitch, Yaw, Roll_gt, Pitch_gt, Yaw_gt; std::vector Roll1, Pitch1, Yaw1, Roll_gt1, Pitch_gt1, Yaw_gt1; std::vector Roll2, Pitch2, Yaw2, Roll_gt2, Pitch_gt2, Yaw_gt2; TicToc tc; do { Eigen::MatrixXd measure; Eigen::Quaterniond quaternion; Vector_3 Euler_single; quaternion = EKF_AHRS.Run(measurements.row(i).transpose()); Euler.row(i) = Quaternion_to_Euler(quaternion).transpose(); quaternion = Mahony.Run(measurements.row(i).transpose()); Euler1.row(i) = Quaternion_to_Euler(quaternion).transpose(); quaternion = ESKF_AHRS.Run(measurements.row(i).transpose()); Euler2.row(i) = Quaternion_to_Euler(quaternion).transpose(); Index.push_back(i*1.0); Roll.push_back(Euler.row(i)[0]); Pitch.push_back(Euler.row(i)[1]); Yaw.push_back(Euler.row(i)[2]); Roll1.push_back(Euler1.row(i)[0]); Pitch1.push_back(Euler1.row(i)[1]); Yaw1.push_back(Euler1.row(i)[2]); Roll2.push_back(Euler2.row(i)[0]); Pitch2.push_back(Euler2.row(i)[1]); Yaw2.push_back(Euler2.row(i)[2]); Roll_gt.push_back(groundtruth.row(i)[0]); Pitch_gt.push_back(groundtruth.row(i)[1]); Yaw_gt.push_back(groundtruth.row(i)[2]); i++; } while (i #include #include #include #include #include #include "TypeDefs.h" #include "tic_toc.h" using namespace std; namespace IMU { void Vect_to_SkewMat(Vector_3 Vector, Matrix_3 &Matrix); void Angular_to_Mat(Vector_3 Vector, Eigen::Matrix &Matrix); //void Rotation_to_Qaut(Matrix_3 rotation, Eigen::Quaterniond &quat); Vector_4 Quaternion_to_Vect(Eigen::Quaterniond q); Eigen::Quaterniond QuatMult(Eigen::Quaterniond q1, Eigen::Quaterniond q2); Matrix_3 Quat_to_Matrix(Eigen::Quaterniond q); // Eigen IO Eigen::MatrixXd readFromfile(const string file); bool writeTofile(Eigen::MatrixXd matrix, const string file); // Eluer(Rotate vector) to rotation matrix Matrix_3 Euler_to_RoatMat(Vector_3 Euler); // Eluer(Rotate vector) to rotation matrix Eigen::Quaterniond Euler_to_Quaternion(Vector_3 Euler); // Quaternion to eulers Vector_3 Quaternion_to_Euler(Eigen::Quaterniond q); // Rotation matrix to eulers, the rotation order is X-Y-Z(roll,pitch and yaw) Vector_3 Rotation_to_Euler(Matrix_3 Rotation); // Rotation matrix to quaternion http://www.cs.ucr.edu/~vbz/resources/quatut.pdf Eigen::Quaterniond Rotation_to_Quater(Matrix_3 Rotation); // Indirect Kalman Filter for 3D Attitude Estimation (Roumeliotis) Eigen::Quaterniond BuildUpdateQuat(Eigen::Vector3d DeltaTheta); } //namesapce IMU #endif ================================================ FILE: include/EKF_Attitude.h ================================================ #ifndef EKF_ATTITUDE_H_ #define EKF_ATTITUDE_H_ #include #include #include #include #include #include "TypeDefs.h" #ifdef _WIN32 #include "windows.h" #else #include #endif using namespace std; namespace IMU { class EKF_Attitude { public: EKF_Attitude(bool approx_prediction, double dt); // Modify the params of the filter void Param_Change(Vector_12 Pro_Nosiecovr, Vector_9 Mea_Nosiecovr); // Calculate the transition matrix A // refer to formula 4.19a void Cal_TransMatrix(); /* The priori prediction: * Xk+1 = F(Xk,0) * Pk+1 = A*Pk*A' + Qk */ void Prior_Predict(); // The posteriori correction void Post_Correct(); // Calculate the Euler angular void Cal_Quaternion(); // read the sensors void Read_SensorData(Vector_9 measurement); Eigen::Quaterniond Run(Vector_9 measurement); void Release(); void RequestStop(); void RequestStart(); bool Stop(); bool isStopped(); private: Vector_9 cur_measurement; bool using_2ndOrder; Eigen::Matrix Q_noise; Eigen::Matrix R_noise; double deltaT; Eigen::Matrix Alin; // Xk+1, the state vector of posteriori correction vector< Vector_12 > state_X_pro; // Xk, the state vector of priori prediction Vector_12 state_X_par; // Pk+1 vector< Eigen::Matrix > CovrMatrix_P_pro; // Pk Eigen::Matrix CovrMatrix_P_par; vector< Eigen::Quaterniond > quaternion; bool mbStopped; bool mbStopRequested; std::mutex mMutexStop; }; } //namespace IMU #endif ================================================ FILE: include/ESKF_Attitude.h ================================================ #ifndef ESKF_ATTITUDE_H #define ESKF_ATTITUDE_H #include #include #include #include #include #include #include "TypeDefs.h" #ifdef _WIN32 #include "windows.h" #else #include "unistd.h" #endif using namespace std; namespace IMU { class ESKF_Attitude { public: ESKF_Attitude(Vector_12 Covar_Mat, double dt); // Initialize the true state of the estimator // including the nomial state and the error state, // and the covariances matrices void Init_Estimator(); // change the parametres of the estimator void Param_Change(Vector_12 Covar_Mat); // Predict the nomial and error state void NominaState_Predict(); void ErrorState_Predict(); // Update the filter parametres void Update_Filter(); // Uptate the nominal state void Update_NomianState(); // Reset the error state void Reset_ErrorState(); // read the sensors data and normalize the accelerometer and magnetometer void Read_SensorData(Vector_9 measurement); Eigen::Quaterniond Run(Vector_9 measurement); void Release(); void RequestStop(); void RequestStart(); bool Stop(); bool isStopped(); private: // the Gaussian noise for the covariances matrices Q and R Vector_3 DetAng_noise; Vector_3 DetAngVel_noise; Vector_3 Acc_noise; Vector_3 Mag_noise; Eigen::Matrix CovarMat_Q; Eigen::Matrix CovarMat_R; struct IMU_State { public: //! normal state Eigen::Quaterniond Nominal_quat; //! quaterion state Vector_3 Nominal_AngVel; //! Gyro bias state //! Error state Vector_3 Error_theta; Vector_3 Error_AngVel; Eigen::Matrix Error_Convar; // calculate the observe matrix and the correction residual Eigen::Matrix Cal_ObserveMat(Vector_9 measurenment, Vector_6 &residual); }; vector< IMU_State > State_Vector; vector< Eigen::Quaterniond > quaternion; // sample time double deltaT; // Current and last time measurement (gyro;acc;mag) Vector_9 Cur_Measurement; Vector_9 Last_Measurement; bool mbStopped; bool mbStopRequested; std::mutex mMutexStop; }; } #endif ================================================ FILE: include/Mahony_Attitude.h ================================================ #ifndef MAHONY_AHRS_H_ #define MAHONY_AHRS_H_ #include #include #include #include #include #include "TypeDefs.h" #ifdef _WIN32 #include "windows.h" #else #include #endif using namespace std; namespace IMU { class Mahony_Attitude { public: Mahony_Attitude(Vector_2 PI, double dt); void Params_Change(Vector_2 PI, double dt); void Mahony_Estimate(); void Read_SensorData(Vector_9 measurement); Eigen::Quaterniond Run(Vector_9 measurement); void Release(); void RequestStop(); void RequestStart(); bool Stop(); bool isStopped(); private: Vector_9 cur_measurement; double Kp, Ki; double deltaT; Vector_3 Integ_angular; vector< Eigen::Quaterniond > quaternion; bool mbStopped; bool mbStopRequested; std::mutex mMutexStop; }; } //namesapce IMU #endif ================================================ FILE: include/TypeDefs.h ================================================ #ifndef TYPEDEFS_H_ #define TYPEDEFS_H_ #include #include //#pragma once namespace IMU { typedef Eigen::Matrix Vector_2; typedef Eigen::Matrix Vector_3; typedef Eigen::Matrix Vector_4; typedef Eigen::Matrix Vector_6; typedef Eigen::Matrix Vector_7; typedef Eigen::Matrix Vector_9; typedef Eigen::Matrix Vector_12; typedef Eigen::Matrix3d Matrix_3; const Matrix_3 Zeros_Matrix3 = Matrix_3::Zero(3, 3); const Matrix_3 Ones_Matrix3 = Matrix_3::Ones(3, 3); const Matrix_3 Identity_Matrix3 = Matrix_3::Identity(3, 3); } // namespace IMU #endif ================================================ FILE: include/matplotlibcpp.h ================================================ #pragma once #include #include #include #include #include #include #include // requires c++11 support #if __cplusplus > 199711L || _MSC_VER > 1800 # include #endif #include #ifndef WITHOUT_NUMPY # define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION # include #endif // WITHOUT_NUMPY #if PY_MAJOR_VERSION >= 3 # define PyString_FromString PyUnicode_FromString #endif namespace matplotlibcpp { namespace detail { static std::string s_backend; struct _interpreter { PyObject *s_python_function_show; PyObject *s_python_function_close; PyObject *s_python_function_draw; PyObject *s_python_function_pause; PyObject *s_python_function_save; PyObject *s_python_function_figure; PyObject *s_python_function_plot; PyObject *s_python_function_semilogx; PyObject *s_python_function_semilogy; PyObject *s_python_function_loglog; PyObject *s_python_function_fill_between; PyObject *s_python_function_hist; PyObject *s_python_function_subplot; PyObject *s_python_function_legend; PyObject *s_python_function_xlim; PyObject *s_python_function_ion; PyObject *s_python_function_ylim; PyObject *s_python_function_title; PyObject *s_python_function_axis; PyObject *s_python_function_xlabel; PyObject *s_python_function_ylabel; PyObject *s_python_function_grid; PyObject *s_python_function_clf; PyObject *s_python_function_errorbar; PyObject *s_python_function_annotate; PyObject *s_python_function_tight_layout; PyObject *s_python_empty_tuple; PyObject *s_python_function_stem; PyObject *s_python_function_xkcd; /* For now, _interpreter is implemented as a singleton since its currently not possible to have multiple independent embedded python interpreters without patching the python source code or starting a separate process for each. http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program */ static _interpreter& get() { static _interpreter ctx; return ctx; } private: #ifndef WITHOUT_NUMPY # if PY_MAJOR_VERSION >= 3 void *import_numpy() { import_array(); // initialize C-API return NULL; } # else void import_numpy() { import_array(); // initialize C-API } # endif #endif _interpreter() { // optional but recommended #if PY_MAJOR_VERSION >= 3 wchar_t name[] = L"plotting"; #else char name[] = "plotting"; #endif Py_SetProgramName(name); Py_Initialize(); #ifndef WITHOUT_NUMPY import_numpy(); // initialize numpy C-API #endif PyObject* matplotlibname = PyString_FromString("matplotlib"); PyObject* pyplotname = PyString_FromString("matplotlib.pyplot"); PyObject* pylabname = PyString_FromString("pylab"); if (!pyplotname || !pylabname || !matplotlibname) { throw std::runtime_error("couldnt create string"); } PyObject* matplotlib = PyImport_Import(matplotlibname); Py_DECREF(matplotlibname); if (!matplotlib) { throw std::runtime_error("Error loading module matplotlib!"); } // matplotlib.use() must be called *before* pylab, matplotlib.pyplot, // or matplotlib.backends is imported for the first time if (!s_backend.empty()) { PyObject_CallMethod(matplotlib, const_cast("use"), const_cast("s"), s_backend.c_str()); } PyObject* pymod = PyImport_Import(pyplotname); Py_DECREF(pyplotname); if (!pymod) { throw std::runtime_error("Error loading module matplotlib.pyplot!"); } PyObject* pylabmod = PyImport_Import(pylabname); Py_DECREF(pylabname); if (!pylabmod) { throw std::runtime_error("Error loading module pylab!"); } s_python_function_show = PyObject_GetAttrString(pymod, "show"); s_python_function_close = PyObject_GetAttrString(pymod, "close"); s_python_function_draw = PyObject_GetAttrString(pymod, "draw"); s_python_function_pause = PyObject_GetAttrString(pymod, "pause"); s_python_function_figure = PyObject_GetAttrString(pymod, "figure"); s_python_function_plot = PyObject_GetAttrString(pymod, "plot"); s_python_function_semilogx = PyObject_GetAttrString(pymod, "semilogx"); s_python_function_semilogy = PyObject_GetAttrString(pymod, "semilogy"); s_python_function_loglog = PyObject_GetAttrString(pymod, "loglog"); s_python_function_fill_between = PyObject_GetAttrString(pymod, "fill_between"); s_python_function_hist = PyObject_GetAttrString(pymod,"hist"); s_python_function_subplot = PyObject_GetAttrString(pymod, "subplot"); s_python_function_legend = PyObject_GetAttrString(pymod, "legend"); s_python_function_ylim = PyObject_GetAttrString(pymod, "ylim"); s_python_function_title = PyObject_GetAttrString(pymod, "title"); s_python_function_axis = PyObject_GetAttrString(pymod, "axis"); s_python_function_xlabel = PyObject_GetAttrString(pymod, "xlabel"); s_python_function_ylabel = PyObject_GetAttrString(pymod, "ylabel"); s_python_function_grid = PyObject_GetAttrString(pymod, "grid"); s_python_function_xlim = PyObject_GetAttrString(pymod, "xlim"); s_python_function_ion = PyObject_GetAttrString(pymod, "ion"); s_python_function_save = PyObject_GetAttrString(pylabmod, "savefig"); s_python_function_annotate = PyObject_GetAttrString(pymod,"annotate"); s_python_function_clf = PyObject_GetAttrString(pymod, "clf"); s_python_function_errorbar = PyObject_GetAttrString(pymod, "errorbar"); s_python_function_tight_layout = PyObject_GetAttrString(pymod, "tight_layout"); s_python_function_stem = PyObject_GetAttrString(pymod, "stem"); s_python_function_xkcd = PyObject_GetAttrString(pymod, "xkcd"); if( !s_python_function_show || !s_python_function_close || !s_python_function_draw || !s_python_function_pause || !s_python_function_figure || !s_python_function_plot || !s_python_function_semilogx || !s_python_function_semilogy || !s_python_function_loglog || !s_python_function_fill_between || !s_python_function_subplot || !s_python_function_legend || !s_python_function_ylim || !s_python_function_title || !s_python_function_axis || !s_python_function_xlabel || !s_python_function_ylabel || !s_python_function_grid || !s_python_function_xlim || !s_python_function_ion || !s_python_function_save || !s_python_function_clf || !s_python_function_annotate || !s_python_function_errorbar || !s_python_function_errorbar || !s_python_function_tight_layout || !s_python_function_stem || !s_python_function_xkcd ) { throw std::runtime_error("Couldn't find required function!"); } if ( !PyFunction_Check(s_python_function_show) || !PyFunction_Check(s_python_function_close) || !PyFunction_Check(s_python_function_draw) || !PyFunction_Check(s_python_function_pause) || !PyFunction_Check(s_python_function_figure) || !PyFunction_Check(s_python_function_plot) || !PyFunction_Check(s_python_function_semilogx) || !PyFunction_Check(s_python_function_semilogy) || !PyFunction_Check(s_python_function_loglog) || !PyFunction_Check(s_python_function_fill_between) || !PyFunction_Check(s_python_function_subplot) || !PyFunction_Check(s_python_function_legend) || !PyFunction_Check(s_python_function_annotate) || !PyFunction_Check(s_python_function_ylim) || !PyFunction_Check(s_python_function_title) || !PyFunction_Check(s_python_function_axis) || !PyFunction_Check(s_python_function_xlabel) || !PyFunction_Check(s_python_function_ylabel) || !PyFunction_Check(s_python_function_grid) || !PyFunction_Check(s_python_function_xlim) || !PyFunction_Check(s_python_function_ion) || !PyFunction_Check(s_python_function_save) || !PyFunction_Check(s_python_function_clf) || !PyFunction_Check(s_python_function_tight_layout) || !PyFunction_Check(s_python_function_errorbar) || !PyFunction_Check(s_python_function_stem) || !PyFunction_Check(s_python_function_xkcd) ) { throw std::runtime_error("Python object is unexpectedly not a PyFunction."); } s_python_empty_tuple = PyTuple_New(0); } ~_interpreter() { Py_Finalize(); } }; } // end namespace detail // must be called before the first regular call to matplotlib to have any effect inline void backend(const std::string& name) { detail::s_backend = name; } inline bool annotate(std::string annotation, double x, double y) { PyObject * xy = PyTuple_New(2); PyObject * str = PyString_FromString(annotation.c_str()); PyTuple_SetItem(xy,0,PyFloat_FromDouble(x)); PyTuple_SetItem(xy,1,PyFloat_FromDouble(y)); PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "xy", xy); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, str); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); if(res) Py_DECREF(res); return res; } #ifndef WITHOUT_NUMPY // Type selector for numpy array conversion template struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default template <> struct select_npy_type { const static NPY_TYPES type = NPY_DOUBLE; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_FLOAT; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_BOOL; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_INT8; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_SHORT; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_INT; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_INT64; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_UINT8; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_USHORT; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_ULONG; }; template <> struct select_npy_type { const static NPY_TYPES type = NPY_UINT64; }; template PyObject* get_array(const std::vector& v) { detail::_interpreter::get(); //interpreter needs to be initialized for the numpy commands to work NPY_TYPES type = select_npy_type::type; if (type == NPY_NOTYPE) { std::vector vd(v.size()); npy_intp vsize = v.size(); std::copy(v.begin(),v.end(),vd.begin()); PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, (void*)(vd.data())); return varray; } npy_intp vsize = v.size(); PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, type, (void*)(v.data())); return varray; } #else // fallback if we don't have numpy: copy every element of the given vector template PyObject* get_array(const std::vector& v) { PyObject* list = PyList_New(v.size()); for(size_t i = 0; i < v.size(); ++i) { PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i))); } return list; } #endif // WITHOUT_NUMPY template bool plot(const std::vector &x, const std::vector &y, const std::map& keywords) { assert(x.size() == y.size()); // using numpy arrays PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); // construct positional args PyObject* args = PyTuple_New(2); PyTuple_SetItem(args, 0, xarray); PyTuple_SetItem(args, 1, yarray); // construct keyword args PyObject* kwargs = PyDict_New(); for(std::map::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str())); } PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); if(res) Py_DECREF(res); return res; } template bool stem(const std::vector &x, const std::vector &y, const std::map& keywords) { assert(x.size() == y.size()); // using numpy arrays PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); // construct positional args PyObject* args = PyTuple_New(2); PyTuple_SetItem(args, 0, xarray); PyTuple_SetItem(args, 1, yarray); // construct keyword args PyObject* kwargs = PyDict_New(); for (std::map::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str())); } PyObject* res = PyObject_Call( detail::_interpreter::get().s_python_function_stem, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); if (res) Py_DECREF(res); return res; } template< typename Numeric > bool fill_between(const std::vector& x, const std::vector& y1, const std::vector& y2, const std::map& keywords) { assert(x.size() == y1.size()); assert(x.size() == y2.size()); // using numpy arrays PyObject* xarray = get_array(x); PyObject* y1array = get_array(y1); PyObject* y2array = get_array(y2); // construct positional args PyObject* args = PyTuple_New(3); PyTuple_SetItem(args, 0, xarray); PyTuple_SetItem(args, 1, y1array); PyTuple_SetItem(args, 2, y2array); // construct keyword args PyObject* kwargs = PyDict_New(); for(std::map::const_iterator it = keywords.begin(); it != keywords.end(); ++it) { PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str())); } PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs); Py_DECREF(args); Py_DECREF(kwargs); if(res) Py_DECREF(res); return res; } template< typename Numeric> bool hist(const std::vector& y, long bins=10,std::string color="b", double alpha=1.0) { PyObject* yarray = get_array(y); PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins)); PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str())); PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha)); PyObject* plot_args = PyTuple_New(1); PyTuple_SetItem(plot_args, 0, yarray); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs); Py_DECREF(plot_args); Py_DECREF(kwargs); if(res) Py_DECREF(res); return res; } template< typename Numeric> bool named_hist(std::string label,const std::vector& y, long bins=10, std::string color="b", double alpha=1.0) { PyObject* yarray = get_array(y); PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(label.c_str())); PyDict_SetItemString(kwargs, "bins", PyLong_FromLong(bins)); PyDict_SetItemString(kwargs, "color", PyString_FromString(color.c_str())); PyDict_SetItemString(kwargs, "alpha", PyFloat_FromDouble(alpha)); PyObject* plot_args = PyTuple_New(1); PyTuple_SetItem(plot_args, 0, yarray); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs); Py_DECREF(plot_args); Py_DECREF(kwargs); if(res) Py_DECREF(res); return res; } template bool plot(const std::vector& x, const std::vector& y, const std::string& s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(s.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args); Py_DECREF(plot_args); if(res) Py_DECREF(res); return res; } template bool stem(const std::vector& x, const std::vector& y, const std::string& s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(s.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject( detail::_interpreter::get().s_python_function_stem, plot_args); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool semilogx(const std::vector& x, const std::vector& y, const std::string& s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(s.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args); Py_DECREF(plot_args); if(res) Py_DECREF(res); return res; } template bool semilogy(const std::vector& x, const std::vector& y, const std::string& s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(s.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args); Py_DECREF(plot_args); if(res) Py_DECREF(res); return res; } template bool loglog(const std::vector& x, const std::vector& y, const std::string& s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(s.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args); Py_DECREF(plot_args); if(res) Py_DECREF(res); return res; } template bool errorbar(const std::vector &x, const std::vector &y, const std::vector &yerr, const std::string &s = "") { assert(x.size() == y.size()); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* yerrarray = get_array(yerr); PyObject *kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "yerr", yerrarray); PyObject *pystring = PyString_FromString(s.c_str()); PyObject *plot_args = PyTuple_New(2); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); else throw std::runtime_error("Call to errorbar() failed."); return res; } template bool named_plot(const std::string& name, const std::vector& y, const std::string& format = "") { PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str())); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(format.c_str()); PyObject* plot_args = PyTuple_New(2); PyTuple_SetItem(plot_args, 0, yarray); PyTuple_SetItem(plot_args, 1, pystring); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool named_plot(const std::string& name, const std::vector& x, const std::vector& y, const std::string& format = "") { PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str())); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(format.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool named_semilogx(const std::string& name, const std::vector& x, const std::vector& y, const std::string& format = "") { PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str())); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(format.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool named_semilogy(const std::string& name, const std::vector& x, const std::vector& y, const std::string& format = "") { PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str())); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(format.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool named_loglog(const std::string& name, const std::vector& x, const std::vector& y, const std::string& format = "") { PyObject* kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "label", PyString_FromString(name.c_str())); PyObject* xarray = get_array(x); PyObject* yarray = get_array(y); PyObject* pystring = PyString_FromString(format.c_str()); PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xarray); PyTuple_SetItem(plot_args, 1, yarray); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs); Py_DECREF(kwargs); Py_DECREF(plot_args); if (res) Py_DECREF(res); return res; } template bool plot(const std::vector& y, const std::string& format = "") { std::vector x(y.size()); for(size_t i=0; i bool stem(const std::vector& y, const std::string& format = "") { std::vector x(y.size()); for (size_t i = 0; i < x.size(); ++i) x.at(i) = i; return stem(x, y, format); } inline void figure() { PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple); if(!res) throw std::runtime_error("Call to figure() failed."); Py_DECREF(res); } inline void legend() { PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple); if(!res) throw std::runtime_error("Call to legend() failed."); Py_DECREF(res); } template void ylim(Numeric left, Numeric right) { PyObject* list = PyList_New(2); PyList_SetItem(list, 0, PyFloat_FromDouble(left)); PyList_SetItem(list, 1, PyFloat_FromDouble(right)); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, list); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args); if(!res) throw std::runtime_error("Call to ylim() failed."); Py_DECREF(args); Py_DECREF(res); } template void xlim(Numeric left, Numeric right) { PyObject* list = PyList_New(2); PyList_SetItem(list, 0, PyFloat_FromDouble(left)); PyList_SetItem(list, 1, PyFloat_FromDouble(right)); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, list); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args); if(!res) throw std::runtime_error("Call to xlim() failed."); Py_DECREF(args); Py_DECREF(res); } inline double* xlim() { PyObject* args = PyTuple_New(0); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args); PyObject* left = PyTuple_GetItem(res,0); PyObject* right = PyTuple_GetItem(res,1); double* arr = new double[2]; arr[0] = PyFloat_AsDouble(left); arr[1] = PyFloat_AsDouble(right); if(!res) throw std::runtime_error("Call to xlim() failed."); Py_DECREF(res); return arr; } inline double* ylim() { PyObject* args = PyTuple_New(0); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args); PyObject* left = PyTuple_GetItem(res,0); PyObject* right = PyTuple_GetItem(res,1); double* arr = new double[2]; arr[0] = PyFloat_AsDouble(left); arr[1] = PyFloat_AsDouble(right); if(!res) throw std::runtime_error("Call to ylim() failed."); Py_DECREF(res); return arr; } inline void subplot(long nrows, long ncols, long plot_number) { // construct positional args PyObject* args = PyTuple_New(3); PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows)); PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols)); PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number)); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args); if(!res) throw std::runtime_error("Call to subplot() failed."); Py_DECREF(args); Py_DECREF(res); } inline void title(const std::string &titlestr) { PyObject* pytitlestr = PyString_FromString(titlestr.c_str()); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, pytitlestr); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_title, args); if(!res) throw std::runtime_error("Call to title() failed."); Py_DECREF(args); Py_DECREF(res); } inline void axis(const std::string &axisstr) { PyObject* str = PyString_FromString(axisstr.c_str()); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, str); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args); if(!res) throw std::runtime_error("Call to title() failed."); Py_DECREF(args); Py_DECREF(res); } inline void xlabel(const std::string &str) { PyObject* pystr = PyString_FromString(str.c_str()); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, pystr); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlabel, args); if(!res) throw std::runtime_error("Call to xlabel() failed."); Py_DECREF(args); Py_DECREF(res); } inline void ylabel(const std::string &str) { PyObject* pystr = PyString_FromString(str.c_str()); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, pystr); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylabel, args); if(!res) throw std::runtime_error("Call to ylabel() failed."); Py_DECREF(args); Py_DECREF(res); } inline void grid(bool flag) { PyObject* pyflag = flag ? Py_True : Py_False; Py_INCREF(pyflag); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, pyflag); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args); if(!res) throw std::runtime_error("Call to grid() failed."); Py_DECREF(args); Py_DECREF(res); } inline void show(const bool block = true) { PyObject* res; if(block) { res = PyObject_CallObject( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple); } else { PyObject *kwargs = PyDict_New(); PyDict_SetItemString(kwargs, "block", Py_False); res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs); Py_DECREF(kwargs); } if (!res) throw std::runtime_error("Call to show() failed."); Py_DECREF(res); } inline void close() { PyObject* res = PyObject_CallObject( detail::_interpreter::get().s_python_function_close, detail::_interpreter::get().s_python_empty_tuple); if (!res) throw std::runtime_error("Call to close() failed."); Py_DECREF(res); } inline void xkcd() { PyObject* res; PyObject *kwargs = PyDict_New(); res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd, detail::_interpreter::get().s_python_empty_tuple, kwargs); Py_DECREF(kwargs); if (!res) throw std::runtime_error("Call to show() failed."); Py_DECREF(res); } inline void draw() { PyObject* res = PyObject_CallObject( detail::_interpreter::get().s_python_function_draw, detail::_interpreter::get().s_python_empty_tuple); if (!res) throw std::runtime_error("Call to draw() failed."); Py_DECREF(res); } template inline void pause(Numeric interval) { PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval)); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args); if(!res) throw std::runtime_error("Call to pause() failed."); Py_DECREF(args); Py_DECREF(res); } inline void save(const std::string& filename) { PyObject* pyfilename = PyString_FromString(filename.c_str()); PyObject* args = PyTuple_New(1); PyTuple_SetItem(args, 0, pyfilename); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args); if (!res) throw std::runtime_error("Call to save() failed."); Py_DECREF(args); Py_DECREF(res); } inline void clf() { PyObject *res = PyObject_CallObject( detail::_interpreter::get().s_python_function_clf, detail::_interpreter::get().s_python_empty_tuple); if (!res) throw std::runtime_error("Call to clf() failed."); Py_DECREF(res); } inline void ion() { PyObject *res = PyObject_CallObject( detail::_interpreter::get().s_python_function_ion, detail::_interpreter::get().s_python_empty_tuple); if (!res) throw std::runtime_error("Call to ion() failed."); Py_DECREF(res); } // Actually, is there any reason not to call this automatically for every plot? inline void tight_layout() { PyObject *res = PyObject_CallObject( detail::_interpreter::get().s_python_function_tight_layout, detail::_interpreter::get().s_python_empty_tuple); if (!res) throw std::runtime_error("Call to tight_layout() failed."); Py_DECREF(res); } #if __cplusplus > 199711L || _MSC_VER > 1800 // C++11-exclusive content starts here (variadic plot() and initializer list support) namespace detail { template using is_function = typename std::is_function>>::type; template struct is_callable_impl; template struct is_callable_impl { typedef is_function type; }; // a non-object is callable iff it is a function template struct is_callable_impl { struct Fallback { void operator()(); }; struct Derived : T, Fallback { }; template struct Check; template static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match template static std::false_type test( Check* ); public: typedef decltype(test(nullptr)) type; typedef decltype(&Fallback::operator()) dtype; static constexpr bool value = type::value; }; // an object is callable iff it defines operator() template struct is_callable { // dispatch to is_callable_impl or is_callable_impl depending on whether T is of class type or not typedef typename is_callable_impl::value, T>::type type; }; template struct plot_impl { }; template<> struct plot_impl { template bool operator()(const IterableX& x, const IterableY& y, const std::string& format) { // 2-phase lookup for distance, begin, end using std::distance; using std::begin; using std::end; auto xs = distance(begin(x), end(x)); auto ys = distance(begin(y), end(y)); assert(xs == ys && "x and y data must have the same number of elements!"); PyObject* xlist = PyList_New(xs); PyObject* ylist = PyList_New(ys); PyObject* pystring = PyString_FromString(format.c_str()); auto itx = begin(x), ity = begin(y); for(size_t i = 0; i < xs; ++i) { PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++)); PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++)); } PyObject* plot_args = PyTuple_New(3); PyTuple_SetItem(plot_args, 0, xlist); PyTuple_SetItem(plot_args, 1, ylist); PyTuple_SetItem(plot_args, 2, pystring); PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args); Py_DECREF(plot_args); if(res) Py_DECREF(res); return res; } }; template<> struct plot_impl { template bool operator()(const Iterable& ticks, const Callable& f, const std::string& format) { if(begin(ticks) == end(ticks)) return true; // We could use additional meta-programming to deduce the correct element type of y, // but all values have to be convertible to double anyways std::vector y; for(auto x : ticks) y.push_back(f(x)); return plot_impl()(ticks,y,format); } }; } // end namespace detail // recursion stop for the above template bool plot() { return true; } template bool plot(const A& a, const B& b, const std::string& format, Args... args) { return detail::plot_impl::type>()(a,b,format) && plot(args...); } /* * This group of plot() functions is needed to support initializer lists, i.e. calling * plot( {1,2,3,4} ) */ inline bool plot(const std::vector& x, const std::vector& y, const std::string& format = "") { return plot(x,y,format); } inline bool plot(const std::vector& y, const std::string& format = "") { return plot(y,format); } inline bool plot(const std::vector& x, const std::vector& y, const std::map& keywords) { return plot(x,y,keywords); } #endif } // end namespace matplotlibcpp ================================================ FILE: include/tic_toc.h ================================================ // // Created by buyi on 18-1-28. // #ifndef IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H #define IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H #include #include #include namespace IMU { class TicToc { public: TicToc() { tic(); } void tic() { start = std::chrono::system_clock::now(); } double toc() //ms { end = std::chrono::system_clock::now(); std::chrono::duration elapsed_seconds = end - start; return elapsed_seconds.count()*1000; } private: std::chrono::time_point start, end; }; } //namesapce IMU #endif //IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H ================================================ FILE: src/Convert.cpp ================================================ #include "Convert.h" #include "TypeDefs.h" #include namespace IMU { void Vect_to_SkewMat(Vector_3 Vector, Matrix_3 &Matrix) { Matrix << 0, -Vector(2), Vector(1), Vector(2), 0, -Vector(0), -Vector(1), Vector(0), 0; } void Angular_to_Mat(Vector_3 Vector, Eigen::Matrix &Matrix) { Matrix << 0, -Vector(0), -Vector(1), -Vector(2), Vector(0), 0, Vector(2), -Vector(1), Vector(1), -Vector(2), 0, Vector(0), Vector(2), Vector(1), -Vector(0), 0; } Vector_4 Quaternion_to_Vect(Eigen::Quaterniond q) { Vector_4 vector; vector(0) = q.w(); vector.block<3, 1>(1, 0) = q.vec(); return vector; } Eigen::Quaterniond QuatMult(Eigen::Quaterniond q1, Eigen::Quaterniond q2) { Eigen::Quaterniond resultQ; resultQ.setIdentity(); resultQ.w() = q1.w() * q2.w() - q1.vec().dot(q2.vec()); resultQ.vec() = q1.w() * q2.vec() + q2.w() * q1.vec() + q1.vec().cross(q2.vec()); return resultQ; } Matrix_3 Quat_to_Matrix(Eigen::Quaterniond q) { Matrix_3 matrix; matrix << q.w()*q.w() + q.x()*q.x() - q.y()*q.y() - q.z()*q.z(), 2 * (q.x()*q.y() - q.w()*q.z()), 2 * (q.x()*q.z() + q.w()*q.y()), 2 * (q.x()*q.y() + q.w()*q.z()), q.w()*q.w() - q.x()*q.x() + q.y()*q.y() - q.z()*q.z(), 2 * (q.y()*q.z() - q.w()*q.x()), 2 * (q.x()*q.z() - q.w()*q.y()), 2 * (q.y()*q.z() + q.w()*q.x()), q.w()*q.w() - q.x()*q.x() - q.y()*q.y() + q.z()*q.z(); return matrix; } Eigen::MatrixXd readFromfile(const string file_name) { Eigen::MatrixXd matrix; std::vector entries; ifstream data(file_name, ios::binary); string lineOfData; if (data.is_open()) { int i = 0; int cols = 0; while (data.good()) { int j = 0; getline(data, lineOfData); stringstream stream(lineOfData); while (!stream.eof()) { double a; stream >> a; entries.push_back(a); j++; } cols = j; i++; } matrix = Eigen::MatrixXd::Map(&entries[0], cols, i).transpose(); return matrix; } else { cout << "Unable to open file" << std::endl; return Eigen::Vector3d::Zero(); } } bool writeTofile(Eigen::MatrixXd matrix, const string file_name) { std::ofstream file(file_name, ios::binary); if (file.is_open()) { file << matrix << '\n'; } else return false; file.close(); return true; } Matrix_3 Euler_to_RoatMat(Vector_3 Euler) { Matrix_3 Rotate_Mat; double theta; Matrix_3 Skew_Euler; theta = Euler.norm(); Euler.normalize(); Vect_to_SkewMat(Euler, Skew_Euler); Rotate_Mat = Matrix_3::Identity() + sin(theta)*Skew_Euler + (1 - cos(theta))*Skew_Euler.transpose()*Skew_Euler; return Rotate_Mat; } Eigen::Quaterniond Euler_to_Quaternion(Vector_3 Euler) { Eigen::Quaterniond quaternion; /* double theta = sqrt(Euler(0)*Euler(0) + Euler(1)*Euler(1) + Euler(2)*Euler(2)); Euler.normalize(); quaternion.w() = cos(0.5*theta); quaternion.vec() = Euler*sin(0.5*theta); */ // using Eigen /* quaternion = Eigen::AngleAxisd(Euler(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(Euler(1), Eigen::Vector3d::UnitY()) *Eigen::AngleAxisd(Euler(2), Eigen::Vector3d::UnitZ()); */ double CosRoll = cos(Euler[0] * 0.5); double SinRoll = sin(Euler[0] * 0.5); double CosPitch = cos(Euler[1] * 0.5); double SinPitch = sin(Euler[1] * 0.5); double CosYaw = cos(Euler[2] * 0.5); double SinYaw = sin(Euler[2] * 0.5); double w = CosRoll*CosPitch*CosYaw + SinRoll*SinPitch*SinYaw; double x = CosPitch*SinRoll*CosYaw - CosRoll*SinPitch*SinYaw; double y = CosRoll*CosYaw*SinPitch + SinRoll*CosPitch*SinYaw; double z = CosRoll*CosPitch*SinYaw - CosYaw*SinPitch*SinRoll; quaternion = Eigen::Quaterniond(w, x, y, z); return quaternion; } Vector_3 Quaternion_to_Euler(Eigen::Quaterniond q) { Vector_3 Euler; // the normal way Euler(0) = atan2(2 * (q.y()*q.z() + q.w()*q.x()), (q.w()*q.w() - q.x()*q.x() - q.y()*q.y() + q.z()*q.z())); Euler(1) = asin(-2 * q.x()*q.z() + 2 * q.w()*q.y()); Euler(2) = atan2(2 * (q.x()*q.y() + q.w()*q.z()), (q.w()*q.w() + q.x()*q.x() - q.y()*q.y() - q.z()*q.z())) - 8.3*M_PI/180; /* // using the eigen q.normalize(); Euler = q.toRotationMatrix().eulerAngles(0, 1, 2); */ return Euler*180/M_PI; } Vector_3 Rotation_to_Euler(Matrix_3 Rotation) { Vector_3 Euler; Euler(0) = atan2(Rotation(1, 2), Rotation(2, 2)); Euler(1) = -asin(Rotation(0, 2)); Euler(2) = atan2(Rotation(0, 1), Rotation(0, 0)); return Euler; } Eigen::Quaterniond Rotation_to_Quater(Matrix_3 Rotation) { Eigen::Quaterniond quaternion; Vector_4 quat_tmp; double tr; tr = Rotation.trace(); if (tr > 0.0) { double s = sqrtf(tr + 1.0); quat_tmp(0) = s*0.5; s = 0.5 / s; quat_tmp(1) = (Rotation(2, 1) - Rotation(1, 2))*s; quat_tmp(2) = (Rotation(0, 2) - Rotation(2, 0))*s; quat_tmp(3) = (Rotation(1, 0) - Rotation(0, 1))*s; } else { int dcm_i = 0; for (int i = 1; i < 3; i++) { if (Rotation(i, i) > Rotation(dcm_i, dcm_i)) dcm_i = i; } int dcm_j = (dcm_i + 1) % 3; int dcm_k = (dcm_i + 2) % 3; double s = sqrtf((Rotation(dcm_i, dcm_i) - Rotation(dcm_j, dcm_j) - Rotation(dcm_k, dcm_k)) + 1.0f); quat_tmp(dcm_i + 1) = s*0.5; s = 0.5 / s; quat_tmp(dcm_j + 1) = (Rotation(dcm_i, dcm_j) + Rotation(dcm_j, dcm_i)) * s; quat_tmp[dcm_k + 1] = (Rotation(dcm_k, dcm_i) + Rotation(dcm_i, dcm_k)) * s; quat_tmp[0] = (Rotation(dcm_k, dcm_j) - Rotation(dcm_j, dcm_k)) * s; } quaternion.w() = quat_tmp(0); quaternion.vec() = quat_tmp.block<3, 1>(1, 0); return quaternion; } Eigen::Quaterniond BuildUpdateQuat(Eigen::Vector3d DeltaTheta) { Eigen::Vector3d DeltaQuat = 0.5*DeltaTheta; double checknorm = DeltaQuat.transpose()*DeltaQuat; Eigen::Quaterniond UpdateQuat; if (checknorm > 1) { UpdateQuat = Eigen::Quaterniond(1, DeltaQuat[0], DeltaQuat[1], DeltaQuat[2]); UpdateQuat = UpdateQuat.coeffs()*sqrt(1 + checknorm); } else UpdateQuat = Eigen::Quaterniond(sqrt(1 - checknorm), DeltaQuat[0], DeltaQuat[1], DeltaQuat[2]); UpdateQuat.normalize(); return UpdateQuat; } } //IMU ================================================ FILE: src/EKF_Attitude.cpp ================================================ #include "EKF_Attitude.h" #include "Convert.h" using namespace std; namespace IMU { EKF_Attitude::EKF_Attitude(bool approx_prediction, double dt): mbStopped(false), mbStopRequested(false), deltaT(dt) { cout << "System initialization!" << endl; /* Set the primary value of state vector and covariance matrix */ if (state_X_pro.size() == 0) { Vector_12 state_X_tmp; /* state_X_tmp << 0.0018, -0.0003, 0.0015, 0.0351, -0.0567, -0.0364, 0.0093, -0.0012, -0.9998, 0.0089, 0.4784, 0.8781; */ state_X_tmp << 0.0, -0.0, 0.0, 0.0, -0.0, -0.0, 0.0, -0.0, -0.9998, 0.0, 0.0, 1; state_X_pro.push_back(state_X_tmp); } if (CovrMatrix_P_pro.size()==0) { // CovrMatrix_P_pro.push_back(Eigen::MatrixXd::Ones(12, 12) * 200); Vector_3 V1(0, 0, 0.0001); Vector_3 V2(0, 0.0001, -0.0001); Matrix_3 M1, M2; Vect_to_SkewMat(V1, M1); Vect_to_SkewMat(V2, M2); Eigen::Matrix CovrMatrix_tmp; CovrMatrix_tmp << 0.004*Identity_Matrix3, 0.056*Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, 0.056*Identity_Matrix3, 0.2971*Identity_Matrix3, M1, M2, Zeros_Matrix3, -M1, 2.9956*Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, -M2, Zeros_Matrix3, 0.7046*Identity_Matrix3; CovrMatrix_P_pro.push_back(CovrMatrix_tmp); } using_2ndOrder = approx_prediction; // set the process noise as the diagnoal of elements Vector_12 Pro_Nosiecovr; Vector_9 Mea_Nosiecovr; Pro_Nosiecovr << 1e-4, 1e-4, 1e-4, 0.08, 0.08, 0.08, 0.009, 0.009, 0.009, 0.005, 0.005, 0.005; Mea_Nosiecovr << 0.0008, 0.0008, 0.0008, 1000, 1000, 1000, 100, 100, 100; Q_noise = Pro_Nosiecovr.asDiagonal(); R_noise = Mea_Nosiecovr.asDiagonal(); } void EKF_Attitude::Param_Change(Vector_12 Pro_Nosiecovr, Vector_9 Mea_Nosiecovr) { if (isStopped()) { Q_noise = Pro_Nosiecovr.asDiagonal(); R_noise = Mea_Nosiecovr.asDiagonal(); } } void EKF_Attitude::Cal_TransMatrix() { Matrix_3 r_acc, r_mag, w_angular, w_angular_T; Vector_3 r_acc_v, r_mag_v, w_angular_v; Vector_12 state_X_tmp; state_X_tmp = state_X_pro.back(); w_angular_v = state_X_tmp.block<3, 1>(0, 0); r_acc_v = state_X_tmp.block<3, 1>(6, 0); r_mag_v = state_X_tmp.block<3, 1>(9, 0); Vect_to_SkewMat(w_angular_v, w_angular_T); w_angular = w_angular_T.transpose(); Vect_to_SkewMat(r_acc_v, r_acc); Vect_to_SkewMat(r_mag_v, r_mag); Alin << Zeros_Matrix3, Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, r_acc, Zeros_Matrix3, w_angular, Zeros_Matrix3, -r_mag, Zeros_Matrix3, Zeros_Matrix3, w_angular; Alin = Eigen::MatrixXd::Identity(12, 12) + Alin*deltaT; } void EKF_Attitude::Prior_Predict() { Vector_12 state_X_tmp; Vector_3 angular_vel, angular_acc, acc_state, mag_state; Matrix_3 w_angular, w_angular_T; state_X_tmp = state_X_pro.back(); angular_vel = state_X_tmp.block<3, 1>(0, 0); angular_acc = state_X_tmp.block<3, 1>(3, 0); Vect_to_SkewMat(angular_vel, w_angular_T); w_angular = w_angular_T.transpose(); angular_vel = angular_vel + angular_acc*deltaT; // calculate the non-liner system, and decide wto use the number of taylor expansion if (using_2ndOrder) { Matrix_3 Temp_Mat = Identity_Matrix3 + w_angular*deltaT + deltaT*deltaT/2*w_angular*w_angular; acc_state = state_X_tmp.block<3, 1>(6, 0); acc_state = Temp_Mat*acc_state; mag_state = state_X_tmp.block<3, 1>(9, 0); mag_state = Temp_Mat*mag_state; } else { Matrix_3 Temp_Mat; acc_state = state_X_tmp.block<3, 1>(6, 0); Temp_Mat = Identity_Matrix3 + w_angular*deltaT; acc_state = Temp_Mat*acc_state; mag_state = state_X_tmp.block<3, 1>(9, 0); mag_state = Temp_Mat*mag_state; } // refer to the 4.20 and 4.21 formula Eigen::Matrix CovrMatrix_tmp; state_X_tmp << angular_vel, angular_acc, acc_state, mag_state; state_X_pro.push_back(state_X_tmp); CovrMatrix_tmp = CovrMatrix_P_pro.back(); CovrMatrix_tmp = Alin*CovrMatrix_tmp*Alin.transpose() + Q_noise; CovrMatrix_P_pro.push_back(CovrMatrix_tmp); } void EKF_Attitude::Post_Correct() { Vector_12 state_X_tmp; Eigen::Matrix CovrMatrix_tmp; state_X_tmp = state_X_pro.back(); state_X_pro.pop_back(); CovrMatrix_tmp = CovrMatrix_P_pro.back(); CovrMatrix_P_pro.pop_back(); // initialize the observe matrix H Eigen::Matrix Observe_Matrix; Observe_Matrix << Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Identity_Matrix3; // calculate the Kalman gain Eigen::Matrix Kal_Matrix; Eigen::Matrix Kalman_gain; Kal_Matrix = Observe_Matrix*CovrMatrix_tmp*Observe_Matrix.transpose() + R_noise; Kalman_gain = CovrMatrix_tmp*Observe_Matrix.transpose()*Kal_Matrix.inverse(); // update the state vector Vector_9 Mea_residual; Mea_residual = cur_measurement - Observe_Matrix*state_X_tmp; state_X_tmp = state_X_tmp + Kalman_gain*Mea_residual; state_X_pro.push_back(state_X_tmp); // update the covariance Matrix CovrMatrix_tmp = (Eigen::MatrixXd::Identity(12, 12) - Kalman_gain*Observe_Matrix)*CovrMatrix_tmp; CovrMatrix_P_pro.push_back(CovrMatrix_tmp); } void EKF_Attitude::Cal_Quaternion() { //if (quaternion.size() >= 358) // cout << " " << endl; // extract the true state of three sensors Vector_3 acc_state, mag_state, angular_state; Vector_12 state_X_tmp; state_X_tmp = state_X_pro.back(); acc_state = state_X_tmp.block<3, 1>(6, 0); mag_state = state_X_tmp.block<3, 1>(9, 0); Vector_3 x_state, y_state, z_state; acc_state.normalize(); mag_state.normalize(); z_state = -acc_state; y_state = z_state.cross(mag_state); y_state.normalize(); x_state = y_state.cross(z_state); x_state.normalize(); // the rotation order is X-Y-Z,and Matrix_3 Rotation_matrix; Rotation_matrix << x_state, y_state, z_state; Eigen::Quaterniond quat_temp(Rotation_matrix.transpose()); // Eigen::Quaterniond quat_temp = Rotation_to_Quater(Rotation_matrix.transpose()); Vector_3 Euler; Euler = Quaternion_to_Euler(quat_temp); // cout << Euler << endl; quaternion.push_back(quat_temp); } void EKF_Attitude::Read_SensorData(Vector_9 measurement) { Vector_3 gyro_mea, acc_mea, mag_mea; acc_mea = measurement.block<3, 1>(0, 0); gyro_mea = measurement.block<3, 1>(3, 0); mag_mea = measurement.block<3, 1>(6, 0); acc_mea.normalize(); mag_mea.normalize(); cur_measurement.block<3, 1>(0, 0) = gyro_mea; cur_measurement.block<3, 1>(3, 0) = acc_mea; cur_measurement.block<3, 1>(6, 0) = mag_mea; } Eigen::Quaterniond EKF_Attitude::Run(Vector_9 measurement) { while (true) { Read_SensorData(measurement); Cal_TransMatrix(); Prior_Predict(); Post_Correct(); Cal_Quaternion(); if (Stop()) { while (isStopped()) { #ifdef _WIN32 Sleep(3000); #else usleep(3000); #endif } } return quaternion.back(); } } void EKF_Attitude::RequestStop() { unique_lock lock(mMutexStop); mbStopRequested = true; } void EKF_Attitude::RequestStart() { unique_lock lock(mMutexStop); if (mbStopped) { mbStopped = false; mbStopRequested = false; } } bool EKF_Attitude::Stop() { unique_lock lock(mMutexStop); if (mbStopRequested) { mbStopped = true; return true; } return false; } bool EKF_Attitude::isStopped() { unique_lock lock(mMutexStop); return mbStopped; } void EKF_Attitude::Release() { unique_lock lock(mMutexStop); mbStopped = false; mbStopRequested = false; state_X_pro.clear(); CovrMatrix_P_pro.clear(); quaternion.clear(); cout << "EKF attitude release " << endl; } } ================================================ FILE: src/ESKF_Attitude.cpp ================================================ #include #include "math.h" #include "ESKF_Attitude.h" #include "Convert.h" using namespace std; namespace IMU { ESKF_Attitude::ESKF_Attitude(Vector_12 Covar_Mat, double dt) { deltaT = dt; DetAng_noise = Covar_Mat.block<3, 1>(0, 0); DetAngVel_noise = Covar_Mat.block<3, 1>(3, 0); Acc_noise = Covar_Mat.block<3, 1>(6, 0); Mag_noise = Covar_Mat.block<3, 1>(9, 0); CovarMat_Q = Eigen::Matrix::Zero(); CovarMat_R = Eigen::Matrix::Zero(); } void ESKF_Attitude::Param_Change(Vector_12 Covar_Mat) { if (isStopped()) { DetAng_noise = Covar_Mat.block<3, 1>(0, 0); DetAngVel_noise = Covar_Mat.block<3, 1>(0, 0); Acc_noise = Covar_Mat.block<3, 1>(0, 0); Mag_noise = Covar_Mat.block<3, 1>(0, 0); // Initialize the covariances matrices Q and R CovarMat_Q.block<3, 3>(0, 0) = DetAng_noise.asDiagonal(); CovarMat_Q.block<3, 3>(3, 3) = DetAngVel_noise.asDiagonal(); CovarMat_R.block<3, 3>(0, 0) = Acc_noise.asDiagonal(); CovarMat_R.block<3, 3>(3, 3) = Mag_noise.asDiagonal(); } } void ESKF_Attitude::Init_Estimator() { // Initialize the covariances matrices Q and R CovarMat_Q.block<3, 3>(0, 0) = DetAng_noise.asDiagonal(); CovarMat_Q.block<3, 3>(3, 3) = DetAngVel_noise.asDiagonal(); CovarMat_R.block<3, 3>(0, 0) = Acc_noise.asDiagonal(); CovarMat_R.block<3, 3>(3, 3) = Mag_noise.asDiagonal(); // Initialize the nominal state //Vector_3 x_state, y_state, z_state; //z_state = Cur_Measurement.block<3, 1>(3, 0); //y_state = z_state.cross(Cur_Measurement.block<3, 1>(6, 0)); //x_state = y_state.cross(z_state); Eigen::Vector3d Acc0, Gyro0, Mag0; Gyro0 = Cur_Measurement.block<3, 1>(0, 0); Acc0 = Cur_Measurement.block<3, 1>(3, 0); Mag0 = Cur_Measurement.block<3, 1>(6, 0); double Pitch0 = asin(Acc0[0]/Acc0.norm()); double Roll0 = atan2(-Acc0[1], -Acc0[2]); double Yaw0 = atan2(-Mag0[1] * cos(Roll0) + Mag0[2] * sin(Roll0), Mag0[0] * cos(Pitch0) + Mag0[1] * sin(Pitch0)*sin(Roll0) + Mag0[2] * sin(Pitch0)*cos(Roll0)) - 8.3*3.14166 / 180; Eigen::Quaterniond quat_temp = Euler_to_Quaternion(Eigen::Vector3d(Roll0, Pitch0, Yaw0)); quat_temp.normalize(); Vector_3 AngVel_temp = DetAngVel_noise; IMU_State state; state.Nominal_quat = quat_temp; state.Nominal_AngVel = AngVel_temp; // Initialize the error state Vector_3 detla_theta, detla_angVel; state.Error_theta = Vector_3::Zero(); state.Error_AngVel = Vector_3::Zero(); state.Error_Convar = Eigen::Matrix::Zero(); state.Error_Convar.block<3, 3>(0, 0) = 1e-5*Eigen::Matrix::Identity(); state.Error_Convar.block<3, 3>(3, 3) = 1e-7*Eigen::Matrix::Identity(); State_Vector.push_back(state); quaternion.push_back(quat_temp); Last_Measurement = Cur_Measurement; } void ESKF_Attitude::NominaState_Predict() { Vector_3 delta_theta; Eigen::Quaterniond quat_temp; IMU_State Piror_State = State_Vector.back(); delta_theta = (0.5*(Cur_Measurement.block<3, 1>(0, 0) + Last_Measurement.block<3, 1>(0, 0)) - Piror_State.Nominal_AngVel)*deltaT; quat_temp.w() = 1; quat_temp.vec() = 0.5*delta_theta; quat_temp = Piror_State.Nominal_quat*quat_temp; quat_temp.normalize(); IMU_State Post_State; Post_State.Nominal_quat = quat_temp; Post_State.Nominal_AngVel = Piror_State.Nominal_AngVel; State_Vector.push_back(Post_State); } void ESKF_Attitude::ErrorState_Predict() { IMU_State Post_State = State_Vector.back(); State_Vector.pop_back(); IMU_State Piror_State = State_Vector.back(); // calculate the transition matrix A Eigen::Matrix Trasition_A; Vector_3 delta_theta; delta_theta = (Last_Measurement.block<3, 1>(0, 0) - Piror_State.Nominal_AngVel)*deltaT; Matrix_3 Rotation_Mat = Euler_to_RoatMat(delta_theta); Trasition_A.block<3, 3>(0, 0) = Rotation_Mat.transpose(); Trasition_A.block<3, 3>(0, 3) = Matrix_3::Identity()*(-deltaT); Trasition_A.block<3, 3>(3, 0) = Matrix_3::Zero(); Trasition_A.block<3, 3>(3, 3) = Matrix_3::Identity(); // priori prediction Vector_6 Errstate_temp; Errstate_temp.block<3, 1>(0, 0) = Piror_State.Error_theta; Errstate_temp.block<3, 1>(3, 0) = Piror_State.Error_AngVel; Errstate_temp = Trasition_A*Errstate_temp; Post_State.Error_theta = Errstate_temp.block<3, 1>(0, 0); Post_State.Error_AngVel = Errstate_temp.block<3, 1>(3, 0); Eigen::Matrix CovarMat_Qi = CovarMat_Q*deltaT; Eigen::Matrix NoiseMat_Fi = Eigen::Matrix::Identity(); Post_State.Error_Convar = Trasition_A*Piror_State.Error_Convar*Trasition_A.transpose() + NoiseMat_Fi*CovarMat_Qi*NoiseMat_Fi.transpose(); State_Vector.push_back(Post_State); } Eigen::Matrix ESKF_Attitude::IMU_State::Cal_ObserveMat(Vector_9 measurenment, Vector_6 &residual) { Vector_3 True_AccMea, True_MagMre, Mea_Mag; Eigen::Matrix Mag_global; Eigen::Quaterniond q = Nominal_quat; Mea_Mag = measurenment.block<3, 1>(6, 0); Eigen::Quaterniond Mag_quat(0.0, Mea_Mag(0), Mea_Mag(1), Mea_Mag(2)); Mag_quat = QuatMult(q, QuatMult(Mag_quat, q.conjugate())); Mag_global << 0, sqrt(Mag_quat.x()*Mag_quat.x() + Mag_quat.y()*Mag_quat.y()), 0, Mag_quat.z(); // calculate the observe Matrix H Eigen::Matrix acc_H, mag_H; acc_H << 2 * q.y(), -2 * q.z(), 2 * q.w(), -2 * q.x(), -2 * q.x(), -2 * q.w(), -2 * q.z(), -2 * q.y(), 0, 4 * q.x(), 4 * q.y(), 0; mag_H << -2 * Mag_global(3)*q.y(), 2 * Mag_global(3)*q.z(), -4 * Mag_global(1)*q.y() - 2 * Mag_global(3)*q.w(), -4 * Mag_global(1)*q.z() + 2 * Mag_global(3)*q.x(), -2 * Mag_global(1)*q.z() + 2 * Mag_global(3)*q.x(), 2 * Mag_global(1)*q.y() + 2 * Mag_global(3)*q.w(), 2 * Mag_global(1)*q.x() + 2 * Mag_global(3)*q.z(), -2 * Mag_global(1)*q.w() + 2 * Mag_global(3)*q.y(), 2 * Mag_global(1)*q.y(), 2 * Mag_global(1)*q.z() - 4 * Mag_global(3)*q.x(), 2 * Mag_global(1)*q.w() - 4 * Mag_global(3)*q.y(), 2 * Mag_global(1)*q.x(); Eigen::Matrix Observe_Hx; Observe_Hx.block<3, 4>(0, 0) = acc_H; Observe_Hx.block<3, 4>(3, 0) = mag_H; Observe_Hx.block<3, 3>(0, 4) = Matrix_3::Zero(); Observe_Hx.block<3, 3>(3, 4) = Matrix_3::Zero(); Eigen::Matrix Observe_Xx; Eigen::Matrix Matrix_Q; Matrix_Q << -q.x(), -q.y(), -q.z(), q.w(), -q.z(), q.y(), q.z(), q.w(), -q.x(), -q.y(), q.x(), q.w(); Observe_Xx.block<4, 3>(0, 0) = 0.5*Matrix_Q; Observe_Xx.block<4, 3>(0, 3) = Eigen::Matrix::Zero(); Observe_Xx.block<3, 3>(4, 0) = Matrix_3::Zero(); Observe_Xx.block<3, 3>(4, 3) = Matrix_3::Identity(); Eigen::Matrix Observe_Matrix; Observe_Matrix = Observe_Hx*Observe_Xx; // Calculate the true measurement // the true accelerometer measurement True_AccMea << -2 * (q.x()*q.z() - q.w()*q.y()), -2 * (q.w()*q.x() + q.y()*q.z()), -2 * (0.5 - q.x()*q.x() - q.y()*q.y()); // the true magnetometer measurement True_MagMre << -(2 * Mag_global(1)*(0.5 - q.y()*q.y() - q.z()*q.z()) + 2 * Mag_global(3)*(q.x()*q.z() - q.w()*q.y())), -(2 * Mag_global(1)*(q.x()*q.y() - q.w()*q.z()) + 2 * Mag_global(3)*(q.w()*q.x() + q.y()*q.z())), -(2 * Mag_global(1)*(q.w()*q.y() + q.x()*q.z()) + 2 * Mag_global(3)*(0.5 - q.x()*q.x() - q.y()*q.y())); // calculate the residual residual.block<3, 1>(0, 0) = measurenment.block<3, 1>(3, 0) + True_AccMea; residual.block<3, 1>(3, 0) = measurenment.block<3, 1>(6, 0) + True_MagMre; return Observe_Matrix; } void ESKF_Attitude::Update_Filter() { Vector_6 Residual; Eigen::Matrix Observe_Matrix; IMU_State Post_State = State_Vector.back(); State_Vector.pop_back(); // calculate the observe matrix and the correction residual Observe_Matrix = Post_State.Cal_ObserveMat(Cur_Measurement, Residual); //Calculate the kalman gain Eigen::Matrix Poste_Cov = Post_State.Error_Convar; Eigen::Matrix Kalman_Gain; Kalman_Gain = Observe_Matrix*Poste_Cov*Observe_Matrix.transpose() + CovarMat_R; Kalman_Gain = Poste_Cov*Observe_Matrix.transpose()*Kalman_Gain.inverse(); // update error state Vector_6 Post_ErrState = Kalman_Gain*Residual; Post_State.Error_theta = Post_ErrState.block<3, 1>(0, 0); Post_State.Error_AngVel = Post_ErrState.block<3, 1>(3, 0); Post_State.Error_Convar = Poste_Cov - Kalman_Gain*(Observe_Matrix*Poste_Cov*Observe_Matrix.transpose() + CovarMat_R)*Kalman_Gain.transpose(); State_Vector.push_back(Post_State); } void ESKF_Attitude::Update_NomianState() { IMU_State Post_State = State_Vector.back(); State_Vector.pop_back(); Eigen::Quaterniond delta_q = BuildUpdateQuat(Post_State.Error_theta); Post_State.Nominal_quat = Post_State.Nominal_quat*delta_q; Post_State.Nominal_quat.normalize(); Post_State.Nominal_AngVel = Post_State.Nominal_AngVel + Post_State.Error_AngVel; State_Vector.push_back(Post_State); quaternion.push_back(Post_State.Nominal_quat); } void ESKF_Attitude::Reset_ErrorState() { IMU_State Post_State = State_Vector.back(); State_Vector.pop_back(); Eigen::Matrix Matrix_G = Eigen::Matrix::Identity(); //Matrix_3 Ang_Mat = Post_State.Error_theta.asDiagonal(); //Matrix_G.block<3, 3>(0, 0) = Matrix_3::Identity() - Ang_Mat; Post_State.Error_theta = Vector_3::Zero(); Post_State.Error_AngVel = Vector_3::Zero(); Post_State.Error_Convar = Matrix_G*Post_State.Error_Convar*Matrix_G.transpose(); State_Vector.push_back(Post_State); Last_Measurement = Cur_Measurement; } void ESKF_Attitude::Read_SensorData(Vector_9 measurement) { Vector_3 gyro_mea, acc_mea, mag_mea; acc_mea = measurement.block<3, 1>(0, 0); gyro_mea = measurement.block<3, 1>(3, 0); mag_mea = measurement.block<3, 1>(6, 0); acc_mea.normalize(); mag_mea.normalize(); Cur_Measurement.block<3, 1>(0, 0) = gyro_mea; Cur_Measurement.block<3, 1>(3, 0) = acc_mea; Cur_Measurement.block<3, 1>(6, 0) = mag_mea; } Eigen::Quaterniond ESKF_Attitude::Run(Vector_9 measurement) { while (true) { Read_SensorData(measurement); if (State_Vector.size() == 0 || quaternion.size() == 0) { // Initialize the true state of the estimator Init_Estimator(); } else { // Predict the nomial and error state NominaState_Predict(); ErrorState_Predict(); // Update the filter parametres Update_Filter(); // Uptate the nominal state Update_NomianState(); // Reset the error state Reset_ErrorState(); } if (Stop()) { while (isStopped()) { #ifdef _WIN32 Sleep(3); #else usleep(3000); #endif } } return quaternion.back(); } } void ESKF_Attitude::RequestStop() { unique_lock lock(mMutexStop); mbStopRequested = true; } void ESKF_Attitude::RequestStart() { unique_lock lock(mMutexStop); if (mbStopped) { mbStopped = false; mbStopRequested = false; } } bool ESKF_Attitude::Stop() { unique_lock lock(mMutexStop); if (mbStopRequested) { mbStopped = true; return true; } return false; } bool ESKF_Attitude::isStopped() { unique_lock lock(mMutexStop); return mbStopped; } void ESKF_Attitude::Release() { unique_lock lock(mMutexStop); mbStopped = false; mbStopRequested = false; State_Vector.clear(); quaternion.clear(); cout << "EKF attitude release " << endl; } }// namespace IMU ================================================ FILE: src/Mahony_Attitude.cpp ================================================ #include #include "Mahony_Attitude.h" #include "Convert.h" using namespace std; namespace IMU { Mahony_Attitude::Mahony_Attitude(Vector_2 PI, double dt): mbStopped(false), mbStopRequested(false) { Kp = PI(0); Ki = PI(1); deltaT = dt; Integ_angular = Vector_3::Zero(); } void Mahony_Attitude::Params_Change(Vector_2 PI, double dt) { if (isStopped()) { Kp = PI(0); Ki = PI(1); deltaT = dt; } } void Mahony_Attitude::Mahony_Estimate() { Vector_3 angular_vel, acc, mag; angular_vel = cur_measurement.block<3, 1>(0, 0); acc = cur_measurement.block<3, 1>(3, 0); mag = cur_measurement.block<3, 1>(6, 0); Eigen::Quaterniond quat_temp; Vector_3 x_state, y_state, z_state; Matrix_3 Rotation_matrix; // if the quaternion is empty, the quaternion will be initialized by tha accelerometer and magnetometer if (quaternion.empty()) { z_state = acc; y_state = z_state.cross(mag); x_state = y_state.cross(z_state); Rotation_matrix << x_state, y_state, z_state; quat_temp = Rotation_matrix; quaternion.push_back(quat_temp); } else { // get the error from the measurement from accelerometer and magnetometer quat_temp = quaternion.back(); quat_temp.normalized(); Rotation_matrix = quat_temp.toRotationMatrix(); Vector_3 error_acc, error_mag, mag_ned, error_sum; error_acc = Rotation_matrix.block<3, 1>(0, 2); error_acc = acc.cross(error_acc); mag_ned = Rotation_matrix.transpose()*mag; error_mag << sqrt(mag_ned(0)*mag_ned(0) + mag_ned(1)*mag_ned(1)), 0, mag_ned(2); error_mag = Rotation_matrix*error_mag; error_mag = mag.cross(error_mag); error_sum = error_acc + error_mag; // get the modify value from the error Vector_3 Integ_angular, Correct_angular; Integ_angular = Integ_angular + Ki*deltaT*error_sum; Correct_angular = angular_vel + Kp*error_sum + Integ_angular; Eigen::Quaterniond Angular_quat; Angular_quat.w() = 0.0; Angular_quat.vec() = Correct_angular; // update the quaternion refer to the correct angular Eigen::Quaterniond quat_temp_new; quat_temp_new = QuatMult(quat_temp, Angular_quat); quat_temp_new.w() = quat_temp_new.w()*0.5*deltaT + quat_temp.w(); quat_temp_new.vec() = quat_temp_new.vec()*0.5*deltaT + quat_temp.vec(); quat_temp_new.normalize(); quaternion.push_back(quat_temp_new); } } void Mahony_Attitude::Read_SensorData(Vector_9 measurement) { Vector_3 gyro_mea, acc_mea, mag_mea; acc_mea = measurement.block<3, 1>(0, 0); gyro_mea = measurement.block<3, 1>(3, 0); mag_mea = measurement.block<3, 1>(6, 0); acc_mea.normalize(); mag_mea.normalize(); cur_measurement.block<3, 1>(0, 0) = gyro_mea; cur_measurement.block<3, 1>(3, 0) = acc_mea; cur_measurement.block<3, 1>(6, 0) = mag_mea; } Eigen::Quaterniond Mahony_Attitude::Run(Vector_9 measurement) { while (true) { Read_SensorData(measurement); Mahony_Estimate(); if (Stop()) { while (isStopped()) { #ifdef _WIN32 Sleep(3000); #else usleep(3000); #endif } } return quaternion.back(); } } void Mahony_Attitude::RequestStop() { unique_lock lock(mMutexStop); mbStopRequested = true; } void Mahony_Attitude::RequestStart() { unique_lock lock(mMutexStop); if (mbStopped) { mbStopped = false; mbStopRequested = false; } } bool Mahony_Attitude::Stop() { unique_lock lock(mMutexStop); if (mbStopRequested) { mbStopped = true; return true; } return false; } bool Mahony_Attitude::isStopped() { unique_lock lock(mMutexStop); return mbStopped; } void Mahony_Attitude::Release() { unique_lock lock(mMutexStop); mbStopped = false; mbStopRequested = false; Integ_angular = Vector_3::Zero(); quaternion.clear(); cout << "Mahony attitude release " << endl; } }