[
  {
    "path": ".gitignore",
    "content": "# Custom\nlog*/\nfigures/\ndata/\niros_paper/\n*.pkl\n*.pt\n_.pylintrc\nsync_gpu.sh\n\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\npip-wheel-metadata/\nshare/python-wheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.nox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n*.py,cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\ndb.sqlite3-journal\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# IPython\nprofile_default/\nipython_config.py\n\n# pyenv\n.python-version\n\n# pipenv\n#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.\n#   However, in case of collaboration, if having platform-specific dependencies or dependencies\n#   having no cross-platform support, pipenv may install dependencies that don't work, or not\n#   install all needed dependencies.\n#Pipfile.lock\n\n# PEP 582; used by e.g. github.com/David-OConnor/pyflow\n__pypackages__/\n\n# Celery stuff\ncelerybeat-schedule\ncelerybeat.pid\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n.dmypy.json\ndmypy.json\n\n# Pyre type checker\n.pyre/\n\n# IDEs\n.idea\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"third_party/g2opy\"]\n\tpath = third_party/g2opy\n\turl = https://github.com/uoip/g2opy.git\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "minimum_pre_commit_version: 2.9.3\ndefault_language_version:\n  # force all unspecified python hooks to run python3\n  python: python3\nrepos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v4.0.1\n    hooks:\n      - id: check-added-large-files\n        name: Check large files (>500kB)\n        args: [\"--maxkb=500\"]\n      - id: trailing-whitespace\n        name: Trim trailing whitespaces\n      - id: end-of-file-fixer\n        name: Add empty line to end of file\n      - id: check-merge-conflict\n        name: Check unresolved merge conflicts\n      - id: check-json\n        name: Check JSON\n      - id: check-yaml\n        name: Check YAML\n      - id: check-toml\n        name: Check TOML\n      - id: check-xml\n        name: Check XML\n  - repo: https://github.com/pycqa/isort\n    rev: 5.10.0\n    hooks:\n      - id: isort\n        name: Reorder python imports\n  - repo: local\n    hooks:\n      - id: yapf\n        name: Run yapf formatter\n        entry: yapf\n        language: system\n        types: [python]\n  - repo: local\n    hooks:\n      - id: pylint\n        name: Run pylint analysis\n        entry: pylint\n        language: system\n        types: [python]\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://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>  <name of author>\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 <https://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    <program>  Copyright (C) <year>  <name of author>\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<https://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<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Continual SLAM\n[**Website**](http://continual-slam.cs.uni-freiburg.de/)\n\nThis repository is the official implementation of the papers **Continual SLAM** and **CoVIO**:\n\n[**arXiv**](https://arxiv.org/abs/2203.01578) | [**Springer**](https://link.springer.com/chapter/10.1007/978-3-031-25555-7_3) | [**Video**](https://youtu.be/ASEzwnV4vNk)\n> **Continual SLAM: Beyond Lifelong Simultaneous Localization and Mapping through Continual Learning** <br>\n> [Niclas Vödisch](https://vniclas.github.io/), [Daniele Cattaneo](https://rl.uni-freiburg.de/people/cattaneo), [Wolfram Burgard](http://www2.informatik.uni-freiburg.de/~burgard/), and [Abhinav Valada](https://rl.uni-freiburg.de/people/valada). <br>\n> *International Symposium on Robotics Research (ISRR)*, 2022\n\n[**arXiv**](https://arxiv.org/abs/2303.10149) | [**IEEE Xplore**](https://ieeexplore.ieee.org/document/10209029)\n> **CoVIO: Online Continual Learning for Visual-Inertial Odometry** <br>\n> [Niclas Vödisch](https://vniclas.github.io/), [Daniele Cattaneo](https://rl.uni-freiburg.de/people/cattaneo), [Wolfram Burgard](http://www2.informatik.uni-freiburg.de/~burgard/), and [Abhinav Valada](https://rl.uni-freiburg.de/people/valada). <br>\n> *IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) Workshops*, 2023\n\n<p align=\"center\">\n  <img src=\"continual_slam_teaser.png\" alt=\"Continual SLAM teaser\" width=\"600\" />\n</p>\n\nIf you find our work useful, please consider citing our papers:\n```\n@InProceedings{voedisch2023clslam,\n  author=\"V{\\\"o}disch, Niclas and Cattaneo, Daniele and Burgard, Wolfram and Valada, Abhinav\",\n  editor=\"Billard, Aude and Asfour, Tamim and Khatib, Oussama\",\n  title=\"Continual SLAM: Beyond Lifelong Simultaneous Localization and Mapping Through Continual Learning\",\n  booktitle=\"Robotics Research\",\n  year=\"2023\",\n  publisher=\"Springer Nature Switzerland\",\n  address=\"Cham\",\n  pages=\"19--35\",\n}\n```\n\n```\n@article{voedisch2023covio,\n  title=\"CoVIO: Online Continual Learning for Visual-Inertial Odometry\",\n  author=\"V{\\\"o}disch, Niclas and Cattaneo, Daniele and Burgard, Wolfram and Valada, Abhinav\",\n  journal=\"IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR) Workshops\",\n  year=\"2023\"\n}\n```\n\n<a href=\"https://github.com/opendr-eu/opendr\"><img src=\"opendr_logo.png\" alt=\"drawing\" width=\"250\"/></a><br>\nCL-SLAM and CoVIO are also featured in the [OpenDR toolkit](https://github.com/opendr-eu/opendr).\n\n## 📔 Abstract\n\n### Continual SLAM\nWhile lifelong SLAM addresses the capability of a robot to adapt to changes within a single environment over time, in this paper we introduce the task of continual SLAM.\nHere, a robot is deployed sequentially in a variety of different environments and has to transfer its knowledge of previously experienced environments to thus far unseen environments, while avoiding catastrophic forgetting.\nThis is particularly relevant in the context of vision-based approaches, where the relevant features vary widely between different environments.\nWe propose a novel approach for solving the continual SLAM problem by introducing CL-SLAM.\nOur approach consists of a dual-network architecture that handles both short-term adaptation and long-term memory retention by incorporating a replay buffer.\nExtensive evaluations of CL-SLAM in three different environments demonstrate that it outperforms several baselines inspired by existing continual learning-based visual odometry methods.\n\n### CoVIO\nVisual odometry is a fundamental task for many applications on mobile devices and robotic platforms.\nSince such applications are oftentimes not limited to predefined target domains and learning-based vision systems are known to generalize poorly to unseen environments, methods for continual adaptation during inference time are of significant interest.\nIn this work, we introduce CoVIO for online continual learning of visual-inertial odometry.\nCoVIO effectively adapts to new domains while mitigating catastrophic forgetting by exploiting experience replay.\nIn particular, we propose a novel sampling strategy to maximize image diversity in a fixed-size replay buffer that targets the limited storage capacity of embedded devices.\nWe further provide an asynchronous version that decouples the odometry estimation from the network weight update step enabling continuous inference in real time.\nWe extensively evaluate CoVIO on various real-world datasets demonstrating that it successfully adapts to new domains while outperforming previous methods.\n\n# 🏗 Setup\n\nClone repository: `git clone --recurse-submodules https://github.com/robot-learning-freiburg/CL-SLAM.git`\n\n## ⚙️ Installation\n- Create conda environment: `conda create --name continual_slam python=3.8`\n- Activate conda environment: `conda activate continual_slam`\n- Install dependencies: `pip install -r requirements.txt`\n- For smooth development, install git hook scripts: `pre-commit install`\n\n## 🔄 Install [g2opy](https://github.com/uoip/g2opy)\nWe use g2o for pose graph optimization.\n- Apply fixes for Eigen version >= 3.3.5: `./third_party/fix_g2opy.py`\n- Install C++ requirements:\n  - `conda install cmake`\n  - `conda install -c conda-forge eigen`\n  - `conda install -c conda-forge suitesparse`\n- Install g2opy:\n```\ncd third_party/g2opy\nmkdir build\ncd build\ncmake -DPYBIND11_PYTHON_VERSION=3.8 ..\nmake -j8        |NOTE: reduce number if running out of memory\ncd ..\n|NOTE: remove any .so file which is not for Python 3.8\npython setup.py install  |NOTE: Ensure that the conda environment is active\n```\n\n## 💾 Data preparation\nTo re-train or run the experiments from our paper, please download and pre-process the respective datasets.\n\n### Cityscapes\nDownload the following files from https://www.cityscapes-dataset.com/downloads/:\n- `leftImg8bit_sequence_trainvaltest.zip` (324GB)\n- `timestamp_sequence.zip` (40MB)\n- `vehicle_sequence.zip` (56MB)\n- `disparity_sequence_trainvaltest.zip` (106GB) (optionally, used for computing the depth error)\n\n### Oxford RobotCar\nDownload the RTK ground truth from https://robotcar-dataset.robots.ox.ac.uk/ground_truth/ (91MB).\n<br>Download the camera models from https://robotcar-dataset.robots.ox.ac.uk/downloads/ (129MB).\n<br>We used the files from https://robotcar-dataset.robots.ox.ac.uk/datasets/2015-08-12-15-04-18/:\n- `2015-08-12-15-04-18_stereo_centre_01.tar`, `...0*.tar` (25GB)\n- `2015-08-12-15-04-18_gps.tar` (20MB)\n\nUndistort the center images:\n```python\npython datasets/robotcar.py <IMG_PATH> <MODELS_PATH>\n```\n\n### KITTI\nDownload the KITTI Odometry data from http://www.cvlibs.net/datasets/kitti/eval_odometry.php:\n- `odometry data set (color, 65 GB)`\n- `odometry ground truth poses (4 MB)`\n\nDownload the KITTI raw data from http://www.cvlibs.net/datasets/kitti/raw_data.php for the runs specified in [`datasets/kitti.py`](datasets/kitti.py) (search for `KITTI_RAW_SEQ_MAPPING`).\n- `[synced+rectified data]`\n\nDownload the ground truth depth from http://www.cvlibs.net/datasets/kitti/eval_depth_all.php (optionally, used for computing the depth error).\n- `annotated depth maps data set (14GB)`\n\nExtract the raw data matching the odometry dataset. Note that sequence 03 is excluded as no IMU data (KITTI raw) has been released.\n```python\npython datasets/kitti.py <RAW_PATH> <ODOMETRY_PATH> --oxts\npython datasets/kitti.py <GT_DEPTH_PATH> <ODOMETRY_PATH> --depth\n```\n\n\n# 🏃 Running the Code\n\n## 🏋 Pre-training\nWe pre-trained CL-SLAM on the Cityscapes Dataset.\nYou can either download the resulting weights, where we masked potentially dynamic objects, or pre-train the DepthNet and PoseNet by yourself by running our code.\n**Note** that you have to adjust the `dataset_path` in [`config/config_pretrain.yaml`](config/config_pretrain.yaml).\n```python\npython main_pretrain.py\n```\nModel weights: https://continual-slam.cs.uni-freiburg.de/downloads/cityscapes_masks_pretrain.zip (Please unzip the file after download.)\n\n\n## 🗺️ Adaptation with CL-SLAM\nFor adaptation, we used the KITTI Odometry Dataset and the Oxford RobotCar Dataset.\nThe experiments in the paper are conducted on the KITTI sequences 09 and 10 as well as on two RobotCar sequences.\n<br>In order to fill the replay buffer with the pre-training data, please run the following script after having adjusted the paths in the file.\nThis can take some time.\n```python\npython make_cityscapes_buffer.py\n```\nIn the configuration file [`config/config_adapt.yaml`](config/config_adapt.yaml), please adjust the following parameters:\n- `Dataset.dataset` --> Set either `Kitti` or `RobotCar`\n- `Dataset.dataset_path` --> Set the path to the data\n- `DepthPosePrediction.load_weights_folder` --> Should be the path to the weights from pre-training or the previous adaptation\n- `Slam.dataset_sequence` --> Set the KITTI sequence, or `1` or `2` for RobotCar\n- `Slam.logging` --> If this is set to true, make sure to enable dataloaders in the [`slam/slam.py`](slam/slam.py) have `with_depths` argument set to `True`, also make sure that you have `gt_depth` in your dataset folder\n\nThen run:\n```python\npython main_adapt.py\n```\n\n## 📒 Notes\n\n### Continual SLAM\nThe originally released code for *Continual SLAM*, i.e., without the extensions of *CoVIO*, can be found under commit [4ac27f6](https://github.com/robot-learning-freiburg/CL-SLAM/tree/4ac27f62478cb8301f73bb294be07b846235fe6a).\n\n### CoVIO\nThe asynchronous variant is provided in the [OpenDR toolkit](https://github.com/opendr-eu/opendr).\n\n\n## 👩‍⚖️ License\n\nFor academic usage, the code is released under the [GPLv3](https://www.gnu.org/licenses/gpl-3.0.en.html) license.\nFor any commercial purpose, please contact the authors.\n\n\n## 🙏 Acknowledgment\n\nThis work was funded by the European Union’s Horizon 2020 research and innovation program under grant agreement No 871449-OpenDR.\n<br><br>\n<a href=\"https://opendr.eu/\"><img src=\"./opendr_logo.png\" alt=\"drawing\" width=\"250\"/></a>\n"
  },
  {
    "path": "config/config_adapt.yaml",
    "content": "Dataset:\n  dataset: Kitti\n#  dataset: RobotCar\n  dataset_path: USER/data/kitti/odometry/dataset\n  frame_ids: [ 0, -1, 1 ]\n  scales: [ 0, 1, 2, 3 ] # Provided by dataloader\n  height: 192\n  width: 640\n\nDepthPosePrediction:\n  train_set: all\n  val_set: 0\n#  train_set: 2015-08-12-15-04-18\n#  val_set: 2015-08-12-15-04-18\n  resnet_depth: 18\n  resnet_pose: 18\n  resnet_pretrained: true\n  scales: [ 0, 1, 2, 3 ]  # Network size\n  learning_rate: 0.0001\n  scheduler_step_size: 15\n  num_workers: 0\n  num_epochs: 20\n  min_depth: .1\n  max_depth:\n  disparity_smoothness: .001\n  velocity_loss_scaling: .05\n  mask_dynamic: False\n  save_frequency: -1\n  save_val_depth: false\n  save_val_depth_batches: 0\n  multiple_gpus: false\n  gpu_ids:\n  batch_size: 3\n  log_path: ./log/slam/c_k9\n  load_weights_folder: ./log/cityscapes/models/weights_025\n  use_wandb: False\n\nReplayBuffer:\n  maximize_diversity: True\n  max_buffer_size: 100\n  similarity_threshold: .95\n  similarity_sampling: False\n  load_path: ./log/slam/c_k9/replay_buffer\n\nLoopClosureDetection:\n  detection_threshold: .99\n  id_threshold: 250\n  num_matches: 1\n\nSlam:\n  dataset_sequence: 6\n  adaptation: True\n  adaptation_epochs: 5\n  min_distance: .2\n  start_frame: 0  # Start mapping after this frame\n  logging: true\n  do_loop_closures: true\n  keyframe_frequency: 5\n  lc_distance_poses: 150  # min num consec poses between lc checks\n"
  },
  {
    "path": "config/config_parser.py",
    "content": "import dataclasses\nimport sys\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import List, Union, get_args, get_origin\n\nimport yaml\n\nfrom datasets import Config as Dataset\nfrom depth_pose_prediction import Config as DepthPosePrediction\nfrom loop_closure_detection import Config as LoopClosureDetection\nfrom slam import Config as Slam\nfrom slam import ReplayBufferConfig as ReplayBuffer\n\n\nclass ConfigParser():\n    def __init__(self, config_file: Union[str, PathLike, Path]) -> None:\n        self.filename = Path(config_file)\n\n        self.config_dict = {}\n        self.dataset = None\n        self.depth_pose = None\n        self.loop_closure = None\n        self.slam = None\n        self.replay_buffer = None\n\n        self.parse()\n\n    def parse(self):\n        with open(self.filename, 'r', encoding='utf-8') as file:\n            self.config_dict = yaml.safe_load(file)\n\n        # Read lists as tuples\n        for config_type in self.config_dict.values():\n            for key, value in config_type.items():\n                if isinstance(value, List):\n                    config_type[key] = tuple(value)\n\n        # Correct wrongly parsed data types\n        for config_type_key, config_type in self.config_dict.items():\n            config_type_class = getattr(sys.modules[__name__], config_type_key)\n            for field in dataclasses.fields(config_type_class):\n                if field.name == 'config_file':\n                    continue\n                value = config_type[field.name]\n                if value is not None:\n                    expected_type = field.type\n                    if get_origin(field.type) is not None:\n                        expected_type = get_origin(field.type)\n                    if expected_type is Union:\n                        expected_type = []\n                        for tp in get_args(field.type):\n                            if get_origin(tp) is not None:\n                                expected_type.append(get_origin(tp))\n                            else:\n                                expected_type.append(tp)\n                    else:\n                        expected_type = [expected_type]\n\n                    # Remove the NoneType before attempting conversions\n                    expected_type = [tp for tp in expected_type if tp is not type(None)]\n\n                    if not any(isinstance(value, tp) for tp in expected_type):\n                        if len(expected_type) == 1:\n                            print(f'[CONFIG] Converting {field.name} from {type(value).__name__} '\n                                  f'to {expected_type[0].__name__}.')\n                            config_type[field.name] = expected_type[0](value)\n                        else:\n                            assert False, 'Found an unknown issue!'\n                elif get_origin(field.type) is Union and type(None) in get_args(field.type):\n                    # Is optional\n                    print(f'[CONFIG] Setting {field.name} to None.')\n                elif get_origin(field.type) is Union:\n                    # Is required\n                    raise ValueError(f'[CONFIG] Required parameter missing: {field.name}')\n                else:\n                    assert False, 'Found an unknown issue!'\n\n        # Add the path to the config file to all Configurations\n        for config_type in self.config_dict.values():\n            config_type['config_file'] = self.filename\n\n        # Convert paths to absolute paths\n        for config_type in self.config_dict.values():\n            for key, value in config_type.items():\n                if isinstance(value, Path):\n                    config_type[key] = value.absolute()\n\n        # Read the sections\n        if 'Dataset' in self.config_dict:\n            self.dataset = Dataset(**self.config_dict['Dataset'])\n        if 'DepthPosePrediction' in self.config_dict:\n            self.depth_pose = DepthPosePrediction(**self.config_dict['DepthPosePrediction'])\n        if 'LoopClosureDetection' in self.config_dict:\n            self.loop_closure = LoopClosureDetection(**self.config_dict['LoopClosureDetection'])\n        if 'Slam' in self.config_dict:\n            self.slam = Slam(**self.config_dict['Slam'])\n        if 'ReplayBuffer' in self.config_dict:\n            self.replay_buffer = ReplayBuffer(**self.config_dict['ReplayBuffer'])\n\n    def __str__(self):\n        string = ''\n        for config_type_name, config_type in self.config_dict.items():\n            string += f'----- {config_type_name} --- START -----\\n'\n            for name, value in config_type.items():\n                if name != 'config_file':\n                    string += f'{name:25} : {value}\\n'\n            string += f'----- {config_type_name} --- END -------\\n'\n        string = string[:-1]\n        return string\n\n\nif __name__ == '__main__':\n    config = ConfigParser('./config.yaml')\n    print(config)\n"
  },
  {
    "path": "config/config_pretrain.yaml",
    "content": "Dataset:\n  type: Cityscapes\n  dataset_path: USER/data/cityscapes\n  scales: [ 0, 1, 2, 3 ] # Provided by dataloader\n  height: 192\n  width: 640\n  frame_ids: [ 0, -1, 1 ]\n\nDepthPosePrediction:\n  train_set: [ train ]\n  val_set: val\n  resnet: 18\n  resnet_pretrained: true\n  scales: [ 0, 1, 2, 3 ]  # Network size\n  learning_rate: 1e-4\n  scheduler_step_size: 15\n  batch_size: 18\n  num_workers: 12\n  num_epochs: 25\n  min_depth: .1\n  max_depth:\n  disparity_smoothness: .001\n  velocity_loss_scaling: .05\n  mask_dynamic: false\n  log_path: ./log/cityscapes\n  save_frequency: 5\n  save_val_depth: true\n  save_val_depth_batches: 1\n  multiple_gpus: true\n  gpu_ids: [ 0 ]\n  load_weights_folder:\n  use_wandb: false\n"
  },
  {
    "path": "datasets/__init__.py",
    "content": "from datasets.cityscapes import Cityscapes\nfrom datasets.config import Dataset as Config\nfrom datasets.kitti import Kitti\nfrom datasets.robotcar import Robotcar\n"
  },
  {
    "path": "datasets/cityscapes.py",
    "content": "import json\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport cv2\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\n\nfrom datasets.utils import Dataset\n\n\nclass Cityscapes(Dataset):\n    def __init__(\n        self,\n        data_path: Union[str, Path, PathLike],\n        subsets: Union[str, List[str], Tuple[str, ...]],\n        frame_ids: Union[List[int], Tuple[int, ...]],\n        scales: Optional[Union[List[int], Tuple[int, ...]]] = None,\n        height: Optional[int] = None,\n        width: Optional[int] = None,\n        do_augmentation: bool = False,\n        views: Union[List[str], Tuple[str, ...]] = ('left', ),\n        with_depth: bool = False,\n        with_mask: bool = False,\n    ) -> None:\n        if any(v != 'left' for v in views):\n            raise ValueError('Cityscapes supports only views = [\"left\"]')\n        super().__init__(data_path, frame_ids, scales, height, width, do_augmentation, views,\n                         with_depth, with_mask)\n\n        # The following subsets are available:\n        # -) train --> used for pretraining\n        # -) val --> used for validation during training\n        # -) test --> not used in the published version\n        # -) frankfurt --> not used in the published version. Refers to \"allFrames_frankfurt\"\n        subsets = (subsets, ) if isinstance(subsets, str) else subsets\n        if any(s not in ['train', 'val', 'test', 'frankfurt'] for s in subsets):\n            raise ValueError('subsets must be one of [\"train\", \"val\", \"test\"]')\n        if 'frankfurt' in subsets and len(subsets) > 1:\n            raise ValueError('The subset \"frankfurt\" cannot be combined with other subsets.')\n        self.subsets = subsets\n\n        self._load_image_filenames()\n        self.vehicle_filenames = self._get_filenames(mode='vehicle')\n        self.timestamp_filenames = self._get_filenames(mode='timestamp')\n        self.disparity_filenames = self._get_filenames(mode='disparity') if self.with_depth else []\n        if self.with_mask:\n            self._load_mask_filenames()\n\n    def _get_filenames(self, mode: str) -> List[Path]:\n        if self.subsets[0] == 'frankfurt':\n            valid_modes = ['rgb_left', 'vehicle', 'timestamp']\n            if mode not in valid_modes:\n                raise ValueError(f'mode must be one of {valid_modes}. [subset == \"frankfurt\"]')\n            mode_dir = {\n                'rgb_left': 'leftImg8bit_allFrames',\n                'vehicle': 'vehicle_allFrames',\n                'timestamp': 'timestamp_allFrames',\n            }[mode]\n            subsets = ('val', )\n        else:\n            valid_modes = ['rgb_left', 'vehicle', 'timestamp', 'disparity', 'mask_left']\n            if mode not in valid_modes:\n                raise ValueError(f'mode must be one of {valid_modes}.')\n            mode_dir = {\n                'rgb_left': 'leftImg8bit_sequence',\n                'vehicle': 'vehicle_sequence',\n                'timestamp': 'timestamp_sequence',\n                'disparity': 'disparity_sequence',\n                'mask_left': 'segm_mask_sequence',\n            }[mode]\n            subsets = self.subsets\n        mode_ext = {\n            'rgb_left': 'png',\n            'vehicle': 'json',\n            'timestamp': 'txt',\n            'disparity': 'png',\n            'mask_left': 'png',\n        }[mode]\n        filenames = []\n        counter_indices = 0\n        for subset in subsets:\n            subset_data_path = self.data_path / mode_dir / subset\n            cities = sorted(subset_data_path.glob('*'))\n            for city_path in cities:\n                city_filenames = sorted(city_path.glob(f'*.{mode_ext}'))\n                filenames += city_filenames\n                city_sequences = self._divide_into_sequences(city_filenames)\n                for city_sequence, count in city_sequences.items():\n                    if city_sequence not in self.sequence_indices:\n                        self.sequence_indices[city_sequence] = (counter_indices,\n                                                                counter_indices + count - 1)\n                        counter_indices += count\n        return filenames\n\n    @staticmethod\n    def _divide_into_sequences(city_filenames: List[Path]) -> Dict[str, int]:\n        # filename: <city>_<seq>_<cnt>_<type>.<ext>\n        # Both <seq> and <cnt> are used in this function to detect the start of a new sequence.\n        filenames = [f.stem for f in city_filenames]\n        city = city_filenames[0].stem.split('_')[0]\n        city_sequences = {}\n        sequence_length = 1\n        sequence_counter = 0\n        for file_1, file_2 in zip(filenames, filenames[1:]):\n            seq_1, seq_2 = int(file_1.split('_')[1]), int(file_2.split('_')[1])\n            cnt_1, cnt_2 = int(file_1.split('_')[2]), int(file_2.split('_')[2])\n            if seq_1 == seq_2 and cnt_1 + 1 == cnt_2:\n                # Continuation of the same sequence\n                sequence_length += 1\n            elif (seq_1 != seq_2) or (seq_1 == seq_2 and cnt_1 + 1 != cnt_2):\n                # New sequence started. Either increment in seq or non-consecutive cnt.\n                city_sequences[f'{city}_{sequence_counter:06}'] = sequence_length\n                sequence_length = 1\n                sequence_counter += 1\n            else:\n                raise RuntimeError('Ran into an unexpected situation.')\n        # Add the final sequence\n        city_sequences[f'{city}_{sequence_counter:06}'] = sequence_length\n        return city_sequences\n\n    def __getitem__(self, index: int) -> Dict[Any, Tensor]:\n        img_filenames, mask_filenames, index, do_color_augmentation, do_flip = self._pre_getitem(\n            index)\n\n        # load the color images\n        item = {('index'): index}\n        original_image_shape = None\n        for frame_id in self.frame_ids:\n            rgb = Image.open(img_filenames[index + frame_id]).convert('RGB')\n            if frame_id == 0:\n                original_image_shape = rgb.size\n            if do_flip:\n                rgb = rgb.transpose(Image.FLIP_LEFT_RIGHT)\n            if len(self.scales) > 0:\n                rgb = self.resize[0](rgb)\n                item[('rgb', frame_id, 0)] = rgb\n            else:\n                item[('rgb', frame_id, -1)] = rgb\n\n        # Adjusting intrinsics to match each scale in the pyramid\n        normalized_camera_matrix, baseline = self._load_camera_calibration(\n            index, original_image_shape)\n        for scale in range(len(self.scales)):\n            camera_matrix, inv_camera_matrix = self._scale_camera_matrix(\n                normalized_camera_matrix, scale)\n            item[('camera_matrix', scale)] = camera_matrix\n            item[('inv_camera_matrix', scale)] = inv_camera_matrix\n        if len(self.scales) == 0:\n            # Load camera matrix of raw image data\n            camera_matrix, baseline = self._load_camera_calibration(index, (1, 1))\n            item[('camera_matrix', -1)] = camera_matrix\n            item[('inv_camera_matrix', -1)] = np.linalg.pinv(camera_matrix)\n\n        # Load mask of potentially dynamic objects\n        if self.with_mask:\n            frame_id = 0\n            mask = Image.open(mask_filenames[index + frame_id])\n            if do_flip:\n                mask = mask.transpose(Image.FLIP_LEFT_RIGHT)\n            if len(self.scales) > 0:\n                mask = self.resize[0](mask)\n                item[('mask', frame_id, 0)] = mask\n            else:\n                item[('mask', frame_id, -1)] = mask\n\n        # Load relative distance (except for first frame)\n        for frame_id in self.frame_ids[1:]:\n            item[('relative_distance', frame_id)] = self._load_relative_distance(index + frame_id)\n\n        # Load unscaled depth based on the provided disparity maps\n        if self.with_depth:\n            for frame_id in self.frame_ids:\n                depth = self._load_depth(index + frame_id, normalized_camera_matrix, baseline,\n                                         original_image_shape)\n                if do_flip:\n                    depth = np.fliplr(depth)\n                item[('depth', frame_id, -1)] = depth\n\n        self._post_getitem(item, do_color_augmentation)  # This will also call _preprocess()\n        return item\n\n    def _load_camera_calibration(\n        self,\n        index: int,\n        image_shape: Tuple[int, int],\n    ) -> Tuple[np.ndarray, float]:\n        \"\"\"\n        Returns the intrinsics matrix normalized by the original image size.\n        \"\"\"\n        width, height = image_shape\n        city = self.vehicle_filenames[index].parent.name\n        subset = self.vehicle_filenames[index].parents[1].name\n        sequence = '_'.join(self.vehicle_filenames[index].name.split('_')[:2])\n        data_path = self.data_path / 'camera' / subset / city\n        # We assume that the camera intrinsics are constant for one recording\n        camera_file = sorted(data_path.glob(f'{sequence}_*_camera.json'))[0]\n        with open(camera_file, 'r', encoding='utf-8') as f:\n            data = json.load(f)\n        intrinsics = data['intrinsic']\n        baseline = data['extrinsic']['baseline']\n        camera_matrix = np.array(\n            [[intrinsics['fx'], 0, intrinsics['u0'], 0], [0, intrinsics['fy'], intrinsics['v0'], 0],\n             [0, 0, 1, 0], [0, 0, 0, 1]],\n            dtype=np.float32)\n        camera_matrix[0, :] /= width\n        camera_matrix[1, :] /= height\n        return camera_matrix, baseline\n\n    def _load_relative_distance(self, index: int) -> float:\n        \"\"\"\n        Distance in meters and with respect to the previous frame.\n        \"\"\"\n        previous_timestamp = np.loadtxt(str(self.timestamp_filenames[index - 1]))\n        current_timestamp = np.loadtxt(str(self.timestamp_filenames[index]))\n        delta_timestamp = (current_timestamp - previous_timestamp) / 1e9  # ns to s\n        with open(self.vehicle_filenames[index - 1], 'r', encoding='utf-8') as f:\n            previous_speed = json.load(f)['speed']\n        with open(self.vehicle_filenames[index], 'r', encoding='utf-8') as f:\n            current_speed = json.load(f)['speed']\n        speed = (previous_speed + current_speed) / 2  # m/s\n        distance = speed * delta_timestamp  # m\n        return distance\n\n    def _load_depth(\n        self,\n        index: int,\n        scaled_camera_matrix: np.ndarray,\n        baseline: float,\n        image_shape: Tuple[int, int],\n    ) -> np.ndarray:\n        \"\"\"\n        Depth in meters computed based on the provided disparity maps.\n        Zero elements encode missing disparity values.\n        \"\"\"\n        disparity = cv2.imread(str(self.disparity_filenames[index]),\n                               cv2.IMREAD_UNCHANGED).astype(np.float32)\n        disparity[disparity > 0] = (disparity[disparity > 0] - 1) / 256  # According to README\n        # Reconstruct the value of the raw data\n        focal_length_x = scaled_camera_matrix[0, 0] * image_shape[0]\n        depth = np.zeros_like(disparity)\n        depth[disparity > 0] = (baseline * focal_length_x) / disparity[disparity > 0]  # m\n        return depth\n\n    def _preprocess(\n        self,\n        item: Dict[Any, Any],\n        augment: Union[Callable, Tuple[Tensor, Optional[float], Optional[float], Optional[float],\n                                       Optional[float]]],\n    ) -> None:\n        # Apply augmentation\n        # Convert to list object as we are changing the size during the iteration\n        for key in list(item.keys()):\n            value = item[key]\n            if 'rgb' in key:\n                k, frame_id, scale = key\n                item[key] = self._to_tensor(value)\n                item[(f'{k}_aug', frame_id, scale)] = self._to_tensor(augment(value))\n            elif 'camera_matrix' in key or 'inv_camera_matrix' in key:\n                item[key] = torch.from_numpy(value)\n            elif 'depth' in key:\n                item[key] = self._to_tensor(value)\n            elif 'mask' in key:\n                item[key] = torch.round(self._to_tensor(value))\n\n\n# if __name__ == '__main__':\n#     dataset = Cityscapes('/home/voedisch/data/cityscapes', ('frankfurt'), (0, -1, 1),\n#                          (0, 1, 2, 3),\n#                          192,\n#                          640,\n#                          with_mask=False,\n#                          with_depth=True)\n#     print(dataset[0].keys())\n"
  },
  {
    "path": "datasets/config.py",
    "content": "import dataclasses\nfrom pathlib import Path\nfrom typing import Optional, Tuple\n\n\n@dataclasses.dataclass\nclass Dataset:\n    dataset: str\n    config_file: Path\n    dataset_path: Optional[Path]\n    scales: Optional[Tuple[int, ...]]\n    height: Optional[int]\n    width: Optional[int]\n    frame_ids: Tuple[int, ...]\n"
  },
  {
    "path": "datasets/kitti.py",
    "content": "# Adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/datasets/kitti_dataset.py\n# https://github.com/nianticlabs/monodepth2/blob/master/datasets/mono_dataset.py#L28\n\nimport argparse\nfrom datetime import datetime\nfrom os import PathLike\nfrom pathlib import Path\nfrom shutil import copyfile\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\nfrom tqdm import tqdm\n\nfrom datasets.utils import Dataset\n\n\nclass Kitti(Dataset):\n    def __init__(\n        self,\n        data_path: Union[str, Path, PathLike],\n        sequences: Union[int, List[int], Tuple[int, ...]],\n        frame_ids: Union[List[int], Tuple[int, ...]],\n        scales: Optional[Union[List[int], Tuple[int, ...]]] = None,\n        height: Optional[int] = None,\n        width: Optional[int] = None,\n        do_augmentation: bool = False,\n        views: Union[List[str], Tuple[str, ...]] = ('left', ),\n        with_depth: bool = False,\n        with_mask: bool = False,\n        poses: bool = False,\n        min_distance: float = 0,\n    ) -> None:\n        super().__init__(data_path,\n                         frame_ids,\n                         scales,\n                         height,\n                         width,\n                         do_augmentation,\n                         views,\n                         with_depth,\n                         with_mask,\n                         min_distance=min_distance)\n\n        # if self.with_depth and (sequences != 8 and sequences[0] != 8):\n        #     raise ValueError('gt_depth only supported for sequence 8')\n\n        self.include_poses = poses\n\n        sequences = (sequences, ) if isinstance(sequences, int) else sequences\n        if any(s > 10 for s in sequences):\n            raise ValueError('Passed a sequence without ground truth data.')\n        if 3 in sequences:\n            raise ValueError('Passed a sequence without IMU data.')\n        self.sequences = sorted(sequences)\n\n        # NOTE: Make sure your intrinsics matrix is *normalized* by the original image size.\n        # To normalize you need to scale the first row by 1 / image_width and the second row\n        # by 1 / image_height. Monodepth2 assumes a principal point to be exactly centered.\n        # If your principal point is far from the center you might need to disable the horizontal\n        # flip augmentation.\n        self.camera_matrix = np.array(\n            [[0.58, 0, 0.5, 0], [0, 1.92, 0.5, 0], [0, 0, 1, 0], [0, 0, 0, 1]], dtype=np.float32)\n\n        self._load_image_filenames()\n        self.left_depth_filenames = self._get_filenames(\n            mode='depth_left') if self.with_depth else []\n        if self.with_mask:\n            self._load_mask_filenames()\n        self.velocity_filenames = self._get_filenames('velocity')\n        self.timestamps = self._load_timestamps()\n        self.global_poses = self._load_global_poses()\n\n        # Make sure that the RGB images and the depth data matches\n        # Adjust other data as well\n        if self.with_depth:\n            assert len(sequences) == 1  # ToDo: update sequence_indices\n            depth_numbers = [int(d.stem) for d in self.left_depth_filenames]\n            tmp_images = []\n            tmp_velocity = []\n            tmp_timestamps = []\n            tmp_masks = []\n            tmp_poses = []\n            for i, img in enumerate(self.left_img_filenames):\n                if int(img.stem) in depth_numbers:\n                    tmp_images.append(img)\n                    tmp_velocity.append(self.velocity_filenames[i])\n                    tmp_timestamps.append(self.timestamps[i])\n                    tmp_poses.append(self.global_poses[i])\n                    if self.with_mask:\n                        tmp_masks.append(self.left_mask_filenames[i])\n            self.left_img_filenames = tmp_images\n            self.velocity_filenames = tmp_velocity\n            self.timestamps = tmp_timestamps\n            self.global_poses = np.stack(tmp_poses)\n            self.left_mask_filenames = tmp_masks\n            self.sequence_indices[sequences[0]] = (0, len(self.left_img_filenames) - 1)\n\n        # Filter data to meet minimum distance requirements\n        self.relative_distances = self._compute_relative_distance()\n        if self.min_distance > 0:\n            assert len(sequences) == 1  # ToDo: update sequence_indices\n            self._filter_by_distance(self.min_distance)\n\n        self.relative_poses = self._load_relative_poses()  # Has to be done in the end\n\n    def _get_filenames(self, mode: str) -> List[Path]:\n        \"\"\"Load the file names of the corresponding subfolders of a sequence.\n        \"\"\"\n        valid_modes = [\n            'rgb_left', 'rgb_right', 'lidar', 'depth_left', 'mask_left', 'mask_right', 'velocity'\n        ]\n        if mode not in valid_modes:\n            raise ValueError(f'mode must be one of {valid_modes}.')\n        mode_dir = {\n            'rgb_left': 'image_2',\n            'rgb_right': 'image_3',\n            'lidar': 'velodyne',\n            'depth_left': 'gt_depth/image_02',\n            'mask_left': 'segm_mask/image_2',\n            'mask_right': 'segm_mask/image_3',\n            'velocity': 'oxts/data',\n        }[mode]\n        mode_ext = {\n            'rgb_left': 'png',\n            'rgb_right': 'png',\n            'lidar': 'bin',\n            'depth_left': 'png',\n            'mask_left': 'png',\n            'mask_right': 'png',\n            'velocity': 'txt',\n        }[mode]\n        filenames = []\n        for sequence in self.sequences:\n            sequence_index = [len(filenames)]\n            sequence_data_path = self.data_path / 'sequences' / f'{sequence:02}' / mode_dir\n            filenames += sorted(sequence_data_path.glob(f'*.{mode_ext}'))\n            sequence_index.append(len(filenames) - 1)\n            if sequence not in self.sequence_indices:\n                self.sequence_indices[sequence] = tuple(sequence_index)\n        return filenames\n\n    def _load_timestamps(self) -> List[int]:\n        timestamp_format = '%Y-%m-%d %H:%M:%S.%f'\n\n        timestamps_ = []\n        for sequence in self.sequences:\n            # Load timestamps as written in the file, e.g., 2011-10-03 12:55:34.997992704\n            timestamps_file = self.data_path / 'sequences' / f'{sequence:02}' / 'oxts' / \\\n                              'timestamps.txt'\n            with open(timestamps_file, 'r', encoding='utf-8') as f:\n                str_timestamps = f.read().splitlines()\n            # Convert relative to timestamp of initial frame and output in seconds\n            # Discard nanoseconds as they are not supported by datetime\n            sequence_timestamps = []\n            for timestamp in str_timestamps:\n                sequence_timestamps.append(\n                    (datetime.strptime(timestamp[:-3], timestamp_format) -\n                     datetime.strptime(str_timestamps[0][:-3], timestamp_format)).total_seconds())\n            timestamps_ += sequence_timestamps\n        return timestamps_\n\n    def _load_global_poses(self) -> np.ndarray:\n        global_poses = []\n        for sequence in self.sequences:\n            # Load global poses\n            poses_data_path = self.data_path / 'poses' / f'{sequence:02}.txt'\n            sequence_poses = np.loadtxt(str(poses_data_path), dtype=np.float32).reshape((-1, 3, 4))\n            # Convert to homogenous coordinates\n            sequence_poses = np.concatenate(\n                (sequence_poses, np.zeros((sequence_poses.shape[0], 1, 4), dtype=np.float32)), 1)\n            sequence_poses[:, 3, 3] = 1\n            global_poses.append(sequence_poses)\n        return np.concatenate(global_poses)\n\n    def _load_relative_poses(self) -> np.ndarray:\n        relative_poses = []\n        for sequence in self.sequences:\n            indices = self.sequence_indices[sequence]\n            sequence_poses = self.global_poses[indices[0]:indices[1] + 1]\n\n            # Convert global poses to poses that are relative to the previous frame\n            # The initial value is zero as there is no previous frame\n            sequence_poses_relative = [np.eye(4, dtype=np.float32)]\n            for i in range(1, len(sequence_poses)):\n                sequence_poses_relative.append(\n                    np.linalg.inv(sequence_poses[i - 1]) @ sequence_poses[i])\n            sequence_poses_relative = np.stack(sequence_poses_relative)\n            relative_poses.append(sequence_poses_relative)\n        return np.concatenate(relative_poses)\n\n    def _compute_relative_distance(self) -> List[float]:\n        relative_distances = [0.]\n        for index in range(1, len(self.timestamps)):\n            relative_distances.append(self._load_relative_distance(index))\n        return relative_distances\n\n    def _filter_by_index(self, keep_indices: Union[np.ndarray, List[int]]) -> None:\n        # Remove all timestamps, images, and velocities without poses\n        self.left_img_filenames = [self.left_img_filenames[i]\n                                   for i in keep_indices] if self.left_img_filenames else []\n        self.right_img_filenames = [self.right_img_filenames[i]\n                                    for i in keep_indices] if self.right_img_filenames else []\n        self.left_mask_filenames = [self.left_mask_filenames[i]\n                                    for i in keep_indices] if self.left_mask_filenames else []\n        self.right_mask_filenames = [self.right_mask_filenames[i]\n                                     for i in keep_indices] if self.right_mask_filenames else []\n        self.left_depth_filenames = [self.left_depth_filenames[i]\n                                     for i in keep_indices] if self.left_depth_filenames else []\n        self.velocity_filenames = [self.velocity_filenames[i] for i in keep_indices]\n        self.timestamps = [self.timestamps[i] for i in keep_indices]\n        self.global_poses = [self.global_poses[i] for i in keep_indices]\n\n    def _filter_by_distance(self, min_distance: float) -> None:\n        distance = 0\n        keep_indices = [0]\n        relative_distances = [0]\n        for i, relative_distance in enumerate(self.relative_distances[1:], start=1):\n            distance += np.abs(relative_distance)\n            if distance >= min_distance:\n                keep_indices.append(i)\n                relative_distances.append(distance)\n                distance = 0\n        self._filter_by_index(keep_indices)\n        # Do no re-compute with function to exploit higher frequency\n        self.relative_distances = relative_distances\n\n    def __getitem__(self, index: int) -> Dict[Any, Tensor]:\n        \"\"\"\n        ('rgb', <frame_id>, <scale>)\n        ('camera_matrix', <scale>)\n        ('inv_camera_matrix', <scale>)\n        ('relative_pose', <frame_id>)        | with respect to frame_id - 1\n\n        <frame_id> is relative to the requested index, i.e., the temporal neighbors\n        <scale> == -1 denotes the original size and is deleted before returning\n        \"\"\"\n\n        img_filenames, mask_filenames, index, do_color_augmentation, do_flip = self._pre_getitem(\n            index)\n\n        # Load the color images\n        item = {('index'): index}\n        original_image_shape = None\n        for frame_id in self.frame_ids:\n            rgb = Image.open(img_filenames[index + frame_id]).convert('RGB')\n            if frame_id == 0:\n                original_image_shape = rgb.size\n            if do_flip:\n                rgb = rgb.transpose(Image.FLIP_LEFT_RIGHT)\n            if len(self.scales) > 0:\n                # Immediately rescale since the images are of various size across the sequences\n                # Keeping the original resolution means that pytorch cannot batch images from\n                #   different sequences\n                rgb = self.resize[0](rgb)\n                item[('rgb', frame_id, 0)] = rgb\n            else:\n                item[('rgb', frame_id, -1)] = rgb\n\n        # Adjusting intrinsics to match each scale in the pyramid\n        for scale in range(len(self.scales)):\n            camera_matrix, inv_camera_matrix = self._scale_camera_matrix(self.camera_matrix, scale)\n            item[('camera_matrix', scale)] = camera_matrix\n            item[('inv_camera_matrix', scale)] = inv_camera_matrix\n        if len(self.scales) == 0:\n            # Load camera matrix of raw image data\n            camera_matrix = self.camera_matrix.copy()\n            camera_matrix[0, :] *= original_image_shape[0]\n            camera_matrix[1, :] *= original_image_shape[1]\n            item[('camera_matrix', -1)] = camera_matrix\n            item[('inv_camera_matrix', -1)] = np.linalg.pinv(camera_matrix)\n\n        # Load mask of potentially dynamic objects\n        if self.with_mask:\n            frame_id = 0\n            mask = Image.open(mask_filenames[index + frame_id])\n            if do_flip:\n                mask = mask.transpose(Image.FLIP_LEFT_RIGHT)\n            if len(self.scales) > 0:\n                mask = self.resize[0](mask)\n                item[('mask', frame_id, 0)] = mask\n            else:\n                item[('mask', frame_id, -1)] = mask\n\n        # Load unscaled depth\n        if self.with_depth:\n            # Debugging checks\n            for frame_id in self.frame_ids:\n                assert int(img_filenames[index + frame_id].stem) == int(\n                    self.left_depth_filenames[index + frame_id].stem)\n\n            for frame_id in self.frame_ids:\n                assert self.views == ('left', )\n                depth = Image.open(self.left_depth_filenames[index + frame_id])\n                if do_flip:\n                    depth = depth.transpose(Image.FLIP_LEFT_RIGHT)\n                item[('depth', frame_id, -1)] = depth\n\n        # Load relative distance (except for first frame)\n        for frame_id in self.frame_ids[1:]:\n            item['relative_distance', frame_id] = self.relative_distances[index + frame_id]\n\n        if self.include_poses:\n            # Load the poses (except for the first frame)\n            for frame_id in self.frame_ids[1:]:\n                item[('relative_pose', frame_id)] = self.relative_poses[index + frame_id]\n                if do_flip:\n                    # We also have to flip the relative pose (rotate around y-axis)\n                    item[('relative_pose', 0)][2, 0] *= -1\n                    item[('relative_pose', 0)][0, 2] *= -1\n                item[('absolute_pose', frame_id)] = self.global_poses[index + frame_id]\n\n        self._post_getitem(item, do_color_augmentation)  # This will also call _preprocess()\n        return item\n\n    def _load_relative_distance(self, index: int) -> float:\n        \"\"\"\n        Distance in meters and with respect to the previous frame.\n        \"\"\"\n        previous_timestamp = self.timestamps[index - 1]\n        current_timestamp = self.timestamps[index]\n        delta_timestamp = current_timestamp - previous_timestamp  # s\n        # Compute speed as norm of forward, leftward, and upward elements\n        previous_speed = np.linalg.norm(np.loadtxt(str(self.velocity_filenames[index - 1]))[8:11])\n        current_speed = np.linalg.norm(np.loadtxt(str(self.velocity_filenames[index]))[8:11])\n        speed = (previous_speed + current_speed) / 2  # m/s\n        distance = speed * delta_timestamp\n        return distance\n\n    def _preprocess(\n        self,\n        item: Dict[Any, Tensor],\n        augment: Union[Callable, Tuple[Tensor, Optional[float], Optional[float], Optional[float],\n                                       Optional[float]]],\n    ) -> None:\n        # Apply augmentation\n        # Convert to list object as we are changing the size during the iteration\n        for key in list(item.keys()):\n            value = item[key]\n            if 'rgb' in key:\n                k, frame_id, scale = key\n                item[key] = self._to_tensor(value)\n                # if self.do_augmentation:\n                item[(f'{k}_aug', frame_id, scale)] = self._to_tensor(augment(value))\n            elif 'camera_matrix' in key or 'inv_camera_matrix' in key:\n                item[key] = torch.from_numpy(value)\n            elif 'depth' in key:\n                item[key] = self._to_tensor(value) / 100  # Convert cm to m\n            elif 'relative_pose' in key or 'absolute_pose' in key:\n                item[key] = self._to_tensor(value)\n            elif 'mask' in key:\n                item[key] = torch.round(self._to_tensor(value))\n\n\n# =========================================================\n\n\ndef extract_raw_data(\n    raw_dataset_path: Path,\n    odometry_dataset_path: Path,\n    oxts: bool = True,\n    gt_depth: bool = False,\n) -> None:\n    # yapf: disable\n    # Mapping between KITTI Raw Drives and KITTI Odometry Sequences\n    KITTI_RAW_SEQ_MAPPING = {\n        0: {'date': '2011_10_03', 'drive': 27, 'start_frame': 0, 'end_frame': 4540},\n        1: {'date': '2011_10_03', 'drive': 42, 'start_frame': 0, 'end_frame': 1100},\n        2: {'date': '2011_10_03', 'drive': 34, 'start_frame': 0, 'end_frame': 4660},\n        # 3:  {'date': '2011_09_26', 'drive': 67, 'start_frame':    0, 'end_frame':  800}, # No IMU\n        4: {'date': '2011_09_30', 'drive': 16, 'start_frame': 0, 'end_frame': 270},\n        5: {'date': '2011_09_30', 'drive': 18, 'start_frame': 0, 'end_frame': 2760},\n        6: {'date': '2011_09_30', 'drive': 20, 'start_frame': 0, 'end_frame': 1100},\n        7: {'date': '2011_09_30', 'drive': 27, 'start_frame': 0, 'end_frame': 1100},\n        8: {'date': '2011_09_30', 'drive': 28, 'start_frame': 1100, 'end_frame': 5170},\n        9: {'date': '2011_09_30', 'drive': 33, 'start_frame': 0, 'end_frame': 1590},\n        10: {'date': '2011_09_30', 'drive': 34, 'start_frame': 0, 'end_frame': 1200},\n    }\n    # yapf: enable\n\n    total_frames = 0\n    for mapping in KITTI_RAW_SEQ_MAPPING.values():\n        total_frames += (mapping['end_frame'] - mapping['start_frame'] + 1)\n\n    if gt_depth:\n        with tqdm(desc='Copying depth files', total=total_frames * 2, unit='files') as pbar:\n            for sequence, mapping in KITTI_RAW_SEQ_MAPPING.items():\n                # This is the improved gt depth using 5 consecutive frames from\n                # \"Sparsity invariant CNNs\", J. Uhrig et al., 3DV, 2017.\n                odometry_sequence_path = odometry_dataset_path / f'{sequence:02}' / 'gt_depth'\n                split = 'val' if sequence == 4 else 'train'\n                raw_sequence_path = raw_dataset_path / split / \\\n                                    f'{mapping[\"date\"]}_drive_{mapping[\"drive\"]:04}_sync' / \\\n                                    'proj_depth' / 'groundtruth'\n                if not raw_sequence_path.exists():\n                    continue\n                for image in ['image_02', 'image_03']:\n                    image_raw_sequence_path = raw_sequence_path / image\n                    (odometry_sequence_path / image).mkdir(exist_ok=True, parents=True)\n                    raw_filenames = sorted(image_raw_sequence_path.glob('*'))\n                    for raw_filename in raw_filenames:\n                        odometry_filename = odometry_sequence_path / image / raw_filename.name\n                        frame = int(raw_filename.stem)\n                        if mapping['start_frame'] <= frame <= mapping['end_frame']:\n                            copyfile(raw_filename, odometry_filename)\n                            pbar.update(1)\n                            pbar.set_postfix({'sequence': sequence})\n\n    if oxts:\n        with tqdm(desc='Copying OXTS files', total=total_frames, unit='files') as pbar:\n            for sequence, mapping in KITTI_RAW_SEQ_MAPPING.items():\n                odometry_sequence_path = odometry_dataset_path / f'{sequence:02}' / 'oxts'\n                raw_sequence_path = raw_dataset_path / \\\n                                    f'{mapping[\"date\"]}' / \\\n                                    f'{mapping[\"date\"]}_drive_{mapping[\"drive\"]:04}_sync' / \\\n                                    'oxts'\n                if not raw_sequence_path.exists():\n                    continue\n                odometry_sequence_path.mkdir(exist_ok=True, parents=True)\n                copyfile(raw_sequence_path / 'dataformat.txt',\n                         odometry_sequence_path / 'dataformat.txt')\n                with open(raw_sequence_path / 'timestamps.txt', 'r', encoding='utf-8') as f:\n                    timestamps = f.readlines()[mapping['start_frame']:mapping['end_frame'] + 1]\n                with open(odometry_sequence_path / 'timestamps.txt', 'w', encoding='utf-8') as f:\n                    f.writelines(timestamps)\n\n                for image in ['data']:\n                    image_raw_sequence_path = raw_sequence_path / image\n                    (odometry_sequence_path / image).mkdir(exist_ok=True, parents=True)\n                    raw_filenames = sorted(image_raw_sequence_path.glob('*'))\n                    for raw_filename in raw_filenames:\n                        odometry_filename = odometry_sequence_path / image / raw_filename.name\n                        frame = int(raw_filename.stem)\n                        if mapping['start_frame'] <= frame <= mapping['end_frame']:\n                            copyfile(raw_filename, odometry_filename)\n                            pbar.update(1)\n                            pbar.set_postfix({'sequence': sequence})\n\n\n# =========================================================\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('raw_path', type=str)\n    parser.add_argument('odom_path', type=str)\n    group = parser.add_mutually_exclusive_group()\n    group.add_argument('--oxts', action='store_true')\n    group.add_argument('--depth', action='store_true')\n    args = parser.parse_args()\n\n    extract_raw_data(Path(args.raw_path), Path(args.odom_path), oxts=args.oxts, gt_depth=args.depth)\n\n    # seq = [i for i in range(11) if i != 3]\n    # dataset = Kitti('/home/voedisch/data/kitti/odometry/dataset',\n    #                 seq, (0, -1, 1), (0, 1, 2, 3),\n    #                 192,\n    #                 640,\n    #                 with_mask=True,\n    #                 poses=True)\n    # print(dataset[0].keys())\n"
  },
  {
    "path": "datasets/robotcar.py",
    "content": "import argparse\nimport bisect\nimport multiprocessing as mp\nimport os\nimport re\nfrom functools import partial\nfrom math import sqrt\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom colour_demosaicing import demosaicing_CFA_Bayer_bilinear as demosaic\nfrom PIL import Image\nfrom scipy.interpolate import interp1d\nfrom scipy.ndimage import map_coordinates\nfrom scipy.spatial.transform import Rotation\nfrom torch import Tensor\nfrom tqdm import tqdm\n\nfrom datasets.utils import Dataset\n\n\nclass Robotcar(Dataset):\n    def __init__(\n        self,\n        data_path: Union[str, Path, PathLike],\n        sequences: Union[str, List[str], Tuple[str, ...]],\n        frame_ids: Union[List[int], Tuple[int, ...]],\n        scales: Optional[Union[List[int], Tuple[int, ...]]] = None,\n        height: Optional[int] = None,\n        width: Optional[int] = None,\n        do_augmentation: bool = False,\n        views: Union[List[str], Tuple[str, ...]] = ('left', ),\n        with_depth: bool = False,\n        with_mask: bool = False,\n        poses: bool = False,\n        min_distance: float = 0,\n        every_n_frame: int = 1,\n        start_frame: int = 750,\n        end_frame: int = -1,\n    ) -> None:\n        if with_mask:\n            raise ValueError('Robotcar does not support loading masks.')\n        if with_depth:\n            raise ValueError('Robotcar does not support loading depth.')\n\n        # This is actually the center\n        if any(v != 'left' for v in views):\n            raise ValueError('Robotcar supports only views = [\"left\"]')\n        super().__init__(data_path,\n                         frame_ids,\n                         scales,\n                         height,\n                         width,\n                         do_augmentation,\n                         views,\n                         with_depth,\n                         with_mask,\n                         min_distance=min_distance)\n\n        self.include_poses = poses\n        self.every_n_frame = every_n_frame\n        self.start_frame = start_frame\n        self.end_frame = end_frame\n\n        sequences = (sequences, ) if isinstance(sequences, str) else sequences\n        self.sequences = sequences\n\n        self._load_image_filenames()\n        self.timestamps = [int(f.stem) for f in self.left_img_filenames]\n        self.camera_matrix = self._load_camera_calibration()\n        self.velocity = self._load_velocity()\n        self.relative_distances = self._compute_relative_distance()\n\n        self.global_poses = None\n        self.relative_poses = None\n        if self.include_poses:\n            self.global_poses = self._load_global_poses()\n\n        # Filter data to meet minimum distance requirements\n        if self.min_distance > 0:\n            self._filter_by_distance(self.min_distance)\n\n        if self.include_poses:\n            self.relative_poses = self._load_relative_poses()  # Has to be done in the end\n\n    def _get_filenames(self, mode: str) -> List[Path]:\n        valid_modes = ['rgb_left']\n        if mode not in valid_modes:\n            raise ValueError(f'mode must be one of {valid_modes}')\n        mode_dir = {\n            'rgb_left': 'stereo/center',\n        }[mode]\n        mode_ext = {\n            'rgb_left': 'png',\n        }[mode]\n        filenames = []\n        for sequence in self.sequences:\n            sequence_index = [len(filenames)]\n            sequence_data_path = self.data_path / sequence / mode_dir\n            filenames += sorted(sequence_data_path.glob(\n                f'*.{mode_ext}'))[self.start_frame:self.end_frame:self.every_n_frame]\n            sequence_index.append(len(filenames) - 1)\n            if sequence not in self.sequence_indices:\n                self.sequence_indices[sequence] = tuple(sequence_index)\n        return filenames\n\n    def _load_velocity(self) -> List[float]:\n        \"\"\"\n        Returns corresponding velocity for each image\n        \"\"\"\n        speed = []\n        for sequence in self.sequences:\n            ins_file = self.data_path / sequence / 'gps' / 'ins.csv'\n            column_list = ['timestamp', 'velocity_north', 'velocity_east', 'velocity_down']\n            data = pd.read_csv(ins_file, usecols=column_list)\n            raw_timestamps = data['timestamp'].to_numpy()\n            raw_speed = np.linalg.norm(data.to_numpy()[:, 1:], axis=1)  # m/s\n            # Linearly interpolate speed for each frame\n            speed = interp1d(raw_timestamps, raw_speed)(self.timestamps)\n        return speed\n\n    def _load_camera_calibration(self) -> np.ndarray:\n        \"\"\"\n        Returns the intrinsics matrix normalized by the original image size.\n        \"\"\"\n        rgb = Image.open(self.left_img_filenames[0]).convert('RGB')\n        width, height = rgb.size\n\n        camera_file = self.data_path / 'camera_models' / 'stereo_narrow_left.txt'\n        with open(camera_file, 'r', encoding='utf-8') as f:\n            vals = [float(x) for x in next(f).split()]\n            focal_length = (vals[0], vals[1])\n            principal_point = (vals[2], vals[3])\n        camera_matrix = np.array(\n            [[focal_length[0], 0, principal_point[0], 0],\n             [0, focal_length[1], principal_point[1], 0], [0, 0, 1, 0], [0, 0, 0, 1]],\n            dtype=np.float32)\n        camera_matrix[0, :] /= width\n        camera_matrix[1, :] /= height\n        return camera_matrix\n\n    def _load_global_poses(self) -> np.ndarray:\n        \"\"\"\n        Reads the poses based on the provided RTK data\n        \"\"\"\n        global_poses = []\n        relative_poses = []\n        for sequence in self.sequences:\n            rtk_file = self.data_path / 'rtk' / sequence / 'rtk.csv'\n            column_list = ['timestamp', 'northing', 'easting', 'down', 'roll', 'pitch', 'yaw']\n            data = pd.read_csv(rtk_file, usecols=column_list)\n            timestamps = data['timestamp'].to_numpy()\n            utm = data.to_numpy()[:, 1:4]\n            rpy = data.to_numpy()[:, 4:]  # pylint: disable=no-member\n            utm -= utm[0, :]  # Set first pose to origin (0, 0, 0) to avoid large numbers\n            utm[:, [1, 2]] = utm[:, [2, 1]]  # Swap y and z axes\n            rpy[:, [1, 2]] = rpy[:, [2, 1]]\n            utm[:, 2] *= -1\n            sequence_poses = list(_xyzrpy_to_tmat(utm, rpy).astype(dtype=np.float32))\n            sequence_poses = _interpolate_poses(timestamps, sequence_poses, self.timestamps,\n                                                self.timestamps[0])\n            sequence_poses = np.stack(sequence_poses)\n            global_poses.append(sequence_poses)\n        return np.concatenate(global_poses)\n\n    def _load_relative_poses(self) -> np.ndarray:\n        relative_poses = []\n        for sequence in self.sequences:\n            indices = self.sequence_indices[sequence]\n            sequence_poses = self.global_poses[indices[0]:indices[1] + 1]\n\n            # Convert global poses to poses that are relative to the previous frame\n            # The initial value is zero as there is no previous frame\n            sequence_poses_relative = [np.eye(4, dtype=np.float32)]\n            for i in range(1, len(sequence_poses)):\n                sequence_poses_relative.append(\n                    np.linalg.inv(sequence_poses[i - 1]) @ sequence_poses[i])\n            sequence_poses_relative = np.stack(sequence_poses_relative)\n            relative_poses.append(sequence_poses_relative)\n        return np.concatenate(relative_poses)\n\n    def _compute_relative_distance(self) -> List[float]:\n        relative_distances = [0.]\n        for index in range(1, len(self.timestamps)):\n            relative_distances.append(self._load_relative_distance(index))\n        return relative_distances\n\n    def _filter_by_index(self, keep_indices: Union[np.ndarray, List[int]]) -> None:\n        # Remove all timestamps, images, and velocities without poses\n        self.left_img_filenames = [self.left_img_filenames[i]\n                                   for i in keep_indices] if self.left_img_filenames else []\n        self.right_img_filenames = [self.right_img_filenames[i]\n                                    for i in keep_indices] if self.right_img_filenames else []\n        self.left_mask_filenames = [self.left_mask_filenames[i]\n                                    for i in keep_indices] if self.left_mask_filenames else []\n        self.right_mask_filenames = [self.right_mask_filenames[i]\n                                     for i in keep_indices] if self.right_mask_filenames else []\n        self.velocity = [self.velocity[i] for i in keep_indices]\n        self.timestamps = [self.timestamps[i] for i in keep_indices]\n        self.global_poses = [self.global_poses[i] for i in keep_indices]\n\n    def _filter_by_distance(self, min_distance: float) -> None:\n        distance = 0\n        keep_indices = [0]\n        relative_distances = [0]\n        for i, relative_distance in enumerate(self.relative_distances[1:], start=1):\n            distance += np.abs(relative_distance)\n            if distance >= min_distance:\n                keep_indices.append(i)\n                relative_distances.append(distance)\n                distance = 0\n        self._filter_by_index(keep_indices)\n        # Do no re-compute with function to exploit higher frequency\n        self.relative_distances = relative_distances\n\n    def __getitem__(self, index: int) -> Dict[Any, Tensor]:\n        img_filenames, mask_filenames, index, do_color_augmentation, do_flip = self._pre_getitem(\n            index)\n\n        # Load the color images\n        item = {('index'): index}\n        original_image_shape = None\n        for frame_id in self.frame_ids:\n            rgb = Image.open(img_filenames[index + frame_id]).convert('RGB')\n            if frame_id == 0:\n                original_image_shape = rgb.size\n            if do_flip:\n                rgb = rgb.transpose(Image.FLIP_LEFT_RIGHT)\n            if len(self.scales) > 0:\n                # Immediately rescale since the images are of various size across the sequences\n                # Keeping the original resolution means that pytorch cannot batch images from\n                #   different sequences\n                rgb = self.resize[0](rgb)\n                item[('rgb', frame_id, 0)] = rgb\n            else:\n                item[('rgb', frame_id, -1)] = rgb\n\n        # Adjusting intrinsics to match each scale in the pyramid\n        for scale in range(len(self.scales)):\n            camera_matrix, inv_camera_matrix = self._scale_camera_matrix(self.camera_matrix, scale)\n            item[('camera_matrix', scale)] = camera_matrix\n            item[('inv_camera_matrix', scale)] = inv_camera_matrix\n        if len(self.scales) == 0:\n            # Load camera matrix of raw image data\n            camera_matrix = self.camera_matrix.copy()\n            camera_matrix[0, :] *= original_image_shape[0]\n            camera_matrix[1, :] *= original_image_shape[1]\n            item[('camera_matrix', -1)] = camera_matrix\n            item[('inv_camera_matrix', -1)] = np.linalg.pinv(camera_matrix)\n\n        # Load relative distance (except for first frame)\n        for frame_id in self.frame_ids[1:]:\n            item['relative_distance', frame_id] = self.relative_distances[index + frame_id]\n\n        if self.include_poses:\n            # Load the poses (except for the first frame)\n            for frame_id in self.frame_ids[1:]:\n                item['relative_pose', frame_id] = self.relative_poses[index + frame_id]\n                if do_flip:\n                    # We also have to flip the relative pose (rotate around y-axis)\n                    item[('relative_pose', 0)][2, 0] *= -1\n                    item[('relative_pose', 0)][0, 2] *= -1\n                item[('absolute_pose', frame_id)] = self.global_poses[index + frame_id]\n\n        self._post_getitem(item, do_color_augmentation)  # This will also call _preprocess()\n        return item\n\n    def _load_relative_distance(self, index: int) -> float:\n        \"\"\"\n        Distance in meters and with respect to the previous frame\n        \"\"\"\n        previous_timestamp = self.timestamps[index - 1]\n        current_timestamp = self.timestamps[index]\n        delta_timestamp = (current_timestamp - previous_timestamp) / 1e6  # ms to s\n        speed = self.velocity[index]  # m/s\n        distance = speed * delta_timestamp  # m\n        return distance\n\n    def _preprocess(\n        self,\n        item: Dict[Any, Tensor],\n        augment: Union[Callable, Tuple[Tensor, Optional[float], Optional[float], Optional[float],\n                                       Optional[float]]],\n    ) -> None:\n        # Apply augmentation\n        # Convert to list object as we are changing the size during the iteration\n        for key in list(item.keys()):\n            value = item[key]\n            if 'rgb' in key:\n                k, frame_id, scale = key\n                item[key] = self._to_tensor(value)\n                # if self.do_augmentation:\n                item[(f'{k}_aug', frame_id, scale)] = self._to_tensor(augment(value))\n            elif 'camera_matrix' in key or 'inv_camera_matrix' in key:\n                item[key] = torch.from_numpy(value)\n            elif 'relative_pose' in key or 'absolute_pose' in key:\n                item[key] = self._to_tensor(value)\n\n\n# =========================================================\n\n\ndef _xyzrpy_to_tmat(utm: np.ndarray, rpy: np.ndarray) -> np.ndarray:\n    assert utm.shape == rpy.shape\n\n    poses = np.array([np.eye(4)] * utm.shape[0])\n    poses[:, :3, :3] = Rotation.from_euler('zyx', rpy).as_matrix()\n    poses[:, :3, 3] = utm\n    return poses\n\n\n# Adapted from:\n# https://github.com/ori-mrg/robotcar-dataset-sdk/blob/master/python/interpolate_poses.py\ndef _interpolate_poses(pose_timestamps,\n                       abs_poses,\n                       requested_timestamps_,\n                       origin_timestamp,\n                       absolute_poses=False):\n    \"\"\"Interpolate between absolute poses.\n    Args:\n        pose_timestamps (list[int]): Timestamps of supplied poses. Must be in ascending order.\n        abs_poses (list[numpy.matrixlib.defmatrix.matrix]): SE3 matrices representing poses at the\n        timestamps specified.\n        requested_timestamps (list[int]): Timestamps for which interpolated timestamps are required.\n        origin_timestamp (int): UNIX timestamp of origin frame. Poses will be reported relative to\n        this frame.\n    Returns:\n        list[numpy.matrixlib.defmatrix.matrix]: SE3 matrix representing interpolated pose for each\n        requested timestamp.\n    Raises:\n        ValueError: if pose_timestamps and abs_poses are not the same length\n        ValueError: if pose_timestamps is not in ascending order\n    \"\"\"\n    requested_timestamps = requested_timestamps_.copy()\n    requested_timestamps.insert(0, origin_timestamp)\n    requested_timestamps = np.array(requested_timestamps)\n    pose_timestamps = np.array(pose_timestamps)\n\n    if len(pose_timestamps) != len(abs_poses):\n        raise ValueError('Must supply same number of timestamps as poses')\n\n    abs_quaternions = np.zeros((4, len(abs_poses)))\n    abs_positions = np.zeros((3, len(abs_poses)))\n    for i, pose in enumerate(abs_poses):\n        if i > 0 and pose_timestamps[i - 1] >= pose_timestamps[i]:\n            raise ValueError('Pose timestamps must be in ascending order')\n\n        abs_quaternions[:, i] = _so3_to_quaternion(pose[0:3, 0:3])\n        abs_positions[:, i] = np.ravel(pose[0:3, 3])\n\n    upper_indices = [bisect.bisect(pose_timestamps, pt) for pt in requested_timestamps]\n    if max(upper_indices) >= len(pose_timestamps):\n        upper_indices = [min(i, len(pose_timestamps) - 1) for i in upper_indices]\n    lower_indices = [u - 1 for u in upper_indices]\n\n    fractions = (requested_timestamps - pose_timestamps[lower_indices]) / \\\n                (pose_timestamps[upper_indices] - pose_timestamps[lower_indices])\n\n    quaternions_lower = abs_quaternions[:, lower_indices]\n    quaternions_upper = abs_quaternions[:, upper_indices]\n\n    d_array = (quaternions_lower * quaternions_upper).sum(0)\n\n    linear_interp_indices = np.nonzero(d_array >= 1)\n    sin_interp_indices = np.nonzero(d_array < 1)\n\n    scale0_array = np.zeros(d_array.shape)\n    scale1_array = np.zeros(d_array.shape)\n\n    scale0_array[linear_interp_indices] = 1 - fractions[linear_interp_indices]\n    scale1_array[linear_interp_indices] = fractions[linear_interp_indices]\n\n    theta_array = np.arccos(np.abs(d_array[sin_interp_indices]))\n\n    scale0_array[sin_interp_indices] = \\\n        np.sin((1 - fractions[sin_interp_indices]) * theta_array) / np.sin(theta_array)\n    scale1_array[sin_interp_indices] = \\\n        np.sin(fractions[sin_interp_indices] * theta_array) / np.sin(theta_array)\n\n    negative_d_indices = np.nonzero(d_array < 0)\n    scale1_array[negative_d_indices] = -scale1_array[negative_d_indices]\n\n    quaternions_interp = np.tile(scale0_array, (4, 1)) * quaternions_lower \\\n                         + np.tile(scale1_array, (4, 1)) * quaternions_upper\n\n    positions_lower = abs_positions[:, lower_indices]\n    positions_upper = abs_positions[:, upper_indices]\n\n    positions_interp = np.multiply(np.tile((1 - fractions), (3, 1)), positions_lower) \\\n                       + np.multiply(np.tile(fractions, (3, 1)), positions_upper)\n\n    poses_mat = np.zeros((4, 4 * len(requested_timestamps)))\n\n    poses_mat[0, 0::4] = 1 - 2 * np.square(quaternions_interp[2, :]) - \\\n                         2 * np.square(quaternions_interp[3, :])\n    poses_mat[0, 1::4] = 2 * np.multiply(quaternions_interp[1, :], quaternions_interp[2, :]) - \\\n                         2 * np.multiply(quaternions_interp[3, :], quaternions_interp[0, :])\n    poses_mat[0, 2::4] = 2 * np.multiply(quaternions_interp[1, :], quaternions_interp[3, :]) + \\\n                         2 * np.multiply(quaternions_interp[2, :], quaternions_interp[0, :])\n\n    poses_mat[1, 0::4] = 2 * np.multiply(quaternions_interp[1, :], quaternions_interp[2, :]) \\\n                         + 2 * np.multiply(quaternions_interp[3, :], quaternions_interp[0, :])\n    poses_mat[1, 1::4] = 1 - 2 * np.square(quaternions_interp[1, :]) \\\n                         - 2 * np.square(quaternions_interp[3, :])\n    poses_mat[1, 2::4] = 2 * np.multiply(quaternions_interp[2, :], quaternions_interp[3, :]) - \\\n                         2 * np.multiply(quaternions_interp[1, :], quaternions_interp[0, :])\n\n    poses_mat[2, 0::4] = 2 * np.multiply(quaternions_interp[1, :], quaternions_interp[3, :]) - \\\n                         2 * np.multiply(quaternions_interp[2, :], quaternions_interp[0, :])\n    poses_mat[2, 1::4] = 2 * np.multiply(quaternions_interp[2, :], quaternions_interp[3, :]) + \\\n                         2 * np.multiply(quaternions_interp[1, :], quaternions_interp[0, :])\n    poses_mat[2, 2::4] = 1 - 2 * np.square(quaternions_interp[1, :]) - \\\n                         2 * np.square(quaternions_interp[2, :])\n\n    poses_mat[0:3, 3::4] = positions_interp\n    poses_mat[3, 3::4] = 1\n\n    if not absolute_poses:\n        poses_mat = np.linalg.solve(poses_mat[0:4, 0:4], poses_mat)\n\n    poses_out = [np.empty(0)] * (len(requested_timestamps) - 1)\n    for i in range(1, len(requested_timestamps)):\n        poses_out[i - 1] = np.asarray(poses_mat[0:4, i * 4:(i + 1) * 4])\n\n    return poses_out\n\n\n# Adapted from:\n# https://github.com/ori-mrg/robotcar-dataset-sdk/blob/master/python/transform.py\ndef _so3_to_quaternion(so3):\n    \"\"\"Converts an SO3 rotation matrix to a quaternion\n    Args:\n        so3: 3x3 rotation matrix\n    Returns:\n        numpy.ndarray: quaternion [w, x, y, z]\n    Raises:\n        ValueError: if so3 is not 3x3\n    \"\"\"\n    if so3.shape != (3, 3):\n        raise ValueError('SO3 matrix must be 3x3')\n\n    R_xx = so3[0, 0]\n    R_xy = so3[0, 1]\n    R_xz = so3[0, 2]\n    R_yx = so3[1, 0]\n    R_yy = so3[1, 1]\n    R_yz = so3[1, 2]\n    R_zx = so3[2, 0]\n    R_zy = so3[2, 1]\n    R_zz = so3[2, 2]\n\n    try:\n        w = sqrt(so3.trace() + 1) / 2\n    except ValueError:\n        # w is non-real\n        w = 0\n\n    # Due to numerical precision the value passed to `sqrt` may be a negative of the order 1e-15.\n    # To avoid this error we clip these values to a minimum value of 0.\n    x = sqrt(max(1 + R_xx - R_yy - R_zz, 0)) / 2\n    y = sqrt(max(1 + R_yy - R_xx - R_zz, 0)) / 2\n    z = sqrt(max(1 + R_zz - R_yy - R_xx, 0)) / 2\n\n    max_index = max(range(4), key=[w, x, y, z].__getitem__)\n\n    if max_index == 0:\n        x = (R_zy - R_yz) / (4 * w)\n        y = (R_xz - R_zx) / (4 * w)\n        z = (R_yx - R_xy) / (4 * w)\n    elif max_index == 1:\n        w = (R_zy - R_yz) / (4 * x)\n        y = (R_xy + R_yx) / (4 * x)\n        z = (R_zx + R_xz) / (4 * x)\n    elif max_index == 2:\n        w = (R_xz - R_zx) / (4 * y)\n        x = (R_xy + R_yx) / (4 * y)\n        z = (R_yz + R_zy) / (4 * y)\n    elif max_index == 3:\n        w = (R_yx - R_xy) / (4 * z)\n        x = (R_zx + R_xz) / (4 * z)\n        y = (R_yz + R_zy) / (4 * z)\n\n    return np.array([w, x, y, z])\n\n\n# =========================================================\n\n\n# Use this function to save undistorted copies of the raw images provided in RobotCar\ndef undistort_images(data_path_in: str, models_path: str) -> None:\n    data_path_out = data_path_in\n    data_path_in = data_path_in.rstrip('/') + '_distorted'\n    os.rename(data_path_out, data_path_in)\n    Path(data_path_out).mkdir(parents=True, exist_ok=True)\n\n    model = CameraModel(models_path, data_path_in)\n    image_files = sorted(x for x in Path(data_path_in).glob('*.png'))\n    # The other photos are overexposed or taken when the car was not (yet) on the road\n    image_files = image_files[1112:-147]\n\n    num_workers = mp.cpu_count() - 1\n    with tqdm(total=len(image_files)) as pbar:\n        with mp.Pool(num_workers) as pool:\n            for _ in pool.imap_unordered(\n                    partial(_undistort, data_path_out=data_path_out, model=model), image_files):\n                pbar.update(1)\n\n\ndef _undistort(image_file: Path, data_path_out: str, model):\n    new_image_file = Path(data_path_out) / image_file.name\n    if not new_image_file.exists():\n        image = Image.fromarray(_load_image(str(image_file), model))\n        image.save(new_image_file)\n\n\n# Adapted from:\n# https://github.com/ori-mrg/robotcar-dataset-sdk/blob/master/python/image.py\ndef _load_image(image_path, model=None, debayer=True):\n    \"\"\"Loads and rectifies an image from file.\n    Args:\n        image_path (str): path to an image from the dataset.\n        model (camera_model.CameraModel): if supplied, model will be used to undistort image.\n    Returns:\n        numpy.ndarray: demosaiced and optionally undistorted image\n    \"\"\"\n    BAYER_STEREO = 'gbrg'\n    BAYER_MONO = 'rggb'\n\n    if model:\n        camera = model.camera\n    else:\n        camera = re.search('(stereo|mono_(left|right|rear))', image_path).group(0)\n    if camera == 'stereo':\n        pattern = BAYER_STEREO\n    else:\n        pattern = BAYER_MONO\n\n    img = Image.open(image_path)\n    if debayer:\n        img = demosaic(img, pattern)\n    if model:\n        img = model.undistort(img)\n\n    return np.array(img).astype(np.uint8)\n\n\n# Adapted from:\n# https://github.com/ori-mrg/robotcar-dataset-sdk/blob/master/python/camera_model.py\nclass CameraModel:\n    \"\"\"Provides intrinsic parameters and undistortion LUT for a camera.\n    Attributes:\n        camera (str): Name of the camera.\n        camera sensor (str): Name of the sensor on the camera for multi-sensor cameras.\n        focal_length (tuple[float]): Focal length of the camera in horizontal and vertical axis,\n        in pixels.\n        principal_point (tuple[float]): Principal point of camera for pinhole projection model,\n        in pixels.\n        G_camera_image (:obj: `numpy.matrixlib.defmatrix.matrix`): Transform from image frame to\n        camera frame.\n        bilinear_lut (:obj: `numpy.ndarray`): Look-up table for undistortion of images, mapping\n        pixels in an undistorted\n            image to pixels in the distorted image\n    \"\"\"\n    def __init__(self, models_dir, images_dir):\n        \"\"\"Loads a camera model from disk.\n        Args:\n            models_dir (str): directory containing camera model files.\n            images_dir (str): directory containing images for which to read camera model.\n        \"\"\"\n        self.camera = None\n        self.camera_sensor = None\n        self.focal_length = None\n        self.principal_point = None\n        self.G_camera_image = None\n        self.bilinear_lut = None\n\n        self.__load_intrinsics(models_dir, images_dir)\n        self.__load_lut(models_dir, images_dir)\n\n    def project(self, xyz, image_size):\n        \"\"\"Projects a pointcloud into the camera using a pinhole camera model.\n        Args:\n            xyz (:obj: `numpy.ndarray`): 3xn array, where each column is (x, y, z) point relative\n            to camera frame.\n            image_size (tuple[int]): dimensions of image in pixels\n        Returns:\n            numpy.ndarray: 2xm array of points, where each column is the (u, v) pixel coordinates\n            of a point in pixels.\n            numpy.array: array of depth values for points in image.\n        Note:\n            Number of output points m will be less than or equal to number of input points n, as\n            points that do not\n            project into the image are discarded.\n        \"\"\"\n        if xyz.shape[0] == 3:\n            xyz = np.stack((xyz, np.ones((1, xyz.shape[1]))))\n        xyzw = np.linalg.solve(self.G_camera_image, xyz)\n\n        # Find which points lie in front of the camera\n        in_front = [i for i in range(0, xyzw.shape[1]) if xyzw[2, i] >= 0]\n        xyzw = xyzw[:, in_front]\n\n        uv = np.vstack((self.focal_length[0] * xyzw[0, :] / xyzw[2, :] + self.principal_point[0],\n                        self.focal_length[1] * xyzw[1, :] / xyzw[2, :] + self.principal_point[1]))\n\n        in_img = [\n            i for i in range(0, uv.shape[1])\n            if 0.5 <= uv[0, i] <= image_size[1] and 0.5 <= uv[1, i] <= image_size[0]\n        ]\n\n        return uv[:, in_img], np.ravel(xyzw[2, in_img])\n\n    def undistort(self, image):\n        \"\"\"Undistorts an image.\n        Args:\n            image (:obj: `numpy.ndarray`): A distorted image. Must be demosaiced - ie. must be a\n            3-channel RGB image.\n        Returns:\n            numpy.ndarray: Undistorted version of image.\n        Raises:\n            ValueError: if image size does not match camera model.\n            ValueError: if image only has a single channel.\n        \"\"\"\n        if image.shape[0] * image.shape[1] != self.bilinear_lut.shape[0]:\n            raise ValueError('Incorrect image size for camera model')\n\n        lut = self.bilinear_lut[:, 1::-1].T.reshape((2, image.shape[0], image.shape[1]))\n\n        if len(image.shape) == 1:\n            raise ValueError('Undistortion function only works with multi-channel images')\n\n        undistorted = np.rollaxis(\n            np.array([\n                map_coordinates(image[:, :, channel], lut, order=1)\n                for channel in range(0, image.shape[2])\n            ]), 0, 3)\n\n        return undistorted.astype(image.dtype)\n\n    def __get_model_name(self, images_dir):\n        self.camera = re.search('(stereo|mono_(left|right|rear))', images_dir).group(0)\n        if self.camera == 'stereo':\n            self.camera_sensor = re.search('(left|center_distorted|centre_distorted|right)',\n                                           images_dir).group(0)\n            if self.camera_sensor == 'left':\n                return 'stereo_wide_left'\n            if self.camera_sensor == 'right':\n                return 'stereo_wide_right'\n            if self.camera_sensor in ['center_distorted', 'centre_distorted']:\n                return 'stereo_narrow_left'\n            raise RuntimeError('Unknown camera model for given directory: ' + images_dir)\n        return self.camera\n\n    def __load_intrinsics(self, models_dir, images_dir):\n        model_name = self.__get_model_name(images_dir)\n        intrinsics_path = os.path.join(models_dir, model_name + '.txt')\n\n        with open(intrinsics_path, 'r', encoding='utf-8') as intrinsics_file:\n            vals = [float(x) for x in next(intrinsics_file).split()]\n            self.focal_length = (vals[0], vals[1])\n            self.principal_point = (vals[2], vals[3])\n\n            G_camera_image = []\n            for line in intrinsics_file:\n                G_camera_image.append([float(x) for x in line.split()])\n            self.G_camera_image = np.array(G_camera_image)\n\n    def __load_lut(self, models_dir, images_dir):\n        model_name = self.__get_model_name(images_dir)\n        lut_path = os.path.join(models_dir, model_name + '_distortion_lut.bin')\n\n        lut = np.fromfile(lut_path, np.double)\n        lut = lut.reshape([2, lut.size // 2])\n        self.bilinear_lut = lut.transpose()\n\n\n# =========================================================\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser()\n    parser.add_argument('img_path', type=str)\n    parser.add_argument('models_path', type=str)\n    args = parser.parse_args()\n\n    undistort_images(args.img_path, args.models_path)\n\n    # dataset = Robotcar('/home/voedisch/data/robotcar',\n    #                    '2015-08-12-15-04-18', (0, -1, 1), (0, 1, 2, 3),\n    #                    192,\n    #                    640,\n    #                    poses=True)\n    # print(dataset[0].keys())\n"
  },
  {
    "path": "datasets/utils.py",
    "content": "import pickle\nimport random\nfrom abc import abstractmethod\nfrom os import PathLike\nfrom pathlib import Path\nfrom typing import Any, Callable, Dict, List, Optional, Tuple, Union\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torchvision.transforms.functional as F\nfrom torch import Tensor\nfrom torch.utils.data import Dataset as TorchDataset\nfrom torchvision import transforms\nfrom torchvision.transforms import Compose, Lambda\n\n\nclass Dataset(TorchDataset):\n    def __init__(\n        self,\n        data_path: Union[str, Path, PathLike],\n        frame_ids: Union[List[int], Tuple[int, ...]],\n        scales: Optional[Union[List[int], Tuple[int, ...]]] = None,\n        height: Optional[int] = None,\n        width: Optional[int] = None,\n        do_augmentation: bool = False,\n        views: Union[List[str], Tuple[str, ...]] = ('left', ),\n        with_depth: bool = False,\n        with_mask: bool = False,\n        use_cache: bool = False,\n        min_distance: float = 0,\n    ) -> None:\n        super().__init__()\n\n        if any(v not in ['left', 'right'] for v in views):\n            raise ValueError('views must be one of [\"left\", \"right\"]')\n        if sum(x is None for x in [scales, height, width]) == 1:\n            raise ValueError('Either none or all of [scales, height, width] must be omitted.')\n\n        self.data_path = Path(data_path)\n        self.frame_ids = sorted(frame_ids)\n        self.scales = scales if scales is not None else ()\n        self.height = height\n        self.width = width\n        self.do_augmentation = do_augmentation\n        self.views = tuple(set(views))\n        self.with_depth = with_depth\n        self.with_mask = with_mask\n        self.min_distance = min_distance  # Minimum distance between poses [in meters]\n\n        # If loading from the original source takes some time, we cache the extracted data\n        self.use_cache = use_cache\n        self.cache_file = None\n\n        # Data augmentation\n        self.brightness = (0.8, 1.2)\n        self.contrast = (0.8, 1.2)\n        self.saturation = (0.8, 1.2)\n        self.hue = (-0.1, 0.1)\n\n        # Precompute the resize functions for each scale relative to the previous scale\n        # If scales is None, the size of the raw data will be used\n        self.resize = {}\n        for s in self.scales:\n            exp_scale = 2**s\n            self.resize[s] = transforms.Resize((self.height // exp_scale, self.width // exp_scale),\n                                               interpolation=transforms.InterpolationMode.LANCZOS)\n\n        self.sequence_indices = {}\n        self.left_img_filenames = []\n        self.right_img_filenames = []\n        self.left_mask_filenames = []\n        self.right_mask_filenames = []\n\n    def _load_image_filenames(self) -> None:\n        if 'left' in self.views:\n            self.left_img_filenames = self._get_filenames(mode='rgb_left')\n        if 'right' in self.views:\n            self.right_img_filenames = self._get_filenames(mode='rgb_right')\n        if len(self.views) == 2:\n            assert len(self.left_img_filenames) == len(self.right_img_filenames)\n\n    def _load_mask_filenames(self) -> None:\n        if 'left' in self.views:\n            self.left_mask_filenames = self._get_filenames(mode='mask_left')\n        if 'right' in self.views:\n            self.right_mask_filenames = self._get_filenames(mode='mask_right')\n        if len(self.views) == 2:\n            assert len(self.left_mask_filenames) == len(self.right_mask_filenames)\n\n    def _len_frames(self) -> int:\n        \"\"\"\n        Subtract requested neighboring frames on either side.\n        \"\"\"\n        if 'left' in self.views:\n            return len(self.left_img_filenames) - 2 * len(self.sequence_indices)\n        return len(self.right_img_filenames) - 2 * len(self.sequence_indices)\n\n    def __len__(self) -> int:\n        \"\"\"\n        Multiply by number of views to account for left and right images.\n        \"\"\"\n        return len(self.views) * self._len_frames()\n\n    def _scale_camera_matrix(self, camera_matrix: np.ndarray,\n                             scale: int) -> Tuple[np.ndarray, np.ndarray]:\n        scaled_camera_matrix = camera_matrix.copy()\n        scaled_camera_matrix[0, :] *= self.width // (2**scale)\n        scaled_camera_matrix[1, :] *= self.height // (2**scale)\n        inv_scaled_camera_matrix = np.linalg.pinv(scaled_camera_matrix)\n        return scaled_camera_matrix, inv_scaled_camera_matrix\n\n    def _pre_getitem(self, index: int) -> Tuple[List[Path], List[Path], int, bool, bool]:\n\n        if index < 0 or index >= self.__len__():\n            raise IndexError()\n\n        if len(self.views) == 2:\n            if index < self._len_frames():\n                img_filenames = self.left_img_filenames\n            else:\n                img_filenames = self.right_img_filenames\n                index -= self._len_frames()\n        elif self.views[0] == 'left':\n            img_filenames = self.left_img_filenames\n        else:\n            img_filenames = self.right_img_filenames\n\n        mask_filenames = []\n        if self.with_mask:\n            if len(self.views) == 2:\n                if index < self._len_frames():\n                    mask_filenames = self.left_mask_filenames\n                else:\n                    mask_filenames = self.right_mask_filenames\n                    index -= self._len_frames()\n            elif self.views[0] == 'left':\n                mask_filenames = self.left_mask_filenames\n            else:\n                mask_filenames = self.right_mask_filenames\n\n        # Get number of shift indices\n        # The formula is: index + 2*i + 1, where i is the i-th element of the ordered sequences\n        for i, seq_indices in enumerate(self.sequence_indices.values()):\n            if seq_indices[0] < index + 2 * i + 1 < seq_indices[1]:\n                index += 2 * i + 1\n                break\n\n        # Determine whether to apply data augmentation\n        do_color_augmentation = self.do_augmentation and random.random() > .5\n        do_flip = self.do_augmentation and random.random() > .5\n\n        return img_filenames, mask_filenames, index, do_color_augmentation, do_flip\n\n    def _post_getitem(self, item: Dict[Any, Any], do_color_augmentation: bool) -> None:\n        # Resize images\n        # Convert to list object as we are changing the size during the iteration\n        for key in list(item.keys()):\n            if 'rgb' in key or 'mask' in key:\n                k, frame_id, _ = key\n                for scale in self.scales:\n                    if scale == 0:\n                        continue\n                    item[(k, frame_id, scale)] = self.resize[scale](item[(k, frame_id, scale - 1)])\n\n        # Apply color augmentation\n        if do_color_augmentation:\n            color_augmentation = get_random_color_jitter(self.brightness, self.contrast,\n                                                         self.saturation, self.hue)\n            self._preprocess(item, color_augmentation)\n        else:\n            self._preprocess(item, augment=(lambda x: x))\n\n    def _load_from_cache(self, cache_name: str) -> Union[None, Any]:\n        if self.cache_file is None:\n            raise RuntimeError('cache_file not set for this dataset.')\n        # Separate cache files for the different names to avoid reading a large cache file\n        cache_file = self.cache_file.parent / \\\n                     f'{self.cache_file.stem}_{cache_name}{self.cache_file.suffix}'\n        if cache_file.exists():\n            with open(cache_file, 'rb') as f:\n                data = pickle.load(f)\n            return data\n        return None\n\n    def _save_to_cache(self, cache_name: str, data: Any, replace: bool = False) -> None:\n        if self.cache_file is None:\n            raise RuntimeError('cache_file not set for this dataset.')\n        # Separate cache files for the different names to avoid reading a large cache file\n        cache_file = self.cache_file.parent / \\\n                     f'{self.cache_file.stem}_{cache_name}{self.cache_file.suffix}'\n        # Write new file or replace existing\n        if not cache_file.exists() or replace:\n            with open(cache_file, 'wb') as f:\n                pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)\n\n    @abstractmethod\n    def _get_filenames(self, mode: str) -> List[Path]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def _preprocess(\n        self,\n        item: Dict[Any, Any],\n        augment: Union[Callable, Tuple[Tensor, Optional[float], Optional[float], Optional[float],\n                                       Optional[float]]],\n    ) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def __getitem__(self, index: int) -> Dict[Any, Tensor]:\n        raise NotImplementedError\n\n    @staticmethod\n    def _to_tensor(data) -> Tensor:\n        return transforms.ToTensor()(data)\n\n    def get_item_filenames(self, index: int):\n        all_img_filenames, all_mask_filenames, index, _, _ = self._pre_getitem(index)\n        img_filenames = []\n        mask_filenames = []\n        for frame_id in self.frame_ids:\n            img_filenames.append(all_img_filenames[index + frame_id])\n            if all_mask_filenames:\n                mask_filenames.append(all_mask_filenames[index + frame_id])\n        filenames = {\n            'index': index,\n            'images': img_filenames,\n            'masks': mask_filenames,\n        }\n        return filenames\n\n\n# =============================================================================\n# Adapted from:\n# https://github.com/pytorch/vision/pull/3001#issuecomment-814919958\ndef get_random_color_jitter(\n    brightness: Optional[Tuple[float, float]] = None,\n    contrast: Optional[Tuple[float, float]] = None,\n    saturation: Optional[Tuple[float, float]] = None,\n    hue: Optional[Tuple[float, float]] = None,\n) -> Compose:\n    transforms_ = []\n\n    if brightness is not None:\n        brightness_factor = random.uniform(brightness[0], brightness[1])\n        transforms_.append(Lambda(lambda img: F.adjust_brightness(img, brightness_factor)))\n    if contrast is not None:\n        contrast_factor = random.uniform(contrast[0], contrast[1])\n        transforms_.append(Lambda(lambda img: F.adjust_contrast(img, contrast_factor)))\n    if saturation is not None:\n        saturation_factor = random.uniform(saturation[0], saturation[1])\n        transforms_.append(Lambda(lambda img: F.adjust_saturation(img, saturation_factor)))\n    if hue is not None:\n        hue_factor = random.uniform(hue[0], hue[1])\n        transforms_.append(Lambda(lambda img: F.adjust_hue(img, hue_factor)))\n\n    random.shuffle(transforms_)\n    transforms_ = Compose(transforms_)\n    return transforms_\n\n\n# =============================================================================\n\n\ndef augment_data(sample):\n    # Data augmentation\n    brightness = (0.8, 1.2)\n    contrast = (0.8, 1.2)\n    saturation = (0.8, 1.2)\n    hue = (-0.1, 0.1)\n\n    augmentation = get_random_color_jitter(brightness, contrast, saturation, hue)\n\n    augmented_sample = {}\n    for key, value in sample.items():\n        if 'rgb_aug' in key:\n            augmented_sample[key] = transforms.ToTensor()(augmentation(transforms.ToPILImage()(\n                value[0, ...]).convert('RGB'))).unsqueeze(0)\n        else:\n            augmented_sample[key] = value.detach().clone()\n    return augmented_sample\n\n\n# =============================================================================\n\n\ndef show_images(batch, scales=(0, 1, 2, 3), frames=(-1, 0, 1), augmented=False):\n    batch_size = batch['index'].shape[0]\n    num_frames = len(frames)\n\n    for s in scales:\n        fig, axs = plt.subplots(nrows=batch_size,\n                                ncols=num_frames,\n                                figsize=(10, 18 / 15 * batch_size))\n        axs = axs.reshape(batch_size, num_frames)\n        for b in range(batch_size):\n            for f in frames:\n                if augmented:\n                    axs[b, f + 1].imshow(batch['rgb_aug', f, s][b, :, :, :].permute(1, 2, 0))\n                else:\n                    axs[b, f + 1].imshow(batch['rgb', f, s][b, :, :, :].permute(1, 2, 0))\n                axs[b, f + 1].axis('off')\n                if f != -1:\n                    axs[b, f + 1].set_title(f'{batch[\"relative_distance\", f][b]:.2f}')\n        fig.tight_layout()\n        fig.show()\n        plt.close(fig)\n"
  },
  {
    "path": "depth_pose_prediction/__init__.py",
    "content": "import depth_pose_prediction.utils\nfrom depth_pose_prediction.config import DepthPosePrediction as Config\nfrom depth_pose_prediction.depth_pose_prediction import DepthPosePrediction\n"
  },
  {
    "path": "depth_pose_prediction/config.py",
    "content": "import dataclasses\nfrom pathlib import Path\nfrom typing import Optional, Tuple, Union\n\n\n@dataclasses.dataclass\nclass DepthPosePrediction:\n    config_file: Path\n    train_set: Optional[Union[Tuple[int, ...], int, str]]\n    val_set: Optional[Union[Tuple[int, ...], Tuple[str, ...], int, str]]\n    resnet_depth: int\n    resnet_pose: int\n    resnet_pretrained: bool\n    scales: Tuple[int, ...]\n    learning_rate: float\n    scheduler_step_size: int\n    batch_size: int\n    num_workers: int\n    num_epochs: int\n    min_depth: Optional[float]\n    max_depth: Optional[float]\n    disparity_smoothness: float\n    velocity_loss_scaling: Optional[float]\n    mask_dynamic: bool\n    log_path: Path\n    save_frequency: int\n    save_val_depth: bool\n    save_val_depth_batches: int\n    multiple_gpus: bool\n    gpu_ids: Optional[Tuple[int, ...]]\n    load_weights_folder: Optional[Path]\n    use_wandb: Optional[bool]\n"
  },
  {
    "path": "depth_pose_prediction/depth_pose_prediction.py",
    "content": "import shutil\nimport warnings\nfrom pathlib import Path\nfrom typing import Any, Dict, Optional, Tuple, Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nimport wandb\nfrom PIL import Image\nfrom torch import Tensor, nn, optim\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom datasets import Cityscapes\nfrom datasets import Config as DatasetConfig\nfrom datasets import Kitti, Robotcar\nfrom depth_pose_prediction.config import DepthPosePrediction as Config\nfrom depth_pose_prediction.networks import (\n    SSIM,\n    BackprojectDepth,\n    DepthDecoder,\n    PoseDecoder,\n    Project3D,\n    ResnetEncoder,\n)\nfrom depth_pose_prediction.utils import (\n    disp_to_depth,\n    h_concat_images,\n    transformation_from_parameters,\n)\n\n# matplotlib.use('Agg')\n\n\nclass DepthPosePrediction:\n    def __init__(self, dataset_config: DatasetConfig, config: Config, use_online: bool = False):\n        # Initialize parameters ===========================\n        self.config_file = config.config_file\n        self.dataset_type = dataset_config.dataset\n        self.dataset_path = dataset_config.dataset_path\n        self.height = dataset_config.height\n        self.width = dataset_config.width\n        self.train_set = config.train_set\n        self.val_set = config.val_set\n        self.resnet_depth = config.resnet_depth\n        self.resnet_pose = config.resnet_pose\n        self.resnet_pretrained = config.resnet_pretrained\n        self.scales = config.scales\n        self.learning_rate = config.learning_rate\n        self.scheduler_step_size = config.scheduler_step_size\n        self.batch_size = config.batch_size\n        self.num_workers = config.num_workers\n        self.num_epochs = config.num_epochs\n        self.min_depth = config.min_depth\n        self.max_depth = config.max_depth\n        self.disparity_smoothness = config.disparity_smoothness\n        self.velocity_loss_scaling = config.velocity_loss_scaling\n        self.mask_dynamic = config.mask_dynamic\n        self.log_path = config.log_path\n        self.save_frequency = config.save_frequency\n        self.save_val_depth = config.save_val_depth\n        self.save_val_depth_batches = config.save_val_depth_batches\n        self.multiple_gpus = config.multiple_gpus\n        self.gpu_ids = config.gpu_ids\n        self.load_weights_folder = config.load_weights_folder\n        self.use_wandb = False\n\n        # Internal parameters =============================\n        self.is_trained = False\n\n        # Fixed parameters ================================\n        self.frame_ids = (0, -1, 1)\n        self.num_pose_frames = 2\n        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n        # Deal with dependent parameters ==================\n        if self.load_weights_folder is not None:\n            self.load_weights_folder = Path(self.load_weights_folder).absolute()\n\n        if isinstance(self.train_set, list):\n            self.train_set = tuple(self.train_set)\n        if isinstance(self.val_set, list):\n            self.val_set = tuple(self.val_set)\n        if dataset_config.dataset == 'Kitti':\n            if isinstance(self.val_set, int):\n                self.val_set = (self.val_set,)\n            if isinstance(self.train_set, str):\n                if self.train_set != 'all':\n                    raise ValueError('train_set of KITTI only accepts these strings: [\"all\"]')\n                self.train_set = tuple([  # pylint: disable=consider-using-generator\n                    s for s in range(11) if s not in self.val_set and s != 3  # No IMU for seq 3\n                ])\n            elif isinstance(self.train_set, int):\n                self.train_set = (self.train_set,)\n            if not (isinstance(self.train_set, tuple) and isinstance(self.train_set[0], int)):\n                raise ValueError('Passed invalid value for train_set')\n            if not (isinstance(self.val_set, tuple) and isinstance(self.val_set[0], int)):\n                raise ValueError('Passed invalid value for val_set')\n        elif dataset_config.dataset in ['Cityscapes', 'RobotCar']:\n            if isinstance(self.train_set, str):\n                self.train_set = (self.train_set,)\n            if isinstance(self.val_set, str):\n                self.val_set = (self.val_set,)\n            if not (isinstance(self.train_set, tuple) and isinstance(self.train_set[0], str)):\n                raise ValueError('Passed invalid value for train_set')\n            if not (isinstance(self.val_set, tuple) and isinstance(self.val_set[0], str)):\n                raise ValueError('Passed invalid value for val_set')\n\n        if self.multiple_gpus and not torch.cuda.is_available():\n            raise ValueError('Activated multiple GPUs but running on a CPU.')\n        if self.multiple_gpus and self.gpu_ids is None:\n            self.gpu_ids = list(range(torch.cuda.device_count()))\n        elif self.multiple_gpus:\n            if any(i >= torch.cuda.device_count() for i in self.gpu_ids):\n                raise ValueError('Passed invalid GPU ID.')\n        if not self.multiple_gpus and self.gpu_ids is not None and len(self.gpu_ids) > 1:\n            raise ValueError('Passed multiple GPU IDs without activating multi-GPU support.')\n        if self.gpu_ids is not None and torch.cuda.is_available():\n            # Set the main GPU for gradient averaging etc.\n            torch.cuda.set_device(self.gpu_ids[0])\n        elif self.gpu_ids is None and torch.cuda.is_available():\n            self.gpu_ids = (0,)\n        # =================================================\n\n        # Construct networks ==============================\n        self.models = {}\n        self.models['depth_encoder'] = ResnetEncoder(self.resnet_depth, self.resnet_pretrained)\n        self.models['depth_decoder'] = DepthDecoder(self.models['depth_encoder'].num_ch_encoder,\n                                                    self.scales)\n        self.models['pose_encoder'] = ResnetEncoder(self.resnet_pose, self.resnet_pretrained,\n                                                    self.num_pose_frames)\n        self.models['pose_decoder'] = PoseDecoder(self.models['pose_encoder'].num_ch_encoder,\n                                                  num_input_features=1,\n                                                  num_frames_to_predict_for=2)\n\n        self.use_online = use_online\n        self.online_models = {}\n        if self.use_online:\n            self.online_models['depth_encoder'] = ResnetEncoder(self.resnet_depth,\n                                                                self.resnet_pretrained)\n            self.online_models['depth_decoder'] = DepthDecoder(\n                self.online_models['depth_encoder'].num_ch_encoder, self.scales)\n            self.online_models['pose_encoder'] = ResnetEncoder(self.resnet_pose,\n                                                               self.resnet_pretrained,\n                                                               self.num_pose_frames)\n            self.online_models['pose_decoder'] = PoseDecoder(\n                self.models['pose_encoder'].num_ch_encoder,\n                num_input_features=1,\n                num_frames_to_predict_for=2)\n        # =================================================\n\n        # Create the projected (warped) image =============\n        self.backproject_depth = {}\n        self.project_3d = {}\n        self.backproject_depth_single = {}\n        self.project_3d_single = {}\n        for scale in self.scales:\n            h = self.height // (2 ** scale)\n            w = self.width // (2 ** scale)\n            self.backproject_depth[scale] = BackprojectDepth(self.batch_size, h, w)\n            self.project_3d[scale] = Project3D(self.batch_size, h, w)\n\n            self.backproject_depth_single[scale] = BackprojectDepth(1, h, w)\n            self.project_3d_single[scale] = Project3D(1, h, w)\n        # =================================================\n\n        # Structural similarity ===========================\n        self.ssim = SSIM()\n        self.ssim.to(self.device)\n        # =================================================\n\n        # Send everything to the GPU(s) ===================\n        if 'cuda' in self.device.type:\n            print(f'Selected GPUs: {list(self.gpu_ids)}')\n        if self.multiple_gpus:\n            for model_name, m in self.models.items():\n                if m is not None:\n                    self.models[model_name] = nn.DataParallel(m, device_ids=self.gpu_ids)\n\n        self.parameters_to_train = []\n        for model_name, m in self.models.items():\n            if m is not None:\n                m.to(self.device)\n                self.parameters_to_train += list(m.parameters())\n        self.online_parameters_to_train = []\n        for m in self.online_models.values():\n            m.to(self.device)\n            self.online_parameters_to_train += list(m.parameters())\n        for m in self.backproject_depth.values():\n            m.to(self.device)\n        for m in self.project_3d.values():\n            m.to(self.device)\n        for m in self.backproject_depth_single.values():\n            m.to(self.device)\n        for m in self.project_3d_single.values():\n            m.to(self.device)\n        # =================================================\n\n        # Set up optimizer ================================\n        self.optimizer = optim.Adam(self.parameters_to_train, self.learning_rate)\n        self.lr_scheduler = optim.lr_scheduler.StepLR(self.optimizer, self.scheduler_step_size, 0.1)\n        self.epoch = 0\n        if use_online:\n            self.online_optimizer = optim.Adam(self.online_parameters_to_train, self.learning_rate)\n        else:\n            self.online_optimizer = None\n        # =================================================\n\n        # Construct datasets ==============================\n        self.train_loader, self.val_loader = None, None\n        # =================================================\n\n    # ============================================================\n    # Training / validation\n\n    def train(self,\n              validate: bool = False,\n              depth_error: bool = False,\n              pose_error: bool = False,\n              dataloader: Optional[DataLoader] = None,\n              verbose: bool = True,\n              use_wandb: Optional[bool] = False) -> None:\n        use_wandb = False if use_wandb is None else use_wandb\n        if use_wandb:\n            self.use_wandb = True\n            self._init_wandb()\n\n        if dataloader is None:\n            self._create_dataloaders(validation=validate)\n        else:\n            validate = False\n            self.train_loader = dataloader\n            print(f'Training samples:   {len(self.train_loader):>5}')\n\n        # Training loop\n        step = 0\n        starting_epoch = self.epoch + 1\n        for self.epoch in range(starting_epoch, self.num_epochs + 1):\n            # Run a single epoch\n            self._set_train()\n            loss = []\n            with tqdm(unit='batches',\n                      total=len(self.train_loader),\n                      desc=f'Training epoch {self.epoch}/{self.num_epochs}',\n                      disable=not verbose) as pbar:\n                for batch_i, sample_i in enumerate(self.train_loader):\n                    # Run a single step\n                    self.optimizer.zero_grad()\n                    outputs, losses = self._process_batch(sample_i)\n                    loss.append(losses['loss'].item())\n\n                    losses['loss'].backward()\n                    self.optimizer.step()\n\n                    if self.use_wandb:\n                        wandb.log(losses)\n\n                    pbar.set_postfix(loss=np.mean(loss))\n                    pbar.update(1)\n                    step += 1\n            self.lr_scheduler.step()\n            self.is_trained = True\n\n            if self.save_frequency > 0 and self.epoch % self.save_frequency == 0:\n                self.save_model()\n\n            if validate:\n                validation_loss = self.validate()\n                if self.use_wandb:\n                    wandb.log({'validation_loss': validation_loss}, commit=False)\n\n            if depth_error:\n                error = self.compute_depth_error(median_scaling=True, print_results=False)\n                if self.use_wandb:\n                    wandb.log(error, commit=False)\n            if pose_error:\n                error = self.compute_pose_error(print_results=False)\n                if self.use_wandb:\n                    wandb.log(error, commit=False)\n\n            if self.use_wandb:\n                wandb.log({'training_loss': np.mean(loss), 'epoch': self.epoch})\n\n        # Save the final model\n        if self.save_frequency > -1:\n            self.save_model()\n\n    def adapt(self,\n              online_data: Dict[Any, Tensor],\n              training_data: Optional[Dict[Any, Tensor]] = None,\n              online_index: int = 0,\n              steps: int = 1,\n              online_loss_weight: Optional[float] = None):\n        if online_loss_weight is None:\n            loss_weights = None\n        elif self.batch_size == 1:\n            loss_weights = torch.ones(1, device=self.device)\n        else:\n            loss_weights = torch.empty(self.batch_size, device=self.device)\n            buffer_loss_weight = (1 - online_loss_weight) / (self.batch_size - 1)\n            loss_weights[online_index] = online_loss_weight\n            loss_weights[np.arange(self.batch_size) != online_index] = buffer_loss_weight\n\n        if training_data is not None:\n            self._set_adapt(freeze_encoder=True)\n            for _ in range(steps):\n                outputs_eval, losses = self._process_batch(training_data, loss_weights)\n                self.optimizer.zero_grad()\n                losses['loss'].backward()\n                self.optimizer.step()\n        else:\n            self._set_eval()\n            with torch.no_grad():\n                outputs_eval, losses = self._process_batch(online_data, loss_weights)\n\n        return outputs_eval, losses\n\n    def validate(self) -> float:\n        \"\"\" Compute the validation loss(es)\n        \"\"\"\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n        if self.val_loader is None:\n            self._create_dataloaders(training=False)\n\n        self._set_eval()\n        loss = []\n        with torch.no_grad(), tqdm(unit='batches', total=len(self.val_loader),\n                                   desc='Validation') as pbar:\n            for batch_i, sample_i in enumerate(self.val_loader):\n                outputs, losses = self._process_batch(sample_i)\n                loss.append(losses['loss'].item())\n\n                if self.save_val_depth and batch_i < self.save_val_depth_batches:\n                    self.save_prediction(sample_i, outputs)\n\n                pbar.set_postfix(loss=np.mean(loss))\n                pbar.update(1)\n        return float(np.mean(loss))\n\n    def compute_depth_error(\n            self,\n            median_scaling: bool = True,\n            print_results: bool = True,\n    ) -> Dict[str, float]:\n        \"\"\" Compute error metrics for depth prediction\n        Follows monodepth2 implementation:\n        https://github.com/nianticlabs/monodepth2/blob/master/evaluate_depth.py\n\n        monodepth2 on Kittti\n        - cap depth at 80 per standard practice\n        - per-image median ground truth scaling (or same for entire test set)\n        - post-process: predict for original and flipped images, then combine both disparities\n        - pred_disp = cv2.resize(pred_disp, (gt_width, gt_height))\n        \"\"\"\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n\n        if self.dataset_type == 'Kitti':\n            dataset = Kitti(self.dataset_path,\n                            self.val_set,\n                            frame_ids=[0],\n                            scales=[0],\n                            height=self.height,\n                            width=self.width,\n                            with_depth=True)\n        elif self.dataset_type == 'Cityscapes':\n            dataset = Cityscapes(self.dataset_path,\n                                 self.val_set,\n                                 frame_ids=[0],\n                                 scales=[0],\n                                 height=self.height,\n                                 width=self.width,\n                                 with_depth=True)\n        else:\n            warnings.warn(f'Unsupported dataset: {self.dataset_type}', RuntimeWarning)\n            return {}\n\n        data_loader = DataLoader(dataset,\n                                 batch_size=1,\n                                 shuffle=False,\n                                 num_workers=self.num_workers,\n                                 pin_memory=True,\n                                 drop_last=True)\n        print(f'Validation samples: {len(dataset):>5}')\n\n        ratios = []\n        num_samples = 0\n        abs_diff, abs_rel, sq_rel, a1, a2, a3, rmse_tot, rmse_log_tot = 0, 0, 0, 0, 0, 0, 0, 0\n\n        self._set_eval()\n        with torch.no_grad(), tqdm(unit='batches', total=len(data_loader),\n                                   desc='Validation') as pbar:\n            for batch_i, sample_i in enumerate(data_loader):\n                for key, val in sample_i.items():\n                    sample_i[key] = val.to(self.device)\n                gt_depth = sample_i[('depth', 0, -1)].squeeze().cpu().detach().numpy()\n                gt_height, gt_width = gt_depth.shape\n\n                # Depth prediction\n                outputs = self._predict_disparity(sample_i)\n                disparity = outputs[('disp', 0)].squeeze().cpu().detach().numpy()\n                pred_depth = disp_to_depth(disparity, self.min_depth, None)\n                # pylint: disable-next=no-member\n                pred_depth = cv2.resize(pred_depth, (gt_width, gt_height))\n\n                # Mask out pixels without ground truth depth\n                # or ground truth depth farther away than the maximum predicted depth\n                if self.max_depth is not None:\n                    mask = np.logical_and(gt_depth > self.min_depth, gt_depth < self.max_depth)\n                else:\n                    mask = gt_depth > self.min_depth\n                pred_depth = pred_depth[mask]\n                gt_depth = gt_depth[mask]\n\n                # Introduced by SfMLearner\n                if median_scaling:\n                    ratio = np.median(gt_depth) / np.median(pred_depth)\n                    ratios.append(ratio)\n                    pred_depth *= ratio\n\n                # Cap predicted depth at min and max depth\n                pred_depth[pred_depth < self.min_depth] = self.min_depth\n                if self.max_depth is not None:\n                    pred_depth[pred_depth > self.max_depth] = self.max_depth\n\n                # Compute error metrics\n                thresh = np.maximum((gt_depth / pred_depth), (pred_depth / gt_depth))\n                a1 += np.mean(thresh < 1.25)\n                a2 += np.mean(thresh < 1.25 ** 2)\n                a3 += np.mean(thresh < 1.25 ** 3)\n                rmse = (gt_depth - pred_depth) ** 2\n                rmse_tot += np.sqrt(np.mean(rmse))\n                rmse_log = (np.log(gt_depth) - np.log(pred_depth)) ** 2\n                rmse_log_tot += np.sqrt(np.mean(rmse_log))\n                abs_diff += np.mean(np.abs(gt_depth - pred_depth))\n                abs_rel += np.mean(np.abs(gt_depth - pred_depth) / gt_depth)\n                sq_rel += np.mean(((gt_depth - pred_depth) ** 2) / gt_depth)\n\n                num_samples += 1\n                pbar.update(1)\n\n        metrics = {\n            'abs_diff': abs_diff / num_samples,\n            'abs_rel': abs_rel / num_samples,\n            'sq_rel': sq_rel / num_samples,\n            'a1': a1 / num_samples,\n            'a2': a2 / num_samples,\n            'a3': a3 / num_samples,\n            'rmse': rmse_tot / num_samples,\n            'rmse_log': rmse_log_tot / num_samples\n        }\n\n        if print_results:\n            for key, value in metrics.items():\n                print(f'{key:<8}: {value:>6.3f}')\n\n        if median_scaling:\n            ratios = np.array(ratios)\n            med = np.median(ratios)\n            metrics['med_scaling'] = med\n            if print_results:\n                print(f'Scaling ratios | med: {med:.3f} | std: {np.std(ratios / med):.3f}')\n\n        return metrics\n\n    def compute_pose_error(self, print_results: bool = True) -> Dict[str, float]:\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n\n        if self.dataset_type == 'Kitti':\n            dataset = Kitti(self.dataset_path,\n                            self.val_set,\n                            frame_ids=[-1, 0],\n                            scales=[0],\n                            height=self.height,\n                            width=self.width,\n                            poses=True,\n                            with_depth=True)\n        else:\n            warnings.warn(f'Unsupported dataset: {self.dataset_type}', RuntimeWarning)\n            return {}\n        data_loader = DataLoader(dataset,\n                                 batch_size=1,\n                                 shuffle=False,\n                                 num_workers=self.num_workers,\n                                 pin_memory=True,\n                                 drop_last=True)\n        print(f'Validation samples: {len(dataset):>5}')\n\n        num_samples = 0\n        rpe_trans, rpe_rot = 0, 0\n\n        self._set_eval()\n        with torch.no_grad(), tqdm(unit='batches', total=len(data_loader),\n                                   desc='Validation') as pbar:\n            for batch_i, sample_i in enumerate(data_loader):\n                image_0 = sample_i['rgb_aug', -1, 0]\n                image_1 = sample_i['rgb_aug', 0, 0]\n                pred_transformation, _ = self.predict_pose(image_0, image_1, as_numpy=False)\n                pred_transformation = pred_transformation.squeeze().detach().cpu()\n                pred_transformation = torch.linalg.inv(pred_transformation)\n\n                gt_transformation = sample_i['relative_pose', 0].squeeze()\n                rel_err = torch.linalg.inv(gt_transformation) @ pred_transformation\n                trans_error = torch.linalg.norm(rel_err[:3, 3]).item()\n                rot_error = np.arccos(\n                    max(min(.5 * (torch.trace(rel_err[:3, :3]).item() - 1), 1.), -1.0))\n\n                rpe_trans += trans_error\n                rpe_rot += rot_error * 180 / np.pi\n\n                num_samples += 1\n                pbar.update(1)\n\n        metrics = {'rpe_trans': rpe_trans / num_samples, 'rpe_rot': rpe_rot / num_samples}\n\n        if print_results:\n            for key, value in metrics.items():\n                print(f'{key:<8}: {value:>6.3f}')\n\n        return metrics\n\n    # ============================================================\n    # Predict functions\n\n    def predict(self, batch) -> Dict[Any, Tensor]:\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n        self._set_eval()\n        with torch.no_grad():\n            outputs, losses = self._process_batch(batch)\n        return outputs\n\n    def predict_from_image(self, image, as_numpy: bool = True):\n        \"\"\" Take one image as input and return the predicted depth\n        \"\"\"\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n        self._set_eval()\n        with torch.no_grad():\n            image = image.to(self.device)\n\n            # Depth network\n            features = self.models['depth_encoder'](image)\n            disp = self.models['depth_decoder'](features)[('disp', 0)]\n            depth = disp_to_depth(disp, self.min_depth, self.max_depth)\n\n        if as_numpy:\n            depth = depth.squeeze().cpu().detach().numpy()\n        return depth\n\n    def predict_from_images(\n            self,\n            image_0: Tensor,\n            image_1: Tensor,\n            as_numpy: bool = True,\n            return_loss: bool = False,\n            camera_matrix: Optional[Tensor] = None,\n            inv_camera_matrix: Optional[Tensor] = None,\n            relative_distance: Optional[Tensor] = None,\n    ):\n        \"\"\" Take two images as input and return depth for both and relative pose\n        \"\"\"\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n\n        if len(image_0.shape) == 3:\n            image_0 = image_0.unsqueeze(dim=0)\n        if len(image_1.shape) == 3:\n            image_1 = image_1.unsqueeze(dim=0)\n\n        self._set_eval()\n        with torch.no_grad():\n            image_0 = image_0.to(self.device)\n            image_1 = image_1.to(self.device)\n\n            # Depth network\n            features_0 = self.models['depth_encoder'](image_0)\n            disp_0 = self.models['depth_decoder'](features_0)\n            depth_0 = disp_to_depth(disp_0[('disp', 0)], self.min_depth, self.max_depth)\n            features_1 = self.models['depth_encoder'](image_1)\n            disp_1 = self.models['depth_decoder'](features_1)\n            depth_1 = disp_to_depth(disp_1[('disp', 0)], self.min_depth, self.max_depth)\n\n            # Pose network\n            pose_inputs = torch.cat([image_0, image_1], 1)\n            pose_features = [self.models['pose_encoder'](pose_inputs)]\n            axis_angle, translation = self.models['pose_decoder'](pose_features)\n            transformation = transformation_from_parameters(axis_angle[:, 0],\n                                                            translation[:, 0],\n                                                            invert=False)\n\n        if as_numpy:\n            depth_0 = depth_0.squeeze().cpu().detach().numpy()\n            depth_1 = depth_1.squeeze().cpu().detach().numpy()\n            transformation = transformation.squeeze().cpu().detach().numpy()\n\n        if return_loss:\n            # Assume: image_0 => frame -1 | image_1 => frame 0\n            frame_ids = self.frame_ids\n            self.frame_ids = (0, -1)\n            outputs = disp_1\n            outputs[('axis_angle', 0, -1)] = axis_angle[:, 0]\n            outputs[('translation', 0, -1)] = translation[:, 0]\n            outputs[('cam_T_cam', 0, -1)] = transformation_from_parameters(axis_angle[:, 0],\n                                                                           translation[:, 0],\n                                                                           invert=True)\n            inputs = {\n                ('rgb', -1, 0): image_0,\n                ('rgb', 0, 0): image_1,\n                ('camera_matrix', 0): camera_matrix.to(self.device),\n                ('inv_camera_matrix', 0): inv_camera_matrix.to(self.device),\n                ('relative_distance', 0): relative_distance.to(self.device)\n            }\n            self._reconstruct_images(inputs, outputs)\n            losses = self._compute_loss(inputs, outputs, scales=(0,))\n            for k, v in losses.items():\n                losses[k] = v.squeeze().cpu().detach().numpy()\n            self.frame_ids = frame_ids\n            return depth_0, depth_1, transformation, losses\n\n        return depth_0, depth_1, transformation\n\n    def predict_pose(\n            self,\n            image_0: Tensor,\n            image_1: Tensor,\n            as_numpy: bool = True,\n            use_online: bool = False,\n    ) -> Tuple[Union[Tensor, np.ndarray], Union[Tensor, np.ndarray]]:\n        if not self.is_trained:\n            warnings.warn('The model has not been trained yet.', RuntimeWarning)\n\n        if len(image_0.shape) == 3:\n            image_0 = image_0.unsqueeze(dim=0)\n        if len(image_1.shape) == 3:\n            image_1 = image_1.unsqueeze(dim=0)\n\n        self._set_eval()\n        with torch.no_grad():\n            image_0 = image_0.to(self.device)\n            image_1 = image_1.to(self.device)\n\n            # Pose network\n            pose_inputs = torch.cat([image_0, image_1], 1)\n            if use_online:\n                pose_features = [self.online_models['pose_encoder'](pose_inputs)]\n                axis_angle, translation = self.online_models['pose_decoder'](pose_features)\n            else:\n                pose_features = [self.models['pose_encoder'](pose_inputs)]\n                axis_angle, translation = self.models['pose_decoder'](pose_features)\n            axis_angle, translation = axis_angle[:, 0], translation[:, 0]\n            transformation = transformation_from_parameters(axis_angle, translation, invert=False)\n\n            cov_matrix = torch.eye(6, device=self.device)\n\n        if as_numpy:\n            transformation = transformation.squeeze().cpu().detach().numpy()\n            cov_matrix = cov_matrix.cpu().detach().numpy()\n        return transformation, cov_matrix\n\n    # ============================================================\n    # Save / load functions\n\n    def save_model(self) -> None:\n        \"\"\"Save model weights to disk\n        \"\"\"\n        save_folder = self.log_path / 'models' / f'weights_{self.epoch:03}'\n        save_folder.mkdir(parents=True, exist_ok=True)\n\n        # Save the network weights\n        for model_name, model in self.models.items():\n            if model is None:\n                continue\n            save_path = save_folder / f'{model_name}.pth'\n            if isinstance(model, nn.DataParallel):\n                to_save = model.module.state_dict()\n            else:\n                to_save = model.state_dict()\n            if 'encoder' in model_name:\n                # ToDo: look into this\n                # Save the sizes - these are needed at prediction time\n                to_save['height'] = Tensor(self.height)\n                to_save['width'] = Tensor(self.width)\n            torch.save(to_save, save_path)\n\n        # Save the optimizer and the LR scheduler\n        optimizer_save_path = save_folder / 'optimizer.pth'\n        to_save = {\n            'optimizer': self.optimizer.state_dict(),\n            'scheduler': self.lr_scheduler.state_dict()\n        }\n        torch.save(to_save, optimizer_save_path)\n\n        # Save the config file\n        config_save_path = self.log_path / 'config.yaml'\n        shutil.copy(self.config_file, config_save_path)\n\n        print(f'Saved model to: {save_folder}')\n\n    def load_model(self, load_optimizer: bool = True) -> None:\n        \"\"\"Load model(s) from disk\n        \"\"\"\n        if self.load_weights_folder is None:\n            print('Weights folder required to load the model is not specified.')\n        if not self.load_weights_folder.exists():\n            print(f'Cannot find folder: {self.load_weights_folder}')\n        print(f'Load model from: {self.load_weights_folder}')\n\n        # Load the network weights\n        for model_name, model in self.models.items():\n            if model is None:\n                continue\n            path = self.load_weights_folder / f'{model_name}.pth'\n            pretrained_dict = torch.load(path, map_location=self.device)\n            if isinstance(model, nn.DataParallel):\n                model_dict = model.module.state_dict()\n            else:\n                model_dict = model.state_dict()\n            pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n            if len(pretrained_dict.keys()) == 0:\n                raise RuntimeError(f'No fitting weights found in: {path}')\n            model_dict.update(pretrained_dict)\n            if isinstance(model, nn.DataParallel):\n                model.module.load_state_dict(model_dict)\n            else:\n                model.load_state_dict(model_dict)\n        self.is_trained = True\n\n        if load_optimizer:\n            # Load the optimizer and LR scheduler\n            optimizer_load_path = self.load_weights_folder / 'optimizer.pth'\n            try:\n                optimizer_dict = torch.load(optimizer_load_path, map_location=self.device)\n                if 'optimizer' in optimizer_dict:\n                    self.optimizer.load_state_dict(optimizer_dict['optimizer'])\n                    self.lr_scheduler.load_state_dict(optimizer_dict['scheduler'])\n                    self.epoch = self.lr_scheduler.last_epoch\n                    print(f'Restored optimizer and LR scheduler (resume from epoch {self.epoch}).')\n                else:\n                    self.optimizer.load_state_dict(optimizer_dict)\n                    print('Restored optimizer (legacy mode).')\n            except:  # pylint: disable=bare-except\n                print('Cannot find matching optimizer weights, so the optimizer is randomly '\n                      'initialized.')\n\n    def load_online_model(self, load_optimizer: bool = True) -> None:\n        \"\"\"Load model(s) from disk\n        \"\"\"\n        if self.load_weights_folder is None:\n            print('Weights folder required to load the model is not specified.')\n        if not self.load_weights_folder.exists():\n            print(f'Cannot find folder: {self.load_weights_folder}')\n        print(f'Load online model from: {self.load_weights_folder}')\n\n        # Load the network weights\n        for model_name, model in self.online_models.items():\n            if model is None:\n                continue\n            path = self.load_weights_folder / f'{model_name}.pth'\n            pretrained_dict = torch.load(path, map_location=self.device)\n            if isinstance(model, nn.DataParallel):\n                model_dict = model.module.state_dict()\n            else:\n                model_dict = model.state_dict()\n            pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict}\n            if len(pretrained_dict.keys()) == 0:\n                raise RuntimeError(f'No fitting weights found in: {path}')\n            model_dict.update(pretrained_dict)\n            if isinstance(model, nn.DataParallel):\n                model.module.load_state_dict(model_dict)\n            else:\n                model.load_state_dict(model_dict)\n\n        if load_optimizer:\n            # Load the optimizer and LR scheduler\n            optimizer_load_path = self.load_weights_folder / 'optimizer.pth'\n            try:\n                optimizer_dict = torch.load(optimizer_load_path, map_location=self.device)\n                if 'optimizer' in optimizer_dict:\n                    self.online_optimizer.load_state_dict(optimizer_dict['optimizer'])\n                    print('Restored online optimizer')\n                else:\n                    self.online_optimizer.load_state_dict(optimizer_dict)\n                    print('Restored online optimizer (legacy mode).')\n            except:  # pylint: disable=bare-except\n                print('Cannot find matching optimizer weights, so the optimizer is randomly '\n                      'initialized.')\n\n    # ============================================================\n    # Auxiliary functions\n\n    def _set_train(self) -> None:\n        for m in self.models.values():\n            if m is not None:\n                m.train()\n\n    def _set_eval(self) -> None:\n        for m in self.models.values():\n            if m is not None:\n                m.eval()\n\n    def _set_adapt(self, freeze_encoder: bool = True) -> None:\n        \"\"\" Set all to train except for batch normalization (freeze parameters)\n        Convert all models to adaptation mode: batch norm is in eval mode + frozen params\n        Adapted from:\n        https://github.com/Yevkuzn/CoMoDA/blob/main/code/CoMoDA.py\n        \"\"\"\n        for model_name, model in self.models.items():\n            model.eval()  # To set the batch norm to eval mode\n            for name, param in model.named_parameters():\n                if name.find('bn') != -1:\n                    param.requires_grad = False  # Freeze batch norm\n                if freeze_encoder and 'encoder' in model_name:\n                    param.requires_grad = False\n\n        for model_name, model in self.online_models.items():\n            model.eval()  # To set the batch norm to eval mode\n            for name, param in model.named_parameters():\n                if name.find('bn') != -1:\n                    param.requires_grad = False  # Freeze batch norm\n                if freeze_encoder and 'encoder' in model_name:\n                    param.requires_grad = False\n\n    def _create_dataloaders(self, training: bool = True, validation: bool = True):\n        valid_dataset_types = ['Kitti', 'Cityscapes', 'RobotCar']\n        if self.dataset_type not in valid_dataset_types:\n            raise ValueError(f'dataset_type must be one of {valid_dataset_types}')\n        if self.train_set is not None and training:\n            if self.dataset_type == 'Kitti':\n                train_dataset = Kitti(self.dataset_path,\n                                      self.train_set,\n                                      self.frame_ids,\n                                      self.scales,\n                                      self.height,\n                                      self.width,\n                                      do_augmentation=True,\n                                      views=('left', 'right'),\n                                      with_mask=self.mask_dynamic)\n            elif self.dataset_type == 'Cityscapes':\n                train_dataset = Cityscapes(self.dataset_path,\n                                           self.train_set,\n                                           self.frame_ids,\n                                           self.scales,\n                                           self.height,\n                                           self.width,\n                                           do_augmentation=True,\n                                           with_mask=self.mask_dynamic)\n            else:  # self.dataset_type == 'RobotCar':\n                train_dataset = Robotcar(self.dataset_path,\n                                         self.train_set,\n                                         self.frame_ids,\n                                         self.scales,\n                                         self.height,\n                                         self.width,\n                                         do_augmentation=True,\n                                         with_mask=self.mask_dynamic,\n                                         start_frame=4000,\n                                         end_frame=24000)\n            print(f'Training samples:   {len(train_dataset):>5}')\n            self.train_loader = DataLoader(train_dataset,\n                                           self.batch_size,\n                                           shuffle=True,\n                                           num_workers=self.num_workers,\n                                           pin_memory=True,\n                                           drop_last=True)\n        if self.val_set is not None and validation:\n            if self.dataset_type == 'Kitti':\n                val_dataset = Kitti(self.dataset_path,\n                                    self.val_set,\n                                    self.frame_ids,\n                                    self.scales,\n                                    self.height,\n                                    self.width,\n                                    with_mask=self.mask_dynamic)\n            elif self.dataset_type == 'Cityscapes':\n                val_dataset = Cityscapes(self.dataset_path,\n                                         self.val_set,\n                                         self.frame_ids,\n                                         self.scales,\n                                         self.height,\n                                         self.width,\n                                         with_mask=self.mask_dynamic)\n            else:  # self.dataset_type == 'RobotCar':\n                val_dataset = Robotcar(self.dataset_path,\n                                       self.val_set,\n                                       self.frame_ids,\n                                       self.scales,\n                                       self.height,\n                                       self.width,\n                                       with_mask=self.mask_dynamic,\n                                       start_frame=500,\n                                       end_frame=4000)\n            print(f'Validation samples: {len(val_dataset):>5}')\n            self.val_loader = DataLoader(val_dataset,\n                                         self.batch_size,\n                                         shuffle=False,\n                                         num_workers=self.num_workers,\n                                         pin_memory=True,\n                                         drop_last=True)\n\n    def _process_batch(\n            self,\n            inputs: Dict[Any, Tensor],\n            loss_sample_weights: Optional[Tensor] = None,\n            use_online: bool = False,\n    ) -> Tuple[Dict[Any, Tensor], Dict[str, Tensor]]:\n        \"\"\"\n        Pass a minibatch through the network\n        \"\"\"\n\n        for key, val in inputs.items():\n            inputs[key] = val.to(self.device)\n        outputs = {}\n        outputs.update(self._predict_disparity(inputs, use_online=use_online))\n        outputs.update(self._predict_poses(inputs, use_online=use_online))\n        self._reconstruct_images(inputs, outputs)  # also converts disparity to depth\n        losses = self._compute_loss(inputs, outputs, sample_weights=loss_sample_weights)\n        return outputs, losses\n\n    def _predict_disparity(self,\n                           inputs: Dict[Any, Tensor],\n                           frame: int = 0,\n                           scale: int = 0,\n                           use_online: bool = False) -> Dict[Any, Tensor]:\n        if use_online:\n            features = self.online_models['depth_encoder'](inputs[('rgb_aug', frame, scale)])\n            outputs = self.online_models['depth_decoder'](features)\n        else:\n            features = self.models['depth_encoder'](inputs[('rgb_aug', frame, scale)])\n            outputs = self.models['depth_decoder'](features)\n        return outputs\n\n    def _predict_poses(self,\n                       inputs: Dict[Any, Tensor],\n                       use_online: bool = False) -> Dict[Any, Tensor]:\n        \"\"\"\n        Predict the poses: 0 -> -1 and 0 -> 1\n        \"\"\"\n        assert self.num_pose_frames == 2, self.num_pose_frames\n        assert self.frame_ids == (0, -1, 1)\n\n        outputs = {}\n        pose_inputs_dict = {f_i: inputs['rgb_aug', f_i, 0] for f_i in self.frame_ids}\n        for frame_i in self.frame_ids[1:]:\n            # To maintain ordering we always pass frames in temporal order\n            if frame_i < 0:\n                pose_inputs = [pose_inputs_dict[frame_i], pose_inputs_dict[0]]\n            else:\n                pose_inputs = [pose_inputs_dict[0], pose_inputs_dict[frame_i]]\n            pose_inputs = torch.cat(pose_inputs, 1)\n            if use_online:\n                pose_features = [self.online_models['pose_encoder'](pose_inputs)]\n                axis_angle, translation = self.online_models['pose_decoder'](pose_features)\n            else:\n                if self.models['pose_encoder'] is None:\n                    axis_angle, translation = self.models['pose_decoder'](pose_inputs)\n                else:\n                    pose_features = [self.models['pose_encoder'](pose_inputs)]\n                    axis_angle, translation = self.models['pose_decoder'](pose_features)\n            axis_angle, translation = axis_angle[:, 0], translation[:, 0]\n            outputs[('axis_angle', 0, frame_i)] = axis_angle\n            outputs[('translation', 0, frame_i)] = translation\n\n            # Invert the matrix such that it is always frame 0 -> frame X\n            outputs[('cam_T_cam', 0,\n                     frame_i)] = transformation_from_parameters(axis_angle,\n                                                                translation,\n                                                                invert=frame_i < 0)\n        return outputs\n\n    def _reconstruct_images(\n            self,\n            inputs: Dict[Any, Tensor],\n            outputs: Dict[Any, Tensor],\n    ) -> None:\n        \"\"\"Generate the warped (reprojected) color images for a minibatch.\n        Generated images are added to the 'outputs' dictionary.\n        \"\"\"\n        batch_size = outputs['disp', self.scales[0]].shape[0]\n\n        for scale in self.scales:\n            # Upsample the disparity from scale to the target height x width\n            disp = outputs[('disp', scale)]\n            disp = F.interpolate(disp, [self.height, self.width],\n                                 mode='bilinear',\n                                 align_corners=False)\n            source_scale = 0\n\n            depth = disp_to_depth(disp, self.min_depth, self.max_depth)\n            outputs[('depth', scale)] = depth\n\n            for i, frame_id in enumerate(self.frame_ids[1:]):\n                T = outputs[('cam_T_cam', 0, frame_id)]\n\n                if batch_size == 1:\n                    cam_points = self.backproject_depth_single[source_scale](\n                        depth, inputs[('inv_camera_matrix', source_scale)])\n                    pixel_coordinates = self.project_3d_single[source_scale](\n                        cam_points, inputs[('camera_matrix', source_scale)], T)\n                else:\n                    cam_points = self.backproject_depth[source_scale](depth,\n                                                                      inputs[('inv_camera_matrix',\n                                                                              source_scale)])\n                    pixel_coordinates = self.project_3d[source_scale](cam_points,\n                                                                      inputs[('camera_matrix',\n                                                                              source_scale)], T)\n                # Save the warped image\n                outputs[('rgb', frame_id, scale)] = F.grid_sample(inputs[('rgb', frame_id,\n                                                                          source_scale)],\n                                                                  pixel_coordinates,\n                                                                  padding_mode='border',\n                                                                  align_corners=True)\n\n    def _compute_loss(\n            self,\n            inputs: Dict[Any, Tensor],\n            outputs: Dict[Any, Tensor],\n            scales: Optional[Tuple[int, ...]] = None,\n            sample_weights: Optional[Tensor] = None,\n    ) -> Dict[str, Tensor]:\n        \"\"\"Compute the losses for a minibatch.\n        \"\"\"\n        assert self.frame_ids in ((0, -1, 1), (0, -1))\n        scales = self.scales if scales is None else scales\n\n        if sample_weights is None:\n            sample_weights = torch.ones(self.batch_size, device=self.device) / self.batch_size\n\n        source_scale = 0\n        losses = {}\n        total_loss = torch.zeros(1, device=self.device)\n\n        for scale in scales:\n            # Compute reprojection loss for every scale ========\n            target = inputs['rgb', 0, source_scale]\n            reprojection_losses = []\n            for frame_id in self.frame_ids[1:]:\n                pred = outputs['rgb', frame_id, scale]\n                reprojection_losses.append(self._compute_reprojection_loss(pred, target))\n            reprojection_losses = torch.cat(reprojection_losses, 1)\n            # ==================================================\n\n            # Auto-masking =====================================\n            identity_reprojection_losses = []\n            for frame_id in self.frame_ids[1:]:\n                pred = inputs['rgb', frame_id, source_scale]\n                identity_reprojection_losses.append(self._compute_reprojection_loss(pred, target))\n            identity_reprojection_losses = torch.cat(identity_reprojection_losses, 1)\n            # Add random numbers to break ties\n            identity_reprojection_losses += torch.randn(identity_reprojection_losses.shape,\n                                                        device=self.device) * 0.00001\n            combined = torch.cat((identity_reprojection_losses, reprojection_losses), dim=1)\n\n            # \"minimum among computed losses allows for robust reprojection\"\n            # https://openaccess.thecvf.com/content_CVPR_2020/papers/Poggi_On_the_Uncertainty_of_Self-Supervised_Monocular_Depth_Estimation_CVPR_2020_paper.pdf\n            to_optimize, _ = torch.min(combined, dim=1)\n\n            # Mask potentially dynamic objects =================\n            if self.mask_dynamic:\n                # 0: dynamic; 1: static\n                mask = 1 - inputs['mask', 0, source_scale].squeeze()\n                mask = mask.type(torch.bool)\n                to_optimize = torch.masked_select(to_optimize, mask)  # Also flattens the array\n            # ==================================================\n\n            # Total self-supervision (reprojection) loss =======\n            if not self.mask_dynamic:\n                reprojection_loss = (to_optimize.mean(2).mean(1) * sample_weights).sum()\n            else:\n                reprojection_loss = to_optimize.mean()  # pre-training with masks\n            losses[f'reprojection_loss/scale_{scale}'] = reprojection_loss\n            # ==================================================\n\n            # Compute smoothness loss for every scale ==========\n            if self.mask_dynamic:\n                mask = 1 - inputs['mask', 0, scale]\n                mask = mask.type(torch.bool)\n            else:\n                mask = torch.ones_like(outputs['disp', scale], dtype=torch.bool, device=self.device)\n            color = inputs['rgb', 0, scale]\n            disp = outputs['disp', scale]\n            mean_disp = disp.mean(2, True).mean(3, True)\n            norm_disp = disp / (mean_disp + 1e-7)\n            smooth_loss = self._compute_smooth_loss(norm_disp, color, mask)\n            smooth_loss = (smooth_loss * sample_weights).sum()\n            losses[f'smooth_loss/scale_{scale}'] = smooth_loss\n            # ==================================================\n\n            regularization_loss = self.disparity_smoothness / (2 ** scale) * smooth_loss\n            losses[f'reg_loss/scale_{scale}'] = regularization_loss\n            # ==================================================\n\n            loss = reprojection_loss + regularization_loss\n            losses[f'depth_loss/scale_{scale}'] = loss\n            total_loss += loss\n        total_loss /= len(self.scales)\n        losses['depth_loss'] = total_loss\n\n        # Velocity supervision loss (scale independent) ====\n        if self.velocity_loss_scaling is not None and self.velocity_loss_scaling > 0:\n            velocity_loss = self.velocity_loss_scaling * self._compute_velocity_loss(\n                inputs, outputs)\n            velocity_loss = (velocity_loss * sample_weights).sum()\n            losses['velocity_loss'] = velocity_loss\n            total_loss += velocity_loss\n        # ==================================================\n\n        losses['loss'] = total_loss\n\n        if np.isnan(losses['loss'].item()):\n            for k, v in losses.items():\n                print(k, v.item())\n            raise RuntimeError('NaN loss')\n\n        return losses\n\n    # ============================================================\n    # Losses\n\n    def _compute_velocity_loss(\n            self,\n            inputs: Dict[Any, Tensor],\n            outputs: Dict[Any, Tensor],\n    ) -> Tensor:\n        batch_size = inputs['index'].shape[0]  # might be different from self.batch_size\n        velocity_loss = torch.zeros(batch_size, device=self.device).squeeze()\n        num_frames = 0\n        for frame in self.frame_ids:\n            if frame == -1:\n                continue\n            if frame == 0:\n                pred_translation = outputs[('translation', 0, -1)]\n            else:  # frame == 1\n                pred_translation = outputs[('translation', 0, 1)]\n            gt_distance = torch.abs(inputs[('relative_distance', frame)]).squeeze()\n            pred_distance = torch.linalg.norm(pred_translation, dim=-1).squeeze()\n            velocity_loss += F.l1_loss(pred_distance, gt_distance,\n                                       reduction='none')  # separated by sample in batch\n            num_frames += 1\n        velocity_loss /= num_frames\n        return velocity_loss\n\n    @staticmethod\n    def _compute_smooth_loss(\n            disp: Tensor,\n            img: Tensor,\n            mask: Tensor,\n    ) -> Tensor:\n        \"\"\"Computes the smoothness loss for a disparity image\n        The color image is used for edge-aware smoothness\n        \"\"\"\n        grad_disp_x = torch.abs(disp[:, :, :, :-1] - disp[:, :, :, 1:])\n        grad_disp_y = torch.abs(disp[:, :, :-1, :] - disp[:, :, 1:, :])\n\n        grad_img_x = torch.mean(torch.abs(img[:, :, :, :-1] - img[:, :, :, 1:]), 1, keepdim=True)\n        grad_img_y = torch.mean(torch.abs(img[:, :, :-1, :] - img[:, :, 1:, :]), 1, keepdim=True)\n\n        grad_disp_x *= torch.exp(-grad_img_x)\n        grad_disp_y *= torch.exp(-grad_img_y)\n\n        grad_disp_x = torch.masked_select(grad_disp_x, mask[..., :-1])\n        grad_disp_y = torch.masked_select(grad_disp_y, mask[..., :-1, :])\n\n        batch_size = disp.shape[0]\n        smooth_loss = torch.empty(batch_size, device=disp.device)\n        for i in range(batch_size):\n            _grad_disp_x = torch.masked_select(grad_disp_x[i, ...], mask[i, :, :, :-1])\n            _grad_disp_y = torch.masked_select(grad_disp_y[i, ...], mask[i, :, :-1, :])\n            smooth_loss[i] = _grad_disp_x.mean() + _grad_disp_y.mean()\n\n        return smooth_loss\n\n    def _compute_reprojection_loss(\n            self,\n            pred: Tensor,\n            target: Tensor,\n    ) -> Tensor:\n        \"\"\"Computes reprojection loss between a batch of predicted and target images\n        This is the photometric error\n        \"\"\"\n        abs_diff = torch.abs(target - pred)\n        l1_loss = abs_diff.mean(1, True)\n\n        ssim_loss = self.ssim(pred, target).mean(1, True)\n        reprojection_loss = 0.85 * ssim_loss + 0.15 * l1_loss\n\n        return reprojection_loss\n\n    # ============================================================\n    # Logging\n\n    def save_prediction(\n            self,\n            inputs: Dict[Any, Tensor],\n            outputs: Dict[Any, Tensor],\n    ) -> None:\n        save_folder = self.log_path / 'prediction' / f'val_depth_{self.epoch:03}'\n        save_folder.mkdir(parents=True, exist_ok=True)\n\n        pil_image = None\n\n        # Iterate over the images\n        for i, index in enumerate(inputs['index']):\n            rgb = inputs['rgb', 0, 0][i]\n            depth = outputs['depth', 0][i]\n\n            rgb_np = rgb.squeeze().cpu().detach().numpy()\n            rgb_np = np.moveaxis(rgb_np, 0, -1)  # Convert from [c, h, w] to [h, w, c]\n            depth_np = depth.squeeze().cpu().detach().numpy()\n\n            fig = plt.figure(figsize=(12.8, 9.6))\n            plt.subplot(211)\n            plt.imshow(rgb_np)\n            plt.title('Input')\n            plt.axis('off')\n            plt.subplot(212)\n            vmax = np.percentile(depth_np, 95)\n            plt.imshow(depth_np, cmap='magma_r', vmax=vmax)\n            plt.title(f'Depth prediction  |  vmax={vmax:.3f}')\n            plt.axis('off')\n\n            save_file = save_folder / f'{index.item():05}.png'\n            # fig.suptitle(str(save_file)[-50:])\n            fig.canvas.draw()\n\n            if pil_image is None:\n                pil_image = Image.frombytes('RGB', fig.canvas.get_width_height(),\n                                            fig.canvas.tostring_rgb())\n            elif pil_image.size[0] < 5 * self.width:\n                pil_image = h_concat_images(\n                    pil_image,\n                    Image.frombytes('RGB', fig.canvas.get_width_height(),\n                                    fig.canvas.tostring_rgb()))\n\n            plt.savefig(save_file, bbox_inches='tight')\n            plt.close()\n\n        if self.use_wandb:\n            wandb.log({'pred_depth': [wandb.Image(pil_image)]})\n\n    def _init_wandb(self):\n        # Name of the run as shown in the wandb GUI\n        name = self.log_path.name\n\n        wandb.init(project='continual_slam', name=name)\n        wandb.config.dataset_type = self.dataset_type\n        wandb.config.train_set = self.train_set\n        wandb.config.val_set = self.val_set\n        wandb.config.height = self.height\n        wandb.config.width = self.width\n        wandb.config.batch_size = self.batch_size\n        wandb.config.num_workers = self.num_workers\n        wandb.config.resnet_depth = self.resnet_depth\n        wandb.config.resnet_pose = self.resnet_pose\n        wandb.config.learning_rate = self.learning_rate\n        wandb.config.scheduler_step_size = self.scheduler_step_size\n        wandb.config.min_depth = self.min_depth\n        wandb.config.max_depth = self.max_depth\n        wandb.config.disparity_smoothness = self.disparity_smoothness\n        wandb.config.velocity_loss_scaling = self.velocity_loss_scaling\n        wandb.config.mask_dynamic = self.mask_dynamic\n        wandb.config.log_path = self.log_path\n"
  },
  {
    "path": "depth_pose_prediction/networks/__init__.py",
    "content": "from depth_pose_prediction.networks.depth_decoder import DepthDecoder\nfrom depth_pose_prediction.networks.layers import (\n    SSIM,\n    BackprojectDepth,\n    Project3D,\n)\nfrom depth_pose_prediction.networks.pose_decoder import PoseDecoder\nfrom depth_pose_prediction.networks.resnet_encoder import ResnetEncoder\n"
  },
  {
    "path": "depth_pose_prediction/networks/depth_decoder.py",
    "content": "# Adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/networks/depth_decoder.py\n\nfrom typing import Dict, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom torch import Tensor, nn\n\nfrom .layers import Conv3x3, ConvBlock\n\n\nclass DepthDecoder(nn.Module):\n    def __init__(\n            self,\n            num_ch_encoder: np.ndarray,\n            scales: Tuple[int, ...] = (0, 1, 2, 3),\n            use_skips: bool = True,\n    ) -> None:\n        super().__init__()\n\n        self.scales = scales\n        self.use_skips = use_skips\n        self.num_output_channels = 1\n\n        self.num_ch_encoder = num_ch_encoder\n        self.num_ch_decoder = np.array([16, 32, 64, 128, 256])\n\n        self.convs = {}\n        for i in range(4, -1, -1):\n            # upconv_0\n            num_ch_in = self.num_ch_encoder[-1] if i == 4 else self.num_ch_decoder[i + 1]\n            num_ch_out = self.num_ch_decoder[i]\n            setattr(self, f'upconv_{i}_0', ConvBlock(num_ch_in, num_ch_out))\n\n            # upconv_1\n            num_ch_in = self.num_ch_decoder[i]\n            if self.use_skips and i > 0:\n                num_ch_in += self.num_ch_encoder[i - 1]\n            num_ch_out = self.num_ch_decoder[i]\n            setattr(self, f'upconv_{i}_1', ConvBlock(num_ch_in, num_ch_out))\n\n        for s in self.scales:\n            setattr(self, f'dispconv_{s}', Conv3x3(self.num_ch_decoder[s],\n                                                   self.num_output_channels))\n\n        self.sigmoid = nn.Sigmoid()\n        self.output = {}\n\n    def forward(self, input_features: Tensor) -> Dict[Tuple[str, int], Tensor]:\n        self.output = {}\n\n        x = input_features[-1]\n        for i in range(4, -1, -1):\n            x = getattr(self, f'upconv_{i}_0')(x)\n            if self.use_skips and i > 0:\n                # Difference to monodepth2 implementation to deal with image resolutions\n                # that cannot be integer-divided by 2, 4, 8, etc.\n                # Only required when evaluating the depth\n                x = [F.interpolate(x, size=input_features[i - 1].shape[2:], mode='nearest')]\n                x += [input_features[i - 1]]\n            else:\n                x = [F.interpolate(x, scale_factor=2, mode='nearest')]\n            x = torch.cat(x, 1)\n            x = getattr(self, f'upconv_{i}_1')(x)\n            if i in self.scales:\n                # monodepth2 paper (w/o uncertainty)\n                self.output[('disp', i)] = self.sigmoid(getattr(self, f'dispconv_{i}')(x))\n\n        return self.output\n"
  },
  {
    "path": "depth_pose_prediction/networks/layers.py",
    "content": "# Adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/layers.py#L64\n\nimport numpy as np\nimport torch\nfrom torch import Tensor, nn\n\n\nclass ConvBlock(nn.Module):\n    \"\"\"Layer to perform a convolution followed by ELU.\n    \"\"\"\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n    ) -> None:\n        super().__init__()\n\n        self.conv = Conv3x3(in_channels, out_channels)\n        self.nonlin = nn.ELU(inplace=True)\n\n    def forward(self, x: Tensor) -> Tensor:\n        out = self.conv(x)\n        out = self.nonlin(out)\n        return out\n\n\nclass Conv3x3(nn.Module):\n    \"\"\"Layer to pad and convolve input.\n    \"\"\"\n    def __init__(\n        self,\n        in_channels: int,\n        out_channels: int,\n        use_reflection: bool = True,\n    ) -> None:\n        super().__init__()\n\n        if use_reflection:\n            self.pad = nn.ReflectionPad2d(1)\n        else:\n            self.pad = nn.ZeroPad2d(1)\n        self.conv = nn.Conv2d(int(in_channels), int(out_channels), 3)\n\n    def forward(self, x: Tensor) -> Tensor:\n        out = self.pad(x)\n        out = self.conv(out)\n        return out\n\n\nclass BackprojectDepth(nn.Module):\n    \"\"\"Layer to transform a depth image into a point cloud\n    \"\"\"\n    def __init__(self, batch_size: int, height: int, width: int) -> None:\n        super().__init__()\n\n        self.batch_size = batch_size\n        self.height = height\n        self.width = width\n\n        meshgrid = np.meshgrid(range(self.width), range(self.height), indexing='xy')\n        self.id_coords = np.stack(meshgrid, axis=0).astype(np.float32)\n        self.id_coords = nn.Parameter(torch.from_numpy(self.id_coords), requires_grad=False)\n\n        self.ones = nn.Parameter(torch.ones(self.batch_size, 1, self.height * self.width),\n                                 requires_grad=False)\n\n        self.pix_coords = torch.unsqueeze(\n            torch.stack([self.id_coords[0].view(-1), self.id_coords[1].view(-1)], 0), 0)\n        self.pix_coords = self.pix_coords.repeat(batch_size, 1, 1)\n        self.pix_coords = nn.Parameter(torch.cat([self.pix_coords, self.ones], 1),\n                                       requires_grad=False)\n\n    def forward(self, depth, inv_K):\n        cam_points = torch.matmul(inv_K[:, :3, :3], self.pix_coords)\n        cam_points = depth.view(self.batch_size, 1, -1) * cam_points\n        cam_points = torch.cat([cam_points, self.ones], 1)\n\n        return cam_points\n\n\nclass Project3D(nn.Module):\n    \"\"\"Layer which projects 3D points into a camera with intrinsics K and at position T\n    \"\"\"\n    def __init__(self, batch_size: int, height: int, width: int, eps: float = 1e-7) -> None:\n        super().__init__()\n\n        self.batch_size = batch_size\n        self.height = height\n        self.width = width\n        self.eps = eps\n\n    def forward(self, points, K, T):\n        P = torch.matmul(K, T)[:, :3, :]\n\n        cam_points = torch.matmul(P, points)\n\n        pixel_coordinates = cam_points[:, :2, :] / (cam_points[:, 2, :].unsqueeze(1) + self.eps)\n        pixel_coordinates = pixel_coordinates.view(self.batch_size, 2, self.height, self.width)\n        pixel_coordinates = pixel_coordinates.permute(0, 2, 3, 1)\n        pixel_coordinates[..., 0] /= self.width - 1\n        pixel_coordinates[..., 1] /= self.height - 1\n        pixel_coordinates = (pixel_coordinates - 0.5) * 2\n        return pixel_coordinates\n\n\nclass SSIM(nn.Module):\n    \"\"\"Layer to compute the SSIM loss between a pair of images\n    \"\"\"\n    def __init__(self) -> None:\n        super().__init__()\n        self.mu_x_pool = nn.AvgPool2d(3, 1)\n        self.mu_y_pool = nn.AvgPool2d(3, 1)\n        self.sig_x_pool = nn.AvgPool2d(3, 1)\n        self.sig_y_pool = nn.AvgPool2d(3, 1)\n        self.sig_xy_pool = nn.AvgPool2d(3, 1)\n\n        self.refl = nn.ReflectionPad2d(1)\n\n        self.C1 = 0.01**2\n        self.C2 = 0.03**2\n\n    def forward(self, x: Tensor, y: Tensor) -> Tensor:\n        x = self.refl(x)\n        y = self.refl(y)\n\n        mu_x = self.mu_x_pool(x)\n        mu_y = self.mu_y_pool(y)\n\n        sigma_x = self.sig_x_pool(x**2) - mu_x**2\n        sigma_y = self.sig_y_pool(y**2) - mu_y**2\n        sigma_xy = self.sig_xy_pool(x * y) - mu_x * mu_y\n\n        SSIM_n = (2 * mu_x * mu_y + self.C1) * (2 * sigma_xy + self.C2)\n        SSIM_d = (mu_x**2 + mu_y**2 + self.C1) * (sigma_x + sigma_y + self.C2)\n\n        return torch.clamp((1 - SSIM_n / SSIM_d) / 2, 0, 1)\n"
  },
  {
    "path": "depth_pose_prediction/networks/pose_decoder.py",
    "content": "# Adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/networks/pose_decoder.py\n\nfrom typing import Optional, Tuple\n\nimport numpy as np\nimport torch\nfrom torch import Tensor, nn\n\n\nclass PoseDecoder(nn.Module):\n    def __init__(\n        self,\n        num_ch_encoder: np.ndarray,\n        num_input_features: int,\n        num_frames_to_predict_for: Optional[int] = None,\n    ) -> None:\n        super().__init__()\n\n        self.num_ch_encoder = num_ch_encoder\n        self.num_input_features = num_input_features\n\n        if num_frames_to_predict_for is None:\n            num_frames_to_predict_for = num_input_features - 1\n        self.num_frames_to_predict_for = num_frames_to_predict_for\n\n        setattr(self, 'squeeze', nn.Conv2d(self.num_ch_encoder[-1], 256, 1))\n        setattr(self, 'pose_0', nn.Conv2d(num_input_features * 256, 256, 3, 1, 1))\n        setattr(self, 'pose_1', nn.Conv2d(256, 256, 3, 1, 1))\n        setattr(self, 'pose_2', nn.Conv2d(256, 6 * num_frames_to_predict_for, 1))\n\n        self.relu = nn.ReLU()\n        self.tanh = nn.Tanh()\n        self.softplus = nn.Softplus()\n        self.sigmoid = nn.Sigmoid()\n\n    def forward(self, input_features: Tensor) -> Tuple[Tensor, Tensor]:\n        last_features = [f[-1] for f in input_features]\n\n        cat_features = [self.relu(getattr(self, 'squeeze')(f)) for f in last_features]\n        cat_features = torch.cat(cat_features, 1)\n\n        out = cat_features\n        for i in range(3):\n            out = getattr(self, f'pose_{i}')(out)\n            if i != 2:\n                out = self.relu(out)\n\n        out = out.mean(3).mean(2)\n        out = 0.01 * out.view(-1, self.num_frames_to_predict_for, 1, 6)\n\n        axis_angle = out[..., :3]\n        translation = out[..., 3:]\n        return axis_angle, translation\n"
  },
  {
    "path": "depth_pose_prediction/networks/resnet_encoder.py",
    "content": "# Adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/networks/resnet_encoder.py\n\nfrom typing import List, Type, Union\n\nimport numpy as np\nimport torch\nfrom torch import Tensor, nn\nfrom torch.utils import model_zoo\nfrom torchvision import models\n\n\nclass ResNetMultiImageInput(models.ResNet):\n    \"\"\"Constructs a resnet model with varying number of input images.\n    Adapted from https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py\n    \"\"\"\n    def __init__(\n        self,\n        block: Type[Union[models.resnet.BasicBlock, models.resnet.Bottleneck]],\n        layers: List[int],\n        num_input_images: int = 1,\n    ) -> None:\n        super().__init__(block, layers)\n        self.inplanes = 64\n        self.conv1 = nn.Conv2d(num_input_images * 3,\n                               64,\n                               kernel_size=7,\n                               stride=2,\n                               padding=3,\n                               bias=False)\n        self.bn1 = nn.BatchNorm2d(64)\n        self.relu = nn.ReLU(inplace=True)\n        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        self.layer1 = self._make_layer(block, 64, layers[0])\n        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, nn.BatchNorm2d):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n\ndef resnet_multiimage_input(\n    num_layers: int,\n    pretrained: bool = False,\n    num_input_images: int = 1,\n) -> models.ResNet:\n    \"\"\"Constructs a resnet model with varying number of input images.\n\n    :param num_layers: Specifies the ResNet model to be used\n    :param pretrained: If True, returns a model pre-trained on ImageNet\n    :param num_input_images: Specifies the number of input images. For PoseNet, >1.\n    \"\"\"\n    if num_layers not in [18, 50]:\n        raise ValueError('Resnet multi-image can only run with 18 or 50 layers.')\n\n    block_type = {\n        18: models.resnet.BasicBlock,\n        50: models.resnet.Bottleneck,\n    }[num_layers]\n    blocks = {\n        18: [2, 2, 2, 2],\n        50: [3, 4, 6, 3],\n    }[num_layers]\n    model = ResNetMultiImageInput(block_type, blocks, num_input_images=num_input_images)\n\n    if pretrained:\n        loaded = model_zoo.load_url(models.resnet.model_urls[f'resnet{num_layers}'])\n        loaded['conv1.weight'] = torch.cat([loaded['conv1.weight']] * num_input_images,\n                                           1) / num_input_images\n        model.load_state_dict(loaded)\n    return model\n\n\nclass ResnetEncoder(nn.Module):\n    AVAILABLE_RESNETS = {\n        18: models.resnet18,\n        34: models.resnet34,\n        # 50: models.resnet50,\n    }\n\n    def __init__(\n        self,\n        num_layers: int,\n        pretrained: bool,\n        num_input_images: int = 1,\n    ) -> None:\n        \"\"\"Constructs a ResNet model.\n\n        :param num_layers: Specifies the ResNet model to be used\n        :param pretrained: If True, returns a model pre-trained on ImageNet\n        :param num_input_images: Specifies the number of input images. For PoseNet, >1.\n        \"\"\"\n        super().__init__()\n        self.num_ch_encoder = np.array([64, 64, 128, 256, 512])\n\n        if num_layers not in self.AVAILABLE_RESNETS.keys():\n            raise ValueError(f'Could not find a ResNet model with {num_layers} layers.')\n\n        if num_input_images < 1:\n            raise ValueError(f'Invalid value ({num_input_images}) for num_input_images.')\n        if num_input_images == 1:\n            self.resnet = self.AVAILABLE_RESNETS[num_layers](pretrained)\n        else:\n            self.resnet = resnet_multiimage_input(num_layers, pretrained, num_input_images)\n\n        # From paper\n        if num_layers > 34:\n            self.num_ch_encoder[1:] *= 4\n\n    def forward(self, x: Tensor) -> List[Tensor]:\n        features = []\n        x = (x - 0.45) / 0.225\n        x = self.resnet.conv1(x)\n        x = self.resnet.bn1(x)\n        features.append(self.resnet.relu(x))\n        features.append(self.resnet.layer1(self.resnet.maxpool(features[-1])))\n        features.append(self.resnet.layer2(features[-1]))\n        features.append(self.resnet.layer3(features[-1]))\n        features.append(self.resnet.layer4(features[-1]))\n        return features\n"
  },
  {
    "path": "depth_pose_prediction/pytorch3d.py",
    "content": "# Copied from:\n# https://pytorch3d.readthedocs.io/en/latest/_modules/pytorch3d/transforms/rotation_conversions.html\n\nimport torch\nimport torch.nn.functional as F\n\n\ndef quaternion_to_axis_angle(quaternions: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Convert rotations given as quaternions to axis/angle.\n\n    Args:\n        quaternions: quaternions with real part first,\n            as tensor of shape (..., 4).\n\n    Returns:\n        Rotations given as a vector in axis angle form, as a tensor\n            of shape (..., 3), where the magnitude is the angle\n            turned anticlockwise in radians around the vector's\n            direction.\n    \"\"\"\n    norms = torch.norm(quaternions[..., 1:], p=2, dim=-1, keepdim=True)\n    half_angles = torch.atan2(norms, quaternions[..., :1])\n    angles = 2 * half_angles\n    eps = 1e-6\n    small_angles = angles.abs() < eps\n    sin_half_angles_over_angles = torch.empty_like(angles)\n    sin_half_angles_over_angles[~small_angles] = (torch.sin(half_angles[~small_angles]) /\n                                                  angles[~small_angles])\n    # for x small, sin(x/2) is about x/2 - (x/2)^3/6\n    # so sin(x/2)/x is about 1/2 - (x*x)/48\n    sin_half_angles_over_angles[small_angles] = (0.5 -\n                                                 (angles[small_angles] * angles[small_angles]) / 48)\n    return quaternions[..., 1:] / sin_half_angles_over_angles\n\n\ndef matrix_to_quaternion(matrix: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Convert rotations given as rotation matrices to quaternions.\n\n    Args:\n        matrix: Rotation matrices as tensor of shape (..., 3, 3).\n\n    Returns:\n        quaternions with real part first, as tensor of shape (..., 4).\n    \"\"\"\n    if matrix.size(-1) != 3 or matrix.size(-2) != 3:\n        raise ValueError(f\"Invalid rotation matrix shape {matrix.shape}.\")\n\n    batch_dim = matrix.shape[:-2]\n    m00, m01, m02, m10, m11, m12, m20, m21, m22 = torch.unbind(matrix.reshape(batch_dim + (9, )),\n                                                               dim=-1)\n\n    q_abs = _sqrt_positive_part(\n        torch.stack(\n            [\n                1.0 + m00 + m11 + m22,\n                1.0 + m00 - m11 - m22,\n                1.0 - m00 + m11 - m22,\n                1.0 - m00 - m11 + m22,\n            ],\n            dim=-1,\n        ))\n\n    # we produce the desired quaternion multiplied by each of r, i, j, k\n    quat_by_rijk = torch.stack(\n        [\n            torch.stack([q_abs[..., 0]**2, m21 - m12, m02 - m20, m10 - m01], dim=-1),\n            torch.stack([m21 - m12, q_abs[..., 1]**2, m10 + m01, m02 + m20], dim=-1),\n            torch.stack([m02 - m20, m10 + m01, q_abs[..., 2]**2, m12 + m21], dim=-1),\n            torch.stack([m10 - m01, m20 + m02, m21 + m12, q_abs[..., 3]**2], dim=-1),\n        ],\n        dim=-2,\n    )\n\n    # We floor here at 0.1 but the exact level is not important; if q_abs is small,\n    # the candidate won't be picked.\n    flr = torch.tensor(0.1).to(dtype=q_abs.dtype, device=q_abs.device)\n    quat_candidates = quat_by_rijk / (2.0 * q_abs[..., None].max(flr))\n\n    # if not for numerical problems, quat_candidates[i] should be same (up to a sign),\n    # forall i; we pick the best-conditioned one (with the largest denominator)\n\n    return quat_candidates[F.one_hot(q_abs.argmax(\n        dim=-1), num_classes=4) > 0.5, :  # pyre-ignore[16]\n                           ].reshape(batch_dim + (4, ))\n\n\ndef _sqrt_positive_part(x: torch.Tensor) -> torch.Tensor:\n    \"\"\"\n    Returns torch.sqrt(torch.max(0, x))\n    but with a zero subgradient where x is 0.\n    \"\"\"\n    ret = torch.zeros_like(x)\n    positive_mask = x > 0\n    ret[positive_mask] = torch.sqrt(x[positive_mask])\n    return ret\n"
  },
  {
    "path": "depth_pose_prediction/utils.py",
    "content": "from typing import Optional, Tuple, Union\n\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\n\nfrom depth_pose_prediction.pytorch3d import (\n    matrix_to_quaternion,\n    quaternion_to_axis_angle,\n)\n\n\ndef parameters_from_transformation(\n    transformation: Tensor,\n    as_numpy: bool = False,\n) -> Tuple[Tensor, Tensor]:\n    \"\"\"Convert a 4x4 transformation matrix to a translation vector and the axis angles\n    \"\"\"\n    translation_vector = transformation[:, :, :3, 3]\n    axis_angle = quaternion_to_axis_angle(matrix_to_quaternion(transformation[:, :, :3, :3]))\n    if as_numpy:\n        translation_vector = translation_vector.squeeze().cpu().numpy()\n        axis_angle = axis_angle.squeeze().cpu().numpy()\n    return translation_vector, axis_angle\n\n\n# -----------------------------------------------------------------------------\n\n# The code below is adapted from:\n# https://github.com/nianticlabs/monodepth2/blob/master/layers.py\n\n\ndef transformation_from_parameters(\n    axis_angle: Tensor,\n    translation: Tensor,\n    invert: bool = False,\n) -> Tensor:\n    \"\"\"Convert the network's (axis angle, translation) output into a 4x4 matrix\n    \"\"\"\n    R = rot_from_axisangle(axis_angle)\n    t = translation.clone()\n\n    if invert:\n        R = R.transpose(1, 2)\n        t *= -1\n\n    T = get_translation_matrix(t)\n\n    if invert:\n        M = torch.matmul(R, T)\n    else:\n        M = torch.matmul(T, R)\n\n    return M\n\n\ndef get_translation_matrix(translation_vector: Tensor) -> Tensor:\n    \"\"\"Convert a translation vector into a 4x4 transformation matrix\n    \"\"\"\n    T = torch.zeros(translation_vector.shape[0], 4, 4).to(device=translation_vector.device)\n\n    t = translation_vector.contiguous().view(-1, 3, 1)\n\n    T[:, 0, 0] = 1\n    T[:, 1, 1] = 1\n    T[:, 2, 2] = 1\n    T[:, 3, 3] = 1\n    T[:, :3, 3, None] = t\n\n    return T\n\n\ndef rot_from_axisangle(axis_angle: Tensor) -> Tensor:\n    \"\"\"Convert an axisangle rotation into a 4x4 transformation matrix\n    (adapted from https://github.com/Wallacoloo/printipi)\n    Input 'axis_angle' has to be Bx1x3\n\n    This is similar to the code below but has less rounding:\n    from scipy.spatial.transform import Rotation\n    Rotation.from_rotvec(axis_angle).as_matrix()\n    \"\"\"\n    angle = torch.norm(axis_angle, 2, 2, True)\n    axis = axis_angle / (angle + 1e-7)\n\n    ca = torch.cos(angle)\n    sa = torch.sin(angle)\n    C = 1 - ca\n\n    x = axis[..., 0].unsqueeze(1)\n    y = axis[..., 1].unsqueeze(1)\n    z = axis[..., 2].unsqueeze(1)\n\n    xs = x * sa\n    ys = y * sa\n    zs = z * sa\n    xC = x * C\n    yC = y * C\n    zC = z * C\n    xyC = x * yC\n    yzC = y * zC\n    zxC = z * xC\n\n    rot = torch.zeros((axis_angle.shape[0], 4, 4)).to(device=axis_angle.device)\n\n    rot[:, 0, 0] = torch.squeeze(x * xC + ca)\n    rot[:, 0, 1] = torch.squeeze(xyC - zs)\n    rot[:, 0, 2] = torch.squeeze(zxC + ys)\n    rot[:, 1, 0] = torch.squeeze(xyC + zs)\n    rot[:, 1, 1] = torch.squeeze(y * yC + ca)\n    rot[:, 1, 2] = torch.squeeze(yzC - xs)\n    rot[:, 2, 0] = torch.squeeze(zxC - ys)\n    rot[:, 2, 1] = torch.squeeze(yzC + xs)\n    rot[:, 2, 2] = torch.squeeze(z * zC + ca)\n    rot[:, 3, 3] = 1\n\n    return rot\n\n\ndef disp_to_depth(\n    disp: Union[Tensor, np.ndarray],\n    min_depth: Optional[float] = None,\n    max_depth: Optional[float] = None,\n) -> Union[Tensor, np.ndarray]:\n    \"\"\"Convert network's sigmoid output into depth prediction\n    The formula for this conversion is given in the 'additional considerations' section of the\n    monodepth2 paper.\n    \"\"\"\n    # if sum(x is None for x in [min_depth, max_depth]) not in [0, 2]:\n    #     raise ValueError('Either none or both of min_depth and max_depth must be None.')\n    if min_depth is None and max_depth is None:\n        depth = 1 / disp\n    elif max_depth is None:\n        depth = min_depth / disp\n    elif min_depth is None:\n        raise ValueError('min_depth is None')\n    else:\n        min_disp = 1 / max_depth\n        max_disp = 1 / min_depth\n        scaled_disp = min_disp + (max_disp - min_disp) * disp\n        depth = 1 / scaled_disp\n    return depth\n\n\n# -----------------------------------------------------------------------------\n\n\ndef h_concat_images(im1: Image, im2: Image) -> Image:\n    dst = Image.new('RGB', (im1.width + im2.width, im1.height))\n    dst.paste(im1, (0, 0))\n    dst.paste(im2, (im1.width, 0))\n    return dst\n"
  },
  {
    "path": "loop_closure_detection/__init__.py",
    "content": "import loop_closure_detection.utils\r\nfrom loop_closure_detection.config import LoopClosureDetection as Config\r\nfrom loop_closure_detection.loop_closure_detection import LoopClosureDetection\r\n"
  },
  {
    "path": "loop_closure_detection/config.py",
    "content": "import dataclasses\nfrom pathlib import Path\n\n\n@dataclasses.dataclass\nclass LoopClosureDetection:\n    config_file: Path\n    detection_threshold: float\n    id_threshold: int\n    num_matches: int\n"
  },
  {
    "path": "loop_closure_detection/encoder.py",
    "content": "import torch\nfrom torch import Tensor\nfrom torchvision import models, transforms\nfrom torchvision.models.feature_extraction import create_feature_extractor\n\n\nclass FeatureEncoder:\n    def __init__(self, device: torch.device):\n        super().__init__()\n        self.device = device\n\n        # self.model = models.inception_v3(pretrained=True, transform_input=False)\n        self.model = models.mobilenet_v3_small(pretrained=True)\n        self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n\n        # self.model.to(self.device)\n        # self.model.eval()\n\n        # train_nodes, eval_nodes = get_graph_node_names(self.model)\n        # pprint(eval_nodes)s\n\n        self.model = create_feature_extractor(self.model, return_nodes=['flatten'])\n        self.num_features = 576\n\n        self.model.to(self.device)\n        self.model.eval()\n\n    def __call__(self, image: Tensor) -> Tensor:\n        image = self.normalize(image)\n        image = image.to(self.device)\n        with torch.no_grad():\n            features = self.model(image)['flatten']\n        return features\n"
  },
  {
    "path": "loop_closure_detection/loop_closure_detection.py",
    "content": "from pathlib import Path\nfrom typing import List, Tuple\n\nimport faiss\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom scipy.spatial.distance import cosine\nfrom torch import Tensor\n\nfrom loop_closure_detection.config import LoopClosureDetection as Config\nfrom loop_closure_detection.encoder import FeatureEncoder\n\n\nclass LoopClosureDetection:\n    def __init__(\n        self,\n        config: Config,\n    ):\n        # Initialize parameters ===========================\n        self.threshold = config.detection_threshold\n        self.id_threshold = config.id_threshold\n        self.num_matches = config.num_matches\n\n        # Fixed parameters ================================\n        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n        # =================================================\n\n        # Construct network ===============================\n        self.model = FeatureEncoder(self.device)\n        # =================================================\n\n        # Feature cache ===================================\n        # Cosine similarity\n        self.faiss_index = faiss.index_factory(self.model.num_features, 'Flat',\n                                               faiss.METRIC_INNER_PRODUCT)\n        self.image_id_to_index = {}\n        self.index_to_image_id = {}\n        # =================================================\n\n    def add(self, image_id: int, image: Tensor) -> None:\n        # Add batch dimension\n        if len(image.shape) == 3:\n            image = image.unsqueeze(dim=0)\n        features = self.model(image).squeeze().cpu().detach().numpy()\n        features = np.expand_dims(features, 0)\n        faiss.normalize_L2(features)  # Then the inner product becomes cosine similarity\n        self.faiss_index.add(features)\n        self.image_id_to_index[image_id] = self.faiss_index.ntotal - 1\n        self.index_to_image_id[self.faiss_index.ntotal - 1] = image_id\n        # print(f'Is Faiss index trained: {self.faiss_index.is_trained}')\n\n    def search(self, image_id: int) -> Tuple[List[int], List[float]]:\n        index_id = self.image_id_to_index[image_id]\n        features = np.expand_dims(self.faiss_index.reconstruct(index_id), 0)\n        distances, indices = self.faiss_index.search(features, 100)\n        distances = distances.squeeze()\n        indices = indices.squeeze()\n        # Remove placeholder entries without a match\n        distances = distances[indices != -1]\n        indices = indices[indices != -1]\n        # Remove self detection\n        distances = distances[indices != index_id]\n        indices = indices[indices != index_id]\n        # Filter by the threshold\n        indices = indices[distances > self.threshold]\n        distances = distances[distances > self.threshold]\n        # Do not return neighbors (trivial matches)\n        distances = distances[np.abs(indices - index_id) > self.id_threshold]\n        indices = indices[np.abs(indices - index_id) > self.id_threshold]\n        # Return best N matches\n        distances = distances[:self.num_matches]\n        indices = indices[:self.num_matches]\n        # Convert back to image IDs\n        image_ids = sorted([self.index_to_image_id[index_id] for index_id in indices])\n        return image_ids, distances\n\n    def predict(self, image_0: Tensor, image_1: Tensor) -> float:\n        features_0 = self.model(image_0)\n        features_1 = self.model(image_1)\n        cos_sim = 1 - cosine(features_0.squeeze().cpu().detach().numpy(),\n                             features_1.squeeze().cpu().detach().numpy())\n        return cos_sim\n\n    @staticmethod\n    def display_matches(image_0, image_1, image_id_0, image_id_1, transformation,\n                        cosine_similarity):\n        # Prevent circular import\n        from slam.transform import \\\n            string_tmat  # pylint: disable=import-outside-toplevel\n        if isinstance(image_0, Tensor):\n            image_0 = image_0.squeeze().cpu().detach().permute(1, 2, 0)\n        if isinstance(image_1, Tensor):\n            image_1 = image_1.squeeze().cpu().detach().permute(1, 2, 0)\n\n        filename = Path(f'./figures/sequence_00/matches/{image_id_0:04}_{image_id_1:04}.png')\n        filename.parent.mkdir(parents=True, exist_ok=True)\n\n        fig = plt.figure()\n        plt.subplot(211)\n        plt.imshow(image_0)\n        plt.axis('off')\n        plt.title(image_id_0)\n        plt.subplot(212)\n        plt.imshow(image_1)\n        plt.axis('off')\n        plt.title(image_id_1)\n        plt.suptitle(f'cos_sim = {cosine_similarity:.4f} \\n {string_tmat(transformation)}')\n        plt.savefig(filename)\n        plt.close(fig)\n"
  },
  {
    "path": "loop_closure_detection/utils.py",
    "content": "from typing import Optional\n\nimport matplotlib.pyplot as plt\n\n\ndef plot_image_matches(\n    image_0,\n    image_1,\n    image_id_0: Optional[int] = None,\n    image_id_1: Optional[int] = None,\n    cosine_similarity: Optional[float] = None,\n    save_figure: bool = True,\n) -> None:\n    fig = plt.figure()\n    plt.subplot(211)\n    plt.imshow(image_0)\n    plt.axis('off')\n    if image_id_0 is not None:\n        plt.title(image_id_0)\n    plt.subplot(212)\n    plt.imshow(image_1)\n    plt.axis('off')\n    if image_id_1 is not None:\n        plt.title(image_id_1)\n    if cosine_similarity is not None:\n        plt.suptitle(f'cos_sim = {cosine_similarity}')\n    if save_figure:\n        assert image_id_0 is not None and image_id_1 is not None\n        plt.savefig(f'./figures/sequence_08/matches/{image_id_0:04}_{image_id_1:04}.png')\n    else:\n        plt.show()\n    plt.close(fig)\n"
  },
  {
    "path": "main_adapt.py",
    "content": "import random\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\nfrom config.config_parser import ConfigParser\nfrom slam import Slam\nfrom slam.utils import calc_error\n\nseed = 42\ntorch.manual_seed(seed)\nrandom.seed(seed)\nnp.random.seed(seed)\n\n# ============================================================\nconfig = ConfigParser('./config/config_adapt.yaml')\nprint(config)\n\n# ============================================================\nslam = Slam(config)\n\nwith tqdm(desc='SLAM', total=len(slam)) as pbar:\n    while slam.current_step < len(slam):\n        losses = slam.step()\n        pbar.set_postfix(depth=f'{losses[\"depth_loss\"]:.5f}', velo=f'{losses[\"velocity_loss\"]:.5f}')\n        pbar.update(1)\n\nif slam.do_adaptation:\n    slam.save_model()\nif slam.logging:\n    slam.plot_metrics()\n    slam.plot_trajectory()\n    slam.pose_graph.visualize_in_meshlab(slam.log_path / 'pose_graph.obj', verbose=True)\n    slam.gt_pose_graph.visualize_in_meshlab(slam.log_path / 'gt_pose_graph.obj', verbose=True)\nerror_log = calc_error(slam.pose_graph.get_all_poses(), slam.gt_pose_graph.get_all_poses())\nprint(error_log)\n\nwith open(config.depth_pose.log_path / 'log.txt', 'a', encoding='utf-8') as file:\n    file.write(error_log)\n"
  },
  {
    "path": "main_pretrain.py",
    "content": "# Use this script to pre-train the depth / pose estimation networks\n\nfrom config.config_parser import ConfigParser\nfrom depth_pose_prediction import DepthPosePrediction\n\n# ============================================================\nconfig = ConfigParser('./config/config_pretrain.yaml')\nprint(config)\n\n# ============================================================\npredictor = DepthPosePrediction(config.dataset, config.depth_pose)\npredictor.train(validate=True, depth_error=True, use_wandb=config.depth_pose.use_wandb)\n"
  },
  {
    "path": "make_cityscapes_buffer.py",
    "content": "from pathlib import Path\n\nfrom torch.utils.data import DataLoader\nfrom tqdm import tqdm\n\nfrom datasets import Cityscapes\nfrom slam.replay_buffer import ReplayBuffer\n\n# ============================================================\n\nreplay_buffer_path = Path(\n    __file__).parent / 'log/cityscapes/replay_buffer'  # <-- MATCH WITH config_pretrain.yaml\nreplay_buffer_path.parent.mkdir(parents=True, exist_ok=True)\nreplay_buffer = ReplayBuffer(replay_buffer_path, 'Cityscapes')\n\n# ============================================================\n\ndataset = Cityscapes(\n    Path('USER/data/cityscapes'),  # <-- ADJUST THIS\n    'train',\n    [-1, 0, 1],\n    [0, 1, 2, 3],\n    192,\n    640,\n    do_augmentation=False,\n    views=('left', ),\n)\ndataloader = DataLoader(dataset, num_workers=12, batch_size=1, shuffle=False, drop_last=True)\n\n# ============================================================\n\nwith tqdm(total=len(dataloader)) as pbar:\n    for i, sample in enumerate(dataloader):\n        replay_buffer.add(sample, dataset.get_item_filenames(i))\n        pbar.update(1)\nreplay_buffer.save_state()\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[tool.yapf]\nbased_on_style = \"pep8\"\ncolumn_limit = 100\nindent_width = 4\n\n[tool.isort]\nmulti_line_output = 3\ninclude_trailing_comma = true\n\n[tool.pylint.master]\nextension-pkg-whitelist = \"cv2\"\njobs = 0\n\n[tool.pylint.design]\nmin-public-methods = 1\n\n[tool.pylint.refactoring]\nmax-nested-blocks = 6\n\n[tool.pylint.format]\nmax-line-length = 100\nignore-long-lines = \"^\\\\s*(# )?<?https?://\\\\S+>?$\"\nmax-module-lines=1500\n\n[tool.pylint.typecheck]\ngenerated-members = [\n    \"numpy.*\",\n    \"torch.*\",\n    \"g2o.*\",\n]\n\n[tool.pylint.string]\ncheck-quote-consistency = \"yes\"\n\n[tool.pylint.messages_control]\ndisable = [\n    \"missing-module-docstring\",\n    \"missing-class-docstring\",\n    \"missing-function-docstring\",\n    \"fixme\",\n    \"too-many-instance-attributes\",\n    \"too-many-locals\",\n    \"too-many-arguments\",\n    \"too-many-statements\",\n    \"too-many-branches\",\n    \"unused-variable\",\n    \"invalid-name\",\n    \"duplicate-code\",\n]\n"
  },
  {
    "path": "requirements.txt",
    "content": "pre-commit\nyapf\npylint\n\ntorch==1.10.0\ntorchvision==0.11.1\nsetuptools==58.2.0\nnumpy\nPillow\ntqdm\nmatplotlib\npyyaml\nwandb\nopencv-python\ncolour_demosaicing\nscipy\nsklearn\nscikit-image\npandas\nfaiss-gpu\n"
  },
  {
    "path": "slam/__init__.py",
    "content": "import slam.utils\nfrom slam.config import ReplayBuffer as ReplayBufferConfig\nfrom slam.config import Slam as Config\nfrom slam.meshlab import MeshlabInf\nfrom slam.pose_graph_optimization import PoseGraphOptimization\nfrom slam.slam import Slam\n"
  },
  {
    "path": "slam/config.py",
    "content": "import dataclasses\nfrom pathlib import Path\n\n\n@dataclasses.dataclass\nclass Slam:\n    config_file: Path\n    dataset_sequence: int\n    adaptation: bool\n    adaptation_epochs: int\n    min_distance: float\n    start_frame: int\n    logging: bool\n    do_loop_closures: bool\n    keyframe_frequency: int\n    lc_distance_poses: int\n\n@dataclasses.dataclass\nclass ReplayBuffer:\n    config_file: Path\n    maximize_diversity: bool\n    max_buffer_size: int\n    similarity_threshold: float\n    similarity_sampling: bool\n    load_path: Path\n"
  },
  {
    "path": "slam/meshlab.py",
    "content": "# pylint: skip-file\n\nfrom subprocess import call\nfrom typing import List, Tuple, Union\n\nimport cv2\nimport matplotlib.cm\nimport numpy as np\nfrom tqdm import trange\n\nDEFAULT_COLOR = (0, 0, 0)\n\n\nclass MeshlabInf:\n    @staticmethod\n    def show_multi_layer(**kwargs):\n        \"\"\"\n        usage: given a set of MeshlabInf objects and their names, displays them in layer format.\n        example:\n        o1 = MeshlabInf()\n        o2 = MeshlabInf()\n        ...\n        MeshlabInf().show_multi_layer(layerA=o1,layerB=o2,...)\n        \"\"\"\n        d = dict(**kwargs)\n        for k, v in d.items():\n            v.write(k + \".obj\")\n\n        call([\"meshlab\"] + [x + \".obj\" for x in d.keys()])\n\n    @staticmethod\n    def plot3d(pts, false_color=False):\n        oo = MeshlabInf()\n        oo.add_points(pts)\n        oo.show(false_color)\n\n    @staticmethod\n    def get_colormap(sz, cmap_name=\"jet\"):\n        colormap = matplotlib.cm.get_cmap(cmap_name)(np.linspace(0, 1, sz))[:, 0:3]\n        return colormap\n\n    def __init__(self, global_transformation=np.eye(4)):\n        self.global_transformation = global_transformation\n        self._xyzrgb = np.empty((0, 6))\n        self._faces = []\n        self._lines = []\n\n    def clear(self):\n        self.__init__()\n\n    def add_camera(self, p, color=DEFAULT_COLOR, scale=0.1, rotation=np.eye(3), camera_matrix=np.eye(3)):\n        q = 1 / camera_matrix[0, 0]\n        b = 1 / camera_matrix[1, 1]\n        u = camera_matrix[-1, 0] / q\n        v = camera_matrix[-1, 1] / b\n        pts = (\n                np.array(\n                    [+u, +v, +0, -q, -b, +1, -q, +b, +1, +q, +b, +1, +q, -b, +1, +q, +v, +0, +u, +b, +0]\n                ).reshape(-1, 3)\n                * scale\n        )\n        zup_from_zfwd = np.array([[0.0, -1.0, -0.0], [0.0, 0.0, -1.0], [1.0, 0.0, 0.0]])\n        pts = pts @ zup_from_zfwd\n        pts = pts @ rotation.T\n        pts = pts + np.array(p).flatten()\n\n        n = self._xyzrgb.shape[0]\n        self.add_points(pts, color)\n        f = np.array([0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1, 0, 5, 6]).reshape(-1, 3)\n        self.add_faces(list(f + n))\n\n    def add_line(self, p1, p2, c=None):\n        self.add_points(p1, c)\n        self.add_points(p2, c)\n        self.add_points(p2, c)\n        n = self._xyzrgb.shape[0]\n        self._lines.append([n - 3, n - 2, n - 1])\n\n    def add_mesh(self, xyz, c=None):\n        m, n, _ = xyz.shape\n        if c is None:\n            c = np.ones((m, n, 3))\n        elif len(c.shape) == 2:\n            c = np.repeat(np.expand_dims(c, 2), 3, axis=2)\n        elif len(c.shape) == 3:\n            pass\n        else:\n            raise Exception(\"unknown color size\")\n\n        good_ind = np.arange(0, m * n).reshape(m, n)\n        va = np.vstack((good_ind[:-1:, :-1:].flatten(), good_ind[:-1:, 1::].flatten(),\n                        good_ind[1::, :-1:].flatten())).T\n\n        vb = np.vstack(\n            (good_ind[1::,\n                      1::].flatten(), good_ind[1::, :-1:].flatten(), good_ind[:-1:,\n                                                                              1::].flatten())).T\n        v = np.vstack((va, vb))\n        v = v[:, [1, 0, 2]]\n        xyzrgb = np.hstack((xyz.reshape(m * n, 3), c.reshape(m * n, 3)))\n        ok = np.all(~np.isnan(xyzrgb), axis=1)\n        good_ind = np.arange(0, xyzrgb.shape[0])[ok]\n        bad_ind = np.arange(0, xyzrgb.shape[0])[~ok]\n        xyzrgb = xyzrgb[good_ind, :]\n\n        for i in bad_ind:\n            v = v[np.all(v != i, axis=1), :]\n\n        for i, idx in enumerate(good_ind):\n            v[v == idx] = i\n        n = self._xyzrgb.shape[0]\n        self.add_points(xyzrgb)\n\n        self.add_faces(list(v + n))\n\n    def add_points(self, xyz, color=None):\n        xyz_ = xyz.copy()\n        if len(xyz_.shape) == 1:\n            xyz_ = xyz_.reshape(1, -1)\n        xyz_ = xyz_[~np.any(np.isnan(xyz_), axis=1), :]\n        n = xyz_.shape[0]\n        if color is None:\n            if xyz_.shape[1] == 3:\n                xyz_ = np.hstack((xyz_, np.ones((n, 3)) * xyz_[:, 2:]))\n            elif xyz_.shape[1] == 4:\n                xyz_ = np.hstack((xyz_, np.ones((n, 2)) * xyz_[:, 3:]))\n            elif xyz_.shape[1] == 6:\n                pass\n            else:\n                raise Exception(\"unknown points dimension\")\n        elif isinstance(color,\n                        np.ndarray) and color.shape[0] == xyz.shape[0] and color.shape[1] == 3:\n            xyz_ = np.c_[xyz_[:, :3], color]\n        else:\n            if len(color) != 3:\n                raise Exception(\"color should be 3 elem vector\")\n            xyz_ = np.c_[xyz_[:, :3], np.ones((n, 1)) * color]\n\n        self._xyzrgb = np.vstack((self._xyzrgb, xyz_))\n\n    def add_pgon(self, xyz, color=None):\n        xyz = xyz[~np.any(np.isnan(xyz), axis=1), :]\n        n = self._xyzrgb.shape[0]\n        self.add_points(xyz, color)\n        self.add_faces([list(np.arange(n, n + xyz.shape[0]))])\n\n    def add_faces(self, verts):\n        self._faces += verts\n\n    def read(self, fname):\n        raise NotImplementedError(\"function 'read' is not yet implemented\")\n\n    def show(self, false_color=False):\n        fn = \"temp.obj\"\n        self.write(fn, false_color)\n        call([\"meshlab\", fn])\n        # call(['rm', fn])\n\n    def write(self, fname, false_color=False, verbose=True):\n\n        xyzrgb = self._xyzrgb.copy()\n\n        if false_color:\n            colind = np.mean(self._xyzrgb[:, 3:], axis=1)\n            mm = norm_range_01(colind, (1, 99))\n            colind = (mm * 255).astype(int)\n\n            colormap = self.get_colormap(256)\n            for i in range(xyzrgb.shape[0]):\n                z = xyzrgb[i, 2]\n                if np.isnan(z):\n                    xyzrgb[i, 3:] = np.array([0, 0, 0])\n                else:\n                    xyzrgb[i, 3:] = colormap[colind[i], :]\n\n            colormap2 = self.get_colormap(len(self._faces))\n            for j, p in enumerate(self._faces):\n                for i in p:\n                    xyzrgb[i, 3:] = colormap2[j, :]\n        else:\n\n            xyzrgb[:, 3:] = norm_range_01(xyzrgb[:, 3:])\n            xyzrgb[:, 3:] += 1 - np.max(xyzrgb[:, 3:])\n        with open(fname, \"w\", encoding='utf-8') as f:\n\n            f.write(\"# OBJ file\\n\")\n            for i in trange(xyzrgb.shape[0],\n                            desc=\"Writing points to meshlab file\",\n                            disable=not verbose):\n                x = xyzrgb[i, :]\n                x[:3] = self.global_transformation[:3, :3] @ x[:3] + self.global_transformation[:3,\n                                                                                                -1]\n                f.write(\"v %.4f %.4f %.4f %.4f %.4f %.4f\\n\" % (x[0], x[1], x[2], x[3], x[4], x[5]))\n\n            for p in self._faces:\n                f.write(\"f\")\n                for i in p:\n                    f.write(\" %d\" % (i + 1))\n                f.write(\"\\n\")\n\n            for p in self._lines:\n                f.write(\"f\")\n                for i in p:\n                    f.write(\" %d\" % (i + 1))\n                f.write(\"\\n\")\n            f.close()\n\n\ndef norm_range_01(v: np.ndarray, prcnt: tuple = None) -> np.ndarray:\n    \"\"\"\n    normalize the input values in range of [0-1].\n    \"\"\"\n    if np.all(np.isnan(v)):\n        return v\n    if prcnt is None:\n        min_value = np.nanmin(v)\n        max_value = np.nanmax(v)\n    else:\n        if len(prcnt) != 2 or prcnt[0] >= prcnt[1] or prcnt[0] < 0 or prcnt[1] > 100:\n            raise Exception(\"input #2 should contain hi and low percentage within [0-100]\")\n\n        min_value, max_value = np.nanpercentile(v, prcnt)\n\n    d = max_value - min_value\n    if d < np.finfo(type(min_value)).eps:\n        d = 1\n    v_out = (v - min_value) / d\n    v_out = np.clip(v_out, 0, 1)\n    return v_out\n\n\ndef rotation_matrix_from_to(v_from: Union[List, Tuple, np.ndarray],\n                            v_to: Union[List, Tuple, np.ndarray],\n                            output4x4: bool = False) -> np.ndarray:\n    \"\"\"\n    calculate the rotation matrix the describes the rotation\n    from input vector v_from to input vector v_to.\n    input vectors must be of length 3\n    \"\"\"\n    assert len(v_from) == 3\n    assert len(v_to) == 3\n    v_to = (v_to / np.linalg.norm(v_to)).flatten()\n    v_from = (v_from / np.linalg.norm(v_from)).flatten()\n\n    if np.all(np.abs(v_to - v_from) < np.finfo(float).eps * 1e3):\n        axis = v_to\n        angle = 0\n    else:\n        axis = np.cross(v_from, v_to)\n        nrm = np.linalg.norm(axis)\n        if nrm == 0:  # co-linear\n            rr = np.random.randn(3)\n            axis = rr - (v_from.T @ rr) * v_from\n            axis = axis / np.linalg.norm(axis)\n            angle = np.pi\n        else:\n            axis /= nrm\n            angle = np.arccos(min(1.0, v_to @ v_from))\n\n    r, _ = cv2.Rodrigues(axis * angle)\n    if output4x4:\n        outmat = np.eye(4)\n        outmat[:3, :3] = r\n    else:\n\n        outmat = r\n    return outmat\n"
  },
  {
    "path": "slam/pose_graph_optimization.py",
    "content": "import g2o\nimport numpy as np\n\nfrom slam.meshlab import MeshlabInf\n\n\nclass PoseGraphOptimization(g2o.SparseOptimizer):\n    def __init__(self):\n        self.edge_vertices = set()\n        self.num_loop_closures = 0\n\n        super().__init__()\n        solver = g2o.BlockSolverSE3(g2o.LinearSolverCholmodSE3())\n        solver = g2o.OptimizationAlgorithmLevenberg(solver)\n        super().set_algorithm(solver)\n\n        # See https://github.com/RainerKuemmerle/g2o/issues/34\n        self.se3_offset_id = 0\n        se3_offset = g2o.ParameterSE3Offset()\n        se3_offset.set_id(self.se3_offset_id)\n        super().add_parameter(se3_offset)\n\n    def __str__(self):\n        string = f'Vertices: {len(self.vertex_ids)}\\n'\n        string += f'Edges:   {len(self.edge_vertices)}\\n'\n        string += f'Loops:   {self.num_loop_closures}'\n        return string\n\n    @property\n    def vertex_ids(self):\n        return sorted(list(self.vertices().keys()))\n\n    def optimize(self, max_iterations=1000, verbose=False):\n        super().initialize_optimization()\n        super().set_verbose(verbose)\n        super().optimize(max_iterations)\n\n    def add_vertex(self, vertex_id, pose, fixed=False):\n        v_se3 = g2o.VertexSE3()\n        v_se3.set_id(vertex_id)\n        v_se3.set_estimate(g2o.Isometry3d(pose))\n        v_se3.set_fixed(fixed)\n        super().add_vertex(v_se3)\n\n    def add_vertex_point(self, vertex_id, point, fixed=False):\n        v_point = g2o.VertexPointXYZ()\n        v_point.set_id(vertex_id)\n        v_point.set_estimate(point)\n        v_point.set_fixed(fixed)\n        super().add_vertex(v_point)\n\n    def add_edge(self,\n                 vertices,\n                 measurement,\n                 information=np.eye(6),\n                 robust_kernel=None,\n                 is_loop_closure=False):\n        self.edge_vertices.add(vertices)\n        if is_loop_closure:\n            self.num_loop_closures += 1\n\n        edge = g2o.EdgeSE3()\n        for i, v in enumerate(vertices):\n            if isinstance(v, int):\n                v = self.vertex(v)\n            edge.set_vertex(i, v)\n\n        edge.set_measurement(g2o.Isometry3d(measurement))  # relative pose\n        edge.set_information(information)\n        # robust_kernel = g2o.RobustKernelHuber()\n        if robust_kernel is not None:\n            edge.set_robust_kernel(robust_kernel)\n        super().add_edge(edge)\n\n    def add_edge_pose_point(self,\n                            vertex_pose,\n                            vertex_point,\n                            measurement,\n                            information=np.eye(3),\n                            robust_kernel=None):\n        edge = g2o.EdgeSE3PointXYZ()\n        edge.set_vertex(0, self.vertex(vertex_pose))\n        edge.set_vertex(1, self.vertex(vertex_point))\n        edge.set_measurement(measurement)\n        edge.set_information(information)\n        if robust_kernel is not None:\n            edge.set_robust_kernel(robust_kernel)\n        edge.set_parameter_id(0, self.se3_offset_id)\n        super().add_edge(edge)\n\n    def get_pose(self, vertex_id):\n        return self.vertex(vertex_id).estimate().matrix()\n\n    def get_all_poses(self):\n        return [self.get_pose(i) for i in self.vertex_ids]\n\n    def get_transform(self, vertex_id_src, vertex_id_dst):\n        pose_src = self.get_pose(vertex_id_src)\n        pose_dst = self.get_pose(vertex_id_dst)\n        transform = np.linalg.inv(pose_src) @ pose_dst\n        return transform\n\n    def does_edge_exists(self, vertex_id_a, vertex_id_b):\n        return (vertex_id_a,\n                vertex_id_b) in self.edge_vertices or (vertex_id_b,\n                                                       vertex_id_a) in self.edge_vertices\n\n    def is_vertex_in_any_edge(self, vertex_id):\n        vertices = set()\n        for edge in self.edge_vertices:\n            vertices.add(edge[0])\n            vertices.add(edge[1])\n        return vertex_id in vertices\n\n    def does_vertex_have_only_global_edges(self, vertex_id):\n        assert self.is_vertex_in_any_edge(vertex_id)\n        for edge in self.edge_vertices:\n            if vertex_id not in edge:\n                continue\n            if np.abs(edge[0] - edge[1]) == 1:\n                return False\n        return True\n\n    def visualize_in_meshlab(self, filename, meshlab=None, verbose=True):\n        if len(self.vertex_ids) > 0:\n            points = {}\n            for vertex_id, vertex in self.vertices().items():\n                if isinstance(vertex, g2o.VertexSE3):\n                    points[vertex_id] = vertex.estimate().matrix()[:3, 3]\n\n            if meshlab is None:\n                meshlab = MeshlabInf()\n            for point in points.values():\n                meshlab.add_points(point)\n            for edge in self.edge_vertices:\n                meshlab.add_line(points[edge[0]], points[edge[1]])\n\n            # for vertex_id, vertex in self.vertices().items():\n            #     if isinstance(vertex, g2o.VertexSE3):\n            #         p = vertex.estimate().matrix()[:3, 3]\n            #         r = vertex.estimate().matrix()[:3, :3]\n            #         meshlab.add_camera(p, rotation=r)\n\n            meshlab.write(filename, verbose=verbose)\n"
  },
  {
    "path": "slam/replay_buffer.py",
    "content": "import os\nimport pickle\nimport shutil\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional\n\nimport faiss\nimport numpy as np\nimport torch\nfrom PIL import Image\nfrom torch import Tensor\nfrom torch.utils.data import Dataset as TorchDataset\nfrom torchvision import transforms\n\nfrom datasets.utils import get_random_color_jitter\nfrom loop_closure_detection.encoder import FeatureEncoder\n\n\nclass ReplayBuffer(TorchDataset):\n    def __init__(\n            self,\n            storage_dir: Path,\n            dataset_type: str,\n            state_path: Optional[Path] = None,\n            height: int = 0,\n            width: int = 0,\n            scales: List[int] = None,\n            frames: List[int] = None,\n            num_workers: int = 1,\n            do_augmentation: bool = False,\n            batch_size: int = 1,\n            maximize_diversity: bool = False,\n            max_buffer_size: int = np.iinfo(int).max,\n            similarity_threshold: float = 1,\n            similarity_sampling: bool = True,\n    ):\n        self.storage_dir = storage_dir\n        # self._reset_storage_dir()\n\n        self.dataset_type = dataset_type.lower()\n        self.num_workers = num_workers\n        self.do_augmentation = do_augmentation\n        self.batch_size = batch_size\n\n        # Restrict size of the replay buffer\n        self.NUMBER_SAMPLES_PER_ENVIRONMENT = 100\n        self.valid_indices = {}\n\n        self.buffer_filenames = {}\n        self.online_filenames = []\n\n        # Precompute the resize functions for each scale relative to the previous scale\n        # If scales is None, the size of the raw data will be used\n        self.scales = scales\n        self.frames = frames\n        self.resize = {}\n        if self.scales is not None:\n            for s in self.scales:\n                exp_scale = 2 ** s\n                self.resize[s] = transforms.Resize(\n                    (height // exp_scale, width // exp_scale),\n                    interpolation=transforms.InterpolationMode.LANCZOS)\n\n        # Ensure repeatability of experiments\n        self.target_sampler = np.random.default_rng(seed=42)\n\n        # Dissimilarity-based buffer\n        self.similarity_sampling = similarity_sampling\n        self.maximize_diversity = maximize_diversity\n        self.buffer_size = max_buffer_size\n        self.similarity_threshold = similarity_threshold\n        self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n        self.feature_encoder = FeatureEncoder(self.device)\n        self.faiss_index = None\n        self.faiss_index_offset = 0\n        self.distance_matrix = None\n        self.distance_matrix_indices = None\n\n        if state_path is not None:\n            self.load_state(state_path)\n\n    def add(self, sample: Dict[str, Any], sample_filenames: Dict[str, Any],\n            image_features: Optional[Tensor] = None, verbose: bool = False):\n        # pylint: disable=no-value-for-parameter\n        index = sample['index'].item()\n        assert index == sample_filenames['index']\n\n        index += self.faiss_index_offset\n\n        if self.faiss_index is None:\n            if image_features is None:\n                num_features = self.feature_encoder.num_features\n            else:\n                num_features = image_features.shape[1]\n            self.faiss_index = faiss.IndexIDMap(\n                faiss.index_factory(num_features, 'Flat', faiss.METRIC_INNER_PRODUCT))\n\n        if image_features is None:\n            image_features = self.feature_encoder(sample['rgb', 0, 0]).detach().cpu().numpy()\n        faiss.normalize_L2(image_features)  # The inner product becomes cosine similarity\n\n        add_sample = False\n        remove_sample = None\n        if self.maximize_diversity:\n\n            # Only add if sufficiently dissimilar to the existing samples\n            if self.faiss_index.ntotal == 0:\n                similarity = 0\n            else:\n                similarity = self.faiss_index.search(image_features, 1)[0][0][0]\n\n            if similarity < self.similarity_threshold:\n                self.faiss_index.add_with_ids(image_features, np.array([index]))\n                add_sample = True\n                if verbose:\n                    print(f'Added sample {index} to the replay buffer | similarity {similarity}')\n\n                if self.faiss_index.ntotal > self.buffer_size:\n                    # Maximize the diversity in the replay buffer\n                    if self.distance_matrix is None:\n                        features = self.faiss_index.index.reconstruct_n(0, self.faiss_index.ntotal)\n                        dist_mat, matching = self.faiss_index.search(features,\n                                                                     self.faiss_index.ntotal)\n                        for i in range(self.faiss_index.ntotal):\n                            dist_mat[i, :] = dist_mat[i, matching[i].argsort()]\n                        self.distance_matrix = dist_mat\n                        self.distance_matrix_indices = faiss.vector_to_array(\n                            self.faiss_index.id_map)\n                    else:\n                        # Only update the elements that actually change\n                        fill_up_index = np.argwhere(self.distance_matrix_indices < 0)[0, 0]\n                        a, b = self.faiss_index.search(image_features, self.faiss_index.ntotal)\n                        self.distance_matrix_indices[fill_up_index] = index\n                        sorter = np.argsort(b[0])\n                        sorter_idx = sorter[\n                            np.searchsorted(b[0], self.distance_matrix_indices, sorter=sorter)]\n                        a = a[:, sorter_idx][0]\n                        self.distance_matrix[fill_up_index, :] = self.distance_matrix[:,\n                                                                 fill_up_index] = a\n\n                    # Subtract self-similarity\n                    remove_index_tmp = np.argmax(\n                        self.distance_matrix.sum(0) - self.distance_matrix.diagonal())\n                    self.distance_matrix[:, remove_index_tmp] = self.distance_matrix[\n                                                                remove_index_tmp,\n                                                                :] = -1\n                    remove_index = self.distance_matrix_indices[remove_index_tmp]\n                    self.distance_matrix_indices[remove_index_tmp] = -1\n                    self.faiss_index.remove_ids(np.array([remove_index]))\n                    remove_sample = remove_index\n                    if verbose:\n                        print(f'Removed sample {remove_index} from the replay buffer')\n\n        else:\n            self.faiss_index.add_with_ids(image_features, np.array([index]))\n            add_sample = True\n            if self.faiss_index.ntotal > self.buffer_size:\n                remove_index = self.target_sampler.choice(self.faiss_index.ntotal, 1)[0]\n                remove_sample = faiss.vector_to_array(self.faiss_index.id_map)[remove_index]\n                self.faiss_index.remove_ids(np.array([remove_sample]))\n                # if verbose:\n                #     print(f'Removed sample {remove_sample} from the target buffer')\n\n        if add_sample:\n            filename = self.storage_dir / f'{self.dataset_type}_{index:>05}.pkl'\n            data = {\n                key: value\n                for key, value in sample.items() if 'index' in key or 'camera_matrix' in key\n                                                    or 'inv_camera_matrix' in key\n                                                    or 'relative_distance' in key\n            }\n            data['rgb', -1] = sample_filenames['images'][0]\n            data['rgb', 0] = sample_filenames['images'][1]\n            data['rgb', 1] = sample_filenames['images'][2]\n            with open(filename, 'wb') as f:\n                pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)\n            self.online_filenames.append(filename)\n\n        if remove_sample is not None:\n            for filename in self.online_filenames:\n                if f'_{remove_sample:>05}.pkl' in filename.name:\n                    os.remove(filename)\n                    self.online_filenames.remove(filename)\n                    break\n\n    def get(self, sample: Dict[str, Any], image_features: Optional[Tensor] = None) -> Dict[\n        str, Any]:\n        return_data = {}\n\n        # Sample from target buffer\n        if self.online_filenames and self.batch_size > 0:\n            index = sample['index'].item() + self.faiss_index_offset\n            filename = self.storage_dir / f'{self.dataset_type}_{index:>05}.pkl'\n            # The current sample is the only one that is in the buffer\n            if len(self.online_filenames) == 1 and filename in self.online_filenames:\n                replace = True\n                num_samples = 1\n                sampling_prob = None\n            else:\n                # Do not sample the current sample\n                if filename in self.online_filenames:\n                    num_samples = len(self.online_filenames) - 1  # -1 for the current sample\n                else:\n                    num_samples = len(self.online_filenames)\n                replace = self.batch_size > num_samples\n\n                if self.similarity_sampling:\n                    assert self.faiss_index.ntotal > 0\n                    if image_features is None:\n                        image_features = self.feature_encoder(\n                            sample['rgb', 0, 0]).detach().cpu().numpy()\n                    faiss.normalize_L2(\n                        image_features)  # The inner product becomes cosine similarity\n                    similarity, indices = self.faiss_index.search(image_features,\n                                                                  self.faiss_index.ntotal)\n                    if index in indices:\n                        similarity = np.delete(similarity, np.argwhere(indices == index))\n                    else:\n                        similarity = similarity[0]\n                    dissimilarity = 1 - similarity\n                    # sampling_prob = dissimilarity / dissimilarity.sum()\n                    sampling_prob = similarity / similarity.sum()\n                else:\n                    sampling_prob = None\n\n            indices = self.target_sampler.choice(num_samples, self.batch_size, replace,\n                                                 sampling_prob)\n            filenames = [self.online_filenames[index] for index in indices]\n            return_data = self._get(filenames[0])\n            for filename in filenames[1:]:\n                data = self._get(filename)\n                for key in return_data:\n                    return_data[key] = torch.cat([return_data[key], data[key]])\n\n        return return_data\n\n    def save_state(self):\n        filename = self.storage_dir / 'buffer_state.pkl'\n        data = {'filenames': self.online_filenames, 'faiss_index': self.faiss_index}\n        with open(filename, 'wb') as f:\n            pickle.dump(data, f)\n        print(f'Saved reply buffer state to: {filename}')\n        for key, value in self.buffer_filenames.items():\n            print(f'{key + \":\":<12} {len(value):>5}')\n\n    def load_state(self, state_path: Path):\n        with open(state_path, 'rb') as f:\n            data = pickle.load(f)\n            # self.buffer_filenames = data['filenames']\n            self.faiss_index = data['faiss_index']\n            self.faiss_index_offset = faiss.vector_to_array(self.faiss_index.id_map).max()\n            self.online_filenames = [state_path.parent / file.name for file in data['filenames']]\n        print(f'Load replay buffer state from: {state_path}')\n        for key, value in self.buffer_filenames.items():\n            print(f'{key + \":\":<12} {len(value):>5}')\n\n    def __getitem__(self, index: int) -> Dict[Any, Tensor]:\n        raise NotImplementedError\n\n    def __len__(self):\n        return 1000000  # Fixed number as the sampling is handled in the get() function\n\n    def _get(self, filename, include_batch=True):\n        if self.do_augmentation:\n            color_augmentation = get_random_color_jitter((0.8, 1.2), (0.8, 1.2), (0.8, 1.2),\n                                                         (-.1, .1))\n\n        with open(filename, 'rb') as f:\n            data = pickle.load(f)\n        for frame in self.frames:\n            rgb = Image.open(data['rgb', frame]).convert('RGB')\n            rgb = self.resize[0](rgb)\n            data['rgb', frame, 0] = rgb\n            for scale in self.scales:\n                if scale == 0:\n                    continue\n                data['rgb', frame, scale] = self.resize[scale](data['rgb', frame, scale - 1])\n            for scale in self.scales:\n                data['rgb', frame, scale] = transforms.ToTensor()(data['rgb', frame, scale])\n                if include_batch:\n                    data['rgb', frame, scale] = data['rgb', frame, scale].unsqueeze(0)\n                if self.do_augmentation:\n                    data['rgb_aug', frame, scale] = color_augmentation(data['rgb', frame, scale])\n                else:\n                    data['rgb_aug', frame, scale] = data['rgb', frame, scale]\n            del data['rgb', frame]  # Removes the filename string\n        if not include_batch:\n            for key in data:\n                if not ('rgb' in key or 'rgb_aug' in key):\n                    data[key] = data[key].squeeze(0)\n        return data\n\n    def _reset_storage_dir(self):\n        if self.storage_dir.exists():\n            shutil.rmtree(self.storage_dir)\n        self.storage_dir.mkdir(parents=True, exist_ok=True)\n"
  },
  {
    "path": "slam/slam.py",
    "content": "import pickle\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport torch\nfrom torch.utils.data import DataLoader\n\nfrom datasets import Kitti, Robotcar\nfrom depth_pose_prediction import DepthPosePrediction\nfrom loop_closure_detection import LoopClosureDetection\nfrom slam.pose_graph_optimization import PoseGraphOptimization\nfrom slam.replay_buffer import ReplayBuffer\nfrom slam.utils import calc_depth_error, rotation_error, translation_error\n\nPLOTTING = True\n\n\nclass Slam:\n    def __init__(self, config):\n        # Config =========================================\n        self.config = config\n        self.online_dataset_type = config.dataset.dataset\n        self.online_dataset_path = config.dataset.dataset_path\n        self.do_adaptation = config.slam.adaptation\n        self.adaptation_epochs = config.slam.adaptation_epochs\n        self.min_distance = config.slam.min_distance\n        self.start_frame = config.slam.start_frame\n        self.logging = config.slam.logging\n        if not self.do_adaptation:\n            config.depth_pose.batch_size = 1\n        self.log_path = config.depth_pose.log_path\n        self.log_path.mkdir(parents=True, exist_ok=True)\n\n        self.do_loop_closures = config.slam.do_loop_closures\n        self.keyframe_frequency = config.slam.keyframe_frequency\n        self.lc_distance_poses = config.slam.lc_distance_poses\n\n        # Depth / pose predictor ==========================\n        self.predictor = DepthPosePrediction(config.dataset, config.depth_pose, use_online=False)\n        self.predictor.load_model(load_optimizer=False)\n\n        # Dataloader ======================================\n        if self.online_dataset_type == 'Kitti':\n            self.online_dataset = Kitti(\n                self.online_dataset_path,\n                config.slam.dataset_sequence,\n                config.dataset.frame_ids,\n                config.dataset.scales,\n                config.dataset.height,\n                config.dataset.width,\n                poses=True,  # Ground truth poses\n                with_depth=False,\n                min_distance=config.slam.min_distance,\n            )\n        elif self.online_dataset_type == 'RobotCar':\n            if config.slam.dataset_sequence == 1:\n                start_frame, end_frame = 750, 4750\n            else:\n                start_frame, end_frame = 22100, 26100\n            self.online_dataset = Robotcar(\n                self.online_dataset_path,\n                '2015-08-12-15-04-18',\n                config.dataset.frame_ids,\n                config.dataset.scales,\n                config.dataset.height,\n                config.dataset.width,\n                poses=True,  # Ground truth poses\n                min_distance=config.slam.min_distance,\n                start_frame=start_frame,\n                end_frame=end_frame,\n                every_n_frame=2,\n            )\n        else:\n            raise ValueError('Unsupported dataset type.')\n        self.online_dataloader = DataLoader(\n            self.online_dataset,\n            batch_size=1,  # Simulates online loading\n            shuffle=False,  # Simulates online loading\n            num_workers=config.depth_pose.num_workers,\n            pin_memory=True,\n            drop_last=True)\n        self.online_dataloader_iter = iter(self.online_dataloader)\n\n        if self.do_adaptation and config.depth_pose.batch_size > 1: # and False:\n            replay_buffer_path = config.replay_buffer.load_path\n            replay_buffer_path.mkdir(parents=True, exist_ok=True)\n            replay_buffer_state_path = replay_buffer_path / 'buffer_state.pkl'\n            replay_buffer_state_path = replay_buffer_state_path if \\\n                replay_buffer_state_path.exists() else None\n            self.replay_buffer = ReplayBuffer(\n                replay_buffer_path,\n                self.online_dataset_type,\n                replay_buffer_state_path,\n                self.online_dataset.height,\n                self.online_dataset.width,\n                self.online_dataset.scales,\n                self.online_dataset.frame_ids,\n                do_augmentation=True,\n                batch_size=config.depth_pose.batch_size - 1,\n                maximize_diversity=config.replay_buffer.maximize_diversity,\n                max_buffer_size=config.replay_buffer.max_buffer_size,\n                similarity_threshold=config.replay_buffer.similarity_threshold,\n                similarity_sampling=config.replay_buffer.similarity_sampling,\n            )\n        else:\n            self.replay_buffer = None\n\n        # Pose graph backend ==============================\n        self.loop_closure_detection = LoopClosureDetection(config.loop_closure)\n        self.pose_graph = PoseGraphOptimization()\n        if self.start_frame == 0:\n            self.pose_graph.add_vertex(0, self.online_dataset.global_poses[1], fixed=True)\n            # self.pose_graph.add_vertex(0, np.eye(4), fixed=True)\n        self.gt_pose_graph = PoseGraphOptimization()  # Used for visualization\n        self.gt_pose_graph.add_vertex(0, self.online_dataset.global_poses[1], fixed=True)\n\n        # Auxiliary variables =============================\n        self.current_step = 0\n        self.since_last_loop_closures = self.lc_distance_poses\n\n        # Logging =========================================\n        # Track the relative error per step\n        self.rel_trans_error = []\n        self.rel_rot_error = []\n        # Track the losses of the online data\n        self.depth_loss = []\n        self.velocity_loss = []\n        # Track the depth error per step\n        self.depth_error = []\n\n        self.depth_loss_threshold = -1  # .04\n        self.velo_loss_threshold = -1\n\n    def __len__(self):\n        return len(self.online_dataset)\n\n    def step(self):\n        self.current_step += 1\n\n        # Combine online and replay data ==================\n        online_data = next(self.online_dataloader_iter)\n\n        self.predictor._set_eval()\n        with torch.no_grad():\n            online_image = online_data['rgb', 0, 0].to(self.predictor.device)\n            online_features = self.predictor.models['depth_encoder'](online_image)[4].detach()\n            online_features = online_features.mean(-1).mean(-1).cpu().numpy()\n\n        if self.replay_buffer is not None:\n            self.replay_buffer.add(online_data,\n                                   self.online_dataset.get_item_filenames(self.current_step - 1),\n                                   online_features,\n                                   verbose=True)\n        if self.replay_buffer is not None:\n            replay_data = self.replay_buffer.get(online_data, online_features)\n            if replay_data:\n                training_data = self._cat_dict(online_data, replay_data)\n            else:\n                training_data = online_data\n        else:\n            training_data = online_data\n        # =================================================\n\n        # Use the measured velocity for this check\n        if self.current_step > 1 and online_data['relative_distance',\n                                                 1] < self.min_distance:\n            print(f'skip: {online_data[\"relative_distance\", 1].detach().cpu().numpy()[0]}')\n            return {'depth_loss': 0, 'velocity_loss': 0}\n\n        # Depth / pose prediction =========================\n        # The returned losses are wrt the online data\n        if self.do_adaptation:\n            # Update the network weights\n            outputs, losses = self.predictor.adapt(online_data,\n                                                   training_data,\n                                                   steps=self.adaptation_epochs)\n        else:\n            outputs, losses = self.predictor.adapt(online_data, None)\n        # Extract input/output for online data\n        image = online_data['rgb', 1, 0]\n        if torch.sign(online_data['relative_distance', 1]) < 0:\n            transformation = outputs['cam_T_cam', 0, 1][0, :]\n        else:\n            transformation = torch.linalg.inv(outputs['cam_T_cam', 0, 1][0, :])\n        # Move to CPU for further processing\n        transformation = transformation.squeeze().cpu().detach().numpy()\n        for k, v in losses.items():\n            losses[k] = float(v.squeeze().cpu().detach().numpy())\n        if 'velocity_loss' not in losses:\n            losses['velocity_loss'] = 0\n        if 'depth_loss' not in losses:\n            losses['depth_loss'] = 0\n        # =================================================\n\n        # Ground truth poses ==============================\n        gt_transformation = online_data['relative_pose', 1].squeeze().cpu().detach().numpy()\n        gt_pose = online_data['absolute_pose', 1].squeeze().cpu().detach().numpy()\n        self.gt_pose_graph.add_vertex(self.current_step, gt_pose)\n        self.gt_pose_graph.add_edge((self.gt_pose_graph.vertex_ids[-2], self.current_step),\n                                    gt_transformation)\n        # =================================================\n\n        # Pose graph ======================================\n        # Mapping can start later to account for initial warming up to the dataset\n        if self.current_step == self.start_frame:\n            self.pose_graph.add_vertex(self.current_step, gt_pose, fixed=True)\n            print(f'Start mapping at frame {self.current_step}')\n        elif self.current_step > self.start_frame:\n            # Initialize with predicted odometry\n            odom_pose = self.pose_graph.get_pose(self.pose_graph.vertex_ids[-1]) @ transformation\n            self.pose_graph.add_vertex(self.current_step, odom_pose)\n            cov_matrix = np.eye(6)\n            cov_matrix[2, 2] = .1\n            cov_matrix[5, 5] = .1\n            self.pose_graph.add_edge((self.pose_graph.vertex_ids[-2], self.current_step),\n                                     transformation,\n                                     information=np.linalg.inv(cov_matrix))\n        # =================================================\n\n        # Loop closure detection ==========================\n        optimized = False\n        if self.do_loop_closures and self.current_step >= self.start_frame:\n            self.loop_closure_detection.add(self.current_step, image.squeeze())\n            if not self.current_step % self.keyframe_frequency and self.current_step < 4000:\n                if self.since_last_loop_closures > self.lc_distance_poses:\n                    lc_step_ids, distances = self.loop_closure_detection.search(self.current_step)\n                    for i, d in zip(lc_step_ids, distances):\n                        lc_image = self.online_dataset[i - 1]['rgb', 1, 0]\n                        lc_transformation, cov_matrix = self.predictor.predict_pose(image,\n                                                                                    lc_image,\n                                                                                    as_numpy=True)\n                        graph_transformation = self.pose_graph.get_transform(self.current_step, i)\n                        print(f'{self.current_step} --> {i} '\n                              f'[sim={d:.3f}, pred_dist={np.linalg.norm(lc_transformation):.1f}m, '\n                              f'graph_dist={np.linalg.norm(graph_transformation):.1f}m]')\n                        # LoopClosureDetection.display_matches(image, lc_image, self.current_step,\n                        #                                      i, lc_transformation, d)\n                        cov_matrix = np.eye(6)\n                        cov_matrix[2, 2] = .1\n                        cov_matrix[5, 5] = .1\n                        self.pose_graph.add_edge((self.current_step, i),\n                                                 lc_transformation,\n                                                 information=.5 * np.linalg.inv(cov_matrix),\n                                                 is_loop_closure=True)\n                    if len(lc_step_ids) > 0:\n                        self.pose_graph.optimize(max_iterations=10000, verbose=False)\n                        optimized = True\n            if optimized:\n                self.since_last_loop_closures = 0\n            else:\n                self.since_last_loop_closures += 1\n        # =================================================\n\n        # Track metrics ===================================\n        if self.logging:\n            # Relative error of prediction\n            rel_err = np.linalg.inv(gt_transformation) @ transformation\n            self.rel_trans_error.append(translation_error(rel_err))\n            self.rel_rot_error.append(rotation_error(rel_err))\n            # Loss\n            self.depth_loss.append(losses['depth_loss'])\n            self.velocity_loss.append(losses['velocity_loss'])\n            # Depth error\n            if self.online_dataset_type == 'Kitti':\n                self.depth_error.append(\n                    calc_depth_error(outputs['depth', 0][0, ...].squeeze().detach().cpu().numpy(),\n                                     online_data['depth', 0,\n                                                 -1][0, ...].squeeze().detach().cpu().numpy(),\n                                     min_depth=self.predictor.min_depth,\n                                     max_depth=self.predictor.max_depth))\n            # Plot the tracked metrics\n            if PLOTTING and (not self.current_step % 100 or optimized):\n                self.plot_metrics()\n                self.plot_trajectory()\n                self.pose_graph.visualize_in_meshlab(self.log_path / 'pose_graph.obj',\n                                                     verbose=False)\n                self.gt_pose_graph.visualize_in_meshlab(self.log_path / 'gt_pose_graph.obj',\n                                                        verbose=False)\n        # =================================================\n\n        return losses\n\n    def save_metrics(self) -> None:\n        data = {\n            'rel_trans_error': self.rel_trans_error,\n            'rel_rot_error': self.rel_rot_error,\n            'depth_loss': self.depth_loss,\n            'velocity_loss': self.velocity_loss,\n            'depth_error': self.depth_error,\n        }\n        filename = self.log_path / 'metrics.pkl'\n        with open(filename, 'wb') as f:\n            pickle.dump(data, f)\n\n    def save_model(self) -> None:\n        self.predictor.save_model()\n        if self.replay_buffer is not None:\n            self.replay_buffer.save_state()\n\n    @staticmethod\n    def _cat_dict(dict_1, dict_2):\n        \"\"\" Concatenate the elements of online input dictionary\n        with the corresponding elements of the replay buffer dictionary\n        \"\"\"\n        res_dict = {}\n        for key in dict_1:\n            if key in dict_2:\n                res_dict[key] = torch.cat([dict_1[key], dict_2[key]])\n        return res_dict\n\n    @staticmethod\n    def _pose_graph_to_2d_trajectory(pose_graph):\n        # Returns the trajectory in X-Z dimension\n        poses = pose_graph.get_all_poses()\n        trajectory = np.asarray([[p[0, 3], p[2, 3]] for p in poses])\n        return trajectory\n\n    def plot_trajectory(self):\n        pred_trajectory = self._pose_graph_to_2d_trajectory(self.pose_graph)\n        gt_trajectory = self._pose_graph_to_2d_trajectory(self.gt_pose_graph)\n        fig = plt.figure()\n        plt.plot(pred_trajectory[:, 0], pred_trajectory[:, 1], '--.', label='pred')\n        plt.plot(gt_trajectory[:, 0], gt_trajectory[:, 1], '--.', label='gt')\n        plt.axis('equal')\n        plt.legend()\n        plt.title(f'Step = {self.current_step}')\n        # filename = self.log_path / 'trajectory' / f'step_{self.current_step:04}.png'\n        # filename.parent.mkdir(parents=True, exist_ok=True)\n        # plt.savefig(str(filename))\n        filename = self.log_path / 'trajectory.png'\n        plt.savefig(str(filename))\n        plt.close(fig)\n        np.save(self.log_path / 'trajectory.npy', pred_trajectory)\n        np.save(self.log_path / 'gt_trajectory.npy', gt_trajectory)\n\n    def plot_metrics(self, filename: str = 'metrics.png'):\n        if self.depth_error:\n            fig, axs = plt.subplots(nrows=2, ncols=4, figsize=(12, 6))\n        else:\n            # fig, axs = plt.subplots(nrows=2, ncols=3, figsize=(16, 12))\n            fig, axs = plt.subplots(nrows=2, ncols=2)\n        # Losses\n        axs[0, 0].plot(self.depth_loss)\n        axs[0, 0].axhline(self.depth_loss_threshold, color='r')\n        axs[0, 0].set_ylim(bottom=0, top=1.1 * max(self.depth_loss))\n        axs[0, 0].set_xlabel('Step')\n        axs[0, 0].set_ylabel('Depth loss')\n        axs[0, 0].set_title('Depth loss')\n        axs[1, 0].plot(self.velocity_loss)\n        axs[1, 0].axhline(self.velo_loss_threshold, color='r')\n        axs[1, 0].set_ylim(bottom=0, top=1.1 * max(self.velocity_loss))\n        axs[1, 0].set_xlabel('Step')\n        axs[1, 0].set_ylabel('Velocity loss')\n        axs[1, 0].set_title('Velocity loss')\n        # Relative errors\n        axs[0, 1].plot(self.rel_trans_error)\n        axs[0, 1].set_ylim(bottom=0)\n        axs[0, 1].set_xlabel('Step')\n        axs[0, 1].set_ylabel('Relative trans. error')\n        axs[0, 1].set_title('Relative trans. error')\n        axs[1, 1].plot(self.rel_rot_error)\n        axs[1, 1].set_ylim(bottom=0)\n        axs[1, 1].set_xlabel('Step')\n        axs[1, 1].set_ylabel('Relative rot. error')\n        axs[1, 1].set_title('Relative rot. error')\n        # Depth error\n        if self.depth_error:\n            axs[0, 2].plot([x['abs_rel'] for x in self.depth_error])\n            axs[0, 2].set_ylim(bottom=0)\n            axs[0, 2].set_xlabel('Step')\n            axs[0, 2].set_ylabel('Abs rel')\n            axs[0, 2].set_title('Abs rel / ARD')\n            axs[1, 2].plot([x['sq_rel'] for x in self.depth_error])\n            axs[1, 2].set_ylim(bottom=0)\n            axs[1, 2].set_xlabel('Step')\n            axs[1, 2].set_ylabel('Sq rel')\n            axs[1, 2].set_title('Sq rel / SRD')\n            axs[0, 3].plot([x['rmse'] for x in self.depth_error])\n            axs[0, 3].set_ylim(bottom=0)\n            axs[0, 3].set_xlabel('Step')\n            axs[0, 3].set_ylabel('RMSE')\n            axs[0, 3].set_title('RMSE')\n            axs[1, 3].plot([x['a1'] for x in self.depth_error])\n            axs[1, 3].set_ylim(top=1)\n            axs[1, 3].set_xlabel('Step')\n            axs[1, 3].set_ylabel('A1')\n            axs[1, 3].set_title('A1')\n\n        fig.tight_layout()\n        plt.savefig(self.log_path / filename, bbox_inches='tight')\n        plt.close(fig)\n"
  },
  {
    "path": "slam/transform.py",
    "content": "import numpy as np\nfrom scipy.spatial.transform import Rotation\n\n\ndef print_tmat(tmat, note=''):\n    return print_sixdof(tmat2sixdof(tmat), note)\n\n\ndef print_array(array, note=''):\n    return print_sixdof(array2sixdof(array), note)\n\n\ndef print_sixdof(sixdof, note=''):\n    print(string_sixdof(sixdof, note))\n\n\ndef string_tmat(tmat, note=''):\n    return string_sixdof(tmat2sixdof(tmat), note)\n\n\ndef string_sixdof(sixdof, note=''):\n    string = f'R({np.rad2deg(sixdof[\"rx\"]):>7.3f}, {np.rad2deg(sixdof[\"ry\"]):>7.3f}, ' \\\n             f'{np.rad2deg(sixdof[\"rz\"]):>7.3f}), T({sixdof[\"tx\"]:>7.3f}, ' \\\n             f'{sixdof[\"ty\"]:>7.3f}, {sixdof[\"tz\"]:>7.3f}) {note}'\n    return string\n\n\ndef create_empty_sixdof():\n    sixdof = {'tx': 0, 'ty': 0, 'tz': 0, 'rx': 0, 'ry': 0, 'rz': 0}\n    return sixdof\n\n\ndef tmat2sixdof(tmat):\n    r = Rotation.from_matrix(tmat[:3, :3]).as_rotvec()\n    sixdof = {\n        'tx': tmat[0, 3],\n        'ty': tmat[1, 3],\n        'tz': tmat[2, 3],\n        'rx': r[0],\n        'ry': r[1],\n        'rz': r[2]\n    }\n    return sixdof\n\n\ndef sixdof2tmat(sixdof):\n    tmat = np.eye(4)\n    tmat[:3, :3] = Rotation.from_rotvec([sixdof['rx'], sixdof['ry'], sixdof['rz']]).as_matrix()\n    tmat[0, 3] = sixdof['tx']\n    tmat[1, 3] = sixdof['ty']\n    tmat[2, 3] = sixdof['tz']\n    return tmat\n\n\ndef tmat2array(tmat):\n    sixdof = tmat2sixdof(tmat)\n    array = np.zeros((6, 1))\n    array[0] = sixdof['rx']\n    array[1] = sixdof['ry']\n    array[2] = sixdof['rz']\n    array[3] = sixdof['tx']\n    array[4] = sixdof['ty']\n    array[5] = sixdof['tz']\n    return array.T.ravel()\n\n\ndef array2tmat(array):\n    return sixdof2tmat(array2sixdof(array))\n\n\ndef array2sixdof(array):\n    array_ = array.T\n    sixdof = {\n        'rx': array_[0],\n        'ry': array_[1],\n        'rz': array_[2],\n        'tx': array_[3],\n        'ty': array_[4],\n        'tz': array_[5]\n    }\n    return sixdof\n\n\ndef apply_transformation(transformation: np.ndarray, input_data: np.ndarray) -> np.ndarray:\n    if len(input_data.shape) != 2 and len(input_data.shape) != 3:\n        raise RuntimeError('data should be a 2D or 3D array')\n    if len(transformation.shape) != 2:\n        raise RuntimeError('transformation should be a 2D array')\n    if transformation.shape[0] != transformation.shape[1]:\n        raise RuntimeError('transformation should be square matrix')\n\n    if len(input_data.shape) == 2:\n        d = input_data.shape[1]\n        input_data_ = input_data\n    else:\n        d = input_data.shape[2]\n        input_data_ = input_data.reshape(-1, 3)\n\n    if transformation.shape[0] != d + 1:\n        raise RuntimeError('transformation dimension mismatch')\n    if np.max(np.abs(transformation[-1, :] - np.r_[np.zeros(d), 1])) > np.finfo(float).eps * 1e3:\n        raise RuntimeError('bad transformation')\n\n    x_t = np.c_[input_data_, np.ones((input_data_.shape[0], 1))] @ transformation.T\n    x_t = x_t[:, :d].reshape(input_data.shape)\n\n    return x_t\n"
  },
  {
    "path": "slam/utils.py",
    "content": "import copy\nimport pickle\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom torch import Tensor\n\nfrom depth_pose_prediction.networks.layers import BackprojectDepth\nfrom slam.meshlab import MeshlabInf\n\n\ndef save_data(fname, obj):\n    with open(fname, 'wb') as f:\n        pickle.dump(obj, f)\n\n\ndef load_data(fname):\n    with open(fname, 'rb') as f:\n        data = pickle.load(f)\n    return data\n\n\ndef depth_to_pcl(backproject_depth: BackprojectDepth,\n                 inv_camera_matrix: Tensor,\n                 depth: Tensor,\n                 image: Tensor,\n                 batch_size: int = 1,\n                 dist_threshold: float = np.inf):\n    pcl = backproject_depth(depth, inv_camera_matrix)\n    pcl = pcl.squeeze().cpu().detach().numpy()[:3, :].T\n    color = image.view(batch_size, 3, -1).squeeze().cpu().detach().numpy().T\n    pcl = np.c_[pcl, color]\n    if not np.isinf(dist_threshold):\n        dist = np.linalg.norm(pcl[:, :3], axis=1)\n        pcl = pcl[dist < dist_threshold, :]\n    return pcl\n\n\ndef pcl_to_image(\n    pcl: np.ndarray,\n    camera_matrix: np.ndarray,\n    image_shape: Tuple[int, int],\n) -> np.ndarray:\n    projection = cv2.projectPoints(pcl[:, :3].astype(np.float64), (0, 0, 0), (0, 0, 0),\n                                   camera_matrix, np.zeros(4))[0].squeeze()\n    image = np.zeros((image_shape[0], image_shape[1], 3))\n    depth = np.ones((image_shape[0], image_shape[1], 1)) * np.inf\n    for i, (u, v) in enumerate(projection):\n        u, v = int(np.floor(u)), int(np.floor(v))\n        if not (0 <= v < image_shape[0] and 0 <= u < image_shape[1]):\n            continue\n        distance = np.linalg.norm(pcl[i, :3])\n        if distance < depth[v, u]:\n            depth[v, u] = distance\n            image[v, u] = pcl[i, 3:]\n    return image\n\n\ndef save_point_cloud(\n    filename: str,\n    pcl: Union[np.ndarray, List[np.ndarray]],\n    global_pose_list: Optional[np.ndarray] = None,\n    verbose: bool = True,\n) -> None:\n    if global_pose_list is not None:\n        accumulated_pcl = accumulate_pcl(pcl, global_pose_list)\n    else:\n        accumulated_pcl = pcl\n    meshlab = MeshlabInf()\n    meshlab.add_points(accumulated_pcl)\n    meshlab.write(filename, verbose=verbose)\n\n\ndef accumulate_pcl(pcl_list: List[np.ndarray], global_pose_list: np.ndarray) -> np.ndarray:\n    accumulated_pcl = []\n    for i, (pcl, tmat) in enumerate(zip(pcl_list, global_pose_list)):\n        accumulated_pcl.append(np.c_[(np.c_[pcl[:, :3], np.ones(\n            (pcl.shape[0], 1))] @ tmat.T)[:, :3], pcl[:, 3:]])\n    accumulated_pcl = np.concatenate(accumulated_pcl)\n    return accumulated_pcl\n\n\ndef generate_figure(\n    batch_i,\n    image,\n    depth,\n    image_pcl,\n    gt_xz,\n    pred_xz,\n    save_figure: bool = True,\n) -> None:\n    fig = plt.figure(figsize=(8, 10))\n    plt.subplot(411)\n    plt.imshow(image)\n    plt.axis('off')\n    plt.title('Current frame')\n    plt.subplot(412)\n    vmax = np.percentile(depth, 95)\n    plt.imshow(depth, cmap='magma_r', vmax=vmax)\n    plt.axis('off')\n    plt.title(f'Predicted depth (vmax={vmax:.3f})')\n    plt.subplot(413)\n    plt.imshow(image_pcl)\n    plt.axis('off')\n    plt.title('Projected PCL (w/o current frame)')\n    plt.subplot(414)\n    plt.plot(gt_xz[:, 0], gt_xz[:, 1], label='gt')\n    plt.plot(pred_xz[:, 0], pred_xz[:, 1], label='pred')\n    plt.xlim((-400, 15))\n    plt.ylim((-60, 160))\n    # plt.xlim((-10, 10))\n    # plt.ylim((-10, 10))\n    plt.legend()\n    plt.tight_layout()\n    if save_figure:\n        plt.savefig(f'./figures/sequence_08/{batch_i:05}.png', )\n    else:\n        plt.show()\n    plt.close(fig)\n\n\n# =============================================================================\n# Adapted from:\n# https://github.com/Huangying-Zhan/kitti-odom-eval/blob/master/kitti_odometry.py\n\n\ndef scale_optimization(pred_poses, gt_poses):\n    \"\"\" Optimize scaling factor\n    \"\"\"\n\n    # 2D trajectory\n    if isinstance(pred_poses, np.ndarray) and pred_poses.shape[1] == 2:\n        scaling = scale_lse_solver(pred_poses, gt_poses)\n        pred_scaled = scaling * pred_poses\n    # 3D poses (6 DoF)\n    elif isinstance(pred_poses, list) and pred_poses[0].shape == (4, 4):\n        # Scale only translation but keep rotation\n        pred_xyz = np.asarray([p[:3, 3] for p in pred_poses])\n        gt_xyz = np.asarray([p[:3, 3] for p in gt_poses])\n        scaling = scale_lse_solver(pred_xyz, gt_xyz)\n        pred_scaled = copy.deepcopy(pred_poses)\n        for p in pred_scaled:\n            p[:3, 3] *= scaling\n    else:\n        assert False\n    return pred_scaled, scaling\n\n\ndef scale_lse_solver(X, Y):\n    \"\"\"Least-squares-error solver\n    Compute optimal scaling factor so that s(X)-Y is minimum\n    Args:\n        X (KxN array): current data\n        Y (KxN array): reference data\n    Returns:\n        scale (float): scaling factor\n    \"\"\"\n    scale = np.sum(X * Y) / np.sum(X**2)\n    return scale\n\n\ndef trajectory_distances(poses):\n    \"\"\"Compute distance for each pose w.r.t frame-0\n    \"\"\"\n    xyz = [p[:3, 3] for p in poses]\n    dist = [0]\n    for i in range(1, len(poses)):\n        d = dist[i - 1] + np.linalg.norm(xyz[i] - xyz[i - 1])\n        dist.append(d)\n    return dist\n\n\ndef last_frame_from_segment_length(dist, first_frame, length):\n    \"\"\"Find frame (index) that away from the first_frame with\n    the required distance\n    Args:\n        dist (float list): distance of each pose w.r.t frame-0\n        first_frame (int): start-frame index\n        length (float): required distance\n    Returns:\n        i (int) / -1: end-frame index. if not found return -1\n    \"\"\"\n    for i in range(first_frame, len(dist), 1):\n        if dist[i] > (dist[first_frame] + length):\n            return i\n    return -1\n\n\ndef rotation_error(pose_error):\n    \"\"\"Compute rotation error\n    Args:\n        pose_error (4x4 array): relative pose error\n    Returns:\n        rot_error (float): rotation error\n    \"\"\"\n    a = pose_error[0, 0]\n    b = pose_error[1, 1]\n    c = pose_error[2, 2]\n    d = 0.5 * (a + b + c - 1.0)\n    rot_error = np.arccos(max(min(d, 1.0), -1.0))\n    return rot_error\n\n\ndef translation_error(pose_error):\n    \"\"\"Compute translation error\n    Args:\n        pose_error (4x4 array): relative pose error\n    Returns:\n        trans_error (float): translation error\n    \"\"\"\n    dx = pose_error[0, 3]\n    dy = pose_error[1, 3]\n    dz = pose_error[2, 3]\n    trans_error = np.sqrt(dx**2 + dy**2 + dz**2)\n    return trans_error\n\n\ndef calc_sequence_errors(pred_poses, gt_poses):\n    \"\"\"calculate sequence error\n    \"\"\"\n    error = []\n    dist = trajectory_distances(gt_poses)\n    step_size = 10\n    sequence_lengths = [100, 200, 300, 400, 500, 600, 700, 800]\n    num_lengths = len(sequence_lengths)\n\n    for first_frame in range(0, len(gt_poses), step_size):\n        for i in range(num_lengths):\n            length = sequence_lengths[i]\n            last_frame = last_frame_from_segment_length(dist, first_frame, length)\n\n            # Continue if sequence is not long enough\n            if last_frame == -1:\n                continue\n\n            # Compute rotational and translational errors\n            pose_delta_gt = np.linalg.inv(gt_poses[first_frame]) @ gt_poses[last_frame]\n            pose_delta_pred = np.linalg.inv(pred_poses[first_frame]) @ pred_poses[last_frame]\n            pose_error = np.linalg.inv(pose_delta_pred) @ pose_delta_gt\n            rot_error = rotation_error(pose_error) / length\n            trans_error = translation_error(pose_error) / length\n\n            # compute speed\n            num_frames = last_frame - first_frame + 1\n            speed = length / (0.1 * num_frames)  # Assume 10fps\n\n            error.append([first_frame, rot_error, trans_error, length, speed])\n    return error\n\n\ndef compute_segment_error(seq_errs):\n    \"\"\"This function calculates average errors for different segment.\n    Args:\n        seq_errs (list list): list of errs; [first_frame, rotation error, translation error,\n                                             length, speed]\n            - first_frame: frist frame index\n            - rotation error: rotation error per length\n            - translation error: translation error per length\n            - length: evaluation trajectory length\n            - speed: car speed (#FIXME: 10FPS is assumed)\n    Returns:\n        avg_segment_errs (dict): {100:[avg_t_err, avg_r_err],...}\n    \"\"\"\n\n    sequence_lengths = [100, 200, 300, 400, 500, 600, 700, 800]\n\n    segment_errs = {}\n    avg_segment_errs = {}\n    for len_ in sequence_lengths:\n        segment_errs[len_] = []\n\n    # Get errors\n    for err in seq_errs:\n        len_ = err[3]\n        t_err = err[2]\n        r_err = err[1]\n        segment_errs[len_].append([t_err, r_err])\n\n    # Compute average\n    for len_ in sequence_lengths:\n        if segment_errs[len_] != []:\n            avg_t_err = np.mean(np.asarray(segment_errs[len_])[:, 0])\n            avg_r_err = np.mean(np.asarray(segment_errs[len_])[:, 1])\n            avg_segment_errs[len_] = [avg_t_err, avg_r_err]\n        else:\n            avg_segment_errs[len_] = []\n    return avg_segment_errs\n\n\ndef compute_overall_err(seq_err):\n    \"\"\"Compute average translation & rotation errors\n    Args:\n        seq_err (list list): [[r_err, t_err],[r_err, t_err],...]\n            - r_err (float): rotation error\n            - t_err (float): translation error\n    Returns:\n        ave_t_err (float): average translation error\n        ave_r_err (float): average rotation error\n    \"\"\"\n    t_err = 0\n    r_err = 0\n\n    seq_len = len(seq_err)\n\n    if seq_len == 0:\n        return 0, 0\n    for item in seq_err:\n        r_err += item[1]\n        t_err += item[2]\n    ave_t_err = t_err / seq_len\n    ave_r_err = r_err / seq_len\n    return ave_t_err, ave_r_err\n\n\ndef compute_ATE(pred_poses, gt_poses):\n    \"\"\"Compute RMSE of ATE (abs. trajectory error)\n    \"\"\"\n    errors = []\n    for pred_pose, gt_pose in zip(pred_poses, gt_poses):\n        gt_xyz = gt_pose[:3, 3]\n        pred_xyz = pred_pose[:3, 3]\n        align_err = gt_xyz - pred_xyz\n\n        errors.append(np.sqrt(np.sum(align_err**2)))\n    ate = np.sqrt(np.mean(np.asarray(errors)**2))\n    return ate\n\n\ndef compute_RPE(pred_poses, gt_poses):\n    \"\"\"Compute RPE (rel. pose error)\n    Returns:\n        rpe_trans\n        rpe_rot\n    \"\"\"\n    trans_errors = []\n    rot_errors = []\n    for i in range(len(pred_poses) - 1):\n        # for i in list(pred.keys())[:-1]:\n        gt1 = gt_poses[i]\n        gt2 = gt_poses[i + 1]\n        gt_rel = np.linalg.inv(gt1) @ gt2\n\n        pred1 = pred_poses[i]\n        pred2 = pred_poses[i + 1]\n        pred_rel = np.linalg.inv(pred1) @ pred2\n\n        rel_err = np.linalg.inv(gt_rel) @ pred_rel\n        trans_errors.append(translation_error(rel_err))\n        rot_errors.append(rotation_error(rel_err))\n    rpe_trans = np.mean(np.asarray(trans_errors))\n    rpe_rot = np.mean(np.asarray(rot_errors))\n    return rpe_trans, rpe_rot\n\n\ndef calc_error(pred_poses, gt_poses, optimize_scale: bool = False) -> str:\n    log = ''\n    if optimize_scale:\n        pred_poses_scaled, scaling = scale_optimization(pred_poses, gt_poses)\n        log += '-' * 10 + ' MEDIAN\\n'\n        log += f'Scaling: {scaling}'\n    else:\n        pred_poses_scaled = pred_poses\n    sequence_error = calc_sequence_errors(pred_poses_scaled, gt_poses)\n    # segment_error = compute_segment_error(sequence_error)\n    ave_t_err, ave_r_err = compute_overall_err(sequence_error)\n\n    log += '-' * 10 + '\\n'\n    log += f'Trans error (%):      {ave_t_err * 100:.4f}' + '\\n'\n    log += f'Rot error (deg/100m): {100 * ave_r_err / np.pi * 180:.4f}' + '\\n'\n\n    # Compute ATE\n    ate = compute_ATE(pred_poses, gt_poses)\n    log += f'Abs traj RMSE (m):    {ate:.4f}' + '\\n'\n\n    # Compute RPE\n    rpe_trans, rpe_rot = compute_RPE(pred_poses, gt_poses)\n    log += f'Rel pose error (m):   {rpe_trans:.4f}' + '\\n'\n    log += f'Rel pose err (deg):   {rpe_rot * 180 / np.pi:.4f}' + '\\n'\n    log += '-' * 10 + '\\n'\n\n    return log\n\n\n# =============================================================================\n\n\ndef calc_depth_error(\n    pred_depth,\n    gt_depth,\n    median_scaling: bool = True,\n    min_depth: Optional[float] = None,\n    max_depth: Optional[float] = None,\n) -> Dict[str, float]:\n    gt_height, gt_width = gt_depth.shape\n    pred_depth = cv2.resize(pred_depth, (gt_width, gt_height))\n\n    # Mask out pixels without ground truth depth\n    # or ground truth depth farther away than the maximum predicted depth\n    if max_depth is not None:\n        mask = np.logical_and(gt_depth > min_depth, gt_depth < max_depth)\n    else:\n        mask = gt_depth > min_depth\n    pred_depth = pred_depth[mask]\n    gt_depth = gt_depth[mask]\n\n    # Introduced by SfMLearner\n    if median_scaling:\n        ratio = np.median(gt_depth) / np.median(pred_depth)\n        pred_depth *= ratio\n\n    # Cap predicted depth at min and max depth\n    pred_depth[pred_depth < min_depth] = min_depth\n    if max_depth is not None:\n        pred_depth[pred_depth > max_depth] = max_depth\n\n    # Compute error metrics\n    thresh = np.maximum((gt_depth / pred_depth), (pred_depth / gt_depth))\n    a1 = np.mean(thresh < 1.25)\n    a2 = np.mean(thresh < 1.25**2)\n    a3 = np.mean(thresh < 1.25**3)\n    rmse = (gt_depth - pred_depth)**2\n    rmse_tot = np.sqrt(np.mean(rmse))\n    rmse_log = (np.log(gt_depth) - np.log(pred_depth))**2\n    rmse_log_tot = np.sqrt(np.mean(rmse_log))\n    abs_diff = np.mean(np.abs(gt_depth - pred_depth))\n    abs_rel = np.mean(np.abs(gt_depth - pred_depth) / gt_depth)\n    sq_rel = np.mean(((gt_depth - pred_depth)**2) / gt_depth)\n\n    metrics = {\n        'abs_diff': abs_diff,\n        'abs_rel': abs_rel,\n        'sq_rel': sq_rel,\n        'a1': a1,\n        'a2': a2,\n        'a3': a3,\n        'rmse': rmse_tot,\n        'rmse_log': rmse_log_tot\n    }\n\n    return metrics\n"
  },
  {
    "path": "third_party/fix_g2opy.py",
    "content": "#!/usr/bin/env python3\n# pylint: disable = line-too-long\n\nimport os\nfrom pathlib import Path\n\nINPUT_FILE = Path(__file__).parent / 'g2opy' / 'python' / 'core' / 'eigen_types.h'\nassert INPUT_FILE.exists()\n\ntmp_file = Path(str(INPUT_FILE) + '_tmp')\n\nwith open(INPUT_FILE, 'r', encoding='utf-8') as input_file:\n    with open(tmp_file, 'w', encoding='utf-8') as output_file:\n        for i, line in enumerate(input_file.readlines()):\n            if line == '        .def(\"x\", (double (Eigen::Quaterniond::*) () const) &Eigen::Quaterniond::x)\\n':\n                line = '        .def(\"x\", (double &(Eigen::Quaterniond::*)()) & Eigen::Quaterniond::x)\\n'\n            elif line == '        .def(\"y\", (double (Eigen::Quaterniond::*) () const) &Eigen::Quaterniond::y)\\n':\n                line = '        .def(\"y\", (double &(Eigen::Quaterniond::*)()) & Eigen::Quaterniond::y)\\n'\n            elif line == '        .def(\"z\", (double (Eigen::Quaterniond::*) () const) &Eigen::Quaterniond::z)\\n':\n                line = '        .def(\"z\", (double &(Eigen::Quaterniond::*)()) & Eigen::Quaterniond::z)\\n'\n            elif line == '        .def(\"w\", (double (Eigen::Quaterniond::*) () const) &Eigen::Quaterniond::w)\\n':\n                line = '        .def(\"w\", (double &(Eigen::Quaterniond::*)()) & Eigen::Quaterniond::w)\\n'\n            output_file.write(line)\n\nos.rename(tmp_file, INPUT_FILE)\n"
  }
]