[
  {
    "path": "Allan_Analysis.py",
    "content": "import numpy as np\nimport matplotlib.pyplot as plt\nimport math\nimport numpy.matlib\nfrom scipy.optimize import nnls\nimport scipy.io as sio\n\n\n# data was sampled in 100hz\nPts_size = 100\nfs = 100\n\ndata = np.loadtxt(\"./datasets/data.dat\")\ndata = data[:,2:5]*3600\n[N, M] = data.shape\n\nn = np.arange(0, math.floor(math.log(N/2, 2))+1)\nn = 2**n\nmaxN = n[n.size-1]\nendLogInc = math.log(maxN, 10);\nm = np.unique(np.ceil(np.logspace(0, endLogInc, Pts_size))).transpose()\n\nt0 = 1.0/fs\nT = m*t0\n\ntheta = np.zeros([N, M])\ntheta[:, 0] = data[:, 0].cumsum()/fs\ntheta[:, 1] = data[:, 1].cumsum()/fs\ntheta[:, 2] = data[:, 2].cumsum()/fs\nsigma2 = np.zeros([T.size, M])\nfor i in range(0, m.size):\n    for k in range(0, int(N-2*m[i])):\n        sigma2[i,:] = sigma2[i,:] + (theta[int(k+2*m[i]), :] - 2*theta[int(k+m[i]), :] + theta[k, :])**2\n    print(i)\n    sigma2[i,:] = sigma2[i,:]/(2*T[i]**2*(N-2*m[i]))\n\nsigma2 = np.load(\"sigma2.dat.npy\")\nT = np.load(\"T.dat.npy\")\n\n\nsigma = np.sqrt(sigma2)\nprint(\"hello\")\n\nplt.loglog(T, sigma2)\nplt.show()\n\nfor j in range(0,2):\n    avar = sigma(j)\n    P = np.empty((T.size, 5))\n    P[:, 0] = 3 / T**2\n    P[:, 1] = 1 / T\n    P[:, 2] = 2 * np.log(2) / np.pi\n    P[:, 3] = T / 3\n    P[:, 4] = T**2 / 2\n    P /= avar[:, np.newaxis]\n    b = np.ones(T.size)\n    s = nnls(P, b)[0]\n    params = np.sqrt(s)\n\nprint(params)"
  },
  {
    "path": "CMakeLists.txt",
    "content": "cmake_minimum_required(VERSION 2.8)\nproject(IMU_Attitude_Estimator)\n\nset(CMAKE_BUILD_TYPE Release)\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11 -o3\")\n\n\nset(CMAKE_RUNTIME_OUTPUT_DIRECTORY  ${PROJECT_SOURCE_DIR}/bin)\nset(CMAKE_ARCHIVE_OUTPUT_DIRECTORY  ${PROJECT_SOURCE_DIR}/lib)\nlist(APPEND CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake_modules)\n\nfind_package(Eigen3 REQUIRED)\ninclude_directories(EIGEN3_INCLUDE_DIR)\n\ninclude_directories(\"/usr/include/eigen3\")\n\nfind_package(Glog REQUIRED)\ninclude_directories(${GLOG_INCLUDE_DIRS})\n\nfind_package(PythonLibs 2.7)\ninclude_directories(${PYTHON_INCLUDE_DIRS})\n\ninclude_directories(${PROJECT_SOURCE_DIR}/include)\n\n\nadd_library(${PROJECT_NAME} SHARED\n        src/Convert.cpp\n        src/EKF_Attitude.cpp\n        src/ESKF_Attitude.cpp\n        src/Mahony_Attitude.cpp)\n\ntarget_link_libraries(${PROJECT_NAME}\n        ${GLOG_LIBRARIES}\n        ${EIGEN3_LIBS}\n        ${PYTHON_LIBRARIES})\n\nadd_executable(Demo demo/Test.cpp)\ntarget_link_libraries(Demo ${PROJECT_NAME})"
  },
  {
    "path": "DataSets.py",
    "content": "import numpy as np\nimport scipy.io as sio\n\nload_fn = './datasets/NAV.mat'\nload_Data = sio.loadmat(load_fn)\ndata = load_Data['NAV']\n\nmea = data[:,8:17]\neuler = data[:,29:32]\n\nout = np.hstack((mea, euler))\n\nnp.savetxt(\"data.bin\", out, fmt='%f')\n\nprint out.shape\n\nprint data"
  },
  {
    "path": "LICENSE",
    "content": "GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. [http://fsf.org/]\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    {one line to give the program's name and a brief idea of what it does.}\n    Copyright (C) {year}  {fullname}\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see [http://www.gnu.org/licenses/].\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    IMU_Attitude_Estiamtor  Copyright (C) 2018  gaochq\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n[http://www.gnu.org/licenses/].\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n[http://www.gnu.org/philosophy/why-not-lgpl.html]."
  },
  {
    "path": "README.md",
    "content": "# IMU_Attitude_Estimator\n\nThis project is aimed at estimating the attitude of Attitude Heading and Reference System(AHRS). And the project contains three popular attitude estimator algorithms.\n- Mahony's algorithm\n- Extend Kalman Filter(EKF)\n- Error State Kalman Filter(ESKF)\n\n```DataSets.py``` for converting estimator data.    \n```Allan_Analysis``` for Allan Variance analysis.\n\n### Refrence\n[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)  \n[2] [Pixhawk state estimation](https://pixhawk.org/_media/firmware/apps/attitude_estimator_ekf/ekf_excerptmasterthesis.pdf)  \n[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)  \n[4] [Trawny N, Roumeliotis S I. Indirect Kalman Filter for 3D Attitude Estimation[J]. 2005.](http://pdfs.semanticscholar.org/2c8e/95bc331024105cbde6f6918cda8493f263c8.pdf)\n\n### Dependencies\n- Eigen3.2.0\n- glog\n```\nsudo apt-get install libgoogle-glog-dev\n```\n- [matplotlib-cpp](https://github.com/lava/matplotlib-cpp)\n\n### Simple Test\nSimple comparision among three methods. And the params of Mahony filter can be further tuned.\n<img src=\"Image/All_roll.png\" width=\"50%\" height=\"50%\"><img src=\"Image/EKF-ESKF-Roll.png\" width=\"50%\" height=\"50%\">\n<img src=\"Image/EKF-ESKF-Pitch.png\" width=\"50%\" height=\"50%\"><img src=\"Image/EKF-ESKF.png\" width=\"50%\" height=\"50%\">"
  },
  {
    "path": "cmake_modules/FindEigen3.cmake",
    "content": "# - Try to find Eigen3 lib\n#\n# This module supports requiring a minimum version, e.g. you can do\n#   find_package(Eigen3 3.1.2)\n# to require version 3.1.2 or newer of Eigen3.\n#\n# Once done this will define\n#\n#  EIGEN3_FOUND - system has eigen lib with correct version\n#  EIGEN3_INCLUDE_DIR - the eigen include directory\n#  EIGEN3_VERSION - eigen version\n\n# Copyright (c) 2006, 2007 Montel Laurent, <montel@kde.org>\n# Copyright (c) 2008, 2009 Gael Guennebaud, <g.gael@free.fr>\n# Copyright (c) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>\n# Redistribution and use is allowed according to the terms of the 2-clause BSD license.\n\nif(NOT Eigen3_FIND_VERSION)\n    if(NOT Eigen3_FIND_VERSION_MAJOR)\n        set(Eigen3_FIND_VERSION_MAJOR 2)\n    endif(NOT Eigen3_FIND_VERSION_MAJOR)\n    if(NOT Eigen3_FIND_VERSION_MINOR)\n        set(Eigen3_FIND_VERSION_MINOR 91)\n    endif(NOT Eigen3_FIND_VERSION_MINOR)\n    if(NOT Eigen3_FIND_VERSION_PATCH)\n        set(Eigen3_FIND_VERSION_PATCH 0)\n    endif(NOT Eigen3_FIND_VERSION_PATCH)\n\n    set(Eigen3_FIND_VERSION \"${Eigen3_FIND_VERSION_MAJOR}.${Eigen3_FIND_VERSION_MINOR}.${Eigen3_FIND_VERSION_PATCH}\")\nendif(NOT Eigen3_FIND_VERSION)\n\nmacro(_eigen3_check_version)\n    file(READ \"${EIGEN3_INCLUDE_DIR}/Eigen/src/Core/util/Macros.h\" _eigen3_version_header)\n\n    string(REGEX MATCH \"define[ \\t]+EIGEN_WORLD_VERSION[ \\t]+([0-9]+)\" _eigen3_world_version_match \"${_eigen3_version_header}\")\n    set(EIGEN3_WORLD_VERSION \"${CMAKE_MATCH_1}\")\n    string(REGEX MATCH \"define[ \\t]+EIGEN_MAJOR_VERSION[ \\t]+([0-9]+)\" _eigen3_major_version_match \"${_eigen3_version_header}\")\n    set(EIGEN3_MAJOR_VERSION \"${CMAKE_MATCH_1}\")\n    string(REGEX MATCH \"define[ \\t]+EIGEN_MINOR_VERSION[ \\t]+([0-9]+)\" _eigen3_minor_version_match \"${_eigen3_version_header}\")\n    set(EIGEN3_MINOR_VERSION \"${CMAKE_MATCH_1}\")\n\n    set(EIGEN3_VERSION ${EIGEN3_WORLD_VERSION}.${EIGEN3_MAJOR_VERSION}.${EIGEN3_MINOR_VERSION})\n    if(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n        set(EIGEN3_VERSION_OK FALSE)\n    else(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n        set(EIGEN3_VERSION_OK TRUE)\n    endif(${EIGEN3_VERSION} VERSION_LESS ${Eigen3_FIND_VERSION})\n\n    if(NOT EIGEN3_VERSION_OK)\n\n        message(STATUS \"Eigen3 version ${EIGEN3_VERSION} found in ${EIGEN3_INCLUDE_DIR}, \"\n                \"but at least version ${Eigen3_FIND_VERSION} is required\")\n    endif(NOT EIGEN3_VERSION_OK)\nendmacro(_eigen3_check_version)\n\nif (EIGEN3_INCLUDE_DIR)\n\n    # in cache already\n    _eigen3_check_version()\n    set(EIGEN3_FOUND ${EIGEN3_VERSION_OK})\n\nelse (EIGEN3_INCLUDE_DIR)\n\n    # specific additional paths for some OS\n    if (WIN32)\n        set(EIGEN_ADDITIONAL_SEARCH_PATHS ${EIGEN_ADDITIONAL_SEARCH_PATHS} \"C:/Program Files/Eigen/include\" \"C:/Program Files (x86)/Eigen/include\")\n    endif(WIN32)\n\n    find_path(EIGEN3_INCLUDE_DIR NAMES signature_of_eigen3_matrix_library\n            PATHS\n            ${CMAKE_INSTALL_PREFIX}/include\n            ${EIGEN_ADDITIONAL_SEARCH_PATHS}\n            ${KDE4_INCLUDE_DIR}\n            PATH_SUFFIXES eigen3 eigen\n            )\n\n    if(EIGEN3_INCLUDE_DIR)\n        _eigen3_check_version()\n    endif(EIGEN3_INCLUDE_DIR)\n\n    include(FindPackageHandleStandardArgs)\n    find_package_handle_standard_args(Eigen3 DEFAULT_MSG EIGEN3_INCLUDE_DIR EIGEN3_VERSION_OK)\n\n    mark_as_advanced(EIGEN3_INCLUDE_DIR)\n\nendif(EIGEN3_INCLUDE_DIR)\n"
  },
  {
    "path": "cmake_modules/FindGlog.cmake",
    "content": "# Ceres Solver - A fast non-linear least squares minimizer\n# Copyright 2015 Google Inc. All rights reserved.\n# http://ceres-solver.org/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n#   this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n#   this list of conditions and the following disclaimer in the documentation\n#   and/or other materials provided with the distribution.\n# * Neither the name of Google Inc. nor the names of its contributors may be\n#   used to endorse or promote products derived from this software without\n#   specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n# Author: alexs.mac@gmail.com (Alex Stewart)\n#\n\n# FindGlog.cmake - Find Google glog logging library.\n#\n# This module defines the following variables:\n#\n# GLOG_FOUND: TRUE iff glog is found.\n# GLOG_INCLUDE_DIRS: Include directories for glog.\n# GLOG_LIBRARIES: Libraries required to link glog.\n#\n# The following variables control the behaviour of this module:\n#\n# GLOG_INCLUDE_DIR_HINTS: List of additional directories in which to\n#                         search for glog includes, e.g: /timbuktu/include.\n# GLOG_LIBRARY_DIR_HINTS: List of additional directories in which to\n#                         search for glog libraries, e.g: /timbuktu/lib.\n#\n# The following variables are also defined by this module, but in line with\n# CMake recommended FindPackage() module style should NOT be referenced directly\n# by callers (use the plural variables detailed above instead).  These variables\n# do however affect the behaviour of the module via FIND_[PATH/LIBRARY]() which\n# are NOT re-called (i.e. search for library is not repeated) if these variables\n# are set with valid values _in the CMake cache_. This means that if these\n# variables are set directly in the cache, either by the user in the CMake GUI,\n# or by the user passing -DVAR=VALUE directives to CMake when called (which\n# explicitly defines a cache variable), then they will be used verbatim,\n# bypassing the HINTS variables and other hard-coded search locations.\n#\n# GLOG_INCLUDE_DIR: Include directory for glog, not including the\n#                   include directory of any dependencies.\n# GLOG_LIBRARY: glog library, not including the libraries of any\n#               dependencies.\n\n# Reset CALLERS_CMAKE_FIND_LIBRARY_PREFIXES to its value when\n# FindGlog was invoked.\nmacro(GLOG_RESET_FIND_LIBRARY_PREFIX)\n    if (MSVC)\n        set(CMAKE_FIND_LIBRARY_PREFIXES \"${CALLERS_CMAKE_FIND_LIBRARY_PREFIXES}\")\n    endif (MSVC)\nendmacro(GLOG_RESET_FIND_LIBRARY_PREFIX)\n\n# Called if we failed to find glog or any of it's required dependencies,\n# unsets all public (designed to be used externally) variables and reports\n# error message at priority depending upon [REQUIRED/QUIET/<NONE>] argument.\nmacro(GLOG_REPORT_NOT_FOUND REASON_MSG)\n    unset(GLOG_FOUND)\n    unset(GLOG_INCLUDE_DIRS)\n    unset(GLOG_LIBRARIES)\n    # Make results of search visible in the CMake GUI if glog has not\n    # been found so that user does not have to toggle to advanced view.\n    mark_as_advanced(CLEAR GLOG_INCLUDE_DIR\n            GLOG_LIBRARY)\n\n    glog_reset_find_library_prefix()\n\n    # Note <package>_FIND_[REQUIRED/QUIETLY] variables defined by FindPackage()\n    # use the camelcase library name, not uppercase.\n    if (Glog_FIND_QUIETLY)\n        message(STATUS \"Failed to find glog - \" ${REASON_MSG} ${ARGN})\n    elseif (Glog_FIND_REQUIRED)\n        message(FATAL_ERROR \"Failed to find glog - \" ${REASON_MSG} ${ARGN})\n    else()\n        # Neither QUIETLY nor REQUIRED, use no priority which emits a message\n        # but continues configuration and allows generation.\n        message(\"-- Failed to find glog - \" ${REASON_MSG} ${ARGN})\n    endif ()\nendmacro(GLOG_REPORT_NOT_FOUND)\n\n# Handle possible presence of lib prefix for libraries on MSVC, see\n# also GLOG_RESET_FIND_LIBRARY_PREFIX().\nif (MSVC)\n    # Preserve the caller's original values for CMAKE_FIND_LIBRARY_PREFIXES\n    # s/t we can set it back before returning.\n    set(CALLERS_CMAKE_FIND_LIBRARY_PREFIXES \"${CMAKE_FIND_LIBRARY_PREFIXES}\")\n    # The empty string in this list is important, it represents the case when\n    # the libraries have no prefix (shared libraries / DLLs).\n    set(CMAKE_FIND_LIBRARY_PREFIXES \"lib\" \"\" \"${CMAKE_FIND_LIBRARY_PREFIXES}\")\nendif (MSVC)\n\n# Search user-installed locations first, so that we prefer user installs\n# to system installs where both exist.\nlist(APPEND GLOG_CHECK_INCLUDE_DIRS\n        /usr/local/include\n        /usr/local/homebrew/include # Mac OS X\n        /opt/local/var/macports/software # Mac OS X.\n        /opt/local/include\n        /usr/include)\n# Windows (for C:/Program Files prefix).\nlist(APPEND GLOG_CHECK_PATH_SUFFIXES\n        glog/include\n        glog/Include\n        Glog/include\n        Glog/Include)\n\nlist(APPEND GLOG_CHECK_LIBRARY_DIRS\n        /usr/local/lib\n        /usr/local/homebrew/lib # Mac OS X.\n        /opt/local/lib\n        /usr/lib)\n# Windows (for C:/Program Files prefix).\nlist(APPEND GLOG_CHECK_LIBRARY_SUFFIXES\n        glog/lib\n        glog/Lib\n        Glog/lib\n        Glog/Lib)\n\n# Search supplied hint directories first if supplied.\nfind_path(GLOG_INCLUDE_DIR\n        NAMES glog/logging.h\n        PATHS ${GLOG_INCLUDE_DIR_HINTS}\n        ${GLOG_CHECK_INCLUDE_DIRS}\n        PATH_SUFFIXES ${GLOG_CHECK_PATH_SUFFIXES})\nif (NOT GLOG_INCLUDE_DIR OR\n        NOT EXISTS ${GLOG_INCLUDE_DIR})\n    glog_report_not_found(\n            \"Could not find glog include directory, set GLOG_INCLUDE_DIR \"\n            \"to directory containing glog/logging.h\")\nendif (NOT GLOG_INCLUDE_DIR OR\n        NOT EXISTS ${GLOG_INCLUDE_DIR})\n\nfind_library(GLOG_LIBRARY NAMES glog\n        PATHS ${GLOG_LIBRARY_DIR_HINTS}\n        ${GLOG_CHECK_LIBRARY_DIRS}\n        PATH_SUFFIXES ${GLOG_CHECK_LIBRARY_SUFFIXES})\nif (NOT GLOG_LIBRARY OR\n        NOT EXISTS ${GLOG_LIBRARY})\n    glog_report_not_found(\n            \"Could not find glog library, set GLOG_LIBRARY \"\n            \"to full path to libglog.\")\nendif (NOT GLOG_LIBRARY OR\n        NOT EXISTS ${GLOG_LIBRARY})\n\n# Mark internally as found, then verify. GLOG_REPORT_NOT_FOUND() unsets\n# if called.\nset(GLOG_FOUND TRUE)\n\n# Glog does not seem to provide any record of the version in its\n# source tree, thus cannot extract version.\n\n# Catch case when caller has set GLOG_INCLUDE_DIR in the cache / GUI and\n# thus FIND_[PATH/LIBRARY] are not called, but specified locations are\n# invalid, otherwise we would report the library as found.\nif (GLOG_INCLUDE_DIR AND\n        NOT EXISTS ${GLOG_INCLUDE_DIR}/glog/logging.h)\n    glog_report_not_found(\n            \"Caller defined GLOG_INCLUDE_DIR:\"\n            \" ${GLOG_INCLUDE_DIR} does not contain glog/logging.h header.\")\nendif (GLOG_INCLUDE_DIR AND\n        NOT EXISTS ${GLOG_INCLUDE_DIR}/glog/logging.h)\n# TODO: This regex for glog library is pretty primitive, we use lowercase\n#       for comparison to handle Windows using CamelCase library names, could\n#       this check be better?\nstring(TOLOWER \"${GLOG_LIBRARY}\" LOWERCASE_GLOG_LIBRARY)\nif (GLOG_LIBRARY AND\n        NOT \"${LOWERCASE_GLOG_LIBRARY}\" MATCHES \".*glog[^/]*\")\n    glog_report_not_found(\n            \"Caller defined GLOG_LIBRARY: \"\n            \"${GLOG_LIBRARY} does not match glog.\")\nendif (GLOG_LIBRARY AND\n        NOT \"${LOWERCASE_GLOG_LIBRARY}\" MATCHES \".*glog[^/]*\")\n\n# Set standard CMake FindPackage variables if found.\nif (GLOG_FOUND)\n    set(GLOG_INCLUDE_DIRS ${GLOG_INCLUDE_DIR})\n    set(GLOG_LIBRARIES ${GLOG_LIBRARY})\nendif (GLOG_FOUND)\n\nglog_reset_find_library_prefix()\n\n# Handle REQUIRED / QUIET optional arguments.\ninclude(FindPackageHandleStandardArgs)\nfind_package_handle_standard_args(Glog DEFAULT_MSG\n        GLOG_INCLUDE_DIRS GLOG_LIBRARIES)\n\n# Only mark internal variables as advanced if we found glog, otherwise\n# leave them visible in the standard GUI for the user to set manually.\nif (GLOG_FOUND)\n    mark_as_advanced(FORCE GLOG_INCLUDE_DIR\n            GLOG_LIBRARY)\nendif (GLOG_FOUND)"
  },
  {
    "path": "demo/Test.cpp",
    "content": "#include <iostream>\r\n#include <vector>\r\n#include \"time.h\"\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n\r\n#include \"Convert.h\"\r\n#include \"EKF_Attitude.h\"\r\n#include \"Mahony_Attitude.h\"\r\n#include \"ESKF_Attitude.h\"\r\n\r\n#include \"matplotlibcpp.h\"\r\n\r\n\r\nusing namespace std;\r\nusing namespace IMU;\r\n\r\nnamespace plt = matplotlibcpp;\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\tEigen::MatrixXd data, measurements, groundtruth;\r\n    data =IMU::readFromfile(\"./datasets/NAV2_data.bin\");\r\n    if(data.isZero())\r\n        return 0;\r\n\r\n    const int Rows = data.rows() - 1;\r\n    measurements = data.block(0, 0, Rows, 9);\r\n    groundtruth = data.block(0, 9, Rows, 3)*180/M_PI;\r\n\r\n\tIMU::EKF_Attitude EKF_AHRS(true, 0.02);\r\n    IMU::Mahony_Attitude Mahony(Eigen::Vector2d(1.0, 0), 0.02);\r\n\r\n    Eigen::Matrix<double, 12, 1> ESKF_InitVec;\r\n    ESKF_InitVec << 1e-5*Eigen::Vector3d::Ones(), 1e-9*Eigen::Vector3d::Ones(),\r\n                    1e-3*Eigen::Vector3d::Ones(), 1e-4*Eigen::Vector3d::Ones();\r\n    IMU::ESKF_Attitude ESKF_AHRS(ESKF_InitVec, 0.02);\r\n\r\n\tunsigned int i = 0;\r\n\tEigen::MatrixXd Euler(measurements.rows(), 3), Euler1(measurements.rows(), 3), Euler2(measurements.rows(), 3);\r\n\r\n    std::vector<double> Index, Roll, Pitch, Yaw, Roll_gt, Pitch_gt, Yaw_gt;\r\n    std::vector<double> Roll1, Pitch1, Yaw1, Roll_gt1, Pitch_gt1, Yaw_gt1;\r\n    std::vector<double> Roll2, Pitch2, Yaw2, Roll_gt2, Pitch_gt2, Yaw_gt2;\r\n\tTicToc tc;\r\n\tdo\r\n\t{\r\n\t\tEigen::MatrixXd measure;\r\n\t\tEigen::Quaterniond quaternion;\r\n\t\t\r\n\t\tVector_3 Euler_single;\r\n\r\n\t\tquaternion = EKF_AHRS.Run(measurements.row(i).transpose());\r\n        Euler.row(i) = Quaternion_to_Euler(quaternion).transpose();\r\n\r\n\r\n        quaternion = Mahony.Run(measurements.row(i).transpose());\r\n        Euler1.row(i) = Quaternion_to_Euler(quaternion).transpose();\r\n\r\n        quaternion = ESKF_AHRS.Run(measurements.row(i).transpose());\r\n        Euler2.row(i) = Quaternion_to_Euler(quaternion).transpose();\r\n\r\n\r\n        Index.push_back(i*1.0);\r\n        Roll.push_back(Euler.row(i)[0]);\r\n        Pitch.push_back(Euler.row(i)[1]);\r\n        Yaw.push_back(Euler.row(i)[2]);\r\n\r\n\r\n        Roll1.push_back(Euler1.row(i)[0]);\r\n        Pitch1.push_back(Euler1.row(i)[1]);\r\n        Yaw1.push_back(Euler1.row(i)[2]);\r\n\r\n        Roll2.push_back(Euler2.row(i)[0]);\r\n        Pitch2.push_back(Euler2.row(i)[1]);\r\n        Yaw2.push_back(Euler2.row(i)[2]);\r\n\r\n        Roll_gt.push_back(groundtruth.row(i)[0]);\r\n        Pitch_gt.push_back(groundtruth.row(i)[1]);\r\n        Yaw_gt.push_back(groundtruth.row(i)[2]);\r\n\r\n\r\n\t\ti++;\r\n\t} while (i<measurements.rows());\r\n\r\n\tcout << tc.toc() << \"ms\" << endl;\r\n\twriteTofile(Euler, \"Euler.bin\");\r\n\r\n    plt::named_plot(\"EKF\", Index, Pitch, \"b\");\r\n    plt::named_plot(\"ESKF\", Index, Pitch2, \"g\");\r\n    plt::named_plot(\"Groundtruth\", Index, Pitch_gt, \"r\");\r\n    //plt::named_plot(\"aa\", Index, Yaw, \"b\");\r\n\r\n\tplt::xlim(0, 1000*20);\r\n\r\n    plt::title(\"Yaw-Comparision\");\r\n    plt::legend();\r\n    plt::show();\r\n\r\n\treturn 0;\r\n}\r\n\r\n"
  },
  {
    "path": "include/Convert.h",
    "content": "#ifndef CONVERT_H_\r\n#define CONVERT_H_\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <fstream>\r\n#include <string>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n\r\n#include \"TypeDefs.h\"\r\n#include \"tic_toc.h\"\r\n\r\nusing namespace std;\r\nnamespace IMU\r\n{\r\nvoid Vect_to_SkewMat(Vector_3 Vector, Matrix_3 &Matrix);\r\nvoid Angular_to_Mat(Vector_3 Vector, Eigen::Matrix<double, 4, 4> &Matrix);\r\n//void Rotation_to_Qaut(Matrix_3 rotation, Eigen::Quaterniond &quat);\r\nVector_4 Quaternion_to_Vect(Eigen::Quaterniond q);\r\nEigen::Quaterniond QuatMult(Eigen::Quaterniond q1, Eigen::Quaterniond q2);\r\nMatrix_3 Quat_to_Matrix(Eigen::Quaterniond q);\r\n\r\n// Eigen IO\r\nEigen::MatrixXd readFromfile(const string file);\r\nbool writeTofile(Eigen::MatrixXd matrix, const string file);\r\n\r\n// Eluer(Rotate vector) to rotation matrix\r\nMatrix_3 Euler_to_RoatMat(Vector_3 Euler);\r\n\r\n// Eluer(Rotate vector) to rotation matrix\r\nEigen::Quaterniond Euler_to_Quaternion(Vector_3 Euler);\r\n\r\n// Quaternion to eulers\r\nVector_3 Quaternion_to_Euler(Eigen::Quaterniond q);\r\n\r\n// Rotation matrix to eulers, the rotation order is X-Y-Z(roll,pitch and yaw)\r\nVector_3 Rotation_to_Euler(Matrix_3 Rotation);\r\n// Rotation matrix to quaternion http://www.cs.ucr.edu/~vbz/resources/quatut.pdf\r\nEigen::Quaterniond Rotation_to_Quater(Matrix_3 Rotation);\r\n\r\n// Indirect Kalman Filter for 3D Attitude Estimation (Roumeliotis)\r\nEigen::Quaterniond BuildUpdateQuat(Eigen::Vector3d DeltaTheta);\r\n\r\n\r\n} //namesapce IMU\r\n\r\n#endif"
  },
  {
    "path": "include/EKF_Attitude.h",
    "content": "#ifndef EKF_ATTITUDE_H_\r\n#define EKF_ATTITUDE_H_\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <mutex>\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n#include \"TypeDefs.h\"\r\n\r\n\r\n#ifdef _WIN32\r\n\t#include \"windows.h\"\r\n#else \r\n\t#include <unistd.h>  \r\n#endif\r\n\r\nusing namespace std;\r\nnamespace IMU\r\n{\r\n\r\nclass EKF_Attitude\r\n{\r\npublic:\r\n    EKF_Attitude(bool approx_prediction, double dt);\r\n\r\n    // Modify the params of the filter\r\n    void Param_Change(Vector_12 Pro_Nosiecovr, Vector_9 Mea_Nosiecovr);\r\n\r\n    // Calculate the transition matrix A\r\n    // refer to formula 4.19a\r\n    void Cal_TransMatrix();\r\n\r\n    /* The priori prediction:\r\n    *  Xk+1 = F(Xk,0)\r\n    *  Pk+1 = A*Pk*A' + Qk\r\n    */\r\n    void Prior_Predict();\r\n\r\n    // The posteriori correction\r\n    void Post_Correct();\r\n\r\n    // Calculate the Euler angular\r\n    void Cal_Quaternion();\r\n\r\n    // read the sensors\r\n    void Read_SensorData(Vector_9 measurement);\r\n\r\n    Eigen::Quaterniond Run(Vector_9 measurement);\r\n    void Release();\r\n    void RequestStop();\r\n    void RequestStart();\r\n    bool Stop();\r\n    bool isStopped();\r\n\r\n\r\n\r\nprivate:\r\n    Vector_9 cur_measurement;\r\n    bool using_2ndOrder;\r\n    Eigen::Matrix<double, 12, 12> Q_noise;\r\n    Eigen::Matrix<double, 9, 9> R_noise;\r\n    double deltaT;\r\n    Eigen::Matrix<double, 12, 12> Alin;\r\n\r\n    // Xk+1, the state vector of posteriori correction\r\n    vector< Vector_12 > state_X_pro;\r\n\r\n    // Xk, the state vector of priori prediction\r\n    Vector_12 state_X_par;\r\n\r\n    // Pk+1\r\n    vector< Eigen::Matrix<double, 12, 12> > CovrMatrix_P_pro;\r\n\r\n    // Pk\r\n    Eigen::Matrix<double, 12, 12> CovrMatrix_P_par;\r\n    vector< Eigen::Quaterniond > quaternion;\r\n\r\n    bool mbStopped;\r\n    bool mbStopRequested;\r\n    std::mutex mMutexStop;\r\n};\r\n\r\n} //namespace IMU\r\n\r\n#endif"
  },
  {
    "path": "include/ESKF_Attitude.h",
    "content": "#ifndef ESKF_ATTITUDE_H\r\n#define ESKF_ATTITUDE_H\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <mutex>\r\n#include <map>\r\n\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n\r\n#include \"TypeDefs.h\"\r\n\r\n#ifdef _WIN32\r\n#include \"windows.h\"\r\n#else\r\n#include \"unistd.h\"\r\n#endif\r\n\r\nusing namespace std;\r\n\r\nnamespace IMU\r\n{\r\nclass ESKF_Attitude\r\n{\r\n\r\npublic:\r\n    ESKF_Attitude(Vector_12 Covar_Mat, double dt);\r\n    // Initialize the true state of the estimator\r\n    // including the nomial state and the error state,\r\n    // and the covariances matrices\r\n    void Init_Estimator();\r\n\r\n    // change the parametres of the estimator\r\n    void Param_Change(Vector_12 Covar_Mat);\r\n\r\n    // Predict the nomial and error state\r\n    void NominaState_Predict();\r\n    void ErrorState_Predict();\r\n\r\n    // Update the filter parametres\r\n    void Update_Filter();\r\n\r\n    // Uptate the nominal state\r\n    void Update_NomianState();\r\n\r\n    // Reset the error state\r\n    void Reset_ErrorState();\r\n\r\n    // read the sensors data and normalize the accelerometer and magnetometer\r\n    void Read_SensorData(Vector_9 measurement);\r\n\r\n    Eigen::Quaterniond Run(Vector_9 measurement);\r\n    void Release();\r\n    void RequestStop();\r\n    void RequestStart();\r\n    bool Stop();\r\n    bool isStopped();\r\n\r\nprivate:\r\n    // the Gaussian noise for the covariances matrices Q and R\r\n    Vector_3 DetAng_noise;\r\n    Vector_3 DetAngVel_noise;\r\n    Vector_3 Acc_noise;\r\n    Vector_3 Mag_noise;\r\n    Eigen::Matrix<double, 6, 6> CovarMat_Q;\r\n    Eigen::Matrix<double, 6, 6> CovarMat_R;\r\n\r\n\r\n    struct IMU_State\r\n    {\r\n    public:\r\n\r\n        //! normal state\r\n        Eigen::Quaterniond Nominal_quat;        //! quaterion state\r\n        Vector_3 Nominal_AngVel;                //! Gyro bias state\r\n\r\n        //! Error state\r\n        Vector_3 Error_theta;\r\n        Vector_3 Error_AngVel;\r\n        Eigen::Matrix<double, 6, 6> Error_Convar;\r\n\r\n        // calculate the observe matrix and the correction residual\r\n        Eigen::Matrix<double, 6, 6> Cal_ObserveMat(Vector_9 measurenment, Vector_6 &residual);\r\n    };\r\n\r\n    vector< IMU_State > State_Vector;\r\n    vector< Eigen::Quaterniond > quaternion;\r\n    // sample time\r\n    double deltaT;\r\n\r\n    // Current and last time measurement (gyro;acc;mag)\r\n    Vector_9 Cur_Measurement;\r\n    Vector_9 Last_Measurement;\r\n\r\n    bool mbStopped;\r\n    bool mbStopRequested;\r\n    std::mutex mMutexStop;\r\n};\r\n\r\n}\r\n\r\n\r\n#endif"
  },
  {
    "path": "include/Mahony_Attitude.h",
    "content": "#ifndef MAHONY_AHRS_H_\r\n#define MAHONY_AHRS_H_\r\n\r\n#include <iostream>\r\n#include <vector>\r\n#include <mutex>\r\n#include <Eigen/Core>\r\n#include <Eigen/Geometry>\r\n#include \"TypeDefs.h\"\r\n\r\n#ifdef _WIN32\r\n#include \"windows.h\"\r\n#else \r\n#include <unistd.h>  \r\n#endif\r\n\r\nusing namespace std;\r\nnamespace IMU\r\n{\r\n\r\nclass Mahony_Attitude\r\n{\r\npublic:\r\n\tMahony_Attitude(Vector_2 PI, double dt);\r\n\tvoid Params_Change(Vector_2 PI, double dt);\r\n\tvoid Mahony_Estimate();\r\n\tvoid Read_SensorData(Vector_9 measurement);\r\n\r\n\tEigen::Quaterniond Run(Vector_9 measurement);\r\n\tvoid Release();\r\n\tvoid RequestStop();\r\n\tvoid RequestStart();\r\n\tbool Stop();\r\n\tbool isStopped();\r\n\r\nprivate:\r\n\tVector_9 cur_measurement;\r\n\r\n\tdouble Kp, Ki;\r\n\tdouble deltaT;\r\n\tVector_3 Integ_angular;\r\n\r\n\tvector< Eigen::Quaterniond > quaternion;\r\n\r\n\tbool mbStopped;\r\n\tbool mbStopRequested;\r\n\tstd::mutex mMutexStop;\r\n};\r\n\r\n} //namesapce IMU\r\n\r\n\r\n#endif"
  },
  {
    "path": "include/TypeDefs.h",
    "content": "#ifndef TYPEDEFS_H_\r\n#define TYPEDEFS_H_\r\n\r\n\r\n#include <iostream>\r\n#include <Eigen/Core>\r\n\r\n//#pragma once\r\n\r\nnamespace IMU\r\n{\r\n\r\ntypedef Eigen::Matrix<double, 2, 1> Vector_2;\r\ntypedef Eigen::Matrix<double, 3, 1> Vector_3;\r\ntypedef Eigen::Matrix<double, 4, 1> Vector_4;\r\ntypedef Eigen::Matrix<double, 6, 1> Vector_6;\r\ntypedef Eigen::Matrix<double, 7, 1> Vector_7;\r\ntypedef Eigen::Matrix<double, 9, 1> Vector_9;\r\ntypedef Eigen::Matrix<double, 12, 1> Vector_12;\r\n\r\ntypedef Eigen::Matrix3d Matrix_3;\r\nconst Matrix_3 Zeros_Matrix3 = Matrix_3::Zero(3, 3);\r\nconst Matrix_3 Ones_Matrix3 = Matrix_3::Ones(3, 3);\r\nconst Matrix_3 Identity_Matrix3 = Matrix_3::Identity(3, 3);\r\n\r\n} // namespace IMU\r\n\r\n#endif "
  },
  {
    "path": "include/matplotlibcpp.h",
    "content": "#pragma once\n\n#include <vector>\n#include <map>\n#include <numeric>\n#include <algorithm>\n#include <stdexcept>\n#include <iostream>\n#include <stdint.h> // <cstdint> requires c++11 support\n\n#if __cplusplus > 199711L || _MSC_VER > 1800\n#  include <functional>\n#endif\n\n#include <Python.h>\n\n#ifndef WITHOUT_NUMPY\n#  define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION\n#  include <numpy/arrayobject.h>\n#endif // WITHOUT_NUMPY\n\n#if PY_MAJOR_VERSION >= 3\n#  define PyString_FromString PyUnicode_FromString\n#endif\n\n\nnamespace matplotlibcpp {\n    namespace detail {\n\n        static std::string s_backend;\n\n        struct _interpreter {\n            PyObject *s_python_function_show;\n            PyObject *s_python_function_close;\n            PyObject *s_python_function_draw;\n            PyObject *s_python_function_pause;\n            PyObject *s_python_function_save;\n            PyObject *s_python_function_figure;\n            PyObject *s_python_function_plot;\n            PyObject *s_python_function_semilogx;\n            PyObject *s_python_function_semilogy;\n            PyObject *s_python_function_loglog;\n            PyObject *s_python_function_fill_between;\n            PyObject *s_python_function_hist;\n            PyObject *s_python_function_subplot;\n            PyObject *s_python_function_legend;\n            PyObject *s_python_function_xlim;\n            PyObject *s_python_function_ion;\n            PyObject *s_python_function_ylim;\n            PyObject *s_python_function_title;\n            PyObject *s_python_function_axis;\n            PyObject *s_python_function_xlabel;\n            PyObject *s_python_function_ylabel;\n            PyObject *s_python_function_grid;\n            PyObject *s_python_function_clf;\n            PyObject *s_python_function_errorbar;\n            PyObject *s_python_function_annotate;\n            PyObject *s_python_function_tight_layout;\n            PyObject *s_python_empty_tuple;\n            PyObject *s_python_function_stem;\n            PyObject *s_python_function_xkcd;\n\n            /* For now, _interpreter is implemented as a singleton since its currently not possible to have\n               multiple independent embedded python interpreters without patching the python source code\n               or starting a separate process for each.\n                http://bytes.com/topic/python/answers/793370-multiple-independent-python-interpreters-c-c-program\n               */\n\n            static _interpreter& get() {\n                static _interpreter ctx;\n                return ctx;\n            }\n\n        private:\n\n#ifndef WITHOUT_NUMPY\n#  if PY_MAJOR_VERSION >= 3\n\n            void *import_numpy() {\n        import_array(); // initialize C-API\n        return NULL;\n    }\n\n#  else\n\n            void import_numpy() {\n                import_array(); // initialize C-API\n            }\n\n#  endif\n#endif\n\n            _interpreter() {\n\n                // optional but recommended\n#if PY_MAJOR_VERSION >= 3\n                wchar_t name[] = L\"plotting\";\n#else\n                char name[] = \"plotting\";\n#endif\n                Py_SetProgramName(name);\n                Py_Initialize();\n\n#ifndef WITHOUT_NUMPY\n                import_numpy(); // initialize numpy C-API\n#endif\n\n                PyObject* matplotlibname = PyString_FromString(\"matplotlib\");\n                PyObject* pyplotname = PyString_FromString(\"matplotlib.pyplot\");\n                PyObject* pylabname  = PyString_FromString(\"pylab\");\n                if (!pyplotname || !pylabname || !matplotlibname) {\n                    throw std::runtime_error(\"couldnt create string\");\n                }\n\n                PyObject* matplotlib = PyImport_Import(matplotlibname);\n                Py_DECREF(matplotlibname);\n                if (!matplotlib) { throw std::runtime_error(\"Error loading module matplotlib!\"); }\n\n                // matplotlib.use() must be called *before* pylab, matplotlib.pyplot,\n                // or matplotlib.backends is imported for the first time\n                if (!s_backend.empty()) {\n                    PyObject_CallMethod(matplotlib, const_cast<char*>(\"use\"), const_cast<char*>(\"s\"), s_backend.c_str());\n                }\n\n                PyObject* pymod = PyImport_Import(pyplotname);\n                Py_DECREF(pyplotname);\n                if (!pymod) { throw std::runtime_error(\"Error loading module matplotlib.pyplot!\"); }\n\n\n                PyObject* pylabmod = PyImport_Import(pylabname);\n                Py_DECREF(pylabname);\n                if (!pylabmod) { throw std::runtime_error(\"Error loading module pylab!\"); }\n\n                s_python_function_show = PyObject_GetAttrString(pymod, \"show\");\n                s_python_function_close = PyObject_GetAttrString(pymod, \"close\");\n                s_python_function_draw = PyObject_GetAttrString(pymod, \"draw\");\n                s_python_function_pause = PyObject_GetAttrString(pymod, \"pause\");\n                s_python_function_figure = PyObject_GetAttrString(pymod, \"figure\");\n                s_python_function_plot = PyObject_GetAttrString(pymod, \"plot\");\n                s_python_function_semilogx = PyObject_GetAttrString(pymod, \"semilogx\");\n                s_python_function_semilogy = PyObject_GetAttrString(pymod, \"semilogy\");\n                s_python_function_loglog = PyObject_GetAttrString(pymod, \"loglog\");\n                s_python_function_fill_between = PyObject_GetAttrString(pymod, \"fill_between\");\n                s_python_function_hist = PyObject_GetAttrString(pymod,\"hist\");\n                s_python_function_subplot = PyObject_GetAttrString(pymod, \"subplot\");\n                s_python_function_legend = PyObject_GetAttrString(pymod, \"legend\");\n                s_python_function_ylim = PyObject_GetAttrString(pymod, \"ylim\");\n                s_python_function_title = PyObject_GetAttrString(pymod, \"title\");\n                s_python_function_axis = PyObject_GetAttrString(pymod, \"axis\");\n                s_python_function_xlabel = PyObject_GetAttrString(pymod, \"xlabel\");\n                s_python_function_ylabel = PyObject_GetAttrString(pymod, \"ylabel\");\n                s_python_function_grid = PyObject_GetAttrString(pymod, \"grid\");\n                s_python_function_xlim = PyObject_GetAttrString(pymod, \"xlim\");\n                s_python_function_ion = PyObject_GetAttrString(pymod, \"ion\");\n                s_python_function_save = PyObject_GetAttrString(pylabmod, \"savefig\");\n                s_python_function_annotate = PyObject_GetAttrString(pymod,\"annotate\");\n                s_python_function_clf = PyObject_GetAttrString(pymod, \"clf\");\n                s_python_function_errorbar = PyObject_GetAttrString(pymod, \"errorbar\");\n                s_python_function_tight_layout = PyObject_GetAttrString(pymod, \"tight_layout\");\n                s_python_function_stem = PyObject_GetAttrString(pymod, \"stem\");\n                s_python_function_xkcd = PyObject_GetAttrString(pymod, \"xkcd\");\n\n                if(    !s_python_function_show\n                       || !s_python_function_close\n                       || !s_python_function_draw\n                       || !s_python_function_pause\n                       || !s_python_function_figure\n                       || !s_python_function_plot\n                       || !s_python_function_semilogx\n                       || !s_python_function_semilogy\n                       || !s_python_function_loglog\n                       || !s_python_function_fill_between\n                       || !s_python_function_subplot\n                       || !s_python_function_legend\n                       || !s_python_function_ylim\n                       || !s_python_function_title\n                       || !s_python_function_axis\n                       || !s_python_function_xlabel\n                       || !s_python_function_ylabel\n                       || !s_python_function_grid\n                       || !s_python_function_xlim\n                       || !s_python_function_ion\n                       || !s_python_function_save\n                       || !s_python_function_clf\n                       || !s_python_function_annotate\n                       || !s_python_function_errorbar\n                       || !s_python_function_errorbar\n                       || !s_python_function_tight_layout\n                       || !s_python_function_stem\n                       || !s_python_function_xkcd\n                        ) { throw std::runtime_error(\"Couldn't find required function!\"); }\n\n                if (   !PyFunction_Check(s_python_function_show)\n                       || !PyFunction_Check(s_python_function_close)\n                       || !PyFunction_Check(s_python_function_draw)\n                       || !PyFunction_Check(s_python_function_pause)\n                       || !PyFunction_Check(s_python_function_figure)\n                       || !PyFunction_Check(s_python_function_plot)\n                       || !PyFunction_Check(s_python_function_semilogx)\n                       || !PyFunction_Check(s_python_function_semilogy)\n                       || !PyFunction_Check(s_python_function_loglog)\n                       || !PyFunction_Check(s_python_function_fill_between)\n                       || !PyFunction_Check(s_python_function_subplot)\n                       || !PyFunction_Check(s_python_function_legend)\n                       || !PyFunction_Check(s_python_function_annotate)\n                       || !PyFunction_Check(s_python_function_ylim)\n                       || !PyFunction_Check(s_python_function_title)\n                       || !PyFunction_Check(s_python_function_axis)\n                       || !PyFunction_Check(s_python_function_xlabel)\n                       || !PyFunction_Check(s_python_function_ylabel)\n                       || !PyFunction_Check(s_python_function_grid)\n                       || !PyFunction_Check(s_python_function_xlim)\n                       || !PyFunction_Check(s_python_function_ion)\n                       || !PyFunction_Check(s_python_function_save)\n                       || !PyFunction_Check(s_python_function_clf)\n                       || !PyFunction_Check(s_python_function_tight_layout)\n                       || !PyFunction_Check(s_python_function_errorbar)\n                       || !PyFunction_Check(s_python_function_stem)\n                       || !PyFunction_Check(s_python_function_xkcd)\n                        ) { throw std::runtime_error(\"Python object is unexpectedly not a PyFunction.\"); }\n\n                s_python_empty_tuple = PyTuple_New(0);\n            }\n\n            ~_interpreter() {\n                Py_Finalize();\n            }\n        };\n\n    } // end namespace detail\n\n// must be called before the first regular call to matplotlib to have any effect\n    inline void backend(const std::string& name)\n    {\n        detail::s_backend = name;\n    }\n\n    inline bool annotate(std::string annotation, double x, double y)\n    {\n        PyObject * xy = PyTuple_New(2);\n        PyObject * str = PyString_FromString(annotation.c_str());\n\n        PyTuple_SetItem(xy,0,PyFloat_FromDouble(x));\n        PyTuple_SetItem(xy,1,PyFloat_FromDouble(y));\n\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"xy\", xy);\n\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, str);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_annotate, args, kwargs);\n\n        Py_DECREF(args);\n        Py_DECREF(kwargs);\n\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n#ifndef WITHOUT_NUMPY\n// Type selector for numpy array conversion\n    template <typename T> struct select_npy_type { const static NPY_TYPES type = NPY_NOTYPE; }; //Default\n    template <> struct select_npy_type<double> { const static NPY_TYPES type = NPY_DOUBLE; };\n    template <> struct select_npy_type<float> { const static NPY_TYPES type = NPY_FLOAT; };\n    template <> struct select_npy_type<bool> { const static NPY_TYPES type = NPY_BOOL; };\n    template <> struct select_npy_type<int8_t> { const static NPY_TYPES type = NPY_INT8; };\n    template <> struct select_npy_type<int16_t> { const static NPY_TYPES type = NPY_SHORT; };\n    template <> struct select_npy_type<int32_t> { const static NPY_TYPES type = NPY_INT; };\n    template <> struct select_npy_type<int64_t> { const static NPY_TYPES type = NPY_INT64; };\n    template <> struct select_npy_type<uint8_t> { const static NPY_TYPES type = NPY_UINT8; };\n    template <> struct select_npy_type<uint16_t> { const static NPY_TYPES type = NPY_USHORT; };\n    template <> struct select_npy_type<uint32_t> { const static NPY_TYPES type = NPY_ULONG; };\n    template <> struct select_npy_type<uint64_t> { const static NPY_TYPES type = NPY_UINT64; };\n\n    template<typename Numeric>\n    PyObject* get_array(const std::vector<Numeric>& v)\n    {\n        detail::_interpreter::get();    //interpreter needs to be initialized for the numpy commands to work\n        NPY_TYPES type = select_npy_type<Numeric>::type;\n        if (type == NPY_NOTYPE)\n        {\n            std::vector<double> vd(v.size());\n            npy_intp vsize = v.size();\n            std::copy(v.begin(),v.end(),vd.begin());\n            PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, NPY_DOUBLE, (void*)(vd.data()));\n            return varray;\n        }\n\n        npy_intp vsize = v.size();\n        PyObject* varray = PyArray_SimpleNewFromData(1, &vsize, type, (void*)(v.data()));\n        return varray;\n    }\n\n#else // fallback if we don't have numpy: copy every element of the given vector\n\n    template<typename Numeric>\nPyObject* get_array(const std::vector<Numeric>& v)\n{\n    PyObject* list = PyList_New(v.size());\n    for(size_t i = 0; i < v.size(); ++i) {\n        PyList_SetItem(list, i, PyFloat_FromDouble(v.at(i)));\n    }\n    return list;\n}\n\n#endif // WITHOUT_NUMPY\n\n    template<typename Numeric>\n    bool plot(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)\n    {\n        assert(x.size() == y.size());\n\n        // using numpy arrays\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        // construct positional args\n        PyObject* args = PyTuple_New(2);\n        PyTuple_SetItem(args, 0, xarray);\n        PyTuple_SetItem(args, 1, yarray);\n\n        // construct keyword args\n        PyObject* kwargs = PyDict_New();\n        for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)\n        {\n            PyDict_SetItemString(kwargs, it->first.c_str(), PyString_FromString(it->second.c_str()));\n        }\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, args, kwargs);\n\n        Py_DECREF(args);\n        Py_DECREF(kwargs);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool stem(const std::vector<Numeric> &x, const std::vector<Numeric> &y, const std::map<std::string, std::string>& keywords)\n    {\n        assert(x.size() == y.size());\n\n        // using numpy arrays\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        // construct positional args\n        PyObject* args = PyTuple_New(2);\n        PyTuple_SetItem(args, 0, xarray);\n        PyTuple_SetItem(args, 1, yarray);\n\n        // construct keyword args\n        PyObject* kwargs = PyDict_New();\n        for (std::map<std::string, std::string>::const_iterator it =\n                keywords.begin(); it != keywords.end(); ++it) {\n            PyDict_SetItemString(kwargs, it->first.c_str(),\n                                 PyString_FromString(it->second.c_str()));\n        }\n\n        PyObject* res = PyObject_Call(\n                detail::_interpreter::get().s_python_function_stem, args, kwargs);\n\n        Py_DECREF(args);\n        Py_DECREF(kwargs);\n        if (res)\n            Py_DECREF(res);\n\n        return res;\n    }\n\n    template< typename Numeric >\n    bool fill_between(const std::vector<Numeric>& x, const std::vector<Numeric>& y1, const std::vector<Numeric>& y2, const std::map<std::string, std::string>& keywords)\n    {\n        assert(x.size() == y1.size());\n        assert(x.size() == y2.size());\n\n        // using numpy arrays\n        PyObject* xarray = get_array(x);\n        PyObject* y1array = get_array(y1);\n        PyObject* y2array = get_array(y2);\n\n        // construct positional args\n        PyObject* args = PyTuple_New(3);\n        PyTuple_SetItem(args, 0, xarray);\n        PyTuple_SetItem(args, 1, y1array);\n        PyTuple_SetItem(args, 2, y2array);\n\n        // construct keyword args\n        PyObject* kwargs = PyDict_New();\n        for(std::map<std::string, std::string>::const_iterator it = keywords.begin(); it != keywords.end(); ++it)\n        {\n            PyDict_SetItemString(kwargs, it->first.c_str(), PyUnicode_FromString(it->second.c_str()));\n        }\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_fill_between, args, kwargs);\n\n        Py_DECREF(args);\n        Py_DECREF(kwargs);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template< typename Numeric>\n    bool hist(const std::vector<Numeric>& y, long bins=10,std::string color=\"b\", double alpha=1.0)\n    {\n\n        PyObject* yarray = get_array(y);\n\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"bins\", PyLong_FromLong(bins));\n        PyDict_SetItemString(kwargs, \"color\", PyString_FromString(color.c_str()));\n        PyDict_SetItemString(kwargs, \"alpha\", PyFloat_FromDouble(alpha));\n\n\n        PyObject* plot_args = PyTuple_New(1);\n\n        PyTuple_SetItem(plot_args, 0, yarray);\n\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);\n\n\n        Py_DECREF(plot_args);\n        Py_DECREF(kwargs);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template< typename Numeric>\n    bool named_hist(std::string label,const std::vector<Numeric>& y, long bins=10, std::string color=\"b\", double alpha=1.0)\n    {\n        PyObject* yarray = get_array(y);\n\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(label.c_str()));\n        PyDict_SetItemString(kwargs, \"bins\", PyLong_FromLong(bins));\n        PyDict_SetItemString(kwargs, \"color\", PyString_FromString(color.c_str()));\n        PyDict_SetItemString(kwargs, \"alpha\", PyFloat_FromDouble(alpha));\n\n\n        PyObject* plot_args = PyTuple_New(1);\n        PyTuple_SetItem(plot_args, 0, yarray);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_hist, plot_args, kwargs);\n\n        Py_DECREF(plot_args);\n        Py_DECREF(kwargs);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool plot(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(s.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);\n\n        Py_DECREF(plot_args);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool stem(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(s.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_stem, plot_args);\n\n        Py_DECREF(plot_args);\n        if (res)\n            Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool semilogx(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(s.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogx, plot_args);\n\n        Py_DECREF(plot_args);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool semilogy(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(s.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_semilogy, plot_args);\n\n        Py_DECREF(plot_args);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool loglog(const std::vector<NumericX>& x, const std::vector<NumericY>& y, const std::string& s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(s.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_loglog, plot_args);\n\n        Py_DECREF(plot_args);\n        if(res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename NumericX, typename NumericY>\n    bool errorbar(const std::vector<NumericX> &x, const std::vector<NumericY> &y, const std::vector<NumericX> &yerr, const std::string &s = \"\")\n    {\n        assert(x.size() == y.size());\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n        PyObject* yerrarray = get_array(yerr);\n\n        PyObject *kwargs = PyDict_New();\n\n        PyDict_SetItemString(kwargs, \"yerr\", yerrarray);\n\n        PyObject *pystring = PyString_FromString(s.c_str());\n\n        PyObject *plot_args = PyTuple_New(2);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n\n        PyObject *res = PyObject_Call(detail::_interpreter::get().s_python_function_errorbar, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n\n        if (res)\n            Py_DECREF(res);\n        else\n            throw std::runtime_error(\"Call to errorbar() failed.\");\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool named_plot(const std::string& name, const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(name.c_str()));\n\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(format.c_str());\n\n        PyObject* plot_args = PyTuple_New(2);\n\n        PyTuple_SetItem(plot_args, 0, yarray);\n        PyTuple_SetItem(plot_args, 1, pystring);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n        if (res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool named_plot(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(name.c_str()));\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(format.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_plot, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n        if (res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool named_semilogx(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(name.c_str()));\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(format.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogx, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n        if (res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool named_semilogy(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(name.c_str()));\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(format.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_semilogy, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n        if (res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool named_loglog(const std::string& name, const std::vector<Numeric>& x, const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        PyObject* kwargs = PyDict_New();\n        PyDict_SetItemString(kwargs, \"label\", PyString_FromString(name.c_str()));\n\n        PyObject* xarray = get_array(x);\n        PyObject* yarray = get_array(y);\n\n        PyObject* pystring = PyString_FromString(format.c_str());\n\n        PyObject* plot_args = PyTuple_New(3);\n        PyTuple_SetItem(plot_args, 0, xarray);\n        PyTuple_SetItem(plot_args, 1, yarray);\n        PyTuple_SetItem(plot_args, 2, pystring);\n\n        PyObject* res = PyObject_Call(detail::_interpreter::get().s_python_function_loglog, plot_args, kwargs);\n\n        Py_DECREF(kwargs);\n        Py_DECREF(plot_args);\n        if (res) Py_DECREF(res);\n\n        return res;\n    }\n\n    template<typename Numeric>\n    bool plot(const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        std::vector<Numeric> x(y.size());\n        for(size_t i=0; i<x.size(); ++i) x.at(i) = i;\n        return plot(x,y,format);\n    }\n\n    template<typename Numeric>\n    bool stem(const std::vector<Numeric>& y, const std::string& format = \"\")\n    {\n        std::vector<Numeric> x(y.size());\n        for (size_t i = 0; i < x.size(); ++i) x.at(i) = i;\n        return stem(x, y, format);\n    }\n\n    inline void figure()\n    {\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_figure, detail::_interpreter::get().s_python_empty_tuple);\n        if(!res) throw std::runtime_error(\"Call to figure() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    inline void legend()\n    {\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_legend, detail::_interpreter::get().s_python_empty_tuple);\n        if(!res) throw std::runtime_error(\"Call to legend() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    template<typename Numeric>\n    void ylim(Numeric left, Numeric right)\n    {\n        PyObject* list = PyList_New(2);\n        PyList_SetItem(list, 0, PyFloat_FromDouble(left));\n        PyList_SetItem(list, 1, PyFloat_FromDouble(right));\n\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, list);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);\n        if(!res) throw std::runtime_error(\"Call to ylim() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    template<typename Numeric>\n    void xlim(Numeric left, Numeric right)\n    {\n        PyObject* list = PyList_New(2);\n        PyList_SetItem(list, 0, PyFloat_FromDouble(left));\n        PyList_SetItem(list, 1, PyFloat_FromDouble(right));\n\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, list);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);\n        if(!res) throw std::runtime_error(\"Call to xlim() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n\n    inline double* xlim()\n    {\n        PyObject* args = PyTuple_New(0);\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlim, args);\n        PyObject* left = PyTuple_GetItem(res,0);\n        PyObject* right = PyTuple_GetItem(res,1);\n\n        double* arr = new double[2];\n        arr[0] = PyFloat_AsDouble(left);\n        arr[1] = PyFloat_AsDouble(right);\n\n        if(!res) throw std::runtime_error(\"Call to xlim() failed.\");\n\n        Py_DECREF(res);\n        return arr;\n    }\n\n\n    inline double* ylim()\n    {\n        PyObject* args = PyTuple_New(0);\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylim, args);\n        PyObject* left = PyTuple_GetItem(res,0);\n        PyObject* right = PyTuple_GetItem(res,1);\n\n        double* arr = new double[2];\n        arr[0] = PyFloat_AsDouble(left);\n        arr[1] = PyFloat_AsDouble(right);\n\n        if(!res) throw std::runtime_error(\"Call to ylim() failed.\");\n\n        Py_DECREF(res);\n        return arr;\n    }\n\n    inline void subplot(long nrows, long ncols, long plot_number)\n    {\n        // construct positional args\n        PyObject* args = PyTuple_New(3);\n        PyTuple_SetItem(args, 0, PyFloat_FromDouble(nrows));\n        PyTuple_SetItem(args, 1, PyFloat_FromDouble(ncols));\n        PyTuple_SetItem(args, 2, PyFloat_FromDouble(plot_number));\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_subplot, args);\n        if(!res) throw std::runtime_error(\"Call to subplot() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void title(const std::string &titlestr)\n    {\n        PyObject* pytitlestr = PyString_FromString(titlestr.c_str());\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, pytitlestr);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_title, args);\n        if(!res) throw std::runtime_error(\"Call to title() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void axis(const std::string &axisstr)\n    {\n        PyObject* str = PyString_FromString(axisstr.c_str());\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, str);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_axis, args);\n        if(!res) throw std::runtime_error(\"Call to title() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void xlabel(const std::string &str)\n    {\n        PyObject* pystr = PyString_FromString(str.c_str());\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, pystr);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_xlabel, args);\n        if(!res) throw std::runtime_error(\"Call to xlabel() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void ylabel(const std::string &str)\n    {\n        PyObject* pystr = PyString_FromString(str.c_str());\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, pystr);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_ylabel, args);\n        if(!res) throw std::runtime_error(\"Call to ylabel() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void grid(bool flag)\n    {\n        PyObject* pyflag = flag ? Py_True : Py_False;\n        Py_INCREF(pyflag);\n\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, pyflag);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_grid, args);\n        if(!res) throw std::runtime_error(\"Call to grid() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void show(const bool block = true)\n    {\n        PyObject* res;\n        if(block)\n        {\n            res = PyObject_CallObject(\n                    detail::_interpreter::get().s_python_function_show,\n                    detail::_interpreter::get().s_python_empty_tuple);\n        }\n        else\n        {\n            PyObject *kwargs = PyDict_New();\n            PyDict_SetItemString(kwargs, \"block\", Py_False);\n            res = PyObject_Call( detail::_interpreter::get().s_python_function_show, detail::_interpreter::get().s_python_empty_tuple, kwargs);\n            Py_DECREF(kwargs);\n        }\n\n\n        if (!res) throw std::runtime_error(\"Call to show() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    inline void close()\n    {\n        PyObject* res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_close,\n                detail::_interpreter::get().s_python_empty_tuple);\n\n        if (!res) throw std::runtime_error(\"Call to close() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    inline void xkcd() {\n        PyObject* res;\n        PyObject *kwargs = PyDict_New();\n\n        res = PyObject_Call(detail::_interpreter::get().s_python_function_xkcd,\n                            detail::_interpreter::get().s_python_empty_tuple, kwargs);\n\n        Py_DECREF(kwargs);\n\n        if (!res)\n            throw std::runtime_error(\"Call to show() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    inline void draw()\n    {\n        PyObject* res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_draw,\n                detail::_interpreter::get().s_python_empty_tuple);\n\n        if (!res) throw std::runtime_error(\"Call to draw() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    template<typename Numeric>\n    inline void pause(Numeric interval)\n    {\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, PyFloat_FromDouble(interval));\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_pause, args);\n        if(!res) throw std::runtime_error(\"Call to pause() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void save(const std::string& filename)\n    {\n        PyObject* pyfilename = PyString_FromString(filename.c_str());\n\n        PyObject* args = PyTuple_New(1);\n        PyTuple_SetItem(args, 0, pyfilename);\n\n        PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_save, args);\n        if (!res) throw std::runtime_error(\"Call to save() failed.\");\n\n        Py_DECREF(args);\n        Py_DECREF(res);\n    }\n\n    inline void clf() {\n        PyObject *res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_clf,\n                detail::_interpreter::get().s_python_empty_tuple);\n\n        if (!res) throw std::runtime_error(\"Call to clf() failed.\");\n\n        Py_DECREF(res);\n    }\n\n    inline void ion() {\n        PyObject *res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_ion,\n                detail::_interpreter::get().s_python_empty_tuple);\n\n        if (!res) throw std::runtime_error(\"Call to ion() failed.\");\n\n        Py_DECREF(res);\n    }\n\n// Actually, is there any reason not to call this automatically for every plot?\n    inline void tight_layout() {\n        PyObject *res = PyObject_CallObject(\n                detail::_interpreter::get().s_python_function_tight_layout,\n                detail::_interpreter::get().s_python_empty_tuple);\n\n        if (!res) throw std::runtime_error(\"Call to tight_layout() failed.\");\n\n        Py_DECREF(res);\n    }\n\n#if __cplusplus > 199711L || _MSC_VER > 1800\n// C++11-exclusive content starts here (variadic plot() and initializer list support)\n\n    namespace detail {\n\n        template<typename T>\n        using is_function = typename std::is_function<std::remove_pointer<std::remove_reference<T>>>::type;\n\n        template<bool obj, typename T>\n        struct is_callable_impl;\n\n        template<typename T>\n        struct is_callable_impl<false, T>\n        {\n            typedef is_function<T> type;\n        }; // a non-object is callable iff it is a function\n\n        template<typename T>\n        struct is_callable_impl<true, T>\n        {\n            struct Fallback { void operator()(); };\n            struct Derived : T, Fallback { };\n\n            template<typename U, U> struct Check;\n\n            template<typename U>\n            static std::true_type test( ... ); // use a variadic function to make sure (1) it accepts everything and (2) its always the worst match\n\n            template<typename U>\n            static std::false_type test( Check<void(Fallback::*)(), &U::operator()>* );\n\n        public:\n            typedef decltype(test<Derived>(nullptr)) type;\n            typedef decltype(&Fallback::operator()) dtype;\n            static constexpr bool value = type::value;\n        }; // an object is callable iff it defines operator()\n\n        template<typename T>\n        struct is_callable\n        {\n            // dispatch to is_callable_impl<true, T> or is_callable_impl<false, T> depending on whether T is of class type or not\n            typedef typename is_callable_impl<std::is_class<T>::value, T>::type type;\n        };\n\n        template<typename IsYDataCallable>\n        struct plot_impl { };\n\n        template<>\n        struct plot_impl<std::false_type>\n        {\n            template<typename IterableX, typename IterableY>\n            bool operator()(const IterableX& x, const IterableY& y, const std::string& format)\n            {\n                // 2-phase lookup for distance, begin, end\n                using std::distance;\n                using std::begin;\n                using std::end;\n\n                auto xs = distance(begin(x), end(x));\n                auto ys = distance(begin(y), end(y));\n                assert(xs == ys && \"x and y data must have the same number of elements!\");\n\n                PyObject* xlist = PyList_New(xs);\n                PyObject* ylist = PyList_New(ys);\n                PyObject* pystring = PyString_FromString(format.c_str());\n\n                auto itx = begin(x), ity = begin(y);\n                for(size_t i = 0; i < xs; ++i) {\n                    PyList_SetItem(xlist, i, PyFloat_FromDouble(*itx++));\n                    PyList_SetItem(ylist, i, PyFloat_FromDouble(*ity++));\n                }\n\n                PyObject* plot_args = PyTuple_New(3);\n                PyTuple_SetItem(plot_args, 0, xlist);\n                PyTuple_SetItem(plot_args, 1, ylist);\n                PyTuple_SetItem(plot_args, 2, pystring);\n\n                PyObject* res = PyObject_CallObject(detail::_interpreter::get().s_python_function_plot, plot_args);\n\n                Py_DECREF(plot_args);\n                if(res) Py_DECREF(res);\n\n                return res;\n            }\n        };\n\n        template<>\n        struct plot_impl<std::true_type>\n        {\n            template<typename Iterable, typename Callable>\n            bool operator()(const Iterable& ticks, const Callable& f, const std::string& format)\n            {\n                if(begin(ticks) == end(ticks)) return true;\n\n                // We could use additional meta-programming to deduce the correct element type of y,\n                // but all values have to be convertible to double anyways\n                std::vector<double> y;\n                for(auto x : ticks) y.push_back(f(x));\n                return plot_impl<std::false_type>()(ticks,y,format);\n            }\n        };\n\n    } // end namespace detail\n\n// recursion stop for the above\n    template<typename... Args>\n    bool plot() { return true; }\n\n    template<typename A, typename B, typename... Args>\n    bool plot(const A& a, const B& b, const std::string& format, Args... args)\n    {\n        return detail::plot_impl<typename detail::is_callable<B>::type>()(a,b,format) && plot(args...);\n    }\n\n/*\n * This group of plot() functions is needed to support initializer lists, i.e. calling\n *    plot( {1,2,3,4} )\n */\n    inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::string& format = \"\")\n    {\n        return plot<double,double>(x,y,format);\n    }\n\n    inline bool plot(const std::vector<double>& y, const std::string& format = \"\") {\n        return plot<double>(y,format);\n    }\n\n    inline bool plot(const std::vector<double>& x, const std::vector<double>& y, const std::map<std::string, std::string>& keywords) {\n        return plot<double>(x,y,keywords);\n    }\n\n#endif\n\n} // end namespace matplotlibcpp\n"
  },
  {
    "path": "include/tic_toc.h",
    "content": "//\n// Created by buyi on 18-1-28.\n//\n\n#ifndef IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H\n#define IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H\n\n#include <ctime>\n#include <cstdlib>\n#include <chrono>\n\nnamespace IMU\n{\n\nclass TicToc\n{\npublic:\n    TicToc()\n    {\n        tic();\n    }\n\n    void tic()\n    {\n        start = std::chrono::system_clock::now();\n    }\n\n    double toc()        //ms\n    {\n        end = std::chrono::system_clock::now();\n        std::chrono::duration<double> elapsed_seconds = end - start;\n        return elapsed_seconds.count()*1000;\n    }\n\nprivate:\n    std::chrono::time_point <std::chrono::system_clock> start, end;\n};\n\n\n} //namesapce IMU\n\n#endif //IMU_ATTITUDE_ESTIMATOR_TIC_TOC_H_H\n"
  },
  {
    "path": "src/Convert.cpp",
    "content": "#include \"Convert.h\"\r\n#include \"TypeDefs.h\"\r\n#include <fstream>\r\n\r\nnamespace IMU\r\n{\r\n\r\nvoid Vect_to_SkewMat(Vector_3 Vector, Matrix_3 &Matrix)\r\n{\r\n    Matrix << 0, -Vector(2), Vector(1),\r\n            Vector(2), 0, -Vector(0),\r\n            -Vector(1), Vector(0), 0;\r\n}\r\n\r\nvoid Angular_to_Mat(Vector_3 Vector, Eigen::Matrix<double, 4, 4> &Matrix)\r\n{\r\n    Matrix << 0, -Vector(0), -Vector(1), -Vector(2),\r\n            Vector(0), 0, Vector(2), -Vector(1),\r\n            Vector(1), -Vector(2), 0, Vector(0),\r\n            Vector(2), Vector(1), -Vector(0), 0;\r\n}\r\n\r\nVector_4 Quaternion_to_Vect(Eigen::Quaterniond q)\r\n{\r\n    Vector_4 vector;\r\n    vector(0) = q.w();\r\n    vector.block<3, 1>(1, 0) = q.vec();\r\n\r\n    return vector;\r\n}\r\n\r\nEigen::Quaterniond QuatMult(Eigen::Quaterniond q1, Eigen::Quaterniond q2)\r\n{\r\n    Eigen::Quaterniond resultQ;\r\n    resultQ.setIdentity();\r\n\r\n    resultQ.w() = q1.w() * q2.w() - q1.vec().dot(q2.vec());\r\n    resultQ.vec() = q1.w() * q2.vec() + q2.w() * q1.vec() + q1.vec().cross(q2.vec());\r\n\r\n    return resultQ;\r\n}\r\n\r\nMatrix_3 Quat_to_Matrix(Eigen::Quaterniond q)\r\n{\r\n    Matrix_3 matrix;\r\n    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()),\r\n            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()),\r\n            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();\r\n\r\n    return matrix;\r\n}\r\n\r\nEigen::MatrixXd readFromfile(const string file_name)\r\n{\r\n    Eigen::MatrixXd matrix;\r\n    std::vector<double> entries;\r\n    ifstream data(file_name, ios::binary);\r\n    string lineOfData;\r\n\r\n    if (data.is_open())\r\n    {\r\n        int i = 0;\r\n        int cols = 0;\r\n        while (data.good())\r\n        {\r\n            int j = 0;\r\n            getline(data, lineOfData);\r\n            stringstream stream(lineOfData);\r\n            while (!stream.eof())\r\n            {\r\n                double a;\r\n                stream >> a;\r\n                entries.push_back(a);\r\n                j++;\r\n            }\r\n            cols = j;\r\n            i++;\r\n        }\r\n        matrix = Eigen::MatrixXd::Map(&entries[0], cols, i).transpose();\r\n\r\n        return matrix;\r\n    }\r\n    else\r\n    {\r\n        cout << \"Unable to open file\" << std::endl;\r\n\r\n        return Eigen::Vector3d::Zero();\r\n    }\r\n\r\n}\r\n\r\nbool writeTofile(Eigen::MatrixXd matrix, const string file_name)\r\n{\r\n    std::ofstream file(file_name, ios::binary);\r\n    if (file.is_open())\r\n    {\r\n        file << matrix << '\\n';\r\n    }\r\n    else\r\n        return false;\r\n    file.close();\r\n    return true;\r\n}\r\n\r\nMatrix_3 Euler_to_RoatMat(Vector_3 Euler)\r\n{\r\n    Matrix_3 Rotate_Mat;\r\n    double theta;\r\n    Matrix_3 Skew_Euler;\r\n\r\n    theta = Euler.norm();\r\n    Euler.normalize();\r\n\r\n    Vect_to_SkewMat(Euler, Skew_Euler);\r\n\r\n    Rotate_Mat = Matrix_3::Identity() + sin(theta)*Skew_Euler + (1 - cos(theta))*Skew_Euler.transpose()*Skew_Euler;\r\n    return Rotate_Mat;\r\n}\r\n\r\nEigen::Quaterniond Euler_to_Quaternion(Vector_3 Euler)\r\n{\r\n    Eigen::Quaterniond quaternion;\r\n\r\n    /*\r\n    double theta = sqrt(Euler(0)*Euler(0) + Euler(1)*Euler(1) + Euler(2)*Euler(2));\r\n    Euler.normalize();\r\n\r\n    quaternion.w() = cos(0.5*theta);\r\n    quaternion.vec() = Euler*sin(0.5*theta);\r\n    */\r\n\r\n\r\n\r\n    // using Eigen\r\n    /*\r\n    quaternion = Eigen::AngleAxisd(Euler(0), Eigen::Vector3d::UnitX())\r\n\r\n    * Eigen::AngleAxisd(Euler(1), Eigen::Vector3d::UnitY())\r\n\r\n    *Eigen::AngleAxisd(Euler(2), Eigen::Vector3d::UnitZ());\r\n    */\r\n    double CosRoll = cos(Euler[0] * 0.5);\r\n    double SinRoll = sin(Euler[0] * 0.5);\r\n    double CosPitch = cos(Euler[1] * 0.5);\r\n    double SinPitch = sin(Euler[1] * 0.5);\r\n    double CosYaw = cos(Euler[2] * 0.5);\r\n    double SinYaw = sin(Euler[2] * 0.5);\r\n\r\n    double w = CosRoll*CosPitch*CosYaw + SinRoll*SinPitch*SinYaw;\r\n    double x = CosPitch*SinRoll*CosYaw - CosRoll*SinPitch*SinYaw;\r\n    double y = CosRoll*CosYaw*SinPitch + SinRoll*CosPitch*SinYaw;\r\n    double z = CosRoll*CosPitch*SinYaw - CosYaw*SinPitch*SinRoll;\r\n\r\n    quaternion = Eigen::Quaterniond(w, x, y, z);\r\n\r\n    return quaternion;\r\n}\r\n\r\nVector_3 Quaternion_to_Euler(Eigen::Quaterniond q)\r\n{\r\n    Vector_3 Euler;\r\n\r\n    // the normal way\r\n\r\n    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()));\r\n    Euler(1) = asin(-2 * q.x()*q.z() + 2 * q.w()*q.y());\r\n    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;\r\n\r\n    /*\r\n    // using the eigen\r\n\r\n    q.normalize();\r\n\r\n    Euler = q.toRotationMatrix().eulerAngles(0, 1, 2);\r\n\r\n    */\r\n    return Euler*180/M_PI;\r\n}\r\n\r\nVector_3 Rotation_to_Euler(Matrix_3 Rotation)\r\n{\r\n    Vector_3 Euler;\r\n\r\n    Euler(0) = atan2(Rotation(1, 2), Rotation(2, 2));\r\n    Euler(1) = -asin(Rotation(0, 2));\r\n    Euler(2) = atan2(Rotation(0, 1), Rotation(0, 0));\r\n\r\n    return Euler;\r\n}\r\n\r\nEigen::Quaterniond Rotation_to_Quater(Matrix_3 Rotation)\r\n{\r\n    Eigen::Quaterniond quaternion;\r\n    Vector_4 quat_tmp;\r\n    double tr;\r\n    tr = Rotation.trace();\r\n    if (tr > 0.0)\r\n    {\r\n        double s = sqrtf(tr + 1.0);\r\n        quat_tmp(0) = s*0.5;\r\n        s = 0.5 / s;\r\n        quat_tmp(1) = (Rotation(2, 1) - Rotation(1, 2))*s;\r\n        quat_tmp(2) = (Rotation(0, 2) - Rotation(2, 0))*s;\r\n        quat_tmp(3) = (Rotation(1, 0) - Rotation(0, 1))*s;\r\n    }\r\n    else\r\n    {\r\n        int dcm_i = 0;\r\n        for (int i = 1; i < 3; i++)\r\n        {\r\n            if (Rotation(i, i) > Rotation(dcm_i, dcm_i))\r\n                dcm_i = i;\r\n        }\r\n        int dcm_j = (dcm_i + 1) % 3;\r\n        int dcm_k = (dcm_i + 2) % 3;\r\n        double s = sqrtf((Rotation(dcm_i, dcm_i) - Rotation(dcm_j, dcm_j) -\r\n                          Rotation(dcm_k, dcm_k)) + 1.0f);\r\n\r\n        quat_tmp(dcm_i + 1) = s*0.5;\r\n        s = 0.5 / s;\r\n        quat_tmp(dcm_j + 1) = (Rotation(dcm_i, dcm_j) + Rotation(dcm_j, dcm_i)) * s;\r\n        quat_tmp[dcm_k + 1] = (Rotation(dcm_k, dcm_i) + Rotation(dcm_i, dcm_k)) * s;\r\n        quat_tmp[0] = (Rotation(dcm_k, dcm_j) - Rotation(dcm_j, dcm_k)) * s;\r\n    }\r\n    quaternion.w() = quat_tmp(0);\r\n    quaternion.vec() = quat_tmp.block<3, 1>(1, 0);\r\n\r\n    return quaternion;\r\n}\r\n\r\nEigen::Quaterniond BuildUpdateQuat(Eigen::Vector3d DeltaTheta)\r\n{\r\n    Eigen::Vector3d DeltaQuat = 0.5*DeltaTheta;\r\n    double checknorm = DeltaQuat.transpose()*DeltaQuat;\r\n\r\n    Eigen::Quaterniond UpdateQuat;\r\n    if (checknorm > 1)\r\n    {\r\n        UpdateQuat = Eigen::Quaterniond(1, DeltaQuat[0], DeltaQuat[1], DeltaQuat[2]);\r\n        UpdateQuat = UpdateQuat.coeffs()*sqrt(1 + checknorm);\r\n    }\r\n    else\r\n        UpdateQuat = Eigen::Quaterniond(sqrt(1 - checknorm), DeltaQuat[0], DeltaQuat[1], DeltaQuat[2]);\r\n\r\n    UpdateQuat.normalize();\r\n\r\n    return  UpdateQuat;\r\n}\r\n\r\n} //IMU"
  },
  {
    "path": "src/EKF_Attitude.cpp",
    "content": "#include \"EKF_Attitude.h\"\r\n#include \"Convert.h\"\r\n\r\nusing namespace std;\r\n\r\nnamespace IMU\r\n{\r\n\r\nEKF_Attitude::EKF_Attitude(bool approx_prediction, double dt):\r\n        mbStopped(false), mbStopRequested(false), deltaT(dt)\r\n{\r\n\tcout << \"System initialization!\" << endl;\r\n\r\n\t/* Set the primary value of state vector and covariance matrix */\r\n\r\n\tif (state_X_pro.size() == 0)\r\n\t{\r\n\t\tVector_12 state_X_tmp;\r\n\t\t/*\r\n\t\tstate_X_tmp <<\t0.0018, -0.0003, 0.0015,\r\n\t\t\t\t\t\t0.0351, -0.0567, -0.0364,\r\n\t\t\t\t\t\t0.0093, -0.0012, -0.9998,\r\n\t\t\t\t\t\t0.0089, 0.4784, 0.8781;\r\n\t\t*/\r\n\t\tstate_X_tmp <<\t0.0, -0.0, 0.0,\r\n\t\t\t\t\t\t0.0, -0.0, -0.0,\r\n\t\t\t\t\t\t0.0, -0.0, -0.9998,\r\n\t\t\t\t\t\t0.0, 0.0, 1;\r\n\t\tstate_X_pro.push_back(state_X_tmp);\r\n\t}\r\n\r\n\tif (CovrMatrix_P_pro.size()==0)\r\n\t{\r\n//\t\tCovrMatrix_P_pro.push_back(Eigen::MatrixXd::Ones(12, 12) * 200);\r\n\t\tVector_3 V1(0, 0, 0.0001);\r\n\t\tVector_3 V2(0, 0.0001, -0.0001);\r\n\t\tMatrix_3 M1, M2;\r\n\t\tVect_to_SkewMat(V1, M1);\r\n\t\tVect_to_SkewMat(V2, M2);\r\n\r\n\t\tEigen::Matrix<double, 12, 12> CovrMatrix_tmp;\r\n\t\tCovrMatrix_tmp <<\t0.004*Identity_Matrix3, 0.056*Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3,\r\n\t\t\t\t\t\t\t0.056*Identity_Matrix3, 0.2971*Identity_Matrix3, M1, M2,\r\n\t\t\t\t\t\t\tZeros_Matrix3, -M1, 2.9956*Identity_Matrix3, Zeros_Matrix3,\r\n\t\t\t\t\t\t\tZeros_Matrix3, -M2, Zeros_Matrix3, 0.7046*Identity_Matrix3;\r\n\t\tCovrMatrix_P_pro.push_back(CovrMatrix_tmp);\r\n\t}\r\n\r\n\tusing_2ndOrder = approx_prediction;\r\n\r\n\t// set the process noise as the diagnoal of elements\r\n\tVector_12 Pro_Nosiecovr;\r\n\tVector_9 Mea_Nosiecovr;\r\n\tPro_Nosiecovr <<\t1e-4, 1e-4, 1e-4,\r\n\t\t\t\t\t\t0.08, 0.08, 0.08,\r\n\t\t\t\t\t\t0.009, 0.009, 0.009,\r\n\t\t\t\t\t\t0.005, 0.005, 0.005;\r\n\tMea_Nosiecovr <<\t0.0008, 0.0008, 0.0008,\r\n\t\t\t\t\t\t1000, 1000, 1000,\r\n\t\t\t\t\t\t100, 100, 100;\r\n\r\n\tQ_noise = Pro_Nosiecovr.asDiagonal();\r\n\tR_noise = Mea_Nosiecovr.asDiagonal();\r\n\r\n}\r\n\r\nvoid EKF_Attitude::Param_Change(Vector_12 Pro_Nosiecovr, Vector_9 Mea_Nosiecovr)\r\n{\r\n\tif (isStopped())\r\n\t{\r\n\t\tQ_noise = Pro_Nosiecovr.asDiagonal();\r\n\t\tR_noise = Mea_Nosiecovr.asDiagonal();\r\n\t}\r\n}\r\n\r\nvoid EKF_Attitude::Cal_TransMatrix()\r\n{\r\n\tMatrix_3 r_acc, r_mag, w_angular, w_angular_T;\r\n\tVector_3 r_acc_v, r_mag_v, w_angular_v;\r\n\tVector_12 state_X_tmp;\r\n\tstate_X_tmp = state_X_pro.back();\r\n\r\n\tw_angular_v = state_X_tmp.block<3, 1>(0, 0);\r\n\tr_acc_v = state_X_tmp.block<3, 1>(6, 0);\r\n\tr_mag_v = state_X_tmp.block<3, 1>(9, 0);\r\n\r\n\tVect_to_SkewMat(w_angular_v, w_angular_T);\r\n\tw_angular = w_angular_T.transpose();\r\n\tVect_to_SkewMat(r_acc_v, r_acc);\r\n\tVect_to_SkewMat(r_mag_v, r_mag);\r\n\r\n\tAlin << Zeros_Matrix3, Identity_Matrix3, Zeros_Matrix3, Zeros_Matrix3,\r\n            Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3,\r\n            r_acc, Zeros_Matrix3, w_angular, Zeros_Matrix3,\r\n            -r_mag, Zeros_Matrix3, Zeros_Matrix3, w_angular;\r\n\r\n\tAlin = Eigen::MatrixXd::Identity(12, 12) + Alin*deltaT;\r\n}\r\n\r\nvoid EKF_Attitude::Prior_Predict()\r\n{\r\n\tVector_12 state_X_tmp;\r\n\tVector_3  angular_vel, angular_acc, acc_state, mag_state;\r\n\tMatrix_3 w_angular, w_angular_T;\r\n\r\n\tstate_X_tmp = state_X_pro.back();\r\n\tangular_vel = state_X_tmp.block<3, 1>(0, 0);\r\n\tangular_acc = state_X_tmp.block<3, 1>(3, 0);\r\n\r\n\tVect_to_SkewMat(angular_vel, w_angular_T);\r\n\tw_angular = w_angular_T.transpose();\r\n\tangular_vel = angular_vel + angular_acc*deltaT;\r\n\r\n\t// calculate the non-liner system, and decide wto use the number of taylor expansion \r\n\tif (using_2ndOrder)\r\n\t{\r\n\t\tMatrix_3 Temp_Mat = Identity_Matrix3 + w_angular*deltaT + deltaT*deltaT/2*w_angular*w_angular;\r\n\r\n        acc_state = state_X_tmp.block<3, 1>(6, 0);\r\n\t\tacc_state = Temp_Mat*acc_state;\r\n\r\n\t\tmag_state = state_X_tmp.block<3, 1>(9, 0);\r\n\t\tmag_state = Temp_Mat*mag_state;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tMatrix_3 Temp_Mat;\r\n\t\tacc_state = state_X_tmp.block<3, 1>(6, 0);\r\n\t\tTemp_Mat = Identity_Matrix3 + w_angular*deltaT;\r\n\t\tacc_state = Temp_Mat*acc_state;\r\n\r\n\t\tmag_state = state_X_tmp.block<3, 1>(9, 0);\r\n\t\tmag_state = Temp_Mat*mag_state;\r\n\t}\r\n\r\n\t// refer to the 4.20 and 4.21 formula\r\n\tEigen::Matrix<double, 12, 12> CovrMatrix_tmp;\r\n\r\n\tstate_X_tmp << angular_vel, angular_acc, acc_state, mag_state;\r\n\tstate_X_pro.push_back(state_X_tmp);\r\n\r\n\tCovrMatrix_tmp = CovrMatrix_P_pro.back();\r\n\tCovrMatrix_tmp = Alin*CovrMatrix_tmp*Alin.transpose() + Q_noise;\r\n\tCovrMatrix_P_pro.push_back(CovrMatrix_tmp);\r\n}\r\n\r\nvoid EKF_Attitude::Post_Correct()\r\n{\r\n\r\n\tVector_12 state_X_tmp;\r\n\tEigen::Matrix<double, 12, 12> CovrMatrix_tmp;\r\n\r\n\tstate_X_tmp = state_X_pro.back();\r\n\tstate_X_pro.pop_back();\r\n\tCovrMatrix_tmp = CovrMatrix_P_pro.back();\r\n\tCovrMatrix_P_pro.pop_back();\r\n\r\n\t// initialize the observe matrix H\r\n\tEigen::Matrix<double, 9, 12> Observe_Matrix;\r\n\tObserve_Matrix <<\tIdentity_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3,\r\n\t\t\t\t\t\tZeros_Matrix3, Zeros_Matrix3, Identity_Matrix3, Zeros_Matrix3,\r\n\t\t\t\t\t\tZeros_Matrix3, Zeros_Matrix3, Zeros_Matrix3, Identity_Matrix3;\r\n\r\n\t// calculate the Kalman gain\r\n\tEigen::Matrix<double, 9, 9> Kal_Matrix;\r\n\tEigen::Matrix<double, 12, 9> Kalman_gain;\r\n\tKal_Matrix = Observe_Matrix*CovrMatrix_tmp*Observe_Matrix.transpose() + R_noise;\r\n\tKalman_gain = CovrMatrix_tmp*Observe_Matrix.transpose()*Kal_Matrix.inverse();\r\n\r\n\t// update the state vector\r\n\tVector_9 Mea_residual;\r\n\tMea_residual = cur_measurement - Observe_Matrix*state_X_tmp;\r\n\tstate_X_tmp = state_X_tmp + Kalman_gain*Mea_residual;\r\n\tstate_X_pro.push_back(state_X_tmp);\r\n\r\n\t// update the covariance Matrix\r\n\tCovrMatrix_tmp = (Eigen::MatrixXd::Identity(12, 12) - Kalman_gain*Observe_Matrix)*CovrMatrix_tmp;\r\n\tCovrMatrix_P_pro.push_back(CovrMatrix_tmp);\r\n\r\n}\r\n\r\nvoid EKF_Attitude::Cal_Quaternion()\r\n{\r\n\t//if (quaternion.size() >= 358)\r\n\t//\tcout << \" \" << endl;\r\n\t// extract the true state of three sensors\r\n\tVector_3 acc_state, mag_state, angular_state;\r\n\tVector_12 state_X_tmp;\r\n\tstate_X_tmp = state_X_pro.back();\r\n\r\n\tacc_state = state_X_tmp.block<3, 1>(6, 0);\r\n\tmag_state = state_X_tmp.block<3, 1>(9, 0);\r\n\r\n\tVector_3 x_state, y_state, z_state;\r\n\tacc_state.normalize();\r\n\tmag_state.normalize();\r\n\r\n\tz_state = -acc_state;\r\n\r\n\ty_state = z_state.cross(mag_state);\r\n\ty_state.normalize();\r\n\r\n\tx_state = y_state.cross(z_state);\r\n\tx_state.normalize();\r\n\r\n\t// the rotation order is X-Y-Z,and \r\n\tMatrix_3 Rotation_matrix;\r\n\tRotation_matrix << x_state, y_state, z_state;\r\n\tEigen::Quaterniond quat_temp(Rotation_matrix.transpose());\r\n//\tEigen::Quaterniond quat_temp = Rotation_to_Quater(Rotation_matrix.transpose());\r\n\r\n\tVector_3 Euler;\r\n\tEuler = Quaternion_to_Euler(quat_temp);\r\n\r\n\t\r\n//\tcout << Euler << endl;\r\n\tquaternion.push_back(quat_temp);\r\n}\r\n\r\nvoid EKF_Attitude::Read_SensorData(Vector_9 measurement)\r\n{\r\n\tVector_3 gyro_mea, acc_mea, mag_mea;\r\n    acc_mea = measurement.block<3, 1>(0, 0);\r\n\tgyro_mea = measurement.block<3, 1>(3, 0);\r\n\tmag_mea = measurement.block<3, 1>(6, 0);\r\n\r\n\tacc_mea.normalize();\r\n\tmag_mea.normalize();\r\n\r\n\tcur_measurement.block<3, 1>(0, 0) = gyro_mea;\r\n\tcur_measurement.block<3, 1>(3, 0) = acc_mea;\r\n\tcur_measurement.block<3, 1>(6, 0) = mag_mea;\r\n}\r\n\r\nEigen::Quaterniond EKF_Attitude::Run(Vector_9 measurement)\r\n{\r\n\twhile (true)\r\n\t{\r\n\t\tRead_SensorData(measurement);\r\n\r\n\t\tCal_TransMatrix();\r\n\r\n\t\tPrior_Predict();\r\n\r\n\t\tPost_Correct();\r\n\r\n\t\tCal_Quaternion();\r\n\r\n\t\tif (Stop())\r\n\t\t{\r\n\t\t\twhile (isStopped())\r\n\t\t\t{\r\n#ifdef _WIN32\r\n\t\t\t\tSleep(3000);\r\n#else\r\n\t\t\t\tusleep(3000);\r\n#endif\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn quaternion.back();\r\n\t}\r\n}\r\n\r\nvoid EKF_Attitude::RequestStop()\r\n{\r\n\tunique_lock<mutex> lock(mMutexStop);\r\n\tmbStopRequested = true;\r\n}\r\n\r\nvoid EKF_Attitude::RequestStart()\r\n{\r\n\tunique_lock<mutex> lock(mMutexStop);\r\n\tif (mbStopped)\r\n\t{\r\n\t\tmbStopped = false;\r\n\t\tmbStopRequested = false;\r\n\t}\r\n\r\n}\r\n\r\nbool EKF_Attitude::Stop()\r\n{\r\n\tunique_lock<mutex> lock(mMutexStop);\r\n\tif (mbStopRequested)\r\n\t{\r\n\t\tmbStopped = true;\r\n\t\treturn true;\r\n\t}\r\n\treturn false;\r\n}\r\n\r\nbool EKF_Attitude::isStopped()\r\n{\r\n\tunique_lock<mutex> lock(mMutexStop);\r\n\treturn mbStopped;\r\n}\r\n\r\nvoid EKF_Attitude::Release()\r\n{\r\n\tunique_lock<mutex> lock(mMutexStop);\r\n\tmbStopped = false;\r\n\tmbStopRequested = false;\r\n\tstate_X_pro.clear();\r\n\tCovrMatrix_P_pro.clear();\r\n\tquaternion.clear();\r\n\r\n\tcout << \"EKF attitude release \" << endl;\r\n}\r\n\r\n}"
  },
  {
    "path": "src/ESKF_Attitude.cpp",
    "content": "#include <iostream>\r\n#include \"math.h\"\r\n#include \"ESKF_Attitude.h\"\r\n#include \"Convert.h\"\r\n\r\n\r\nusing namespace std;\r\n\r\nnamespace IMU\r\n{\r\n\r\nESKF_Attitude::ESKF_Attitude(Vector_12 Covar_Mat, double dt)\r\n{\r\n    deltaT = dt;\r\n\r\n    DetAng_noise = Covar_Mat.block<3, 1>(0, 0);\r\n    DetAngVel_noise = Covar_Mat.block<3, 1>(3, 0);\r\n    Acc_noise = Covar_Mat.block<3, 1>(6, 0);\r\n    Mag_noise = Covar_Mat.block<3, 1>(9, 0);\r\n\r\n    CovarMat_Q = Eigen::Matrix<double, 6, 6>::Zero();\r\n    CovarMat_R = Eigen::Matrix<double, 6, 6>::Zero();\r\n}\r\n\r\nvoid ESKF_Attitude::Param_Change(Vector_12 Covar_Mat)\r\n{\r\n    if (isStopped())\r\n    {\r\n        DetAng_noise = Covar_Mat.block<3, 1>(0, 0);\r\n        DetAngVel_noise = Covar_Mat.block<3, 1>(0, 0);\r\n        Acc_noise = Covar_Mat.block<3, 1>(0, 0);\r\n        Mag_noise = Covar_Mat.block<3, 1>(0, 0);\r\n\r\n        // Initialize the covariances matrices Q and R\r\n\r\n        CovarMat_Q.block<3, 3>(0, 0) = DetAng_noise.asDiagonal();\r\n        CovarMat_Q.block<3, 3>(3, 3) = DetAngVel_noise.asDiagonal();\r\n        CovarMat_R.block<3, 3>(0, 0) = Acc_noise.asDiagonal();\r\n        CovarMat_R.block<3, 3>(3, 3) = Mag_noise.asDiagonal();\r\n    }\r\n}\r\n\r\nvoid ESKF_Attitude::Init_Estimator()\r\n{\r\n    // Initialize the covariances matrices Q and R\r\n\r\n    CovarMat_Q.block<3, 3>(0, 0) = DetAng_noise.asDiagonal();\r\n    CovarMat_Q.block<3, 3>(3, 3) = DetAngVel_noise.asDiagonal();\r\n    CovarMat_R.block<3, 3>(0, 0) = Acc_noise.asDiagonal();\r\n    CovarMat_R.block<3, 3>(3, 3) = Mag_noise.asDiagonal();\r\n\r\n    // Initialize the nominal state\r\n\r\n    //Vector_3 x_state, y_state, z_state;\r\n    //z_state = Cur_Measurement.block<3, 1>(3, 0);\r\n    //y_state = z_state.cross(Cur_Measurement.block<3, 1>(6, 0));\r\n    //x_state = y_state.cross(z_state);\r\n    Eigen::Vector3d Acc0, Gyro0, Mag0;\r\n    Gyro0 = Cur_Measurement.block<3, 1>(0, 0);\r\n    Acc0 = Cur_Measurement.block<3, 1>(3, 0);\r\n    Mag0 = Cur_Measurement.block<3, 1>(6, 0);\r\n\r\n    double Pitch0 = asin(Acc0[0]/Acc0.norm());\r\n    double Roll0 = atan2(-Acc0[1], -Acc0[2]);\r\n    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;\r\n\r\n    Eigen::Quaterniond quat_temp = Euler_to_Quaternion(Eigen::Vector3d(Roll0, Pitch0, Yaw0));\r\n    quat_temp.normalize();\r\n\r\n    Vector_3 AngVel_temp = DetAngVel_noise;\r\n\r\n    IMU_State state;\r\n    state.Nominal_quat = quat_temp;\r\n    state.Nominal_AngVel = AngVel_temp;\r\n\r\n    // Initialize the error state\r\n\r\n    Vector_3 detla_theta, detla_angVel;\r\n    state.Error_theta = Vector_3::Zero();\r\n    state.Error_AngVel = Vector_3::Zero();\r\n    state.Error_Convar = Eigen::Matrix<double, 6, 6>::Zero();\r\n    state.Error_Convar.block<3, 3>(0, 0) = 1e-5*Eigen::Matrix<double, 3, 3>::Identity();\r\n    state.Error_Convar.block<3, 3>(3, 3) = 1e-7*Eigen::Matrix<double, 3, 3>::Identity();\r\n\r\n    State_Vector.push_back(state);\r\n    quaternion.push_back(quat_temp);\r\n\r\n    Last_Measurement = Cur_Measurement;\r\n}\r\n\r\nvoid ESKF_Attitude::NominaState_Predict()\r\n{\r\n    Vector_3 delta_theta;\r\n    Eigen::Quaterniond quat_temp;\r\n    IMU_State Piror_State = State_Vector.back();\r\n    delta_theta = (0.5*(Cur_Measurement.block<3, 1>(0, 0) + Last_Measurement.block<3, 1>(0, 0)) - Piror_State.Nominal_AngVel)*deltaT;\r\n\r\n    quat_temp.w() = 1;\r\n    quat_temp.vec() = 0.5*delta_theta;\r\n    quat_temp = Piror_State.Nominal_quat*quat_temp;\r\n    quat_temp.normalize();\r\n\r\n    IMU_State Post_State;\r\n    Post_State.Nominal_quat = quat_temp;\r\n    Post_State.Nominal_AngVel = Piror_State.Nominal_AngVel;\r\n    State_Vector.push_back(Post_State);\r\n}\r\n\r\nvoid ESKF_Attitude::ErrorState_Predict()\r\n{\r\n    IMU_State Post_State = State_Vector.back();\r\n    State_Vector.pop_back();\r\n    IMU_State Piror_State = State_Vector.back();\r\n\r\n    // calculate the transition matrix A\r\n    Eigen::Matrix<double, 6, 6> Trasition_A;\r\n    Vector_3 delta_theta;\r\n    delta_theta = (Last_Measurement.block<3, 1>(0, 0) - Piror_State.Nominal_AngVel)*deltaT;\r\n    Matrix_3 Rotation_Mat = Euler_to_RoatMat(delta_theta);\r\n\r\n    Trasition_A.block<3, 3>(0, 0) = Rotation_Mat.transpose();\r\n    Trasition_A.block<3, 3>(0, 3) = Matrix_3::Identity()*(-deltaT);\r\n    Trasition_A.block<3, 3>(3, 0) = Matrix_3::Zero();\r\n    Trasition_A.block<3, 3>(3, 3) = Matrix_3::Identity();\r\n\r\n    // priori prediction\r\n\r\n    Vector_6 Errstate_temp;\r\n    Errstate_temp.block<3, 1>(0, 0) = Piror_State.Error_theta;\r\n    Errstate_temp.block<3, 1>(3, 0) = Piror_State.Error_AngVel;\r\n    Errstate_temp = Trasition_A*Errstate_temp;\r\n\r\n    Post_State.Error_theta = Errstate_temp.block<3, 1>(0, 0);\r\n    Post_State.Error_AngVel = Errstate_temp.block<3, 1>(3, 0);\r\n\r\n    Eigen::Matrix<double, 6, 6> CovarMat_Qi = CovarMat_Q*deltaT;\r\n    Eigen::Matrix<double, 6, 6> NoiseMat_Fi = Eigen::Matrix<double, 6, 6>::Identity();\r\n\r\n    Post_State.Error_Convar = Trasition_A*Piror_State.Error_Convar*Trasition_A.transpose() +\r\n                              NoiseMat_Fi*CovarMat_Qi*NoiseMat_Fi.transpose();\r\n\r\n    State_Vector.push_back(Post_State);\r\n}\r\n\r\nEigen::Matrix<double, 6, 6> ESKF_Attitude::IMU_State::Cal_ObserveMat(Vector_9 measurenment, Vector_6 &residual)\r\n{\r\n    Vector_3 True_AccMea, True_MagMre, Mea_Mag;\r\n    Eigen::Matrix<double, 4, 1> Mag_global;\r\n\r\n    Eigen::Quaterniond q = Nominal_quat;\r\n\r\n    Mea_Mag = measurenment.block<3, 1>(6, 0);\r\n    Eigen::Quaterniond Mag_quat(0.0, Mea_Mag(0), Mea_Mag(1), Mea_Mag(2));\r\n    Mag_quat = QuatMult(q, QuatMult(Mag_quat, q.conjugate()));\r\n\r\n    Mag_global <<   0, sqrt(Mag_quat.x()*Mag_quat.x() + Mag_quat.y()*Mag_quat.y()),\r\n            0, Mag_quat.z();\r\n\r\n    // calculate the observe Matrix H\r\n\r\n    Eigen::Matrix<double, 3, 4> acc_H, mag_H;\r\n    acc_H << 2 * q.y(), -2 * q.z(), 2 * q.w(), -2 * q.x(),\r\n            -2 * q.x(), -2 * q.w(), -2 * q.z(), -2 * q.y(),\r\n            0, 4 * q.x(), 4 * q.y(), 0;\r\n\r\n    mag_H << -2 * Mag_global(3)*q.y(), 2 * Mag_global(3)*q.z(),\r\n            -4 * Mag_global(1)*q.y() - 2 * Mag_global(3)*q.w(), -4 * Mag_global(1)*q.z() + 2 * Mag_global(3)*q.x(),\r\n\r\n            -2 * Mag_global(1)*q.z() + 2 * Mag_global(3)*q.x(), 2 * Mag_global(1)*q.y() + 2 * Mag_global(3)*q.w(),\r\n            2 * Mag_global(1)*q.x() + 2 * Mag_global(3)*q.z(), -2 * Mag_global(1)*q.w() + 2 * Mag_global(3)*q.y(),\r\n\r\n            2 * Mag_global(1)*q.y(), 2 * Mag_global(1)*q.z() - 4 * Mag_global(3)*q.x(),\r\n            2 * Mag_global(1)*q.w() - 4 * Mag_global(3)*q.y(), 2 * Mag_global(1)*q.x();\r\n\r\n    Eigen::Matrix<double, 6, 7> Observe_Hx;\r\n    Observe_Hx.block<3, 4>(0, 0) = acc_H;\r\n    Observe_Hx.block<3, 4>(3, 0) = mag_H;\r\n    Observe_Hx.block<3, 3>(0, 4) = Matrix_3::Zero();\r\n    Observe_Hx.block<3, 3>(3, 4) = Matrix_3::Zero();\r\n\r\n    Eigen::Matrix<double, 7, 6> Observe_Xx;\r\n    Eigen::Matrix<double, 4, 3> Matrix_Q;\r\n    Matrix_Q << -q.x(), -q.y(), -q.z(),\r\n            q.w(), -q.z(), q.y(),\r\n            q.z(), q.w(), -q.x(),\r\n            -q.y(), q.x(), q.w();\r\n    Observe_Xx.block<4, 3>(0, 0) = 0.5*Matrix_Q;\r\n    Observe_Xx.block<4, 3>(0, 3) = Eigen::Matrix<double, 4, 3>::Zero();\r\n    Observe_Xx.block<3, 3>(4, 0) = Matrix_3::Zero();\r\n    Observe_Xx.block<3, 3>(4, 3) = Matrix_3::Identity();\r\n\r\n    Eigen::Matrix<double, 6, 6> Observe_Matrix;\r\n    Observe_Matrix = Observe_Hx*Observe_Xx;\r\n\r\n    // Calculate the true measurement\r\n    // the true accelerometer measurement\r\n    True_AccMea <<  -2 * (q.x()*q.z() - q.w()*q.y()),\r\n            -2 * (q.w()*q.x() + q.y()*q.z()),\r\n            -2 * (0.5 - q.x()*q.x() - q.y()*q.y());\r\n\r\n    // the true magnetometer measurement\r\n    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())),\r\n            -(2 * Mag_global(1)*(q.x()*q.y() - q.w()*q.z()) + 2 * Mag_global(3)*(q.w()*q.x() + q.y()*q.z())),\r\n            -(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()));\r\n\r\n    // calculate the residual\r\n    residual.block<3, 1>(0, 0) = measurenment.block<3, 1>(3, 0) + True_AccMea;\r\n    residual.block<3, 1>(3, 0) = measurenment.block<3, 1>(6, 0) + True_MagMre;\r\n\r\n    return Observe_Matrix;\r\n}\r\n\r\nvoid ESKF_Attitude::Update_Filter()\r\n{\r\n    Vector_6 Residual;\r\n    Eigen::Matrix<double, 6, 6> Observe_Matrix;\r\n    IMU_State Post_State = State_Vector.back();\r\n    State_Vector.pop_back();\r\n\r\n    // calculate the observe matrix and the correction residual\r\n    Observe_Matrix = Post_State.Cal_ObserveMat(Cur_Measurement, Residual);\r\n\r\n    //Calculate the kalman gain\r\n    Eigen::Matrix<double, 6, 6> Poste_Cov = Post_State.Error_Convar;\r\n    Eigen::Matrix<double, 6, 6> Kalman_Gain;\r\n    Kalman_Gain = Observe_Matrix*Poste_Cov*Observe_Matrix.transpose() + CovarMat_R;\r\n    Kalman_Gain = Poste_Cov*Observe_Matrix.transpose()*Kalman_Gain.inverse();\r\n\r\n    // update error state\r\n    Vector_6 Post_ErrState = Kalman_Gain*Residual;\r\n    Post_State.Error_theta = Post_ErrState.block<3, 1>(0, 0);\r\n    Post_State.Error_AngVel = Post_ErrState.block<3, 1>(3, 0);\r\n\r\n    Post_State.Error_Convar = Poste_Cov - Kalman_Gain*(Observe_Matrix*Poste_Cov*Observe_Matrix.transpose() +\r\n                                                       CovarMat_R)*Kalman_Gain.transpose();\r\n\r\n    State_Vector.push_back(Post_State);\r\n}\r\n\r\nvoid ESKF_Attitude::Update_NomianState()\r\n{\r\n    IMU_State Post_State = State_Vector.back();\r\n    State_Vector.pop_back();\r\n\r\n    Eigen::Quaterniond delta_q = BuildUpdateQuat(Post_State.Error_theta);\r\n    Post_State.Nominal_quat = Post_State.Nominal_quat*delta_q;\r\n    Post_State.Nominal_quat.normalize();\r\n\r\n    Post_State.Nominal_AngVel = Post_State.Nominal_AngVel + Post_State.Error_AngVel;\r\n\r\n    State_Vector.push_back(Post_State);\r\n    quaternion.push_back(Post_State.Nominal_quat);\r\n}\r\n\r\nvoid ESKF_Attitude::Reset_ErrorState()\r\n{\r\n    IMU_State Post_State = State_Vector.back();\r\n    State_Vector.pop_back();\r\n\r\n    Eigen::Matrix<double, 6, 6> Matrix_G = Eigen::Matrix<double, 6, 6>::Identity();\r\n    //Matrix_3 Ang_Mat = Post_State.Error_theta.asDiagonal();\r\n\r\n    //Matrix_G.block<3, 3>(0, 0) = Matrix_3::Identity() - Ang_Mat;\r\n\r\n\r\n    Post_State.Error_theta = Vector_3::Zero();\r\n    Post_State.Error_AngVel = Vector_3::Zero();\r\n\r\n    Post_State.Error_Convar = Matrix_G*Post_State.Error_Convar*Matrix_G.transpose();\r\n\r\n    State_Vector.push_back(Post_State);\r\n\r\n    Last_Measurement = Cur_Measurement;\r\n}\r\n\r\nvoid ESKF_Attitude::Read_SensorData(Vector_9 measurement)\r\n{\r\n    Vector_3 gyro_mea, acc_mea, mag_mea;\r\n    acc_mea = measurement.block<3, 1>(0, 0);\r\n    gyro_mea = measurement.block<3, 1>(3, 0);\r\n    mag_mea = measurement.block<3, 1>(6, 0);\r\n\r\n    acc_mea.normalize();\r\n    mag_mea.normalize();\r\n\r\n    Cur_Measurement.block<3, 1>(0, 0) = gyro_mea;\r\n    Cur_Measurement.block<3, 1>(3, 0) = acc_mea;\r\n    Cur_Measurement.block<3, 1>(6, 0) = mag_mea;\r\n}\r\n\r\nEigen::Quaterniond ESKF_Attitude::Run(Vector_9 measurement)\r\n{\r\n    while (true)\r\n    {\r\n\r\n        Read_SensorData(measurement);\r\n\r\n        if (State_Vector.size() == 0 || quaternion.size() == 0)\r\n        {\r\n            // Initialize the true state of the estimator\r\n\r\n            Init_Estimator();\r\n        }\r\n        else\r\n        {\r\n            // Predict the nomial and error state\r\n\r\n            NominaState_Predict();\r\n            ErrorState_Predict();\r\n\r\n            // Update the filter parametres\r\n\r\n            Update_Filter();\r\n\r\n            // Uptate the nominal state\r\n\r\n            Update_NomianState();\r\n\r\n            // Reset the error state\r\n\r\n            Reset_ErrorState();\r\n        }\r\n\r\n        if (Stop())\r\n        {\r\n            while (isStopped())\r\n            {\r\n#ifdef _WIN32\r\n\r\n                Sleep(3);\r\n#else\r\n\r\n                usleep(3000);\r\n#endif\r\n\r\n            }\r\n        }\r\n        return quaternion.back();\r\n    }\r\n\r\n}\r\n\r\nvoid ESKF_Attitude::RequestStop()\r\n{\r\n    unique_lock<mutex> lock(mMutexStop);\r\n    mbStopRequested = true;\r\n}\r\n\r\nvoid ESKF_Attitude::RequestStart()\r\n{\r\n    unique_lock<mutex> lock(mMutexStop);\r\n    if (mbStopped)\r\n    {\r\n        mbStopped = false;\r\n        mbStopRequested = false;\r\n    }\r\n\r\n}\r\n\r\nbool ESKF_Attitude::Stop()\r\n{\r\n    unique_lock<mutex> lock(mMutexStop);\r\n    if (mbStopRequested)\r\n    {\r\n        mbStopped = true;\r\n        return true;\r\n    }\r\n    return false;\r\n}\r\n\r\nbool ESKF_Attitude::isStopped()\r\n{\r\n    unique_lock<mutex> lock(mMutexStop);\r\n    return mbStopped;\r\n}\r\n\r\nvoid ESKF_Attitude::Release()\r\n{\r\n    unique_lock<mutex> lock(mMutexStop);\r\n    mbStopped = false;\r\n    mbStopRequested = false;\r\n\r\n    State_Vector.clear();\r\n    quaternion.clear();\r\n\r\n    cout << \"EKF attitude release \" << endl;\r\n}\r\n\r\n}// namespace IMU"
  },
  {
    "path": "src/Mahony_Attitude.cpp",
    "content": "#include <iostream>\r\n#include \"Mahony_Attitude.h\"\r\n#include \"Convert.h\"\r\n\r\nusing namespace std;\r\nnamespace IMU\r\n{\r\n\tMahony_Attitude::Mahony_Attitude(Vector_2 PI, double dt):\r\n\t\t\tmbStopped(false), mbStopRequested(false)\r\n\t{\r\n\t\tKp = PI(0);\r\n\t\tKi = PI(1);\r\n\t\tdeltaT = dt;\r\n\t\tInteg_angular = Vector_3::Zero();\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::Params_Change(Vector_2 PI, double dt)\r\n\t{\r\n\t\tif (isStopped())\r\n\t\t{\r\n\t\t\tKp = PI(0);\r\n\t\t\tKi = PI(1);\r\n\t\t\tdeltaT = dt;\r\n\t\t}\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::Mahony_Estimate()\r\n\t{\r\n\t\tVector_3 angular_vel, acc, mag;\r\n\t\tangular_vel = cur_measurement.block<3, 1>(0, 0);\r\n\t\tacc = cur_measurement.block<3, 1>(3, 0);\r\n\t\tmag = cur_measurement.block<3, 1>(6, 0);\r\n\r\n\t\tEigen::Quaterniond quat_temp;\r\n\t\tVector_3 x_state, y_state, z_state;\r\n\t\tMatrix_3 Rotation_matrix;\r\n\t\t\r\n\t\t// if the quaternion is empty, the quaternion will be initialized by tha accelerometer and magnetometer\r\n\t\tif (quaternion.empty())\r\n\t\t{\r\n\t\t\tz_state = acc;\r\n\t\t\ty_state = z_state.cross(mag);\r\n\t\t\tx_state = y_state.cross(z_state);\r\n\t\t\t\r\n\t\t\tRotation_matrix << x_state, y_state, z_state;\r\n\t\t\tquat_temp = Rotation_matrix;\r\n\t\t\tquaternion.push_back(quat_temp);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\t// get the error from the measurement from accelerometer and magnetometer\r\n\t\t\tquat_temp = quaternion.back();\r\n\t\t\tquat_temp.normalized();\r\n\t\t\tRotation_matrix = quat_temp.toRotationMatrix();\r\n\r\n\t\t\tVector_3 error_acc, error_mag, mag_ned, error_sum;\r\n\t\t\terror_acc = Rotation_matrix.block<3, 1>(0, 2);\r\n\t\t\terror_acc = acc.cross(error_acc);\r\n\r\n\t\t\tmag_ned = Rotation_matrix.transpose()*mag;\r\n\t\t\terror_mag << sqrt(mag_ned(0)*mag_ned(0) + mag_ned(1)*mag_ned(1)), 0, mag_ned(2);\r\n\t\t\terror_mag = Rotation_matrix*error_mag;\r\n\t\t\terror_mag = mag.cross(error_mag);\r\n\t\t\terror_sum = error_acc + error_mag;\r\n\r\n\t\t\t// get the modify value from the error\r\n\t\t\tVector_3 Integ_angular, Correct_angular;\r\n\t\t\tInteg_angular = Integ_angular + Ki*deltaT*error_sum;\r\n\t\t\tCorrect_angular = angular_vel + Kp*error_sum + Integ_angular;\r\n\r\n\t\t\tEigen::Quaterniond Angular_quat;\r\n\t\t\tAngular_quat.w() = 0.0;\r\n\t\t\tAngular_quat.vec() = Correct_angular;\r\n\r\n\t\t\t// update the quaternion refer to the correct angular\r\n\t\t\tEigen::Quaterniond quat_temp_new;\r\n\t\t\tquat_temp_new = QuatMult(quat_temp, Angular_quat);\r\n\t\t\tquat_temp_new.w() = quat_temp_new.w()*0.5*deltaT + quat_temp.w();\r\n\t\t\tquat_temp_new.vec() = quat_temp_new.vec()*0.5*deltaT + quat_temp.vec();\r\n\t\t\tquat_temp_new.normalize();\r\n\t\t\tquaternion.push_back(quat_temp_new);\r\n\t\t}\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::Read_SensorData(Vector_9 measurement)\r\n\t{\r\n\t\tVector_3 gyro_mea, acc_mea, mag_mea;\r\n        acc_mea = measurement.block<3, 1>(0, 0);\r\n\t\tgyro_mea = measurement.block<3, 1>(3, 0);\r\n\t\tmag_mea = measurement.block<3, 1>(6, 0);\r\n\r\n\t\tacc_mea.normalize();\r\n\t\tmag_mea.normalize();\r\n\r\n\t\tcur_measurement.block<3, 1>(0, 0) = gyro_mea;\r\n\t\tcur_measurement.block<3, 1>(3, 0) = acc_mea;\r\n\t\tcur_measurement.block<3, 1>(6, 0) = mag_mea;\r\n\t}\r\n\r\n\tEigen::Quaterniond Mahony_Attitude::Run(Vector_9 measurement)\r\n\t{\r\n\t\twhile (true)\r\n\t\t{\r\n            Read_SensorData(measurement);\r\n\t\t\tMahony_Estimate();\r\n\r\n\t\t\tif (Stop())\r\n\t\t\t{\r\n\t\t\t\twhile (isStopped())\r\n\t\t\t\t{\r\n\t\t\t\t\t#ifdef _WIN32\r\n\t\t\t\t\tSleep(3000);\r\n\t\t\t\t\t#else\r\n\t\t\t\t\tusleep(3000);\r\n\t\t\t\t\t#endif\r\n\t\t\t\t}\r\n\t\t\t}\r\n            return quaternion.back();\r\n\t\t}\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::RequestStop()\r\n\t{\r\n\t\tunique_lock<mutex> lock(mMutexStop);\r\n\t\tmbStopRequested = true;\r\n\r\n\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::RequestStart()\r\n\t{\r\n\t\tunique_lock<mutex> lock(mMutexStop);\r\n\t\tif (mbStopped)\r\n\t\t{\r\n\t\t\tmbStopped = false;\r\n\t\t\tmbStopRequested = false;\r\n\t\t}\r\n\r\n\t}\r\n\r\n\tbool Mahony_Attitude::Stop()\r\n\t{\r\n\t\tunique_lock<mutex> lock(mMutexStop);\r\n\t\tif (mbStopRequested)\r\n\t\t{\r\n\t\t\tmbStopped = true;\r\n\t\t\treturn true;\r\n\t\t}\r\n\t\treturn false;\r\n\t}\r\n\r\n\tbool Mahony_Attitude::isStopped()\r\n\t{\r\n\t\tunique_lock<mutex> lock(mMutexStop);\r\n\t\treturn mbStopped;\r\n\t}\r\n\r\n\tvoid Mahony_Attitude::Release()\r\n\t{\r\n\t\tunique_lock<mutex> lock(mMutexStop);\r\n\t\tmbStopped = false;\r\n\t\tmbStopRequested = false;\r\n\t\t\r\n\t\tInteg_angular = Vector_3::Zero();\r\n\t\tquaternion.clear();\r\n\t\tcout << \"Mahony attitude release \" << endl;\r\n\t}\r\n}"
  }
]