Full Code of GREAT-WHU/DBA-Fusion for AI

main 2c658a3be747 cached
71 files
377.7 KB
112.5k tokens
260 symbols
1 requests
Download .txt
Showing preview only (399K chars total). Download the full file or copy to clipboard to get everything.
Repository: GREAT-WHU/DBA-Fusion
Branch: main
Commit: 2c658a3be747
Files: 71
Total size: 377.7 KB

Directory structure:
gitextract_ny3kcvri/

├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── batch_kitti360.py
├── batch_subt.py
├── batch_tumvi.py
├── batch_whu.py
├── calib/
│   ├── 0412.txt
│   ├── 0412new.txt
│   ├── 1012.txt
│   ├── barn.txt
│   ├── carla.txt
│   ├── eth.txt
│   ├── euroc.txt
│   ├── handheld.txt
│   ├── kitti_360.txt
│   ├── subt.txt
│   ├── tartan.txt
│   ├── tum3.txt
│   └── tumvi.txt
├── dataset/
│   ├── euroc_to_hdf5.py
│   ├── kitti360_to_hdf5.py
│   └── tumvi_to_hdf5.py
├── dbaf/
│   ├── covisible_graph.py
│   ├── data_readers/
│   │   ├── __init__.py
│   │   ├── augmentation.py
│   │   ├── base.py
│   │   ├── factory.py
│   │   ├── rgbd_utils.py
│   │   ├── stream.py
│   │   ├── tartan.py
│   │   └── tartan_test.txt
│   ├── dbaf.py
│   ├── dbaf_frontend.py
│   ├── depth_video.py
│   ├── droid_net.py
│   ├── geoFunc/
│   │   ├── __init__.py
│   │   ├── const_value.py
│   │   └── trans.py
│   ├── geom/
│   │   ├── __init__.py
│   │   ├── ba.py
│   │   ├── chol.py
│   │   ├── graph_utils.py
│   │   ├── losses.py
│   │   └── projective_ops.py
│   ├── modules/
│   │   ├── __init__.py
│   │   ├── clipping.py
│   │   ├── corr.py
│   │   ├── extractor.py
│   │   └── gru.py
│   ├── motion_filter.py
│   └── multi_sensor.py
├── demo_vio_kitti360.py
├── demo_vio_subt.py
├── demo_vio_tumvi.py
├── demo_vio_whu.py
├── evaluation_scripts/
│   ├── batch_tumvi.py
│   ├── evaluate_kitti.py
│   └── evaluate_tumvi.py
├── results/
│   └── PLACEHOLDER
├── setup.py
├── src/
│   ├── altcorr_kernel.cu
│   ├── bacore.h
│   ├── correlation_kernels.cu
│   ├── droid.cpp
│   └── droid_kernels.cu
└── visualization/
    ├── check_reconstruction_kitti.py
    ├── check_reconstruction_kitti_animation.py
    ├── check_reconstruction_tumvi.py
    └── check_reconstruction_tumvi_animation.py

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
a# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
.pybuilder/
target/

# Jupyter Notebook
.ipynb_checkpoints

# IPython
profile_default/
ipython_config.py

# pyenv
#   For a library or package, you might want to ignore these files since the code is
#   intended to run in multiple environments; otherwise, check them in:
# .python-version

# pipenv
#   According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
#   However, in case of collaboration, if having platform-specific dependencies or dependencies
#   having no cross-platform support, pipenv may install dependencies that don't work, or not
#   install all needed dependencies.
#Pipfile.lock

# PEP 582; used by e.g. github.com/David-OConnor/pyflow
__pypackages__/

# Celery stuff
celerybeat-schedule
celerybeat.pid

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/
.dmypy.json
dmypy.json

# Pyre type checker
.pyre/

# pytype static type analyzer
.pytype/

# Cython debug symbols
cython_debug/



__pycache__
build
dist
*.egg-info
*.vscode/
*.pth
tests
checkpoints
datasets
runs
cache
*.out
*.o
data
figures/*.pdf




================================================
FILE: .gitmodules
================================================
[submodule "thirdparty/lietorch"]
	path = thirdparty/lietorch
	url = https://github.com/princeton-vl/lietorch
[submodule "thirdparty/eigen"]
	path = thirdparty/eigen
	url = https://gitlab.com/libeigen/eigen.git


================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The GNU General Public License is a free, copyleft license for
software and other kinds of works.

  The licenses for most software and other practical works are designed
to take away your freedom to share and change the works.  By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.  We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors.  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.

  To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights.  Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received.  You must make sure that they, too, receive
or can get the source code.  And you must show them these terms so they
know their rights.

  Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.

  For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software.  For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.

  Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so.  This is fundamentally incompatible with the aim of
protecting users' freedom to change the software.  The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable.  Therefore, we
have designed this version of the GPL to prohibit the practice for those
products.  If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.

  Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary.  To prevent this, the GPL assures that
patents cannot be used to render the program non-free.

  The precise terms and conditions for copying, distribution and
modification follow.

                       TERMS AND CONDITIONS

  0. Definitions.

  "This License" refers to version 3 of the GNU General Public License.

  "Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.

  "The Program" refers to any copyrightable work licensed under this
License.  Each licensee is addressed as "you".  "Licensees" and
"recipients" may be individuals or organizations.

  To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy.  The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.

  A "covered work" means either the unmodified Program or a work based
on the Program.

  To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy.  Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.

  To "convey" a work means any kind of propagation that enables other
parties to make or receive copies.  Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.

  An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License.  If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.

  1. Source Code.

  The "source code" for a work means the preferred form of the work
for making modifications to it.  "Object code" means any non-source
form of a work.

  A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.

  The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form.  A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.

  The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities.  However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work.  For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.

  The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.

  The Corresponding Source for a work in source code form is that
same work.

  2. Basic Permissions.

  All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met.  This License explicitly affirms your unlimited
permission to run the unmodified Program.  The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work.  This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.

  You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force.  You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright.  Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.

  Conveying under any other circumstances is permitted solely under
the conditions stated below.  Sublicensing is not allowed; section 10
makes it unnecessary.

  3. Protecting Users' Legal Rights From Anti-Circumvention Law.

  No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.

  When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.

  4. Conveying Verbatim Copies.

  You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.

  You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.

  5. Conveying Modified Source Versions.

  You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:

    a) The work must carry prominent notices stating that you modified
    it, and giving a relevant date.

    b) The work must carry prominent notices stating that it is
    released under this License and any conditions added under section
    7.  This requirement modifies the requirement in section 4 to
    "keep intact all notices".

    c) You must license the entire work, as a whole, under this
    License to anyone who comes into possession of a copy.  This
    License will therefore apply, along with any applicable section 7
    additional terms, to the whole of the work, and all its parts,
    regardless of how they are packaged.  This License gives no
    permission to license the work in any other way, but it does not
    invalidate such permission if you have separately received it.

    d) If the work has interactive user interfaces, each must display
    Appropriate Legal Notices; however, if the Program has interactive
    interfaces that do not display Appropriate Legal Notices, your
    work need not make them do so.

  A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit.  Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.

  6. Conveying Non-Source Forms.

  You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:

    a) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by the
    Corresponding Source fixed on a durable physical medium
    customarily used for software interchange.

    b) Convey the object code in, or embodied in, a physical product
    (including a physical distribution medium), accompanied by a
    written offer, valid for at least three years and valid for as
    long as you offer spare parts or customer support for that product
    model, to give anyone who possesses the object code either (1) a
    copy of the Corresponding Source for all the software in the
    product that is covered by this License, on a durable physical
    medium customarily used for software interchange, for a price no
    more than your reasonable cost of physically performing this
    conveying of source, or (2) access to copy the
    Corresponding Source from a network server at no charge.

    c) Convey individual copies of the object code with a copy of the
    written offer to provide the Corresponding Source.  This
    alternative is allowed only occasionally and noncommercially, and
    only if you received the object code with such an offer, in accord
    with subsection 6b.

    d) Convey the object code by offering access from a designated
    place (gratis or for a charge), and offer equivalent access to the
    Corresponding Source in the same way through the same place at no
    further charge.  You need not require recipients to copy the
    Corresponding Source along with the object code.  If the place to
    copy the object code is a network server, the Corresponding Source
    may be on a different server (operated by you or a third party)
    that supports equivalent copying facilities, provided you maintain
    clear directions next to the object code saying where to find the
    Corresponding Source.  Regardless of what server hosts the
    Corresponding Source, you remain obligated to ensure that it is
    available for as long as needed to satisfy these requirements.

    e) Convey the object code using peer-to-peer transmission, provided
    you inform other peers where the object code and Corresponding
    Source of the work are being offered to the general public at no
    charge under subsection 6d.

  A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.

  A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling.  In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage.  For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.  A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.

  "Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source.  The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.

  If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information.  But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).

  The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed.  Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.

  Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.

  7. Additional Terms.

  "Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law.  If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.

  When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it.  (Additional permissions may be written to require their own
removal in certain cases when you modify the work.)  You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.

  Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:

    a) Disclaiming warranty or limiting liability differently from the
    terms of sections 15 and 16 of this License; or

    b) Requiring preservation of specified reasonable legal notices or
    author attributions in that material or in the Appropriate Legal
    Notices displayed by works containing it; or

    c) Prohibiting misrepresentation of the origin of that material, or
    requiring that modified versions of such material be marked in
    reasonable ways as different from the original version; or

    d) Limiting the use for publicity purposes of names of licensors or
    authors of the material; or

    e) Declining to grant rights under trademark law for use of some
    trade names, trademarks, or service marks; or

    f) Requiring indemnification of licensors and authors of that
    material by anyone who conveys the material (or modified versions of
    it) with contractual assumptions of liability to the recipient, for
    any liability that these contractual assumptions directly impose on
    those licensors and authors.

  All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10.  If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term.  If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.

  If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.

  Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.

  8. Termination.

  You may not propagate or modify a covered work except as expressly
provided under this License.  Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).

  However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.

  Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.

  Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License.  If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.

  9. Acceptance Not Required for Having Copies.

  You are not required to accept this License in order to receive or
run a copy of the Program.  Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance.  However,
nothing other than this License grants you permission to propagate or
modify any covered work.  These actions infringe copyright if you do
not accept this License.  Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.

  10. Automatic Licensing of Downstream Recipients.

  Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License.  You are not responsible
for enforcing compliance by third parties with this License.

  An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations.  If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.

  You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License.  For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.

  11. Patents.

  A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based.  The
work thus licensed is called the contributor's "contributor version".

  A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version.  For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.

  Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.

  In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement).  To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.

  If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients.  "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.

  If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.

  A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License.  You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.

  Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.

  12. No Surrender of Others' Freedom.

  If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all.  For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.

  13. Use with the GNU Affero General Public License.

  Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work.  The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.

  14. Revised Versions of this License.

  The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

  Each version is given a distinguishing version number.  If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation.  If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.

  If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.

  Later license versions may give you additional or different
permissions.  However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.

  15. Disclaimer of Warranty.

  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.

  16. Limitation of Liability.

  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.

  17. Interpretation of Sections 15 and 16.

  If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.

Also add information on how to contact you by electronic and paper mail.

  If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:

    <program>  Copyright (C) <year>  <name of author>
    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".

  You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.

  The GNU General Public License does not permit incorporating your program
into proprietary programs.  If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.  But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# DBA-Fusion

>Tightly Integrating Deep Dense Visual Bundle Adjustment with Multiple Sensors for Large-Scale  Localization and Mapping


<div align=center>
<img alt="" src="./assets/abstract.png" width='500px' />
</div>


[[Paper](https://arxiv.org/abs/2403.13714)] [[Video](https://www.bilibili.com/video/BV1yeNEecEwR/?share_source=copy_web&vd_source=a659a573a520a1151e294d0c8b9c842a)]

## What is this? 

**DBA-Fusion** is basically a VIO system which fuses DROID-SLAM-like dense bundle adjustment (DBA) with classic factor graph optimization. This work enables **realtime metric-scale localization and dense mapping** with excellent accuracy and robustness. Besides, this framework supports the **flexible fusion of multiple sensors** like GNSS or wheel speed sensors, extending its applicability to large-scale scenarios.  
<br />
<div align=center>
<img alt="" src="./assets/Hv.svg" width='400px' />
</div>
<br />
<div align=center>
<img alt="" src="./assets/0005.gif" width='500px' />
</div>
<div align=center>
<img alt="" src="./assets/outdoors6.gif" width='500px' />
</div>

## Update log
- [x] Code Upload (2024/02/28)
- [x] Monocular VIO Examples (2024/02/28)
- [x] Multi-sensor data sequence (WUH1012) used in the manuscript is available [here](https://drive.google.com/file/d/1w7UsAwreou_9YRYHz13QIGu6jOJGpdg5/view?usp=sharing).
- [x] Multi-Sensor Fusion Examples 
- [ ] Stereo/RGB-D VIO Support

## Installation
The pipeline of the work is based on python, and the computation part is mainly based on Pytorch (with CUDA) and GTSAM.

Use the following commands to set up the python environment.

```Bash
conda create -n dbaf python=3.10.11
conda activate dbaf
# Other CUDA versions should also be fine.
pip install torch==1.11.0+cu113 torchvision==0.12.0+cu113 torchaudio==0.11.0 --extra-index-url https://download.pytorch.org/whl/cu113
pip install torch-scatter==2.0.9 -f https://data.pyg.org/whl/torch-1.11.0+cu113.html
pip install gdown tqdm numpy==1.25.0 numpy-quaternion==2022.4.3 opencv-python==4.7.0.72 scipy pyparsing matplotlib h5py 
pip install evo --upgrade --no-binary evo
pip install open3d # optional for visualization
```

As for GTSAM, we make some modifications to it to extend the python wrapper APIs, clone it from the following repository and install it under your python environment.

```Bash
git clone https://github.com/yuxuanzhou97/gtsam
cd gtsam
mkdir build
cd build
cmake .. -DGTSAM_BUILD_PYTHON=1 -DGTSAM_PYTHON_VERSION=3.10.11
make python-install
```

Finally, run the following command to build DBA-Fusion.

```Bash
git clone --recurse-submodules https://github.com/GREAT-WHU/DBA-Fusion.git
cd DBA-Fusion
python setup.py install
```

## Run DBA-Fusion
We don't modify the model of DROID-SLAM so you can directly employ the  weight trained for DROID-SLAM. Here we use the [model](https://drive.google.com/file/d/1PpqVt1H4maBa_GbPJp4NwxRsd9jk-elh/view?usp=sharing) pre-trained on TartanAir (provided by [DROID-SLAM](https://github.com/princeton-vl/DROID-SLAM?tab=readme-ov-file)), which shows great zero-shot performance on real-world datasets.

**(Attention!!!)**
For the default configurations, around ~10GB GPU memory is needed. Lower the "max_factors" argument to 36 or lower could help reduce the memory usage to ~6GB.

### 1. TUM-VI
1.1 Download the [TUM-VI](https://cvg.cit.tum.de/data/datasets/visual-inertial-dataset) datasets (512*512).

**(Optional)**
For better speed performance, it is recommended to convert the PNG images to a single HDF5 file through
```Bash
python dataset/tumvi_to_hdf5.py --imagedir=${DATASET_DIR}/dataset-${SEQ}_512_16/mav0/cam0/data --imagestamp=${DATASET_DIR}/dataset-${SEQ}_512_16/mav0/cam0/data.csv --h5path=${SEQ}.h5 --calib=calib/tumvi.txt --stride 4
```

1.2  Specify the data path in [batch_tumvi.py](../batch_tumvi.py) (if you use HDF5 file, activate the "--enable_h5" and "--h5_path" arguments), run the following command 

```Bash
python batch_tumvi.py  # This would trigger demo_vio_tumvi.py automatically.
```

Look into [demo_vio_tumvi.py](../demo_vio_tumvi.py) to learn about the arguments. Data loading and almost all the parameters are specified in this **one** file.

1.3 The outputs of the program includes **a text file** which contains real-time navigation results and **a .pkl file** which contains all keyframe poses and point clouds.

To evaluate the realtime pose estimation performance, run the following command (notice to change the file paths in *evaluate_kitti.py*)

```Bash
python evaluation_scripts/evaluate_tumvi.py --seq ${SEQ}
```
or 
```Bash
python evaluation_scripts/batch_evaluate_tumvi.py
```


For 3D visualization, currently we haven't handled the realtime visualization functionality. Run the scripts in the **"visualization"** folder for post-time visualization. 

```Bash
python visualization/check_reconstruction_tumvi.py
```

### 2. KITTI-360
2.1 Download the [KITTI-360](https://www.cvlibs.net/datasets/kitti-360/index.php) datasets. Notice that we use the **unrectified perspective images** for the evaluation (named like "2013_05_28_drive_XXXX_sync/image_00/data_rgb").



For **IMU** data and IMU-centered **ground-truth poses**, we transform the axises to **Right-Forward-Up (RFU)** and check the synchronization. Besides, we use [OpenVINS](https://github.com/rpng/open_vins/) (in stereo VIO mode) to online refine the Camera-IMU extrinsics and time offsets (whose pre-calibrated values seem not very accurate) on the sequences. The refined parameters are used for for all the tests.  

**To reproduce the results**, just download the our prepared IMU and ground-truth data from [here](https://drive.google.com/file/d/1BO8zGvoey7IdwbWXmAdlhGPr6hiCFJ6Y/view?usp=drive_link), then uncompress it to the data path.

**(Optional)**
Similar to the TUM-VI part, you can use the following script to generate a HDF5 file for best speed performance.

```Bash
python dataset/kitti360_to_hdf5.py --imagedir=${DATASET_DIR}/2013_05_28_drive_%s_sync/image_00/data_rgb --imagestamp=${DATASET_DIR}/2013_05_28_drive_%s_sync/camstamp.txt --h5path=${SEQ}.h5 --calib=calib/kitti360.txt --stride 2
```

2.2 Run the following command

```Bash
python batch_kitti360.py
```
Dataloading and parameters are specified in [demo_vio_kitti360.py](../demo_vio_kitti360.py).

2.3 For evaluation and visualization, run
```Bash
python evaluation_scripts/evaluate_kitti360.py --seq ${SEQ}
python visualization/check_reconstruction_kitti360.py
```

### 3. WUH1012
Download our self-collected data sequence from [here](https://drive.google.com/file/d/1w7UsAwreou_9YRYHz13QIGu6jOJGpdg5/view?usp=sharing).

See [batch_whu.py](../batch_whu.py) for multi-sensor fusion in different modes (VIO + wheel speed/GNSS), as described in the manuscript.

### 4. Run on Your Own Dataset
To run monocular VIO on your own dataset,
* Duplicate a script from [demo_vio_kitti360.py](../demo_vio_kitti360.py) or [demo_vio_tumvi.py](../demo_vio_tumvi.py). 
* In the script, specify the data loading procedure of IMU data and images.
* Specify the camera intrinsics and camera-IMU extrinsics in the script. 
* Try it!

## Some Results
- Visual point cloud map compared to accumulated LiDAR point clouds.
<div align=center>
<img alt="" src="./assets/lidar.jpg" width='500px' />
</div>

- Further processing on the visual point clouds. (P.S. For 3-D GS, the point positions and number are fixed. The training time is around 3 minutes on RTX4080 laptop. )
<div align=center>
<img alt="" src="./assets/postprocessing.png" width='750px' />
</div>

## Acknowledgement
DBA-Fusion is developed by [GREAT](http://igmas.users.sgg.whu.edu.cn/group) (GNSS+ REsearch, Application and Teaching) Group, School of Geodesy and Geomatics, Wuhan University. 

<br/>
<div align=center>
<img alt="" src="./assets/GREAT.png" width='300px' />
</div>
<br/>
<div align=center>
<img alt="" src="./assets/whu.png" width='300px' />
</div>
<br/>

This work is based on [DROID-SLAM](https://github.com/princeton-vl/DROID-SLAM) and [GTSAM](https://github.com/borglab/gtsam). We use evaluation tools from [evo](https://github.com/MichaelGrupp/evo) and 3D visualization tools from [Open3d](https://github.com/MichaelGrupp/evo).


================================================
FILE: batch_kitti360.py
================================================
import os
import subprocess

for i in ['0000','0002','0003','0004','0005','0006','0009','0010']:
    p = subprocess.Popen("python demo_vio_kitti360.py" +\
     " --imagedir=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/image_00/data_rgb"%i +\
     " --imagestamp=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/camstamp.txt"%i +\
     " --imupath=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/imu.txt"%i +\
     " --gtpath=/home/zhouyuxuan/data/2013_05_28_drive_%s_sync/gt_local.txt"%i +\
    #  " --enable_h5" +\
    #  " --h5path=/home/zhouyuxuan/DROID-SLAM/%s.h5"%i +\
     " --resultpath=results/result_%s.txt"%i +\
     " --calib=calib/kitti_360.txt" +\
     " --stride=2" +\
     " --max_factors=48" +\
     " --active_window=12" +\
     " --frontend_window=5" +\
     " --frontend_radius=2" +\
     " --frontend_nms=1" +\
     " --inac_range=3" +\
     " --visual_only=0" +\
     " --far_threshold=-1" +\
     " --translation_threshold=0.5" +\
     " --mask_threshold=1.0" +\
     " --skip_edge=[-4,-5,-6]" +\
     " --save_pkl" +\
     " --pklpath=results/%s.pkl"%i +\
     " --show_plot",shell=True)
    p.wait()


================================================
FILE: batch_subt.py
================================================
import os
import subprocess

for i in [\
    # 'Handheld1_Folder',\
    'Handheld2_Folder',\
      ]:
    p = subprocess.Popen("python demo_vio_subt.py" +\
    " --imagedir=/mnt/e/subt/%s/cam_0"%i +\
    " --imagestamp=/mnt/e/subt/%s/cam_0/timestamps.txt"%i +\
    " --imupath=/mnt/e/subt/%s/imu/imu_data.csv"%i +\
    " --resultpath=results/result_%s.txt"%i +\
    " --calib=calib/subt.txt" +\
    " --stride=8" +\
    " --max_factors=48" +\
    " --active_window=12" +\
    " --frontend_window=5" +\
    " --frontend_radius=2" +\
    " --frontend_nms=1" +\
    " --far_threshold=0.02" +\
    " --inac_range=3" +\
    " --visual_only=0" +\
    " --translation_threshold=0.2" +\
    " --mask_threshold=-1.0" +\
    " --skip_edge=[-4,-5,-6]" +\
    " --save_pkl" +\
    " --pklpath=results/%s.pkl"%i +\
    " --show_plot",shell=True)
    p.wait()


================================================
FILE: batch_tumvi.py
================================================
import os
import subprocess

for i in [\
    'outdoors1',\
    'outdoors2',\
    'outdoors3',\
    'outdoors4',\
    'outdoors5',\
    'outdoors6',\
    'outdoors7',\
    'outdoors8',\
    'magistrale1',\
    'magistrale2',\
    'magistrale3',\
    'magistrale4',\
    'magistrale5',\
    'magistrale6'
      ]:
    p = subprocess.Popen("python demo_vio_tumvi.py" +\
    " --imagedir=/mnt/z/tum-vi/dataset-%s_512_16/mav0/cam0/data"%i +\
    " --imagestamp=/mnt/z/tum-vi/dataset-%s_512_16/mav0/cam0/data.csv"%i +\
    " --imupath=/mnt/z/tum-vi/dataset-%s_512_16/mav0/imu0/data.csv"%i +\
    " --gtpath=/mnt/z/tum-vi/dataset-%s_512_16/dso/gt_imu.csv"%i +\
    # " --enable_h5" +\
    # " --h5path=/home/zhouyuxuan/DROID-SLAM/%s.h5"%i +\
    " --resultpath=results/result_%s.txt"%i +\
    " --calib=calib/tumvi.txt" +\
    " --stride=4" +\
    " --max_factors=48" +\
    " --active_window=12" +\
    " --frontend_window=5" +\
    " --frontend_radius=2" +\
    " --frontend_nms=1" +\
    " --far_threshold=0.02" +\
    " --inac_range=3" +\
    " --visual_only=0" +\
    " --translation_threshold=0.2" +\
    " --mask_threshold=-1.0" +\
    " --skip_edge=[-4,-5,-6]" +\
    " --save_pkl" +\
    " --pklpath=results/%s.pkl"%i +\
    " --show_plot",shell=True)
    p.wait()


================================================
FILE: batch_whu.py
================================================
import os
import subprocess

# VIO
p = subprocess.Popen("python demo_vio_whu.py" +\
    " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\
    " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\
    " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\
    " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\
    " --resultpath=results/result_whu_vio.txt" +\
    " --calib=calib/1012.txt" +\
    " --stride=2" +\
    " --max_factors=48" +\
    " --active_window=12" +\
    " --frontend_window=5" +\
    " --frontend_radius=2" +\
    " --frontend_nms=1" +\
    " --inac_range=3" +\
    " --visual_only=0" +\
    " --far_threshold=-1" +\
    " --translation_threshold=0.25" +\
    " --mask_threshold=0.0" +\
    " --skip_edge=[]" +\
    " --save_pkl" +\
    " --use_zupt" +\
    " --pklpath=results/whu.pkl" +\
    " --show_plot",
 shell=True)
p.wait()

# VIO + wheel
p = subprocess.Popen("python demo_vio_whu.py" +\
    " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\
    " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\
    " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\
    " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\
    " --resultpath=results/result_whu_viow.txt" +\
    " --calib=calib/1012.txt" +\
    " --stride=2" +\
    " --max_factors=48" +\
    " --active_window=12" +\
    " --frontend_window=5" +\
    " --frontend_radius=2" +\
    " --frontend_nms=1" +\
    " --inac_range=3" +\
    " --visual_only=0" +\
    " --far_threshold=-1" +\
    " --translation_threshold=0.25" +\
    " --mask_threshold=0.0" +\
    " --skip_edge=[]" +\
    " --save_pkl" +\
    " --use_odo" +\
    " --odopath=/home/zhouyuxuan/data/WUH1012/odo_synthesis.txt" +\
    " --pklpath=results/whu.pkl" +\
    " --show_plot",
 shell=True)
p.wait()

# VIO + GNSS
p = subprocess.Popen("python demo_vio_whu.py" +\
        " --imagedir=/home/zhouyuxuan/data/WUH1012/cam0" +\
        " --imagestamp=/home/zhouyuxuan/data/WUH1012/camstamp.txt" +\
        " --imupath=/home/zhouyuxuan/data/WUH1012/imu.txt" +\
        " --gtpath=/home/zhouyuxuan/data/WUH1012/IE.txt" +\
        " --resultpath=results/result_whu_viog.txt" +\
        " --calib=calib/1012.txt" +\
        " --stride=2" +\
        " --max_factors=48" +\
        " --active_window=12" +\
        " --frontend_window=5" +\
        " --frontend_radius=2" +\
        " --frontend_nms=1" +\
        " --inac_range=3" +\
        " --visual_only=0" +\
        " --far_threshold=-1" +\
        " --translation_threshold=0.25" +\
        " --mask_threshold=0.0" +\
        " --skip_edge=[]" +\
        " --save_pkl" +\
        " --use_gnss" +\
        " --gnsspath=/home/zhouyuxuan/data/data_20221012103154/SEPT-PVT.flt" +\
        " --pklpath=results/whu.pkl" +\
        " --show_plot",
 shell=True)
p.wait()


================================================
FILE: calib/0412.txt
================================================
889.32868436 889.32868436 515.73648834 202.43873596

================================================
FILE: calib/0412new.txt
================================================
885.839465 882.512623 505.509972 389.860117 -0.125551 0.065179 -0.000074 -0.000698


================================================
FILE: calib/1012.txt
================================================
890.21388839 889.56330572 512.88196119 381.38486858 -0.13095809 0.06640391 -0.00094794 0.0003389


================================================
FILE: calib/barn.txt
================================================
1161.545689 1161.545689 960.000000 540.000000 -0.025158 0.0 0.0 0.0

================================================
FILE: calib/carla.txt
================================================
886.8100 886.8100 512 256

================================================
FILE: calib/eth.txt
================================================
726.21081542969 726.21081542969 359.2048034668 202.47247314453

================================================
FILE: calib/euroc.txt
================================================
458.654 457.296 367.215 248.375 -0.28340811 0.07395907 0.00019359 1.76187114e-05

================================================
FILE: calib/handheld.txt
================================================
531.0895358407821 530.9183032386885 511.3708876141611 399.1276554093305 -0.3367182787437319 0.10679061024072911 0.0003055063102509499 0.0009756613499403765

================================================
FILE: calib/kitti_360.txt
================================================
788.629315 786.382230 687.158398 317.752196 -0.344441 0.141678 0.000414 -0.000222 -0.029608

================================================
FILE: calib/subt.txt
================================================
758.3153257832925 676.6492212772476 318.27111164892506 239.79816832491474 1.583106303248484 -0.059098218173967695 0.1793477408661115 0.0016819528105368057 -0.0005887999624264534

================================================
FILE: calib/tartan.txt
================================================
320.0 320.0 320.0 240.0

================================================
FILE: calib/tum3.txt
================================================
535.4 539.2 320.1 247.6

================================================
FILE: calib/tumvi.txt
================================================
190.97847715128717 190.9733070521226 254.93170605935475 256.8974428996504 0.0034823894022493434 0.0007150348452162257 -0.0020532361418706202 0.00020293673591811182

================================================
FILE: dataset/euroc_to_hdf5.py
================================================
from tqdm import tqdm
import numpy as np
import torch
import cv2
import os
import argparse

import h5py
import pickle

def show_image(image):
    image = image.permute(1, 2, 0).cpu().numpy()
    cv2.imshow('image', image / 255.0)
    cv2.waitKey(1)

def image_stream(imagedir, imagestamp, h5path, calib, stride):
    """ image generator """

    calib = np.loadtxt(calib, delimiter=" ")
    fx, fy, cx, cy = calib[:4]

    K = np.eye(3)
    K[0,0] = fx
    K[0,2] = cx
    K[1,1] = fy
    K[1,2] = cy

    Kn = np.eye(3)
    Kn[0,0] = fx 
    Kn[0,2] = cx 
    Kn[1,1] = fy 
    Kn[1,2] = cy

    image_list = sorted(os.listdir(imagedir))[::stride]
    image_stamps = np.loadtxt(imagestamp,str,delimiter=',')
    image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0]))
    h5_f = h5py.File(h5path,'w')
    for t, imfile in enumerate(image_list):
        image = cv2.imread(os.path.join(imagedir, imfile))

        if len(calib) > 4:
            m1, m2 = cv2.initUndistortRectifyMap(K,calib[4:],np.eye(3),Kn,(image.shape[1],image.shape[0]),cv2.CV_32FC1)
            image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

        tt = float(image_dict[imfile]) /1e9

        h0, w0, _ = image.shape
        h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0)))
        w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0)))

        image = cv2.resize(image, (w1, h1))
        image = image[:h1-h1%8, :w1-w1%8]
        image = torch.as_tensor(image).permute(2, 0, 1)

        intrinsics = torch.as_tensor([fx, fy, cx, cy ])
        intrinsics[0::2] *= (w1 / w0)
        intrinsics[1::2] *= (h1 / h0)

        h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8'))

        yield tt, image[None], intrinsics
    h5_f.close()

if __name__ == '__main__':

    print(torch.cuda.device_count())
    print(torch.cuda.is_available())
    print(torch.cuda.current_device())

    parser = argparse.ArgumentParser()
    parser.add_argument("--imagedir", type=str, help="path to image directory")
    parser.add_argument("--imagestamp", type=str, help="")
    parser.add_argument("--h5path", type=str, help="")
    parser.add_argument("--calib", type=str, help="path to calibration file")
    parser.add_argument("--stride", default=4, type=int, help="frame stride")
    parser.add_argument("--show_plot", action="store_true", help="")

    args = parser.parse_args()

    for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\
                                                     args.h5path, args.calib, args.stride)):
        if args.show_plot:
            show_image(image[0])


================================================
FILE: dataset/kitti360_to_hdf5.py
================================================
from tqdm import tqdm
import numpy as np
import torch
import cv2
import os
import argparse

import h5py
import pickle

def show_image(image):
    image = image.permute(1, 2, 0).cpu().numpy()
    cv2.imshow('image', image / 255.0)
    cv2.waitKey(1)

def image_stream(imagedir, imagestamp, h5path, calib, stride):
    """ image generator """

    calib = np.loadtxt(calib, delimiter=" ")
    fx, fy, cx, cy = calib[:4]

    K = np.eye(3)
    K[0,0] = fx
    K[0,2] = cx
    K[1,1] = fy
    K[1,2] = cy

    Kn = np.eye(3)
    Kn[0,0] = fx 
    Kn[0,2] = cx 
    Kn[1,1] = fy 
    Kn[1,2] = cy

    image_list = sorted(os.listdir(imagedir))[::stride]
    image_stamps = np.loadtxt(imagestamp,str)
    image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0]))
    h5_f = h5py.File(h5path,'w')
    for t, imfile in enumerate(image_list):
        image = cv2.imread(os.path.join(imagedir, imfile))

        if len(calib) > 4:
            image = cv2.undistort(image, K, calib[4:])
        tt = float(image_dict[imfile])

        h0, w0, _ = image.shape
        h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0)))
        w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0)))

        image = cv2.resize(image, (w1, h1))
        image = image[:h1-h1%8, :w1-w1%8]
        image = torch.as_tensor(image).permute(2, 0, 1)

        intrinsics = torch.as_tensor([fx, fy, cx, cy])
        intrinsics[0::2] *= (w1 / w0)
        intrinsics[1::2] *= (h1 / h0)

        h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8'))

        yield tt, image[None], intrinsics
    h5_f.close()

if __name__ == '__main__':

    print(torch.cuda.device_count())
    print(torch.cuda.is_available())
    print(torch.cuda.current_device())

    parser = argparse.ArgumentParser()
    parser.add_argument("--imagedir", type=str, help="path to image directory")
    parser.add_argument("--imagestamp", type=str, help="")
    parser.add_argument("--h5path", type=str, help="")
    parser.add_argument("--calib", type=str, help="path to calibration file")
    parser.add_argument("--stride", default=2, type=int, help="frame stride")
    parser.add_argument("--show_plot", action="store_true", help="")

    args = parser.parse_args()

    for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\
                                                     args.h5path, args.calib, args.stride)):
        if args.show_plot:
            show_image(image[0])

================================================
FILE: dataset/tumvi_to_hdf5.py
================================================
from tqdm import tqdm
import numpy as np
import torch
import cv2
import os
import argparse

import h5py
import pickle

def show_image(image):
    image = image.permute(1, 2, 0).cpu().numpy()
    cv2.imshow('image', image / 255.0)
    cv2.waitKey(1)

def image_stream(imagedir, imagestamp, h5path, calib, stride):
    """ image generator """

    calib = np.loadtxt(calib, delimiter=" ")
    fx, fy, cx, cy = calib[:4]

    K = np.eye(3)
    K[0,0] = fx
    K[0,2] = cx
    K[1,1] = fy
    K[1,2] = cy

    Kn = np.eye(3)
    Kn[0,0] = fx 
    Kn[0,2] = cx 
    Kn[1,1] = fy 
    Kn[1,2] = cy

    image_list = sorted(os.listdir(imagedir))[::stride]
    image_stamps = np.loadtxt(imagestamp,str,delimiter=',')
    image_dict = dict(zip(image_stamps[:,1],image_stamps[:,0]))
    h5_f = h5py.File(h5path,'w')
    for t, imfile in enumerate(image_list):
        image = cv2.imread(os.path.join(imagedir, imfile))

        if len(calib) > 4:
            m1, m2 = cv2.fisheye.initUndistortRectifyMap(K,calib[4:],np.eye(3),Kn,(512,512),cv2.CV_32FC1)
            image = cv2.remap(image, m1, m2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)

        tt = float(image_dict[imfile]) /1e9

        h0, w0, _ = image.shape
        h1 = int(h0 * np.sqrt((384 * 512) / (h0 * w0)))
        w1 = int(w0 * np.sqrt((384 * 512) / (h0 * w0)))

        image = cv2.resize(image, (w1, h1))
        image = image[:h1-h1%8, :w1-w1%8]
        image = torch.as_tensor(image).permute(2, 0, 1)

        intrinsics = torch.as_tensor([fx, fy, cx, cy ])
        intrinsics[0::2] *= (w1 / w0)
        intrinsics[1::2] *= (h1 / h0)

        h5_f.create_dataset('%.10f'%tt,data = np.fromstring(pickle.dumps((tt, image[None], intrinsics)),dtype='uint8'))

        yield tt, image[None], intrinsics
    h5_f.close()

if __name__ == '__main__':

    print(torch.cuda.device_count())
    print(torch.cuda.is_available())
    print(torch.cuda.current_device())

    parser = argparse.ArgumentParser()
    parser.add_argument("--imagedir", type=str, help="path to image directory")
    parser.add_argument("--imagestamp", type=str, help="")
    parser.add_argument("--h5path", type=str, help="")
    parser.add_argument("--calib", type=str, help="path to calibration file")
    parser.add_argument("--stride", default=4, type=int, help="frame stride")
    parser.add_argument("--show_plot", action="store_true", help="")

    args = parser.parse_args()

    for (t, image, intrinsics) in tqdm(image_stream(args.imagedir, args.imagestamp,\
                                                     args.h5path, args.calib, args.stride)):
        if args.show_plot:
            show_image(image[0])


================================================
FILE: dbaf/covisible_graph.py
================================================
import torch
import lietorch
import numpy as np

import matplotlib.pyplot as plt
from lietorch import SE3
from modules.corr import CorrBlock, AltCorrBlock
import geom.projective_ops as pops
import matplotlib.pyplot as plt
import cv2
from depth_video import DepthVideo
import matplotlib.cm as cm
import matplotlib

class CovisibleGraph:
    def __init__(self, video: DepthVideo, update_op, device="cuda:0", corr_impl="volume", args = None):
        self.video = video
        self.update_op = update_op
        self.device = device
        self.max_factors = args.max_factors
        self.corr_impl = corr_impl
        self.upsample = args.upsample

        # operator at 1/8 resolution
        self.ht = ht = video.ht // 8
        self.wd = wd = video.wd // 8

        self.coords0 = pops.coords_grid(ht, wd, device=device)
        self.ii = torch.as_tensor([], dtype=torch.long, device=device)
        self.jj = torch.as_tensor([], dtype=torch.long, device=device)
        self.age = torch.as_tensor([], dtype=torch.long, device=device)

        self.corr, self.net, self.inp = None, None, None
        self.damping = 1e-6 * torch.ones_like(self.video.disps)

        self.target = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)
        self.weight = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)

        # inactive factors
        self.ii_inac = torch.as_tensor([], dtype=torch.long, device=device)
        self.jj_inac = torch.as_tensor([], dtype=torch.long, device=device)
        self.ii_bad = torch.as_tensor([], dtype=torch.long, device=device)
        self.jj_bad = torch.as_tensor([], dtype=torch.long, device=device)

        self.target_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)
        self.weight_inac = torch.zeros([1, 0, ht, wd, 2], device=device, dtype=torch.float)

        self.far_threshold = args.far_threshold
        self.inac_range = args.inac_range
        self.mask_threshold = args.mask_threshold
        self.img_count = 0

        self.skip_edge = args.skip_edge
        self.frontend_window = args.frontend_window
        
        # simple online visualization
        self.show_covisible_graph = False
        self.show_oldest_disparity = False
        self.show_flow_and_weight = False

    def __filter_repeated_edges(self, ii, jj):
        """ remove duplicate edges """

        keep = torch.zeros(ii.shape[0], dtype=torch.bool, device=ii.device)
        eset = set(
            [(i.item(), j.item()) for i, j in zip(self.ii, self.jj)] +
            [(i.item(), j.item()) for i, j in zip(self.ii_inac, self.jj_inac)])

        for k, (i, j) in enumerate(zip(ii, jj)):
            keep[k] = (i.item(), j.item()) not in eset

        return ii[keep], jj[keep]

    def print_edges(self):
        ii = self.ii.cpu().numpy()
        jj = self.jj.cpu().numpy()

        ix = np.argsort(ii)
        ii = ii[ix]
        jj = jj[ix]

        w = torch.mean(self.weight, dim=[0,2,3,4]).cpu().numpy()
        w = w[ix]
        for e in zip(ii, jj, w):
            print(e)
        print()

    def filter_edges(self):
        """ remove bad edges """
        conf = torch.mean(self.weight, dim=[0,2,3,4])
        mask = (torch.abs(self.ii-self.jj) > 2) & (conf < 0.001)

        self.ii_bad = torch.cat([self.ii_bad, self.ii[mask]])
        self.jj_bad = torch.cat([self.jj_bad, self.jj[mask]])
        self.rm_factors(mask, store=False)

    def clear_edges(self):
        self.rm_factors(self.ii >= 0)
        self.net = None
        self.inp = None

    @torch.cuda.amp.autocast(enabled=True)
    def add_factors(self, ii, jj, remove=False):
        """ add edges to factor graph """
        if not isinstance(ii, torch.Tensor):
            ii = torch.as_tensor(ii, dtype=torch.long, device=self.device)

        if not isinstance(jj, torch.Tensor):
            jj = torch.as_tensor(jj, dtype=torch.long, device=self.device)

        # remove duplicate edges
        ii, jj = self.__filter_repeated_edges(ii, jj)

        if ii.shape[0] == 0:
            return

        # place limit on number of factors
        if self.max_factors > 0 and self.ii.shape[0] + ii.shape[0] > self.max_factors \
                and self.corr is not None and remove:
            
            ix = torch.arange(len(self.age))[torch.argsort(self.age).cpu()]
            self.rm_factors(ix >= self.max_factors - ii.shape[0], store=True)

        net = self.video.nets[ii].to(self.device).unsqueeze(0)

        # correlation volume for new edges
        if self.corr_impl == "volume":
            c = (ii == jj).long()
            fmap1 = self.video.fmaps[ii,0].to(self.device).unsqueeze(0)
            fmap2 = self.video.fmaps[jj,c].to(self.device).unsqueeze(0)
            corr = CorrBlock(fmap1, fmap2)
            self.corr = corr if self.corr is None else self.corr.cat(corr)

            inp = self.video.inps[ii].to(self.device).unsqueeze(0)
            self.inp = inp if self.inp is None else torch.cat([self.inp, inp], 1)

        with torch.cuda.amp.autocast(enabled=False):
            target, _ = self.video.reproject(ii, jj)
            weight = torch.zeros_like(target)

        self.ii = torch.cat([self.ii, ii], 0)
        self.jj = torch.cat([self.jj, jj], 0)
        self.age = torch.cat([self.age, torch.zeros_like(ii)], 0)

        # reprojection factors
        self.net = net if self.net is None else torch.cat([self.net, net], 1)

        self.target = torch.cat([self.target, target], 1)
        self.weight = torch.cat([self.weight, weight], 1)

    @torch.cuda.amp.autocast(enabled=True)
    def rm_factors(self, mask, store=False):
        """ drop edges from factor graph """

        # store estimated factors
        if store:
            self.ii_inac = torch.cat([self.ii_inac, self.ii[mask]], 0)
            self.jj_inac = torch.cat([self.jj_inac, self.jj[mask]], 0)
            self.target_inac = torch.cat([self.target_inac, self.target[:,mask]], 1)
            self.weight_inac = torch.cat([self.weight_inac, self.weight[:,mask]], 1)

        self.ii = self.ii[~mask]
        self.jj = self.jj[~mask]
        self.age = self.age[~mask]
        
        if self.corr_impl == "volume":
            self.corr = self.corr[~mask]

        if self.net is not None:
            self.net = self.net[:,~mask]

        if self.inp is not None:
            self.inp = self.inp[:,~mask]

        self.target = self.target[:,~mask]
        self.weight = self.weight[:,~mask]


    @torch.cuda.amp.autocast(enabled=True)
    def rm_keyframe(self, ix):
        """ drop edges from factor graph """


        with self.video.get_lock():
            self.video.images[ix] = self.video.images[ix+1]
            self.video.poses[ix] = self.video.poses[ix+1]
            self.video.disps[ix] = self.video.disps[ix+1]
            self.video.disps_sens[ix] = self.video.disps_sens[ix+1]
            self.video.intrinsics[ix] = self.video.intrinsics[ix+1]

            self.video.nets[ix] = self.video.nets[ix+1]
            self.video.inps[ix] = self.video.inps[ix+1]
            self.video.fmaps[ix] = self.video.fmaps[ix+1]

            self.video.tstamp[ix] = self.video.tstamp[ix+1] # BUG fix

        m = (self.ii_inac == ix) | (self.jj_inac == ix)
        self.ii_inac[self.ii_inac >= ix] -= 1
        self.jj_inac[self.jj_inac >= ix] -= 1

        if torch.any(m):
            self.ii_inac = self.ii_inac[~m]
            self.jj_inac = self.jj_inac[~m]
            self.target_inac = self.target_inac[:,~m]
            self.weight_inac = self.weight_inac[:,~m]

        m = (self.ii == ix) | (self.jj == ix)

        self.ii[self.ii >= ix] -= 1
        self.jj[self.jj >= ix] -= 1
        self.rm_factors(m, store=False)

    @torch.cuda.amp.autocast(enabled=True)
    def update(self, t0=None, t1=None, itrs=2, use_inactive=False, EP=1e-7, motion_only=False, marg = False):
        """ run update operator on factor graph """

        self.video.logger.info('update')

        with torch.cuda.amp.autocast(enabled=False):
            coords1, mask = self.video.reproject(self.ii, self.jj)
            motn = torch.cat([coords1 - self.coords0, self.target - coords1], dim=-1)
            motn = motn.permute(0,1,4,2,3).clamp(-64.0, 64.0) # 1,2,4,48,96

        corr = self.corr(coords1) 

        self.net, delta, weight, damping, upmask = \
            self.update_op(self.net, self.inp, corr, motn, self.ii, self.jj, self.upsample)
                    
        if t0 is None:
            t0 = max(1, self.ii.min().item()+1)
            
        self.video.logger.info('ba')

        with torch.cuda.amp.autocast(enabled=False):
            self.target = coords1 + delta.to(dtype=torch.float)
            self.weight = weight.to(dtype=torch.float)

            ht, wd = self.coords0.shape[0:2]
            if self.upsample: 
                self.damping[torch.unique(self.ii)] = damping

            if use_inactive:
                m = (self.ii_inac >= t0 - self.inac_range) & (self.jj_inac >= t0 - self.inac_range)
                ii = torch.cat([self.ii_inac[m], self.ii], 0)
                jj = torch.cat([self.jj_inac[m], self.jj], 0)
                target = torch.cat([self.target_inac[:,m], self.target], 1)
                weight = torch.cat([self.weight_inac[:,m], self.weight], 1)
            else:
                ii, jj, target, weight = self.ii, self.jj, self.target, self.weight

            # Some real-time visualization for debugging
            # 1) Disparity
            if self.show_oldest_disparity:
                disp_show_front = self.video.disps[self.ii[0]].cpu().numpy()
                disp_show_front = cv2.resize(disp_show_front,[disp_show_front.shape[1]*8,disp_show_front.shape[0]*8],interpolation =  cv2.INTER_NEAREST)
                disp_show_front= disp_show_front.astype(np.float32)
    
                normalizer = matplotlib.colors.Normalize(vmin=-0.2, vmax=1.0)
                mapper = cm.ScalarMappable(norm=normalizer,cmap='magma')
                colormapped_im = (mapper.to_rgba(disp_show_front)[:, :, :3] * 255).astype(np.uint8)
                colormapped_im = cv2.cvtColor(colormapped_im,cv2.COLOR_RGB2BGR)
                cv2.imshow('colormapped_im',colormapped_im)
                cv2.waitKey(1)

            # 2) Optical flow and weight
            if self.show_flow_and_weight:
                rgb = self.video.images[torch.max(self.ii)].cpu().numpy().transpose(1,2,0)
                new_flow_id = torch.where(torch.logical_and(self.ii==torch.max(self.ii),self.jj==torch.max(self.ii)-5))[0][0].item()
                weight_cpu = weight[0,new_flow_id].cpu().numpy().astype(np.float32)
                weight_cpu = np.linalg.norm(weight_cpu,axis=2)
                normalizer = matplotlib.colors.Normalize(vmin=-0.0, vmax=1.5)
                mapper = cm.ScalarMappable(norm=normalizer,cmap='jet')
                colormapped_im = (mapper.to_rgba(weight_cpu)[:, :, :3] * 255).astype(np.uint8)
                colormapped_im = cv2.cvtColor(colormapped_im,cv2.COLOR_RGB2BGR)
                colormapped_im = cv2.resize(colormapped_im,[rgb.shape[1],rgb.shape[0]])
                colormapped_im = cv2.addWeighted(rgb,0.5,colormapped_im,0.5,0)
                absflow = (self.target[0,new_flow_id] - self.coords0).cpu().numpy()
                for iii in range(0,absflow.shape[0],4):
                    for jjj in range(0,absflow.shape[1],4):
                        colormapped_im = cv2.line(colormapped_im, (jjj * 8,iii * 8),(int(round((jjj-absflow[iii,jjj,0])* 8)) ,int(round((iii-absflow[iii,jjj,1]) * 8))),(255,255,255),1,cv2.LINE_AA)

                cv2.imshow('weight_cpu',colormapped_im)
                self.img_count += 1

            # 3) Covisible graph
            if self.show_covisible_graph:
                i0 = min(ii)
                i1 = max(ii)
                ppp = SE3(self.video.poses[i0:(i1+1)]).inv().matrix()[:,0:3,3].cpu().numpy()
                # [:,:3].cpu().numpy()
                scale = max(max(ppp[:,0]) - min(ppp[:,0]),max(ppp[:,1]) - min(ppp[:,1]))
                ppp[:,0] -= np.mean(ppp[:,0])
                ppp[:,1] = -(ppp[:,1]- np.mean(ppp[:,1]))
                ppp *= max(round(1/scale * 200 / 50)*50,50)
                ppp += 500
                mmm = np.zeros([1000,1000],dtype=np.uint8)
                for iii in range(0,i1+1-i0):
                    mmm = cv2.circle(mmm,(int(round(ppp[iii,0])),int(round(ppp[iii,1]))),4,255,0)
                for iii in range(self.ii_inac[m].shape[0]):
                    iiii = self.ii_inac[m][iii]-i0
                    jjjj = self.jj_inac[m][iii]-i0
                    mmm = cv2.line(mmm,(int(round(ppp[iiii,0])),int(round(ppp[iiii,1]))),(int(round(ppp[jjjj,0])),int(round(ppp[jjjj,1]))),128,1)
                for iii in range(self.ii.shape[0]):
                    iiii = self.ii[iii]-i0
                    jjjj = self.jj[iii]-i0
                    mmm = cv2.line(mmm,(int(round(ppp[iiii,0])),int(round(ppp[iiii,1]))),(int(round(ppp[jjjj,0])),int(round(ppp[jjjj,1]))),255,1)
                cv2.imshow('window',mmm)

            ## Tricks for better performance
            # 1) downweight far points
            if self.far_threshold > 0 and self.video.imu_enabled:
                disp_mask = (self.video.disps < self.far_threshold)
                mask = disp_mask[ii, :, :]
                weight[:, mask] /= 1000.0
            
            # 2) downweight far points
            if self.mask_threshold > 0 and self.video.imu_enabled:
                pose0 = SE3(self.video.poses[ii])
                pose1 = SE3(self.video.poses[jj])
                pose01 = pose0*pose1.inv()
                mask = torch.norm(pose01.translation()[:,:3],dim=1) < self.mask_threshold
                weight[:,mask,:,:,:] /= 1000.0
            
            # 3) downweight edges related to the newest frame
            downweight_newframe = True
            if downweight_newframe:
                weight[:,ii==max(ii)] /= 10.0
                weight[:,jj==max(jj)] /= 4.0

            damping = .2 * self.damping[torch.unique(ii)].contiguous() + EP

            target = target.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()
            weight = weight.view(-1, ht, wd, 2).permute(0,3,1,2).contiguous()

            # Dense bundle adjustment
            self.video.ba(target, weight, damping, ii, jj, t0, t1, 
                itrs=itrs, lm=1e-4, ep=0.1, motion_only=motion_only)
        
            if self.upsample:
                self.video.upsample(torch.unique(self.ii), upmask)

        self.age += 1

    def add_neighborhood_factors(self, t0, t1, r=3):
        """ add edges between neighboring frames within radius r """

        ii, jj = torch.meshgrid(torch.arange(t0,t1), torch.arange(t0,t1))
        ii = ii.reshape(-1).to(dtype=torch.long, device=self.device)
        jj = jj.reshape(-1).to(dtype=torch.long, device=self.device)

        c = 1 if self.video.stereo else 0

        keep = ((ii - jj).abs() > c) & ((ii - jj).abs() <= r)
        self.add_factors(ii[keep], jj[keep])

    
    def add_proximity_factors(self, t0=0, t1=0, rad=2, nms=2, beta=0.25, thresh=16.0, remove=False):
        """ add edges to the factor graph based on distance """

        t = self.video.counter.value
        ix = torch.arange(t0, t)
        jx = torch.arange(t1, t)

        ii, jj = torch.meshgrid(ix, jx)
        ii = ii.reshape(-1)
        jj = jj.reshape(-1)
        
        cc = ii.shape[0]

        # Opportunistic "skip" edges in the graph
        if self.skip_edge:
            if torch.max(ii) - torch.min(ii) == self.frontend_window - 1:
                jj_add = torch.min(ii) + torch.tensor(self.skip_edge)
                jj_add = jj_add[jj_add>0]
                ii_add = torch.zeros_like(jj_add) + torch.max(ii)
                jj = torch.cat([jj,jj_add])
                ii = torch.cat([ii,ii_add])

        d = self.video.distance(ii, jj, beta=beta)
        d[ii - rad < jj] = np.inf
        d[d > 100] = np.inf

        ii1 = torch.cat([self.ii, self.ii_bad, self.ii_inac], 0)
        jj1 = torch.cat([self.jj, self.jj_bad, self.jj_inac], 0)
        for i, j in zip(ii1.cpu().numpy(), jj1.cpu().numpy()):
            for di in range(-nms, nms+1):
                for dj in range(-nms, nms+1):
                    if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0):
                        i1 = i + di
                        j1 = j + dj

                        if (t0 <= i1 < t) and (t1 <= j1 < t):
                            d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf

        es = []
        for i in range(t0, t):
            if self.video.stereo:
                es.append((i, i))
                d[(i-t0)*(t-t1) + (i-t1)] = np.inf

            for j in range(max(i-rad-1,0), i):
                es.append((i,j))
                es.append((j,i))
                if (i-t0)*(t-t1) + (j-t1) >=0:
                    d[(i-t0)*(t-t1) + (j-t1)] = np.inf

        ix = torch.argsort(d)
        for k in ix:
            if k >= cc:
                continue

            if d[k].item() > thresh:
                continue

            if len(es) > self.max_factors:
                break

            i = ii[k]
            j = jj[k]
            
            # bidirectional
            es.append((i, j))
            es.append((j, i))

            for di in range(-nms, nms+1):
                for dj in range(-nms, nms+1):
                    if abs(di) + abs(dj) <= max(min(abs(i-j)-2, nms), 0):
                        i1 = i + di
                        j1 = j + dj

                        if (t0 <= i1 < t) and (t1 <= j1 < t):
                            d[(i1-t0)*(t-t1) + (j1-t1)] = np.inf
        
        if ii.shape[0] > cc:
            ix = torch.argsort(d[cc:ii.shape[0]])
            if d[cc + ix[0]] < thresh and  d[cc + ix[0]]  > 0:
                es.append((ii[cc+ix[0]],jj[cc+ix[0]]))
                es.append((jj[cc+ix[0]],ii[cc+ix[0]]))

        ii, jj = torch.as_tensor(es, device=self.device).unbind(dim=-1)
        self.add_factors(ii, jj, remove)


================================================
FILE: dbaf/data_readers/__init__.py
================================================



================================================
FILE: dbaf/data_readers/augmentation.py
================================================
import torch
import torchvision.transforms as transforms
import numpy as np
import torch.nn.functional as F


class RGBDAugmentor:
    """ perform augmentation on RGB-D video """

    def __init__(self, crop_size):
        self.crop_size = crop_size
        self.augcolor = transforms.Compose([
            transforms.ToPILImage(),
            transforms.ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.4/3.14),
            transforms.RandomGrayscale(p=0.1),
            transforms.ToTensor()])

        self.max_scale = 0.25

    def spatial_transform(self, images, depths, poses, intrinsics):
        """ cropping and resizing """
        ht, wd = images.shape[2:]

        max_scale = self.max_scale
        min_scale = np.log2(np.maximum(
            (self.crop_size[0] + 1) / float(ht),
            (self.crop_size[1] + 1) / float(wd)))

        scale = 2 ** np.random.uniform(min_scale, max_scale)
        intrinsics = scale * intrinsics
        depths = depths.unsqueeze(dim=1)

        images = F.interpolate(images, scale_factor=scale, mode='bilinear', 
            align_corners=False, recompute_scale_factor=True)
        
        depths = F.interpolate(depths, scale_factor=scale, recompute_scale_factor=True)

        # always perform center crop (TODO: try non-center crops)
        y0 = (images.shape[2] - self.crop_size[0]) // 2
        x0 = (images.shape[3] - self.crop_size[1]) // 2

        intrinsics = intrinsics - torch.tensor([0.0, 0.0, x0, y0])
        images = images[:, :, y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]
        depths = depths[:, :, y0:y0+self.crop_size[0], x0:x0+self.crop_size[1]]

        depths = depths.squeeze(dim=1)
        return images, poses, depths, intrinsics

    def color_transform(self, images):
        """ color jittering """
        num, ch, ht, wd = images.shape
        images = images.permute(1, 2, 3, 0).reshape(ch, ht, wd*num)
        images = 255 * self.augcolor(images[[2,1,0]] / 255.0)
        return images[[2,1,0]].reshape(ch, ht, wd, num).permute(3,0,1,2).contiguous()

    def __call__(self, images, poses, depths, intrinsics):
        images = self.color_transform(images)
        return self.spatial_transform(images, depths, poses, intrinsics)


================================================
FILE: dbaf/data_readers/base.py
================================================

import numpy as np
import torch
import torch.utils.data as data
import torch.nn.functional as F

import csv
import os
import cv2
import math
import random
import json
import pickle
import os.path as osp

from .augmentation import RGBDAugmentor
from .rgbd_utils import *

class RGBDDataset(data.Dataset):
    def __init__(self, name, datapath, n_frames=4, crop_size=[384,512], fmin=8.0, fmax=75.0, do_aug=True):
        """ Base class for RGBD dataset """
        self.aug = None
        self.root = datapath
        self.name = name

        self.n_frames = n_frames
        self.fmin = fmin # exclude very easy examples
        self.fmax = fmax # exclude very hard examples
        
        if do_aug:
            self.aug = RGBDAugmentor(crop_size=crop_size)

        # building dataset is expensive, cache so only needs to be performed once
        cur_path = osp.dirname(osp.abspath(__file__))
        if not os.path.isdir(osp.join(cur_path, 'cache')):
            os.mkdir(osp.join(cur_path, 'cache'))
        
        cache_path = osp.join(cur_path, 'cache', '{}.pickle'.format(self.name))

        if osp.isfile(cache_path):
            scene_info = pickle.load(open(cache_path, 'rb'))[0]
        else:
            scene_info = self._build_dataset()
            with open(cache_path, 'wb') as cachefile:
                pickle.dump((scene_info,), cachefile)

        self.scene_info = scene_info
        self._build_dataset_index()
                
    def _build_dataset_index(self):
        self.dataset_index = []
        for scene in self.scene_info:
            if not self.__class__.is_test_scene(scene):
                graph = self.scene_info[scene]['graph']
                for i in graph:
                    if len(graph[i][0]) > self.n_frames:
                        self.dataset_index.append((scene, i))
            else:
                print("Reserving {} for validation".format(scene))

    @staticmethod
    def image_read(image_file):
        return cv2.imread(image_file)

    @staticmethod
    def depth_read(depth_file):
        return np.load(depth_file)

    def build_frame_graph(self, poses, depths, intrinsics, f=16, max_flow=256):
        """ compute optical flow distance between all pairs of frames """
        def read_disp(fn):
            depth = self.__class__.depth_read(fn)[f//2::f, f//2::f]
            depth[depth < 0.01] = np.mean(depth)
            return 1.0 / depth

        poses = np.array(poses)
        intrinsics = np.array(intrinsics) / f
        
        disps = np.stack(list(map(read_disp, depths)), 0)
        d = f * compute_distance_matrix_flow(poses, disps, intrinsics)

        # uncomment for nice visualization
        # import matplotlib.pyplot as plt
        # plt.imshow(d)
        # plt.show()

        graph = {}
        for i in range(d.shape[0]):
            j, = np.where(d[i] < max_flow)
            graph[i] = (j, d[i,j])

        return graph

    def __getitem__(self, index):
        """ return training video """

        index = index % len(self.dataset_index)
        scene_id, ix = self.dataset_index[index]

        frame_graph = self.scene_info[scene_id]['graph']
        images_list = self.scene_info[scene_id]['images']
        depths_list = self.scene_info[scene_id]['depths']
        poses_list = self.scene_info[scene_id]['poses']
        intrinsics_list = self.scene_info[scene_id]['intrinsics']

        inds = [ ix ]
        while len(inds) < self.n_frames:
            # get other frames within flow threshold
            k = (frame_graph[ix][1] > self.fmin) & (frame_graph[ix][1] < self.fmax)
            frames = frame_graph[ix][0][k]

            # prefer frames forward in time
            if np.count_nonzero(frames[frames > ix]):
                ix = np.random.choice(frames[frames > ix])
            
            elif np.count_nonzero(frames):
                ix = np.random.choice(frames)

            inds += [ ix ]

        images, depths, poses, intrinsics = [], [], [], []
        for i in inds:
            images.append(self.__class__.image_read(images_list[i]))
            depths.append(self.__class__.depth_read(depths_list[i]))
            poses.append(poses_list[i])
            intrinsics.append(intrinsics_list[i])

        images = np.stack(images).astype(np.float32)
        depths = np.stack(depths).astype(np.float32)
        poses = np.stack(poses).astype(np.float32)
        intrinsics = np.stack(intrinsics).astype(np.float32)

        images = torch.from_numpy(images).float()
        images = images.permute(0, 3, 1, 2)

        disps = torch.from_numpy(1.0 / depths)
        poses = torch.from_numpy(poses)
        intrinsics = torch.from_numpy(intrinsics)

        if self.aug is not None:
            images, poses, disps, intrinsics = \
                self.aug(images, poses, disps, intrinsics)

        # scale scene
        if len(disps[disps>0.01]) > 0:
            s = disps[disps>0.01].mean()
            disps = disps / s
            poses[...,:3] *= s

        return images, poses, disps, intrinsics 

    def __len__(self):
        return len(self.dataset_index)

    def __imul__(self, x):
        self.dataset_index *= x
        return self


================================================
FILE: dbaf/data_readers/factory.py
================================================

import pickle
import os
import os.path as osp

# RGBD-Dataset
from .tartan import TartanAir

from .stream import ImageStream
from .stream import StereoStream
from .stream import RGBDStream

# streaming datasets for inference
from .tartan import TartanAirStream
from .tartan import TartanAirTestStream

def dataset_factory(dataset_list, **kwargs):
    """ create a combined dataset """

    from torch.utils.data import ConcatDataset

    dataset_map = { 'tartan': (TartanAir, ) }
    db_list = []
    for key in dataset_list:
        # cache datasets for faster future loading
        db = dataset_map[key][0](**kwargs)

        print("Dataset {} has {} images".format(key, len(db)))
        db_list.append(db)

    return ConcatDataset(db_list)
            

def create_datastream(dataset_path, **kwargs):
    """ create data_loader to stream images 1 by 1 """

    from torch.utils.data import DataLoader

    if osp.isfile(osp.join(dataset_path, 'calibration.txt')):
        db = ETH3DStream(dataset_path, **kwargs)

    elif osp.isdir(osp.join(dataset_path, 'image_left')):
        db = TartanAirStream(dataset_path, **kwargs)

    elif osp.isfile(osp.join(dataset_path, 'rgb.txt')):
        db = TUMStream(dataset_path, **kwargs)

    elif osp.isdir(osp.join(dataset_path, 'mav0')):
        db = EurocStream(dataset_path, **kwargs)

    elif osp.isfile(osp.join(dataset_path, 'calib.txt')):
        db = KITTIStream(dataset_path, **kwargs)

    else:
        # db = TartanAirStream(dataset_path, **kwargs)
        db = TartanAirTestStream(dataset_path, **kwargs)
    
    stream = DataLoader(db, shuffle=False, batch_size=1, num_workers=4)
    return stream


def create_imagestream(dataset_path, **kwargs):
    """ create data_loader to stream images 1 by 1 """
    from torch.utils.data import DataLoader

    db = ImageStream(dataset_path, **kwargs)
    return DataLoader(db, shuffle=False, batch_size=1, num_workers=4)

def create_stereostream(dataset_path, **kwargs):
    """ create data_loader to stream images 1 by 1 """
    from torch.utils.data import DataLoader

    db = StereoStream(dataset_path, **kwargs)
    return DataLoader(db, shuffle=False, batch_size=1, num_workers=4)

def create_rgbdstream(dataset_path, **kwargs):
    """ create data_loader to stream images 1 by 1 """
    from torch.utils.data import DataLoader

    db = RGBDStream(dataset_path, **kwargs)
    return DataLoader(db, shuffle=False, batch_size=1, num_workers=4)



================================================
FILE: dbaf/data_readers/rgbd_utils.py
================================================
import numpy as np
import os.path as osp

import torch
from lietorch import SE3

import geom.projective_ops as pops
from scipy.spatial.transform import Rotation


def parse_list(filepath, skiprows=0):
    """ read list data """
    data = np.loadtxt(filepath, delimiter=' ', dtype=np.unicode_, skiprows=skiprows)
    return data

def associate_frames(tstamp_image, tstamp_depth, tstamp_pose, max_dt=1.0):
    """ pair images, depths, and poses """
    associations = []
    for i, t in enumerate(tstamp_image):
        if tstamp_pose is None:
            j = np.argmin(np.abs(tstamp_depth - t))
            if (np.abs(tstamp_depth[j] - t) < max_dt):
                associations.append((i, j))

        else:
            j = np.argmin(np.abs(tstamp_depth - t))
            k = np.argmin(np.abs(tstamp_pose - t))
        
            if (np.abs(tstamp_depth[j] - t) < max_dt) and \
                    (np.abs(tstamp_pose[k] - t) < max_dt):
                associations.append((i, j, k))
            
    return associations

def loadtum(datapath, frame_rate=-1):
    """ read video data in tum-rgbd format """
    if osp.isfile(osp.join(datapath, 'groundtruth.txt')):
        pose_list = osp.join(datapath, 'groundtruth.txt')
    
    elif osp.isfile(osp.join(datapath, 'pose.txt')):
        pose_list = osp.join(datapath, 'pose.txt')

    else:
        return None, None, None, None

    image_list = osp.join(datapath, 'rgb.txt')
    depth_list = osp.join(datapath, 'depth.txt')

    calib_path = osp.join(datapath, 'calibration.txt')
    intrinsic = None
    if osp.isfile(calib_path):
        intrinsic = np.loadtxt(calib_path, delimiter=' ')
        intrinsic = intrinsic.astype(np.float64)

    image_data = parse_list(image_list)
    depth_data = parse_list(depth_list)
    pose_data = parse_list(pose_list, skiprows=1)
    pose_vecs = pose_data[:,1:].astype(np.float64)

    tstamp_image = image_data[:,0].astype(np.float64)
    tstamp_depth = depth_data[:,0].astype(np.float64)
    tstamp_pose = pose_data[:,0].astype(np.float64)
    associations = associate_frames(tstamp_image, tstamp_depth, tstamp_pose)

    # print(len(tstamp_image))
    # print(len(associations))

    indicies = range(len(associations))[::5]

    # indicies = [ 0 ]
    # for i in range(1, len(associations)):
    #     t0 = tstamp_image[associations[indicies[-1]][0]]
    #     t1 = tstamp_image[associations[i][0]]
    #     if t1 - t0 > 1.0 / frame_rate:
    #         indicies += [ i ]

    images, poses, depths, intrinsics, tstamps = [], [], [], [], []
    for ix in indicies:
        (i, j, k) = associations[ix]
        images += [ osp.join(datapath, image_data[i,1]) ]
        depths += [ osp.join(datapath, depth_data[j,1]) ]
        poses += [ pose_vecs[k] ]
        tstamps += [ tstamp_image[i] ]
        
        if intrinsic is not None:
            intrinsics += [ intrinsic ]

    return images, depths, poses, intrinsics, tstamps


def all_pairs_distance_matrix(poses, beta=2.5):
    """ compute distance matrix between all pairs of poses """
    poses = np.array(poses, dtype=np.float32)
    poses[:,:3] *= beta # scale to balence rot + trans
    poses = SE3(torch.from_numpy(poses))

    r = (poses[:,None].inv() * poses[None,:]).log()
    return r.norm(dim=-1).cpu().numpy()

def pose_matrix_to_quaternion(pose):
    """ convert 4x4 pose matrix to (t, q) """
    q = Rotation.from_matrix(pose[:3, :3]).as_quat()
    return np.concatenate([pose[:3, 3], q], axis=0)

def compute_distance_matrix_flow(poses, disps, intrinsics):
    """ compute flow magnitude between all pairs of frames """
    if not isinstance(poses, SE3):
        poses = torch.from_numpy(poses).float().cuda()[None]
        poses = SE3(poses).inv()

        disps = torch.from_numpy(disps).float().cuda()[None]
        intrinsics = torch.from_numpy(intrinsics).float().cuda()[None]

    N = poses.shape[1]
    
    ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N))
    ii = ii.reshape(-1).cuda()
    jj = jj.reshape(-1).cuda()

    MAX_FLOW = 100.0
    matrix = np.zeros((N, N), dtype=np.float32)

    s = 2048
    for i in range(0, ii.shape[0], s):
        flow1, val1 = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s])
        flow2, val2 = pops.induced_flow(poses, disps, intrinsics, jj[i:i+s], ii[i:i+s])
        
        flow = torch.stack([flow1, flow2], dim=2)
        val = torch.stack([val1, val2], dim=2)
        
        mag = flow.norm(dim=-1).clamp(max=MAX_FLOW)
        mag = mag.view(mag.shape[1], -1)
        val = val.view(val.shape[1], -1)

        mag = (mag * val).mean(-1) / val.mean(-1)
        mag[val.mean(-1) < 0.7] = np.inf

        i1 = ii[i:i+s].cpu().numpy()
        j1 = jj[i:i+s].cpu().numpy()
        matrix[i1, j1] = mag.cpu().numpy()

    return matrix


def compute_distance_matrix_flow2(poses, disps, intrinsics, beta=0.4):
    """ compute flow magnitude between all pairs of frames """
    # if not isinstance(poses, SE3):
    #     poses = torch.from_numpy(poses).float().cuda()[None]
    #     poses = SE3(poses).inv()

    #     disps = torch.from_numpy(disps).float().cuda()[None]
    #     intrinsics = torch.from_numpy(intrinsics).float().cuda()[None]

    N = poses.shape[1]
    
    ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N))
    ii = ii.reshape(-1)
    jj = jj.reshape(-1)

    MAX_FLOW = 128.0
    matrix = np.zeros((N, N), dtype=np.float32)

    s = 2048
    for i in range(0, ii.shape[0], s):
        flow1a, val1a = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s], tonly=True)
        flow1b, val1b = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s])
        flow2a, val2a = pops.induced_flow(poses, disps, intrinsics, jj[i:i+s], ii[i:i+s], tonly=True)
        flow2b, val2b = pops.induced_flow(poses, disps, intrinsics, ii[i:i+s], jj[i:i+s])

        flow1 = flow1a + beta * flow1b
        val1 = val1a * val2b

        flow2 = flow2a + beta * flow2b
        val2 = val2a * val2b
        
        flow = torch.stack([flow1, flow2], dim=2)
        val = torch.stack([val1, val2], dim=2)
        
        mag = flow.norm(dim=-1).clamp(max=MAX_FLOW)
        mag = mag.view(mag.shape[1], -1)
        val = val.view(val.shape[1], -1)

        mag = (mag * val).mean(-1) / val.mean(-1)
        mag[val.mean(-1) < 0.8] = np.inf

        i1 = ii[i:i+s].cpu().numpy()
        j1 = jj[i:i+s].cpu().numpy()
        matrix[i1, j1] = mag.cpu().numpy()

    return matrix


================================================
FILE: dbaf/data_readers/stream.py
================================================

import numpy as np
import torch
import torch.utils.data as data
import torch.nn.functional as F

import csv
import os
import cv2
import math
import random
import json
import pickle
import os.path as osp

from .rgbd_utils import *

class RGBDStream(data.Dataset):
    def __init__(self, datapath, frame_rate=-1, image_size=[384,512], crop_size=[0,0]):
        self.datapath = datapath
        self.frame_rate = frame_rate
        self.image_size = image_size
        self.crop_size = crop_size
        self._build_dataset_index()
    
    @staticmethod
    def image_read(image_file):
        return cv2.imread(image_file)

    @staticmethod
    def depth_read(depth_file):
        return np.load(depth_file)

    def __len__(self):
        return len(self.images)

    def __getitem__(self, index):
        """ return training video """
        image = self.__class__.image_read(self.images[index])
        image = torch.from_numpy(image).float()
        image = image.permute(2, 0, 1)

        try:
            tstamp = self.tstamps[index]
        except:
            tstamp = index

        pose = torch.from_numpy(self.poses[index]).float()
        intrinsic = torch.from_numpy(self.intrinsics[index]).float()

        # resize image
        sx = self.image_size[1] / image.shape[2]
        sy = self.image_size[0] / image.shape[1]

        image = F.interpolate(image[None], self.image_size, mode='bilinear', align_corners=False)[0]

        fx, fy, cx, cy = intrinsic.unbind(dim=0)
        fx, cx = sx * fx, sx * cx
        fy, cy = sy * fy, sy * cy
        
        # crop image
        if self.crop_size[0] > 0:
            cy = cy - self.crop_size[0]
            image = image[:,self.crop_size[0]:-self.crop_size[0],:]

        if self.crop_size[1] > 0:
            cx = cx - self.crop_size[1]
            image = image[:,:,self.crop_size[1]:-self.crop_size[1]]

        intrinsic = torch.stack([fx, fy, cx, cy])

        return tstamp, image, pose, intrinsic


class ImageStream(data.Dataset):
    def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512]):
        rgb_list = osp.join(datapath, 'rgb.txt')
        if os.path.isfile(rgb_list):
            rgb_list = np.loadtxt(rgb_list, delimiter=' ', dtype=np.unicode_)
            self.timestamps = rgb_list[:,0].astype(np.float)
            self.images = [os.path.join(datapath, x) for x in rgb_list[:,1]]
            self.images = self.images[::rate]
            self.timestamps = self.timestamps[::rate]

        else:
            import glob
            self.images = sorted(glob.glob(osp.join(datapath, '*.jpg'))) +  sorted(glob.glob(osp.join(datapath, '*.png')))
            self.images = self.images[::rate]

        self.intrinsics = intrinsics
        self.image_size = image_size

    def __len__(self):
        return len(self.images)

    @staticmethod
    def image_read(imfile):
        return cv2.imread(imfile)

    def __getitem__(self, index):
        """ return training video """
        image = self.__class__.image_read(self.images[index])

        try:
            tstamp = self.timestamps[index]
        except:
            tstamp = index

        ht0, wd0 = image.shape[:2]
        ht1, wd1 = self.image_size

        intrinsics = torch.as_tensor(self.intrinsics)
        intrinsics[0] *= wd1 / wd0
        intrinsics[1] *= ht1 / ht0
        intrinsics[2] *= wd1 / wd0
        intrinsics[3] *= ht1 / ht0

        # resize image
        ikwargs = {'mode': 'bilinear', 'align_corners': True}
        image = torch.from_numpy(image).float().permute(2, 0, 1)
        image = F.interpolate(image[None], self.image_size, **ikwargs)[0]

        return tstamp, image, intrinsics



class StereoStream(data.Dataset):
    def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512], 
            map_left=None, map_right=None, left_root='image_left', right_root='image_right'):
        import glob
        self.intrinsics = intrinsics
        self.image_size = image_size
        
        imgs = sorted(glob.glob(osp.join(datapath, left_root, '*.png')))[::rate]
        self.images_l = []
        self.images_r = []
        self.tstamps = []

        for img_l in imgs:
            img_r = img_l.replace(left_root, right_root)
            if os.path.isfile(img_r):
                t = np.float(img_l.split('/')[-1].replace('.png', ''))
                self.tstamps.append(t)
                self.images_l += [ img_l ]
                self.images_r += [ img_r ]

        self.map_left = map_left
        self.map_right = map_right

    def __len__(self):
        return len(self.images_l)

    @staticmethod
    def image_read(imfile, imap=None):
        image = cv2.imread(imfile)
        if imap is not None:
            image = cv2.remap(image, imap[0], imap[1], interpolation=cv2.INTER_LINEAR)
        return image

    def __getitem__(self, index):
        """ return training video """
        tstamp = self.tstamps[index]
        image_l = self.__class__.image_read(self.images_l[index], self.map_left)
        image_r = self.__class__.image_read(self.images_r[index], self.map_right)

        ht0, wd0 = image_l.shape[:2]
        ht1, wd1 = self.image_size

        intrinsics = torch.as_tensor(self.intrinsics)
        intrinsics[0] *= wd1 / wd0
        intrinsics[1] *= ht1 / ht0
        intrinsics[2] *= wd1 / wd0
        intrinsics[3] *= ht1 / ht0

        image_l = torch.from_numpy(image_l).float().permute(2, 0, 1)
        image_r = torch.from_numpy(image_r).float().permute(2, 0, 1)

        # resize image
        ikwargs = {'mode': 'bilinear', 'align_corners': True}
        image_l = F.interpolate(image_l[None], self.image_size, **ikwargs)[0]
        image_r = F.interpolate(image_r[None], self.image_size, **ikwargs)[0]

        return tstamp, image_l, image_r, intrinsics



# class RGBDStream(data.Dataset):
#     def __init__(self, datapath, intrinsics=None, rate=1, image_size=[384,512]):
#         assoc_file = osp.join(datapath, 'associated.txt')
#         assoc_list = np.loadtxt(assoc_file, delimiter=' ', dtype=np.unicode_)
        
#         self.intrinsics = intrinsics
#         self.image_size = image_size
        
#         self.timestamps = assoc_list[:,0].astype(np.float)[::rate]
#         self.images = [os.path.join(datapath, x) for x in assoc_list[:,1]][::rate]
#         self.depths = [os.path.join(datapath, x) for x in assoc_list[:,3]][::rate]

#     def __len__(self):
#         return len(self.images)

#     @staticmethod
#     def image_read(imfile):
#         return cv2.imread(imfile)

#     @staticmethod
#     def depth_read(depth_file):
#         depth = cv2.imread(depth_file, cv2.IMREAD_ANYDEPTH)
#         return depth.astype(np.float32) / 5000.0

#     def __getitem__(self, index):
#         """ return training video """
#         tstamp = self.timestamps[index]
#         image = self.__class__.image_read(self.images[index])
#         depth = self.__class__.depth_read(self.depths[index])

#         ht0, wd0 = image.shape[:2]
#         ht1, wd1 = self.image_size

#         intrinsics = torch.as_tensor(self.intrinsics)
#         intrinsics[0] *= wd1 / wd0
#         intrinsics[1] *= ht1 / ht0
#         intrinsics[2] *= wd1 / wd0
#         intrinsics[3] *= ht1 / ht0

#         # resize image
#         ikwargs = {'mode': 'bilinear', 'align_corners': True}
#         image = torch.from_numpy(image).float().permute(2, 0, 1)
#         image = F.interpolate(image[None], self.image_size, **ikwargs)[0]

#         depth = torch.from_numpy(depth).float()[None,None]
#         depth = F.interpolate(depth, self.image_size, mode='nearest').squeeze()

#         return tstamp, image, depth, intrinsics


================================================
FILE: dbaf/data_readers/tartan.py
================================================

import numpy as np
import torch
import glob
import cv2
import os
import os.path as osp

from lietorch import SE3
from .base import RGBDDataset
from .stream import RGBDStream

cur_path = osp.dirname(osp.abspath(__file__))
test_split = osp.join(cur_path, 'tartan_test.txt')
test_split = open(test_split).read().split()


class TartanAir(RGBDDataset):

    # scale depths to balance rot & trans
    DEPTH_SCALE = 5.0

    def __init__(self, mode='training', **kwargs):
        self.mode = mode
        self.n_frames = 2
        super(TartanAir, self).__init__(name='TartanAir', **kwargs)

    @staticmethod 
    def is_test_scene(scene):
        # print(scene, any(x in scene for x in test_split))
        return any(x in scene for x in test_split)

    def _build_dataset(self):
        from tqdm import tqdm
        print("Building TartanAir dataset")

        scene_info = {}
        scenes = glob.glob(osp.join(self.root, '*/*/*/*'))
        for scene in tqdm(sorted(scenes)):
            images = sorted(glob.glob(osp.join(scene, 'image_left/*.png')))
            depths = sorted(glob.glob(osp.join(scene, 'depth_left/*.npy')))
            
            poses = np.loadtxt(osp.join(scene, 'pose_left.txt'), delimiter=' ')
            poses = poses[:, [1, 2, 0, 4, 5, 3, 6]]
            poses[:,:3] /= TartanAir.DEPTH_SCALE
            intrinsics = [TartanAir.calib_read()] * len(images)

            # graph of co-visible frames based on flow
            graph = self.build_frame_graph(poses, depths, intrinsics)

            scene = '/'.join(scene.split('/'))
            scene_info[scene] = {'images': images, 'depths': depths, 
                'poses': poses, 'intrinsics': intrinsics, 'graph': graph}

        return scene_info

    @staticmethod
    def calib_read():
        return np.array([320.0, 320.0, 320.0, 240.0])

    @staticmethod
    def image_read(image_file):
        return cv2.imread(image_file)

    @staticmethod
    def depth_read(depth_file):
        depth = np.load(depth_file) / TartanAir.DEPTH_SCALE
        depth[depth==np.nan] = 1.0
        depth[depth==np.inf] = 1.0
        return depth


class TartanAirStream(RGBDStream):
    def __init__(self, datapath, **kwargs):
        super(TartanAirStream, self).__init__(datapath=datapath, **kwargs)

    def _build_dataset_index(self):
        """ build list of images, poses, depths, and intrinsics """
        self.root = 'datasets/TartanAir'

        scene = osp.join(self.root, self.datapath)
        image_glob = osp.join(scene, 'image_left/*.png')
        images = sorted(glob.glob(image_glob))

        poses = np.loadtxt(osp.join(scene, 'pose_left.txt'), delimiter=' ')
        poses = poses[:, [1, 2, 0, 4, 5, 3, 6]]

        poses = SE3(torch.as_tensor(poses))
        poses = poses[[0]].inv() * poses
        poses = poses.data.cpu().numpy()

        intrinsic = self.calib_read(self.datapath)
        intrinsics = np.tile(intrinsic[None], (len(images), 1))

        self.images = images[::int(self.frame_rate)]
        self.poses = poses[::int(self.frame_rate)]
        self.intrinsics = intrinsics[::int(self.frame_rate)]

    @staticmethod
    def calib_read(datapath):
        return np.array([320.0, 320.0, 320.0, 240.0])

    @staticmethod
    def image_read(image_file):
        return cv2.imread(image_file)


class TartanAirTestStream(RGBDStream):
    def __init__(self, datapath, **kwargs):
        super(TartanAirTestStream, self).__init__(datapath=datapath, **kwargs)

    def _build_dataset_index(self):
        """ build list of images, poses, depths, and intrinsics """
        self.root = 'datasets/mono'
        image_glob = osp.join(self.root, self.datapath, '*.png')
        images = sorted(glob.glob(image_glob))

        poses = np.loadtxt(osp.join(self.root, 'mono_gt', self.datapath + '.txt'), delimiter=' ')
        poses = poses[:, [1, 2, 0, 4, 5, 3, 6]]

        poses = SE3(torch.as_tensor(poses))
        poses = poses[[0]].inv() * poses
        poses = poses.data.cpu().numpy()

        intrinsic = self.calib_read(self.datapath)
        intrinsics = np.tile(intrinsic[None], (len(images), 1))

        self.images = images[::int(self.frame_rate)]
        self.poses = poses[::int(self.frame_rate)]
        self.intrinsics = intrinsics[::int(self.frame_rate)]

    @staticmethod
    def calib_read(datapath):
        return np.array([320.0, 320.0, 320.0, 240.0])

    @staticmethod
    def image_read(image_file):
        return cv2.imread(image_file)

================================================
FILE: dbaf/data_readers/tartan_test.txt
================================================
abandonedfactory/abandonedfactory/Easy/P011
abandonedfactory/abandonedfactory/Hard/P011
abandonedfactory_night/abandonedfactory_night/Easy/P013
abandonedfactory_night/abandonedfactory_night/Hard/P014
amusement/amusement/Easy/P008
amusement/amusement/Hard/P007
carwelding/carwelding/Easy/P007
endofworld/endofworld/Easy/P009
gascola/gascola/Easy/P008
gascola/gascola/Hard/P009
hospital/hospital/Easy/P036
hospital/hospital/Hard/P049
japanesealley/japanesealley/Easy/P007
japanesealley/japanesealley/Hard/P005
neighborhood/neighborhood/Easy/P021
neighborhood/neighborhood/Hard/P017
ocean/ocean/Easy/P013
ocean/ocean/Hard/P009
office2/office2/Easy/P011
office2/office2/Hard/P010
office/office/Hard/P007
oldtown/oldtown/Easy/P007
oldtown/oldtown/Hard/P008
seasidetown/seasidetown/Easy/P009
seasonsforest/seasonsforest/Easy/P011
seasonsforest/seasonsforest/Hard/P006
seasonsforest_winter/seasonsforest_winter/Easy/P009
seasonsforest_winter/seasonsforest_winter/Hard/P018
soulcity/soulcity/Easy/P012
soulcity/soulcity/Hard/P009
westerndesert/westerndesert/Easy/P013
westerndesert/westerndesert/Hard/P007


================================================
FILE: dbaf/dbaf.py
================================================
import torch
import lietorch
import numpy as np
from droid_net import DroidNet
from depth_video import DepthVideo
from motion_filter import MotionFilter
from dbaf_frontend import DBAFusionFrontend
from collections import OrderedDict
from torch.multiprocessing import Process

from lietorch import SE3
import geom.projective_ops as pops
import droid_backends
import pickle

class DBAFusion:
    def __init__(self, args):
        super(DBAFusion, self).__init__()
        self.load_weights(args.weights) # load DroidNet weights
        self.args = args

        # store images, depth, poses, intrinsics (shared between processes)
        self.video = DepthVideo(args.image_size, args.buffer, save_pkl = args.save_pkl, stereo=args.stereo, upsample=args.upsample)

        # filter incoming frames so that there is enough motion
        self.filterx = MotionFilter(self.net, self.video, thresh=args.filter_thresh)

        # frontend process
        self.frontend = DBAFusionFrontend(self.net, self.video, self.args)

        self.pklpath = args.pklpath
        self.upsample = args.upsample

    def load_weights(self, weights):
        """ load trained model weights """

        print(weights)
        self.net = DroidNet()
        state_dict = OrderedDict([
            (k.replace("module.", ""), v) for (k, v) in torch.load(weights).items()])

        state_dict["update.weight.2.weight"] = state_dict["update.weight.2.weight"][:2]
        state_dict["update.weight.2.bias"] = state_dict["update.weight.2.bias"][:2]
        state_dict["update.delta.2.weight"] = state_dict["update.delta.2.weight"][:2]
        state_dict["update.delta.2.bias"] = state_dict["update.delta.2.bias"][:2]

        self.net.load_state_dict(state_dict)
        self.net.to("cuda:0").eval()

    def track(self, tstamp, image, depth=None, intrinsics=None):
        """ main thread - update map """

        with torch.no_grad():
            # check there is enough motion
            self.filterx.track(tstamp, image, depth, intrinsics)

            # local bundle adjustment
            self.frontend()

    def terminate(self, stream=None):
        """ terminate the visualization process, return poses [t, q] """
        del self.frontend

    def save_vis_easy(self):
        mcameras = {}
        mpoints = {}
        mstamps = {}
        with torch.no_grad():
            dirty_index = torch.arange(0,self.video.count_save,device='cuda')

            stamps= torch.index_select(self.video.tstamp_save, 0 ,dirty_index)
            poses=  torch.index_select( self.video.poses_save, 0 ,dirty_index)
            disps=  torch.index_select( self.video.disps_save, 0 ,dirty_index)
            images = torch.index_select( self.video.images_save, 0 ,dirty_index)
            Ps = SE3(poses).inv().matrix().cpu().numpy()
            points = droid_backends.iproj(SE3(poses).inv().data, disps, self.video.intrinsics[0]).cpu()
            thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2])) / 4.0  * (1.0 / torch.median(disps.mean(dim=[1,2])))
            # thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2])) 
            count = droid_backends.depth_filter(
                self.video.poses_save, self.video.disps_save, self.video.intrinsics[0], dirty_index, thresh)

            count = count.cpu()
            disps = disps.cpu()

            if self.upsample:
                disps_up=  torch.index_select( self.video.disps_up_save, 0 ,dirty_index)
                disps_up = disps_up.cpu()

            masks = ((count >= 1) & (disps > .5*disps.mean(dim=[1,2], keepdim=True)))

            for i in range(len(dirty_index)):
                pose = Ps[i]
                ix = dirty_index[i].item()
                mcameras[ix] = pose
                mask = masks[i].reshape(-1)
                pts = points[i].reshape(-1, 3)[mask].cpu().numpy()
                clr = images[i].reshape(-1, 3)[mask].cpu().numpy()
                stamp = stamps[i].cpu()
                if self.upsample:
                    mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'disps_up':disps_up[i].cpu().numpy(),'rgb':images[i].cpu().numpy()}
                else:
                    mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'rgb':images[i].cpu().numpy()}
                mstamps[ix] = stamp
        ddict = {'points':mpoints,'cameras':mcameras,'stamps':mstamps}
        f_save = open(self.pklpath, 'wb')
        pickle.dump(ddict,f_save) 

        mcameras = {}
        mpoints = {}
        mstamps = {}
        with torch.no_grad():
            dirty_index = torch.arange(0,self.video.count_save,device='cuda')

            stamps= torch.index_select(self.video.tstamp_save, 0 ,dirty_index)
            poses=  torch.index_select( self.video.poses_save, 0 ,dirty_index)
            disps=  torch.index_select( self.video.disps_save, 0 ,dirty_index)
            images = torch.index_select( self.video.images_save, 0 ,dirty_index)
            Ps = SE3(poses).inv().matrix().cpu().numpy()
            points = droid_backends.iproj(SE3(poses).inv().data, disps, self.video.intrinsics[0]).cpu()
            thresh = 0.4 * torch.ones_like(disps.mean(dim=[1,2]))
            count = droid_backends.depth_filter(
                self.video.poses_save, self.video.disps_save, self.video.intrinsics[0], dirty_index, thresh)

            count = count.cpu()
            disps = disps.cpu()
            masks = ((count >= 0) & (disps > .5*disps.mean(dim=[1,2], keepdim=True)))

            for i in range(len(dirty_index)):
                pose = Ps[i]
                ix = dirty_index[i].item()
                mcameras[ix] = pose
                mask = masks[i].reshape(-1)
                pts = points[i].reshape(-1, 3)[mask].cpu().numpy()
                clr = images[i].reshape(-1, 3)[mask].cpu().numpy()
                stamp = stamps[i].cpu()
                mpoints[ix] = {'pts':pts,'clr':clr,'disp':disps[i].cpu().numpy(),'rgb':images[i].cpu().numpy()}
                mstamps[ix] = stamp
        ddict = {'points':mpoints,'cameras':mcameras,'stamps':mstamps}
        f_save = open(self.pklpath.split('.')[0] + '_raw.pkl', 'wb')
        pickle.dump(ddict,f_save) 


================================================
FILE: dbaf/dbaf_frontend.py
================================================
import torch
import torchvision
import numpy as np

from lietorch import SE3, SO3
from covisible_graph import CovisibleGraph
import matplotlib.pyplot as plt

import gtsam
import math
import bisect
from math import atan2, cos, sin
import geoFunc.trans as trans
from scipy.spatial.transform import Rotation

class DBAFusionFrontend:
    def __init__(self, net, video, args):
        self.video = video
        self.update_op = net.update
        self.graph = CovisibleGraph(video, net.update, args=args)

        # local optimization window
        self.t0 = 0
        self.t1 = 0

        # frontend variables
        self.is_initialized = False
        self.count = 0

        self.warmup = args.warmup
        self.vi_warmup = 12
        if 'vi_warmup' in args: self.vi_warmup = args.vi_warmup
        self.beta = args.beta
        self.frontend_nms = args.frontend_nms
        self.keyframe_thresh = args.keyframe_thresh
        self.frontend_window = args.frontend_window
        self.frontend_thresh = args.frontend_thresh
        self.frontend_radius = args.frontend_radius

        ### DBAFusion
        self.all_imu = None
        self.cur_imu_ii = 0
        self.is_init = False
        self.all_gnss = None
        self.all_odo = None
        self.all_gt = None
        self.all_gt_keys = None
        self.all_stamp = None
        self.cur_stamp_ii = 0
        self.visual_only = args.visual_only
        self.visual_only_init = False
        self.translation_threshold = 0.0
        self.active_window = args.active_window
        self.high_freq_output = True
        self.zupt = ('use_zupt' in args and args.use_zupt)

        if  not self.visual_only:
            self.max_age = 25
            self.iters1 = 2
            self.iters2 = 1
        else:
            self.max_age = 25
            self.iters1 = 4
            self.iters2 = 2

        # visualization/output
        self.show_plot = args.show_plot
        self.result_file = open(args.resultpath,'wt')
        self.plt_pos     = [[],[]]    # X, Y
        self.plt_pos_ref = [[],[]]    # X, Y
        self.plt_att     = [[],[],[]] # pitch, roll, yaw
        self.plt_bg      = [[],[],[]] # X, Y, Z
        self.plt_t       = []
        self.refTw       = np.eye(4,4)

        if self.show_plot:
            plt.figure('monitor',figsize=[13,4])
            plt.subplot(1,3,1); plt.gca().set_title('Trajectory')
            plt.gca().set_aspect(1)
            plt.subplot(1,3,2); plt.gca().set_title('Attitude Error/Attitude')
            plt.subplot(1,3,3); plt.gca().set_title('Gyroscope Bias')
            plt.ion()
            plt.pause(0.1)

    def get_pose_ref(self, tt:float):
        tt_found = self.all_gt_keys[bisect.bisect(self.all_gt_keys,tt)]
        return tt_found, self.all_gt[tt_found]
    
    def __rollup(self, roll):
        """ roll up window states to save memory """
        self.t1 -= roll
        self.count -= roll
        self.video.counter.value -= roll
        self.video.tstamp     = torch.roll(self.video.tstamp    ,-roll,0) 
        self.video.images     = torch.roll(self.video.images    ,-roll,0) 
        self.video.dirty      = torch.roll(self.video.dirty     ,-roll,0) 
        self.video.red        = torch.roll(self.video.red       ,-roll,0) 
        self.video.poses      = torch.roll(self.video.poses     ,-roll,0) 
        self.video.disps      = torch.roll(self.video.disps     ,-roll,0) 
        self.video.disps_sens = torch.roll(self.video.disps_sens,-roll,0) 
        self.video.disps_up   = torch.roll(self.video.disps_up  ,-roll,0) 
        self.video.intrinsics = torch.roll(self.video.intrinsics,-roll,0) 
        self.video.fmaps      = torch.roll(self.video.fmaps     ,-roll,0) 
        self.video.nets       = torch.roll(self.video.nets      ,-roll,0) 
        self.video.inps       = torch.roll(self.video.inps      ,-roll,0) 
        self.graph.ii -= roll
        self.graph.jj -= roll
        self.graph.ii_inac -= roll
        self.graph.jj_inac -= roll
        rm_inac_index = torch.logical_and(torch.greater_equal(self.graph.ii_inac,0),torch.greater_equal(self.graph.jj_inac,0))
        self.graph.ii_inac = self.graph.ii_inac[rm_inac_index]
        self.graph.jj_inac = self.graph.jj_inac[rm_inac_index]
        self.graph.target_inac = self.graph.target_inac[:,rm_inac_index,:,:,:]
        self.graph.weight_inac = self.graph.weight_inac[:,rm_inac_index,:,:,:] # need test

        self.graph.ii_bad  -= roll
        self.graph.jj_bad  -= roll

        self.video.last_t0 -= roll
        self.video.last_t1 -= roll
        self.video.cur_ii  -= roll
        self.video.cur_jj  -= roll
        if self.video.imu_enabled:
            graph_temp = gtsam.NonlinearFactorGraph()
            for i in range(self.video.cur_graph.size()):
                f = self.video.cur_graph.at(i)
                graph_temp.push_back(f.rekey((np.array(f.keys())-roll).tolist()))
            self.video.cur_graph = graph_temp
            result_temp = gtsam.Values()
            for i in self.video.cur_result.keys():
                if gtsam.Symbol(i).chr() == ord('b'):
                    result_temp.insert(i-roll,self.video.cur_result.atConstantBias(i))
                elif gtsam.Symbol(i).chr() == ord('v'):
                    result_temp.insert(i-roll,self.video.cur_result.atVector(i))
                elif gtsam.Symbol(i).chr() == ord('x'):
                    result_temp.insert(i-roll,self.video.cur_result.atPose3(i))
                else:
                    raise Exception()
            self.video.cur_result = result_temp
            self.video.marg_factor = self.video.marg_factor.rekey((np.array(self.video.marg_factor.keys())-roll).tolist())

        self.video.state.timestamps           = self.video.state.timestamps           [roll:]
        self.video.state.wTbs                 = self.video.state.wTbs                 [roll:]
        self.video.state.vs                   = self.video.state.vs                   [roll:]
        self.video.state.bs                   = self.video.state.bs                   [roll:]
        self.video.state.preintegrations      = self.video.state.preintegrations      [roll:]
        self.video.state.preintegrations_meas = self.video.state.preintegrations_meas [roll:]
        self.video.state.gnss_valid           = self.video.state.gnss_valid           [roll:]
        self.video.state.gnss_position        = self.video.state.gnss_position        [roll:]
        self.video.state.odo_valid            = self.video.state.odo_valid            [roll:]
        self.video.state.odo_vel              = self.video.state.odo_vel              [roll:]

    def __update(self):
        """ add edges, perform update """
        self.count += 1
        self.t1 += 1

        if self.video.imu_enabled and (self.video.tstamp[self.t1-1] - self.video.vi_init_time > 5.0):
            self.video.reinit = True
            self.video.vi_init_time = 1e9

        ## new frame comes, append IMU
        cur_t = float(self.video.tstamp[self.t1-1].detach().cpu())
        self.video.logger.info('predict %f' %cur_t)

        while self.all_imu[self.cur_imu_ii][0] < cur_t:
            ## high-frequency output
            # predict the pose of skipped frames through IMU preintegration
            if self.high_freq_output and self.video.imu_enabled: 
                if self.all_imu[self.cur_imu_ii][0] > float(self.all_stamp[self.cur_stamp_ii][0]):
                    self.video.state.append_imu_temp(float(self.all_stamp[self.cur_stamp_ii][0]),\
                                    self.all_imu[self.cur_imu_ii][4:7],\
                                    self.all_imu[self.cur_imu_ii][1:4]/180*math.pi,True)
                    if float(self.all_stamp[self.cur_stamp_ii][0]) > self.video.state.timestamps[-1] and\
                          math.fabs(cur_t - float(self.all_stamp[self.cur_stamp_ii][0]))>1e-3:
                        pose_temp = self.video.state.pose_temp
                        ppp = pose_temp.pose().translation()
                        qqq = Rotation.from_matrix(pose_temp.pose().rotation().matrix()).as_quat()
                        line = '%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f'%(float(self.all_stamp[self.cur_stamp_ii][0]),ppp[0],ppp[1],ppp[2]\
                                            ,qqq[0],qqq[1],qqq[2],qqq[3])
                        if self.video.gnss_init_t1>0:
                            p = self.video.ten0 + np.matmul(trans.Cen(self.video.ten0), ppp)
                            line += ' %.6f %.6f %.6f'% (p[0],p[1],p[2]) 
                        self.result_file.writelines(line+'\n')
                        # self.result_file.flush()
                    self.cur_stamp_ii += 1
                self.video.state.append_imu_temp(self.all_imu[self.cur_imu_ii][0],\
                                    self.all_imu[self.cur_imu_ii][4:7],\
                                    self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
                
            self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\
                                    self.all_imu[self.cur_imu_ii][4:7],\
                                    self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
            self.cur_imu_ii += 1
        self.video.state.append_imu(cur_t,\
                                    self.all_imu[self.cur_imu_ii][4:7],\
                                    self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
        self.video.state.append_img(cur_t)
        
        ## append GNSS
        if len(self.all_gnss) > 0: gnss_found = bisect.bisect(self.all_gnss[:,0],cur_t - 1e-6)
        else: gnss_found = -1        
        if gnss_found > 0 and self.all_gnss[gnss_found,0] - cur_t < 0.01 :
            self.video.state.append_gnss(cur_t,self.all_gnss[gnss_found,1:4])

        ## append ZUPT
        if self.zupt and self.video.state.preintegrations[self.t1-3].deltaTij() > 3.0:
            if np.linalg.norm(self.video.state.vs[self.t1-2]) < 0.025:
                self.video.state.append_odo(cur_t,np.array([.0,.0,.0]))

        ## append ODO
        if len(self.all_odo) > 0: odo_found = bisect.bisect(self.all_odo[:,0],cur_t - 1e-6)
        else: odo_found = -1        
        if odo_found > 0 and self.all_odo[odo_found,0] - cur_t < 0.01 :
            self.video.state.append_odo(cur_t,self.all_odo[odo_found,1:4])

        self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\
                        self.all_imu[self.cur_imu_ii][4:7],\
                        self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
        self.cur_imu_ii += 1

        ## predict pose (<5 ms)
        if self.video.imu_enabled:
            Twc = (self.video.state.wTbs[-1] * self.video.Tbc).matrix()
            TTT = torch.tensor(np.linalg.inv(Twc))
            q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat())
            t = TTT[:3,3]
            self.video.poses[self.t1-1] = torch.cat([t,q])

        self.video.logger.info('manage edges')

        ## manage edges (60 ms)
        if self.graph.corr is not None:
            if self.visual_only:
                self.graph.rm_factors(torch.logical_and(self.graph.age > self.max_age,\
                torch.logical_or(self.graph.ii < self.t1-self.active_window,self.graph.jj < self.t1-self.active_window)), store=True)
            else:
                self.graph.rm_factors(torch.logical_or(self.graph.age > self.max_age,\
                torch.logical_or(self.graph.ii < self.t1-self.active_window,self.graph.jj < self.t1-self.active_window)), store=True)

        self.graph.add_proximity_factors(self.t1-5, max(self.t1-self.frontend_window, 0), 
            rad=self.frontend_radius, nms=self.frontend_nms, thresh=self.frontend_thresh, beta=self.beta, remove=True)

        self.video.logger.info('non-keyframes %d' % self.graph.ii.shape[0])

        ## non-keyframe update
        self.video.disps[self.t1-1] = torch.where(self.video.disps_sens[self.t1-1] > 0, 
           self.video.disps_sens[self.t1-1], self.video.disps[self.t1-1])

        for itr in range(self.iters1):
            self.graph.update(None, None, use_inactive=True)

        self.rollup = False
        if self.t1 > 65:
            self.__rollup(30)
            print('rollup ',self.graph.ii)
            self.rollup = True

        self.video.logger.info('output')

        ## visualization/output
        poses = SE3(self.video.poses)
        d = self.video.distance([self.t1-3], [self.t1-2], beta=self.beta, bidirectional=True)
        TTT = np.matmul(poses[self.t1-1].cpu().inv().matrix(),np.linalg.inv(self.video.Ti1c))
        if self.video.imu_enabled or (self.visual_only and self.visual_only_init):
            ppp = TTT[0:3,3]
            qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat()
            line = '%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f'%(cur_t,ppp[0],ppp[1],ppp[2]\
                                        ,qqq[0],qqq[1],qqq[2],qqq[3])
            if self.video.gnss_init_t1>0:
                p = self.video.ten0 + np.matmul(trans.Cen(self.video.ten0), ppp.numpy())
                line += ' %.6f %.6f %.6f'% (p[0],p[1],p[2]) 
            self.result_file.writelines(line+'\n')
            self.result_file.flush()

        TTTref = np.matmul(self.refTw,TTT)
        ppp = TTTref[0:3,3]
        if self.show_plot:
            # if math.fabs(tt_found - cur_t) < 0.1: # for kitti and whu
            self.plt_pos[0].append(ppp[0])
            self.plt_pos[1].append(ppp[1])
            a1 = np.array(trans.m2att(TTTref[0:3,0:3])     )* 57.3
            if self.all_gt is not None:
                tt_found,dd = self.get_pose_ref(cur_t -1e-3)
                self.plt_pos_ref[0].append(dd['T'][0,3])
                self.plt_pos_ref[1].append(dd['T'][1,3])    
                a2 = np.array(trans.m2att(dd['T'][0:3,0:3]) )* 57.3    
                a1 -= a2
            self.plt_att[0].append(a1[0])
            self.plt_att[1].append(a1[1])
            self.plt_att[2].append(a1[2])
            bg = self.video.state.bs[self.t1-1].gyroscope()
            self.plt_bg[0].append(bg[0])
            self.plt_bg[1].append(bg[1])
            self.plt_bg[2].append(bg[2])
            self.plt_t.append(cur_t)
            
            if self.rollup:
                plt.subplot(1,3,1)
                plt.cla(); plt.gca().set_title('Trajectory')
                plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^')
                plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^')
                plt.subplot(1,3,2)
                plt.cla(); plt.gca().set_title('Attitude Error/Attitude')
                plt.plot(self.plt_t,self.plt_att[0],c='r')
                plt.plot(self.plt_t,self.plt_att[1],c='g')
                plt.plot(self.plt_t,self.plt_att[2],c='b')
                plt.ylim([-10,10])
                plt.subplot(1,3,3)
                plt.cla(); plt.gca().set_title('Gyroscope Bias')
                plt.plot(self.plt_t,self.plt_bg[0],c='r')
                plt.plot(self.plt_t,self.plt_bg[1],c='g')
                plt.plot(self.plt_t,self.plt_bg[2],c='b')
                plt.pause(0.1)


        ## keyframe update
        self.video.logger.info('keyframes %d' % self.graph.ii.shape[0])
        if self.t1 > 10:
            cam_translation =  torch.norm((poses[(self.t1-10):(self.t1-3)] * poses[self.t1-2].inv()[None]).translation()[:,0:3],dim=1)
        else:
            cam_translation =  torch.norm((poses[(self.t1-6):(self.t1-3)] * poses[self.t1-2].inv()[None]).translation()[:,0:3],dim=1)

        if (d.item() < self.keyframe_thresh or (self.video.imu_enabled and torch.sum(cam_translation < self.translation_threshold)>0)): # gnss
            self.video.logger.info('remove new frame!!!!!!!!!!!!1')
            self.graph.rm_keyframe(self.t1 - 2)

            # merge preintegration[self.t1-2] and preintegration[self.t1-3]
            for iii in range(len(self.video.state.preintegrations_meas[self.t1-2])):
                dd = self.video.state.preintegrations_meas[self.t1-2][iii]
                if dd[2] > 0:
                    self.video.state.preintegrations[self.t1-3].integrateMeasurement(dd[0],\
                                                                                      dd[1],\
                                                                                      dd[2])
                self.video.state.preintegrations_meas[self.t1-3].append(dd)
                
            self.video.state.preintegrations[self.t1-2] = self.video.state.preintegrations[self.t1-1]
            self.video.state.preintegrations_meas[self.t1-2] = self.video.state.preintegrations_meas[self.t1-1]
            self.video.state.preintegrations.pop()
            self.video.state.preintegrations_meas.pop()

            self.video.rm_new_gnss(self.t1-2)
            self.video.state.wTbs[self.t1-2] = self.video.state.wTbs[self.t1-1]; self.video.state.wTbs.pop()
            self.video.state.bs  [self.t1-2] = self.video.state.bs  [self.t1-1]; self.video.state.bs.pop()
            self.video.state.vs  [self.t1-2] = self.video.state.vs  [self.t1-1]; self.video.state.vs .pop()
            self.video.state.gnss_valid     [self.t1-2] = self.video.state.gnss_valid     [self.t1-1]; self.video.state.gnss_valid .pop()
            self.video.state.gnss_position  [self.t1-2] = self.video.state.gnss_position  [self.t1-1]; self.video.state.gnss_position .pop()
            self.video.state.odo_valid      [self.t1-2] = self.video.state.odo_valid      [self.t1-1]; self.video.state.odo_valid .pop()
            self.video.state.odo_vel        [self.t1-2] = self.video.state.odo_vel        [self.t1-1]; self.video.state.odo_vel .pop()            

            with self.video.get_lock():
                self.video.counter.value -= 1
                self.t1 -= 1
        else:
            for itr in range(self.iters2):
                # print('b%d' % itr)
                self.graph.update(None, None, use_inactive=True)

        ## try initializing VI/GNSS
        if self.t1 > self.vi_warmup and self.video.vi_init_t1 < 0:
            self.init_VI()
            if not self.visual_only:
                for i in range(len(self.all_stamp)): # skip to next image
                    if float(self.all_stamp[i][0]) < cur_t + 1e-6: continue
                    else:
                        self.cur_stamp_ii = i
                        break
        if self.video.imu_enabled and self.video.gnss_init_time <= 0.0 and len(self.all_gnss)>0:
            self.init_GNSS()

        ## set pose for next itration
        self.video.poses[self.t1] = self.video.poses[self.t1-1]
        self.video.disps[self.t1] = self.video.disps[self.t1-1].mean() * 1.0

        self.video.dirty[self.graph.ii.min():self.t1] = True

    def init_IMU(self):
        """ initialize IMU states """
        cur_t = float(self.video.tstamp[self.t0].detach().cpu())
        for i in range(len(self.all_imu)):
            if self.all_imu[i][0] < cur_t - 1e-6: continue
            else:
                self.cur_imu_ii = i
                break

        for i in range(self.t0,self.t1):
            tt = self.video.tstamp[i]
            if i == self.t0:
                self.video.state.init_first_state(cur_t,np.zeros(3),\
                                            np.eye(3),\
                                            np.zeros(3))
                self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\
                                        self.all_imu[self.cur_imu_ii][4:7],\
                                        self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
                self.cur_imu_ii += 1
                self.is_init = True
            else:
                cur_t = float(self.video.tstamp[i].detach().cpu())
                while self.all_imu[self.cur_imu_ii][0] < cur_t:
                    self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\
                                            self.all_imu[self.cur_imu_ii][4:7],\
                                            self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
                    self.cur_imu_ii += 1
                self.video.state.append_imu(cur_t,\
                                            self.all_imu[self.cur_imu_ii][4:7],\
                                            self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
                self.video.state.append_img(cur_t)
                
                if len(self.all_gnss) > 0: gnss_found = bisect.bisect(self.all_gnss[:,0],cur_t - 1e-6)
                else: gnss_found = -1
                if gnss_found > 0 and self.all_gnss[gnss_found,0] - cur_t < 0.01:
                    self.video.state.append_gnss(cur_t,self.all_gnss[gnss_found,1:4])

                if len(self.all_odo) > 0: odo_found = bisect.bisect(self.all_odo[:,0],cur_t - 1e-6)
                else: odo_found = -1        
                if odo_found > 0 and self.all_odo[odo_found,0] - cur_t < 0.01 :
                    self.video.state.append_odo(cur_t,self.all_odo[odo_found,1:4])

                self.video.state.append_imu(self.all_imu[self.cur_imu_ii][0],\
                                self.all_imu[self.cur_imu_ii][4:7],\
                                self.all_imu[self.cur_imu_ii][1:4]/180*math.pi)
            
                self.cur_imu_ii += 1
            Twc = np.matmul(np.array([[1,0,0,0],\
                                     [0,1,0,0],\
                                     [0,0,1,0.02*i],\
                                     [0,0,0,1]]),self.video.Ti1c) #  perturb the camera poses, which benefits the robustness of initial BA
            TTT = torch.tensor(np.linalg.inv(Twc))
            q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat())
            t = TTT[:3,3]
            if not self.video.imu_enabled:
                self.video.poses[i] = torch.cat([t,q])

    def init_VI(self):
        """ initialize the V-I system, referring to VIN-Fusion """
        sum_g = np.zeros(3,dtype = np.float64)
        ccount = 0
        for i in range(self.t1 - 8 ,self.t1-1):
            dt = self.video.state.preintegrations[i].deltaTij()
            tmp_g = self.video.state.preintegrations[i].deltaVij()/dt
            sum_g += tmp_g
            ccount += 1
        aver_g = sum_g * 1.0 / ccount
        var_g = 0.0
        for i in range(self.t1 - 8 ,self.t1-1):
            dt = self.video.state.preintegrations[i].deltaTij()
            tmp_g = self.video.state.preintegrations[i].deltaVij()/dt
            var_g += np.linalg.norm(tmp_g - aver_g)**2
        var_g =math.sqrt(var_g/ccount)
        if var_g < 0.25:
            print("IMU excitation not enough!",var_g)
        else:
            poses = SE3(self.video.poses)
            self.plt_pos = [[],[]]
            self.plt_pos_ref = [[],[]]
            for i in range(0,self.t1):
                ppp = np.matmul(poses[i].cpu().inv().matrix(),np.linalg.inv(self.video.Ti1c))[0:3,3]
                self.plt_pos[0].append(ppp[0])
                self.plt_pos[1].append(ppp[1])
                if self.all_gt is not None:
                    tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3)
                    self.plt_pos_ref[0].append(dd['T'][0,3])
                    self.plt_pos_ref[1].append(dd['T'][1,3])     

            if self.show_plot:
                plt.subplot(1,3,1) 
                plt.cla(); plt.gca().set_title('Trajectory')
                plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^')
                plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^')
                plt.pause(0.1)

            if not self.visual_only:
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= True)
                self.graph.update(None, None, use_inactive=True)
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False)
                self.graph.update(None, None, use_inactive=True)
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False)
                self.video.imu_enabled = True
            else:
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= True)
                self.graph.update(None, None, use_inactive=True)
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False)
                self.graph.update(None, None, use_inactive=True)
                self.VisualIMUAlignment(self.t1 - 8 ,self.t1, ignore_lever= False)
                self.visual_only_init = True

            self.video.set_prior(self.video.last_t0,self.t1)

            self.plt_pos = [[],[]]
            self.plt_pos_ref = [[],[]]
            for i in range(0,self.t1):
                TTT = self.video.state.wTbs[i].matrix()
                ppp = TTT[0:3,3]
                qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat()
                self.result_file.writelines('%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n'%(self.video.tstamp[i],ppp[0],ppp[1],ppp[2]\
                                            ,qqq[0],qqq[1],qqq[2],qqq[3]))
                
                TTTref = np.matmul(self.refTw,TTT) # for visualization
                ppp = TTTref[0:3,3]
                qqq = Rotation.from_matrix(TTTref[:3, :3]).as_quat()
                self.plt_pos[0].append(ppp[0])
                self.plt_pos[1].append(ppp[1])
                if self.all_gt is not None:
                    tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3)
                    self.plt_pos_ref[0].append(dd['T'][0,3])
                    self.plt_pos_ref[1].append(dd['T'][1,3])
            if self.show_plot:
                plt.subplot(1,3,1)
                plt.cla(); plt.gca().set_title('Trajectory')
                plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^')
                plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^')
                plt.pause(0.1)

            for itr in range(1):
                self.graph.update(None, None, use_inactive=True)

    def init_GNSS(self):
        """ initialize the GNSS for geo-referencing fusion """
        ten0 = np.array([self.all_gt[self.all_gt_keys[0]]['X0'],\
                         self.all_gt[self.all_gt_keys[0]]['Y0'],\
                         self.all_gt[self.all_gt_keys[0]]['Z0']])
        self.video.ten0 = ten0
        tn0 = []; tw =[]
        for i in range(len(self.video.state.wTbs) - 10,len(self.video.state.wTbs)):
            if self.video.state.gnss_valid[i]:
                # if not is_ref_set:
                #     ten0 = self.video.sgraph.gnss_position[i]
                #     is_ref_set = True
                teg = self.video.state.gnss_position[i]
                print(self.video.ten0)
                print(self.video.state.gnss_position[i])
                tn0g = np.matmul(trans.Cen(self.video.ten0).T,(self.video.state.gnss_position[i] - self.video.ten0))
                twb = self.video.state.wTbs[i].translation()
                tn0.append(tn0g)
                tw.append(twb)
        if len(tn0) > 1:
            tn0 = np.array(tn0)
            tw = np.array(tw)
            bl = np.linalg.norm(tn0[-1] - tn0[0])
            print('GNSS Alignment Baseline: %.5f' % bl)
            if bl < 10.0:
                print('Baseline too short!!')
                return
            heading_w = math.atan2(tw[-1,1]-tw[0,1],tw[-1,0]-tw[0,0])
            heading_n0 = math.atan2(tn0[-1,1]-tn0[0,1],tn0[-1,0]-tn0[0,0])
            s_w = np.linalg.norm(tw[-1] - tw[0])
            s_n0 = np.linalg.norm(tn0[-1] - tn0[0])

            s = s_n0 / s_w
            Rn0w = trans.att2m(np.array([.0,.0,-heading_w + heading_n0]))
            tn0w = tn0  - np.matmul(Rn0w,tw.T * s).T

            poses = SE3(self.video.poses)
            wTcs = poses.inv().matrix().cpu().numpy()
            wTbs = np.matmul(wTcs,self.video.Tbc.inverse().matrix())
            wTbs[:,0:3,3] = np.matmul(Rn0w,(wTbs[:,0:3,3]*s).T).T + tn0w[0]
            wTbs[:,0:3,0:3] = np.matmul(Rn0w, (wTbs[:,0:3,0:3]).T).T
            
            self.refTw = np.eye(4,4)
            
            for i in range(0,self.t1):
                self.video.state.wTbs[i] = gtsam.Pose3(wTbs[i])
                self.video.state.vs[i] *=  s
            wTcs = np.matmul(wTbs,self.video.Tbc.matrix())
            for i in range(0,self.t1):
                TTT = np.linalg.inv(wTcs[i])
                q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat())
                t = torch.tensor(TTT[:3,3])
                self.video.poses[i] = torch.cat([t,q])
                self.video.disps[i] /= s

            self.video.gnss_init_t1 = self.t1
            self.video.gnss_init_time = self.video.tstamp[self.t1-1]
            
            self.video.set_prior(self.video.last_t0,self.t1)

            self.plt_pos = [[],[]]
            self.plt_pos_ref = [[],[]]
            for i in range(0,self.t1):
                TTT = self.video.state.wTbs[i].matrix()
                ppp = TTT[0:3,3]
                qqq = Rotation.from_matrix(TTT[:3, :3]).as_quat()
                self.result_file.writelines('%.6f %.6f %.6f %.6f %.6f %.6f %.6f %.6f\n'%(self.video.tstamp[i],ppp[0],ppp[1],ppp[2]\
                                            ,qqq[0],qqq[1],qqq[2],qqq[3]))
                
                TTTref = np.matmul(self.refTw,TTT) # for visualization
                ppp = TTTref[0:3,3]
                qqq = Rotation.from_matrix(TTTref[:3, :3]).as_quat()
                self.plt_pos[0].append(ppp[0])
                self.plt_pos[1].append(ppp[1])
                if self.all_gt is not None:
                    tt_found,dd = self.get_pose_ref(self.video.tstamp[i]-1e-3)
                    self.plt_pos_ref[0].append(dd['T'][0,3])
                    self.plt_pos_ref[1].append(dd['T'][1,3])
            if self.show_plot:
                plt.subplot(1,3,1)
                plt.cla(); plt.gca().set_title('Trajectory')
                plt.plot(self.plt_pos[0],self.plt_pos[1],marker='^')
                plt.plot(self.plt_pos_ref[0],self.plt_pos_ref[1],marker='^')
                plt.pause(0.1)

            for itr in range(1):
                self.graph.update(None, None, use_inactive=True)
            print('GNSS initialized!!!!')

    def VisualIMUAlignment(self, t0, t1, ignore_lever, disable_scale = False):
        poses = SE3(self.video.poses)
        wTcs = poses.inv().matrix().cpu().numpy()

        if not ignore_lever:
            wTbs = np.matmul(wTcs,self.video.Tbc.inverse().matrix())
        else:
            T_tmp = self.video.Tbc.inverse().matrix()
            T_tmp[0:3,3] = 0.0
            wTbs = np.matmul(wTcs,T_tmp)
        cost = 0.0

        # solveGyroscopeBias
        A = np.zeros([3,3])
        b = np.zeros(3)
        H1 =np.zeros([15,6], order='F', dtype=np.float64)
        H2 =np.zeros([15,3], order='F', dtype=np.float64)
        H3 =np.zeros([15,6], order='F', dtype=np.float64)
        H4 =np.zeros([15,3], order='F', dtype=np.float64)
        H5 =np.zeros([15,6], order='F', dtype=np.float64) # navstate wrt. bias
        H6 =np.zeros([15,6], order='F', dtype=np.float64)
        for i in range(t0,t1-1):
            pose_i = gtsam.Pose3(wTbs[i])
            pose_j = gtsam.Pose3(wTbs[i+1])
            Rij = np.matmul(pose_i.rotation().matrix().T,pose_j.rotation().matrix())
            imu_factor = gtsam.gtsam.CombinedImuFactor(0,1,2,3,4,5,self.video.state.preintegrations[i])
            err = imu_factor.evaluateErrorCustom(pose_i,self.video.state.vs[i],\
                                                 pose_j,self.video.state.vs[i+1],\
                self.video.state.bs[i],self.video.state.bs[i+1],\
                    H1,H2,H3,H4,H5,H6)
            tmp_A = H5[0:3,3:6]
            tmp_b = err[0:3]
            cost +=  np.dot(tmp_b,tmp_b)
            A += np.matmul(tmp_A.T,tmp_A)
            b += np.matmul(tmp_A.T,tmp_b)
        bg = -np.matmul(np.linalg.inv(A),b)

        for i in range(0,t1-1):
            pim = gtsam.PreintegratedCombinedMeasurements(self.video.state.params,\
                  gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),bg))
            for iii in range(len(self.video.state.preintegrations_meas[i])):
                dd = self.video.state.preintegrations_meas[i][iii]
                if dd[2] > 0: pim.integrateMeasurement(dd[0],dd[1],dd[2])
            self.video.state.preintegrations[i] = pim
            self.video.state.bs[i] = gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),bg)
        print('bg: ',bg)
        
        # linearAlignment
        all_frame_count = t1 - t0
        n_state = all_frame_count * 3 + 3 + 1
        A = np.zeros([n_state,n_state])
        b = np.zeros(n_state)
        i_count = 0
        for i in range(t0,t1-1):
            pose_i = gtsam.Pose3(wTbs[i])
            pose_j = gtsam.Pose3(wTbs[i+1])
            R_i = pose_i.rotation().matrix()
            t_i = pose_i.translation()
            R_j = pose_j.rotation().matrix()
            t_j = pose_j.translation()
            pim = self.video.state.preintegrations[i]
            tic = self.video.Tbc.translation()

            tmp_A = np.zeros([6,10])
            tmp_b = np.zeros(6)
            dt = pim.deltaTij()
            tmp_A[0:3,0:3] = -dt * np.eye(3,3)
            tmp_A[0:3,6:9] = R_i.T * dt * dt / 2
            tmp_A[0:3,9] = np.matmul(R_i.T, t_j-t_i) / 100.0
            tmp_b[0:3] = pim.deltaPij()
            tmp_A[3:6,0:3] = -np.eye(3,3)
            tmp_A[3:6,3:6] = np.matmul(R_i.T, R_j)
            tmp_A[3:6,6:9] = R_i.T * dt
            tmp_b[3:6] = pim.deltaVij()

            r_A = np.matmul(tmp_A.T,tmp_A)
            r_b = np.matmul(tmp_A.T,tmp_b)

            A[i_count*3:i_count*3+6,i_count*3:i_count*3+6] += r_A[0:6,0:6]
            b[i_count*3:i_count*3+6] += r_b[0:6]
            A[-4:,-4:] += r_A[-4:,-4:]
            b[-4:] += r_b[-4:]
            
            A[i_count*3:i_count*3+6,n_state-4:] += r_A[0:6,-4:]
            A[n_state-4:,i_count*3:i_count*3+6] += r_A[-4:,0:6]
            i_count += 1
        
        A = A * 1000.0
        b = b * 1000.0
        x = np.matmul(np.linalg.inv(A),b)
        s = x[n_state-1] / 100.0

        g = x[-4:-1]

        # RefineGravity
        g0 = g / np.linalg.norm(g) * 9.81
        lx = np.zeros(3)
        ly = np.zeros(3)
        n_state = all_frame_count * 3 + 2 + 1
        A = np.zeros([n_state,n_state])
        b = np.zeros(n_state)

        for k in range(4):
            aa = g / np.linalg.norm(g)
            tmp = np.array([.0,.0,1.0])

            bb = (tmp - np.dot(aa,tmp) * aa)
            bb /= np.linalg.norm(bb)
            cc = np.cross(aa,bb)
            bc = np.zeros([3,2])
            bc[0:3,0] = bb
            bc[0:3,1] = cc
            lxly = bc
            
            i_count = 0
            for i in range(t0,t1-1):
                pose_i = gtsam.Pose3(wTbs[i])
                pose_j = gtsam.Pose3(wTbs[i+1])
                R_i = pose_i.rotation().matrix()
                t_i = pose_i.translation()
                R_j = pose_j.rotation().matrix()
                t_j = pose_j.translation()
                tmp_A = np.zeros([6,9])
                tmp_b = np.zeros(6)
                pim = self.video.state.preintegrations[i]
                dt = pim.deltaTij()

                tmp_A[0:3,0:3] = -dt *np.eye(3,3)
                tmp_A[0:3,6:8] = np.matmul(R_i.T,lxly) * dt * dt /2 
                tmp_A[0:3,8]   = np.matmul(R_i.T,t_j - t_i) / 100.0
                tmp_b[0:3] = pim.deltaPij() - np.matmul(R_i.T,g0) * dt * dt / 2

                tmp_A[3:6,0:3] = -np.eye(3)
                tmp_A[3:6,3:6] = np.matmul(R_i.T,R_j)
                tmp_A[3:6,6:8] = np.matmul(R_i.T,lxly) * dt
                tmp_b[3:6] = pim.deltaVij() - np.matmul(R_i.T,g0) * dt

                r_A = np.matmul(tmp_A.T,tmp_A)
                r_b = np.matmul(tmp_A.T,tmp_b)

                A[i_count*3:i_count*3+6,i_count*3:i_count*3+6] += r_A[0:6,0:6]
                b[i_count*3:i_count*3+6] += r_b[0:6]
                A[-3:,-3:] += r_A[-3:,-3:]
                b[-3:] += r_b[-3:]

                A[i_count*3:i_count*3+6,n_state-3:] += r_A[0:6,-3:]
                A[n_state-3:,i_count*3:i_count*3+6] += r_A[-3:,0:6]
                i_count += 1
            
            A = A * 1000.0
            b = b * 1000.0
            x = np.matmul(np.linalg.inv(A),b)
            dg = x[-3:-1]
            g0 = g0 + np.matmul(lxly,dg)
            g0 = g0 / np.linalg.norm(g0) * 9.81
            s = x[-1] / 100.0
        print(s,g0,x)

        if disable_scale:
            s = 1.0
            
        print('g,s:',g,s)
        if math.fabs(np.linalg.norm(g) - 9.81) < 0.5 and s > 0:
            print('V-I successfully initialized!')
        
        # visualInitialAlign
        wTbs[:,0:3,3] *= s # !!!!!!!!!!!!!!!!!!!!!!!!
        for i in range(0, t1-t0):
            self.video.state.vs[i+t0] = np.matmul(wTbs[i+t0,0:3,0:3],x[i*3:i*3+3])
        
        # g2R
        ng1 = g0/ np.linalg.norm(g0)
        ng2 = np.array([0,0,1.0])
        R0 = trans.FromTwoVectors(ng1,ng2)
        yaw = trans.R2ypr(R0)[0]
        R0 = np.matmul(trans.ypr2R(np.array([-yaw,0,0])),R0)

        # align for visualization
        ppp =  np.matmul(R0,wTbs[t1-1,0:3,3])
        RRR =  np.matmul(R0,wTbs[t1-1,0:3,0:3])

        if self.all_gt is not None: # align the initial poses for visualization
            tt_found,dd = self.get_pose_ref(self.video.tstamp[t1-1]-1e-3)
            self.refTw = np.matmul(dd['T'],np.linalg.inv(wTbs[t1-1]))
            self.refTw[0:3,0:3] = trans.att2m([0,0,trans.m2att(self.refTw[0:3,0:3])[2]])

        g = np.matmul(R0,g0)
        for i in range(0,t1):
            wTbs[i,0:3,3] = np.matmul(R0,wTbs[i,0:3,3])
            wTbs[i,0:3,0:3] = np.matmul(R0,wTbs[i,0:3,0:3])
            self.video.state.vs[i] = np.matmul(R0, self.video.state.vs[i])
            self.video.state.wTbs[i] = gtsam.Pose3(wTbs[i])

        self.video.vi_init_t1 = t1
        self.video.vi_init_time = self.video.tstamp[t1-1]

        if not ignore_lever:
            wTcs = np.matmul(wTbs,self.video.Tbc.matrix())
        else:
            T_tmp = self.video.Tbc.matrix()
            T_tmp[0:3,3] = 0.0
            wTcs = np.matmul(wTbs,T_tmp)
    
        for i in range(0,t1):
            TTT = np.linalg.inv(wTcs[i])
            q = torch.tensor(Rotation.from_matrix(TTT[:3, :3]).as_quat())
            t = torch.tensor(TTT[:3,3])
            self.video.poses[i] = torch.cat([t,q])
            self.video.disps[i] /= s

    def __initialize(self):
        """ initialize the SLAM system """

        self.t0 = 0
        self.t1 = self.video.counter.value

        self.graph.add_neighborhood_factors(self.t0, self.t1, r=3)

        self.init_IMU()

        self.graph.video.imu_enabled = False
        for itr in range(8):
            self.graph.update(1, use_inactive=True)

        self.graph.add_proximity_factors(0, 0, rad=2, nms=2, thresh=self.frontend_thresh, remove=False)

        for itr in range(8):
            self.graph.update(1, use_inactive=True)

        self.graph.video.imu_enabled = False
        for itr in range(8):
            self.graph.update(1, use_inactive=True)
            
        # torch.concat([self.graph.ii[None],self.graph.jj[None]]).T
        # self.video.normalize()
        self.video.poses[self.t1] = self.video.poses[self.t1-1].clone()
        self.video.disps[self.t1] = self.video.disps[self.t1-4:self.t1].mean()
        
        # initialization complete
        self.is_initialized = True

        with self.video.get_lock():
            self.video.ready.value = 1
            self.video.dirty[:self.t1] = True

        self.graph.rm_factors(self.graph.ii < self.warmup-4, store=True)

    def __call__(self):
        """ main update """

        # do initialization
        if not self.is_initialized and self.video.counter.value == self.warmup:
            self.__initialize()
        # do update
        elif self.is_initialized and self.t1 < self.video.counter.value:
            self.__update()

        


================================================
FILE: dbaf/depth_video.py
================================================
import numpy as np
import torch
import lietorch
import droid_backends

from torch.multiprocessing import Process, Queue, Lock, Value

from droid_net import cvx_upsample
import geom.projective_ops as pops

from multi_sensor import MultiSensorState
import gtsam
from gtsam.symbol_shorthand import B, V, X
from scipy.spatial.transform import Rotation
import copy
import logging
import geoFunc.trans as trans
from lietorch import SE3

def BA2GTSAM(H: np.ndarray, v: np.ndarray, Tbc: gtsam.Pose3):
    A = -Tbc.inverse().AdjointMap()
    # A = -np.eye(6,6)
    A = np.concatenate([A[3:6,:],A[0:3,:]],axis=0)
    ss = H.shape[0]//6
    J = np.zeros_like(H)
    for i in range(ss):
       J[(i*6):(i*6+6),(i*6):(i*6+6)] = A
    JT = J.T
    return np.matmul(np.matmul(JT,H),J),np.matmul(JT,v)

def CustomHessianFactor(values: gtsam.Values, H: np.ndarray, v: np.ndarray):
    info_expand = np.zeros([H.shape[0]+1,H.shape[1]+1])
    info_expand[0:-1,0:-1] = H
    info_expand[0:-1,-1] = v
    info_expand[-1,-1] = 0.0 # This is meaningless.
    h_f = gtsam.HessianFactor(values.keys(),[6]*len(values.keys()),info_expand)
    l_c = gtsam.LinearContainerFactor(h_f,values)
    return l_c

class DepthVideo:
    def __init__(self, image_size=[480, 640], buffer=1024, save_pkl = False, stereo=False, upsample = False, device="cuda:0"):
                
        # current keyframe count
        self.counter = Value('i', 0)
        self.ready = Value('i', 0)
        self.ht = ht = image_size[0]
        self.wd = wd = image_size[1]

        ### state attributes ###
        self.tstamp = torch.zeros(buffer, device="cuda", dtype=torch.float64).share_memory_()
        self.images = torch.zeros(buffer, 3, ht, wd, device="cuda", dtype=torch.uint8)
        self.dirty = torch.zeros(buffer, device="cuda", dtype=torch.bool).share_memory_()
        self.red = torch.zeros(buffer, device="cuda", dtype=torch.bool).share_memory_()
        self.poses = torch.zeros(buffer, 7, device="cuda", dtype=torch.float).share_memory_()
        self.disps = torch.ones(buffer, ht//8, wd//8, device="cuda", dtype=torch.float).share_memory_()
        self.disps_sens = torch.zeros(buffer, ht//8, wd//8, device="cuda", dtype=torch.float).share_memory_()
        self.disps_up = torch.zeros(buffer, ht, wd, device="cuda", dtype=torch.float).share_memory_()
        self.intrinsics = torch.zeros(buffer, 4, device="cuda", dtype=torch.float).share_memory_()

        self.stereo = stereo
        c = 1 if not self.stereo else 2

        ### feature attributes ###
        self.fmaps = torch.zeros(buffer, c, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_()
        self.nets = torch.zeros(buffer, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_()
        self.inps = torch.zeros(buffer, 128, ht//8, wd//8, dtype=torch.half, device="cuda").share_memory_()

        # initialize poses to identity transformation
        self.poses[:] = torch.as_tensor([0, 0, 0, 0, 0, 0, 1], dtype=torch.float, device="cuda")
        
        ### DBAFusion
        # for .pkl saving
        self.disps_save = torch.ones(5000, ht//8, wd//8, device="cuda", dtype=torch.float)
        self.poses_save = torch.ones(5000, 7, device="cuda", dtype=torch.float)
        self.tstamp_save = torch.zeros(5000, device="cuda", dtype=torch.float64)
        self.images_save = torch.zeros(5000, ht//8, wd//8, 3, device="cuda", dtype=torch.float)
        if upsample:
            self.disps_up_save = torch.zeros(5000, ht, wd, device="cuda", dtype=torch.float).share_memory_()
        self.count_save = 0
        self.save_pkl = save_pkl
        self.upsample_flag = upsample

        self.state = MultiSensorState()
        self.last_t0 = 0
        self.last_t1 = 0
        self.cur_graph = None
        self.cur_result = None
        self.marg_factor = None
        self.prior_factor = []
        self.prior_factor_map = {}
        self.cur_ii = None
        self.cur_jj = None
        self.cur_target = None
        self.cur_weight = None
        self.cur_eta = None

        self.imu_enabled = False
        self.ignore_imu = False

        self.xyz_ref = []
        
        # extrinsics, need to be set in the main .py
        self.Ti1c = None  # shape = (4,4)
        self.Tbc = None   # gtsam.Pose3
        self.tbg = None   # shape = (3)

        self.reinit = False
        self.vi_init_t1 = -1
        self.vi_init_time = 0.0
        self.gnss_init_t1 = -1
        self.gnss_init_time = 0.0
        self.ten0 = None
        
        self.init_pose_sigma =np.array([0.1, 0.1, 0.0001, 0.0001,0.0001,0.0001])
        self.init_bias_sigma =np.array([1.0,1.0,1.0, 0.1, 0.1, 0.1])

        self.logger = logging.getLogger('dba_fusion')
        self.logger.setLevel(logging.DEBUG)
        fh = logging.FileHandler('dba_fusion.log')
        formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter)
        # add the handlers to the logger
        self.logger.addHandler(fh)
        self.logger.info('Start logging!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
        
    def get_lock(self):
        return self.counter.get_lock()

    def __item_setter(self, index, item):
        if isinstance(index, int) and index >= self.counter.value:
            self.counter.value = index + 1
        
        elif isinstance(index, torch.Tensor) and index.max().item() > self.counter.value:
            self.counter.value = index.max().item() + 1

        self.tstamp[index] = item[0]
        self.images[index] = item[1]

        if item[2] is not None:
            self.poses[index] = item[2]

        if item[3] is not None:
            self.disps[index] = item[3]

        if item[4] is not None:
            depth = item[4][3::8,3::8]
            self.disps_sens[index] = torch.where(depth>0, 1.0/depth, depth)

        if item[5] is not None:
            self.intrinsics[index] = item[5]

        if len(item) > 6:
            self.fmaps[index] = item[6]

        if len(item) > 7:
            self.nets[index] = item[7]

        if len(item) > 8:
            self.inps[index] = item[8]

    def __setitem__(self, index, item):
        with self.get_lock():
            self.__item_setter(index, item)

    def __getitem__(self, index):
        """ index the depth video """

        with self.get_lock():
            # support negative indexing
            if isinstance(index, int) and index < 0:
                index = self.counter.value + index

            item = (
                self.poses[index],
                self.disps[index],
                self.intrinsics[index],
                self.fmaps[index],
                self.nets[index],
                self.inps[index])

        return item

    def append(self, *item):
        with self.get_lock():
            self.__item_setter(self.counter.value, item)


    ### geometric operations ###

    @staticmethod
    def format_indicies(ii, jj):
        """ to device, long, {-1} """

        if not isinstance(ii, torch.Tensor):
            ii = torch.as_tensor(ii)

        if not isinstance(jj, torch.Tensor):
            jj = torch.as_tensor(jj)

        ii = ii.to(device="cuda", dtype=torch.long).reshape(-1)
        jj = jj.to(device="cuda", dtype=torch.long).reshape(-1)

        return ii, jj

    def upsample(self, ix, mask):
        """ upsample disparity """

        disps_up = cvx_upsample(self.disps[ix].unsqueeze(-1), mask)
        self.disps_up[ix] = disps_up.squeeze()

    def normalize(self):
        """ normalize depth and poses """

        with self.get_lock():
            s = self.disps[:self.counter.value].mean()
            self.disps[:self.counter.value] /= s
            self.poses[:self.counter.value,:3] *= s
            self.dirty[:self.counter.value] = True


    def reproject(self, ii, jj):
        """ project points from ii -> jj """
        ii, jj = DepthVideo.format_indicies(ii, jj)
        Gs = lietorch.SE3(self.poses[None])

        coords, valid_mask = \
            pops.projective_transform(Gs, self.disps[None], self.intrinsics[None], ii, jj)

        return coords, valid_mask
    
    def reproject_comp(self, ii, jj, xyz_comp):
        ii, jj = DepthVideo.format_indicies(ii,jj)
        Gs = lietorch.SE3(self.poses[None])

        coords, valid_mask = \
            pops.projective_transform_comp(Gs, self.disps[None], self.intrinsics[None], ii, jj, xyz_comp)

        return coords, valid_mask
    
    def distance(self, ii=None, jj=None, beta=0.3, bidirectional=True):
        """ frame distance metric """

        return_matrix = False
        if ii is None:
            return_matrix = True
            N = self.counter.value
            ii, jj = torch.meshgrid(torch.arange(N), torch.arange(N))
        
        ii, jj = DepthVideo.format_indicies(ii, jj)

        if bidirectional:

            poses = self.poses[:self.counter.value].clone()

            d1 = droid_backends.frame_distance(
                poses, self.disps, self.intrinsics[0], ii, jj, beta)

            d2 = droid_backends.frame_distance(
                poses, self.disps, self.intrinsics[0], jj, ii, beta)

            d = .5 * (d1 + d2)

        else:
            d = droid_backends.frame_distance(
                self.poses, self.disps, self.intrinsics[0], ii, jj, beta)

        if return_matrix:
            return d.reshape(N, N)

        return d

    def rm_new_gnss(self, t1):
        if (self.gnss_init_t1> 0 and self.state.gnss_valid[t1]) or self.state.odo_valid[t1]:
            graph_temp = gtsam.NonlinearFactorGraph()
            linear_point  = self.marg_factor.linearizationPoint()
            graph_temp.push_back(self.marg_factor)

            if self.state.gnss_valid[t1]:
                T1 = self.state.wTbs[t1]
                T0 = self.state.wTbs[t1-1]
                p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[t1] - self.ten0)
                n0pbg = self.state.wTbs[t1].rotation().rotate(self.tbg)
                p = p - n0pbg
                p = p - T1.translation() + T0.translation()
                if not linear_point.exists(X(t1-1)):
                    linear_point.insert(X(t1-1), self.cur_result.atPose3(X(t1-1)))
                gnss_factor = gtsam.GPSFactor(X(t1-1), p,\
                              gtsam.noiseModel.Robust.Create(\
                              gtsam.noiseModel.mEstimator.Cauchy(0.08),\
                  gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0]))))
                graph_temp.push_back(gnss_factor)
            if self.state.odo_valid[t1]:
                v1 = np.matmul(self.state.wTbs[t1].rotation().matrix().T, self.state.vs[t1])
                v0 = np.matmul(self.state.wTbs[t1-1].rotation().matrix().T, self.state.vs[t1-1])
                v = self.state.odo_vel[t1] - v1 + v0
                if not linear_point.exists(X(t1-1)):
                    linear_point.insert(X(t1-1), self.cur_result.atPose3(X(t1-1)))
                if not linear_point.exists(V(t1-1)):
                    linear_point.insert(V(t1-1), self.cur_result.atVector(V(t1-1)))
                odo_factor = gtsam.VelFactor(X(t1-1),V(t1-1),v,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0])))
                graph_temp.push_back(odo_factor)           
            
            h_factor = graph_temp.linearizeToHessianFactor(linear_point)
            self.marg_factor = gtsam.LinearContainerFactor(h_factor,linear_point)
            
    
    def set_prior(self, t0, t1):
        for i in range(t0,t0+2):
            self.prior_factor_map[i] = []
            init_pose_sigma = self.init_pose_sigma
            if len(self.init_pose_sigma.shape) > 1:
                init_pose_sigma = self.init_pose_sigma[i-t0]
            self.prior_factor_map[i].append(gtsam.PriorFactorPose3(X(i),\
                                         self.state.wTbs[i], \
                                         gtsam.noiseModel.Diagonal.Sigmas(init_pose_sigma)))
            if not self.ignore_imu:
                self.prior_factor_map[i].append(gtsam.PriorFactorConstantBias(B(i),\
                                             self.state.bs[i], \
                                             gtsam.noiseModel.Diagonal.Sigmas(self.init_bias_sigma)))
            self.last_t0 = t0
            self.last_t1 = t1

    def ba(self, target, weight, eta, ii, jj, t0=1, t1=None, itrs=2, lm=1e-4, ep=0.1, motion_only=False):
        """ dense bundle adjustment (DBA) """
        with self.get_lock():
            if t1 is None:
                t1 = max(ii.max().item(), jj.max().item()) + 1

            # 1) visual-only BA
            # 2) multi-sensor BA
            if not self.imu_enabled: 
                droid_backends.ba(self.poses, self.disps, self.intrinsics[0], self.disps_sens,
                    target, weight, eta, ii, jj, t0, t1, itrs, lm, ep, motion_only)
                for i in range(self.last_t0, min(ii.min().item(), jj.min().item())):
                    if self.save_pkl:
                        # save marginalized results
                        self.tstamp_save[self.count_save] = self.tstamp[i].clone()
                        self.disps_save[self.count_save] = self.disps[i].clone()
                        self.poses_save[self.count_save] = self.poses[i].clone()
                        if self.upsample_flag:
                            self.disps_up_save[self.count_save] = self.disps_up[i].clone()
                        self.images_save[self.count_save] = self.images[i,[2,1,0],::8,::8].permute(1,2,0) / 255.0 # might be "3::8, 3::8"?
                        self.count_save += 1

                self.last_t0 = min(ii.min().item(), jj.min().item())
                self.last_t1 = t1
            else:
                t0 = min(ii.min().item(), jj.min().item())

                """ marginalization """
                if self.last_t1!=t1 or self.last_t0 != t0:
                    if self.last_t0 > t0:
                        t0 = self.last_t0
                    elif self.last_t0 == t0:
                        t0 = self.last_t0
                    else:
                        marg_paras = []
                        # Construct a temporary factor graph (related to the old states) to obtain the marginalization information
                        graph = gtsam.NonlinearFactorGraph()
                        marg_idx = torch.logical_and(torch.greater_equal(self.cur_ii,self.last_t0),\
                                                    torch.less(self.cur_ii,t0))
                        marg_idx2 = torch.logical_and(torch.less(self.cur_ii,self.last_t1-2),\
                                                     torch.less(self.cur_jj,self.last_t1-2))
                        marg_idx = torch.logical_and(marg_idx,marg_idx2)

                        marg_ii = self.cur_ii[marg_idx]
                        marg_jj = self.cur_jj[marg_idx]
                        marg_t0 = self.last_t0 
                        marg_t1 = t0 + 1
                        if len(marg_ii) > 0:
                            marg_t0 = self.last_t0 
                            marg_t1 = torch.max(marg_jj).item()+1
                            marg_result = gtsam.Values()
                            for i in range(self.last_t0,marg_t1):
                                if i < t0:
                                    marg_paras.append(X(i))
                                    if self.save_pkl:
                                        # save marginalized results
                                        self.tstamp_save[self.count_save] = self.tstamp[i].clone()
                                        self.disps_save[self.count_save] = self.disps[i].clone()
                                        self.poses_save[self.count_save] = self.poses[i].clone()
                                        if self.upsample_flag:
                                            self.disps_up_save[self.count_save] = self.disps_up[i].clone()
                                        self.images_save[self.count_save] = self.images[i,[2,1,0],::8,::8].permute(1,2,0) / 255.0 # might be "3::8, 3::8"?
                                        self.count_save += 1
                                marg_result.insert(X(i), self.cur_result.atPose3(X(i)))
                                
                            marg_target = self.cur_target[marg_idx]
                            marg_weight = self.cur_weight[marg_idx]
                            marg_eta = self.cur_eta[0:marg_t1-marg_t0]
    
                            bacore = droid_backends.BACore()
                            bacore.init(self.poses, self.disps, self.intrinsics[0], torch.zeros_like(self.disps_sens),
                                marg_target, marg_weight, marg_eta, marg_ii, marg_jj, marg_t0, marg_t1, itrs, lm, ep, motion_only)
                            H = torch.zeros([(marg_t1-marg_t0)*6,(marg_t1-marg_t0)*6],dtype=torch.float64,device='cpu')
                            v = torch.zeros([(marg_t1-marg_t0)*6],dtype=torch.float64,device='cpu')
                            bacore.hessian(H,v)
                            
                            for i in range(6): H[i,i] += 0.00025  # for stability

                            # Hg,vg = BA2GTSAM(H,v,self.Tbc)
                            Hgg = gtsam.BA2GTSAM(H,v,self.Tbc)
                            Hg = Hgg[0:(marg_t1-marg_t0)*6,0:(marg_t1-marg_t0)*6]
                            vg = Hgg[0:(marg_t1-marg_t0)*6,  (marg_t1-marg_t0)*6]
                            vis_factor = CustomHessianFactor(marg_result,Hg,vg)
    
                            graph.push_back(vis_factor)

                        for i in range(self.last_t0,marg_t1):
                            if i < t0:
                                if X(i) not in marg_paras:
                                    marg_paras.append(X(i))
                                if not self.ignore_imu:
                                    marg_paras.append(V(i))
                                    marg_paras.append(B(i))
                                    graph.push_back(gtsam.gtsam.CombinedImuFactor(\
                                                X(i),V(i),X(i+1),V(i+1),B(i),B(i+1),\
                                                self.state.preintegrations[i]))
                                if self.gnss_init_t1 > 0:
                                    if self.state.gnss_valid[i]:
                                        p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[i] - self.ten0)
                                        n0pbg = self.state.wTbs[i].rotation().rotate(self.tbg)
                                        p = p - n0pbg
                                        gnss_factor = gtsam.GPSFactor(X(i), p,\
                                                      gtsam.noiseModel.Robust.Create(\
                                                      gtsam.noiseModel.mEstimator.Cauchy(0.08),\
                                          gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0]))))
                                        graph.push_back(gnss_factor)
                                if self.state.odo_valid[i]:
                                    vb = self.state.odo_vel[i]
                                    odo_factor = gtsam.VelFactor(X(i),V(i),vb,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0])))
                                    graph.push_back(odo_factor)
                        
                        keys = self.prior_factor_map.keys()
                        for i in sorted(keys):
                            if i < t0:
                                for iii in range(len(self.prior_factor_map[i])):
                                    graph.push_back(self.prior_factor_map[i][iii])
                            del self.prior_factor_map[i]
                        if not self.marg_factor == None:
                            graph.push_back(self.marg_factor)

                        self.marg_factor = gtsam.marginalizeOut(graph,self.cur_result,marg_paras)

                        # covariance inflation of IMU biases
                        if self.reinit == True:
                            all_keys = self.marg_factor.keys()
                            for i in range(len(all_keys)):
                                if all_keys[i] == B(t0):
                                    all_keys[i] = B(0)
                            graph = gtsam.NonlinearFactorGraph()
                            graph.push_back(self.marg_factor.rekey(all_keys))
                            b_l = gtsam.BetweenFactorConstantBias(B(0),B(t0),gtsam.imuBias.ConstantBias(np.array([.0,.0,.0]),np.array([.0,.0,.0])),\
                                                                  gtsam.noiseModel.Diagonal.Sigmas(self.init_bias_sigma))
                            graph.push_back(b_l)
                            result_tmp = self.marg_factor.linearizationPoint()
                            result_tmp.insert(B(0),result_tmp.atConstantBias(B(t0)))
                            self.marg_factor = gtsam.marginalizeOut(graph,result_tmp,[B(0)])
                            self.reinit = False

                    self.last_t0 = t0
                    self.last_t1 = t1

                """ optimization """
                H = torch.zeros([(t1-t0)*6,(t1-t0)*6],dtype=torch.float64,device='cpu')
                v = torch.zeros([(t1-t0)*6],dtype=torch.float64,device='cpu')
                dx = torch.zeros([(t1-t0)*6],dtype=torch.float64,device='cpu') 

                bacore = droid_backends.BACore()
                active_index    = torch.logical_and(ii>=t0,jj>=t0)
                self.cur_ii     = ii[active_index]
                self.cur_jj     = jj[active_index]
                self.cur_target = target[active_index]
                self.cur_weight = weight[active_index]
                self.cur_eta    = eta[(t0-ii.min().item()):]

                bacore.init(self.poses, self.disps, self.intrinsics[0], self.disps_sens,
                    self.cur_target, self.cur_weight, self.cur_eta, self.cur_ii, self.cur_jj, t0, t1, itrs, lm, ep, motion_only)

                self.cur_graph = gtsam.NonlinearFactorGraph()
                params = gtsam.LevenbergMarquardtParams()#;params.setMaxIterations(1)

                # imu factor
                if not self.ignore_imu:
                    for i in range(t0,t1):
                        if i > t0:
                            imu_factor = gtsam.gtsam.CombinedImuFactor(\
                                X(i-1),V(i-1),X(i),V(i),B(i-1),B(i),\
                                self.state.preintegrations[i-1])
                            self.cur_graph.add(imu_factor)

                # prior factor
                keys = self.prior_factor_map.keys()
                for i in sorted(keys):
                    if i >= t0 and i < t1:
                        for iii in range(len(self.prior_factor_map[i])):
                            self.cur_graph.push_back(self.prior_factor_map[i][iii])
                
                # marginalization factor
                if self.marg_factor is not None:
                    self.cur_graph.push_back(self.marg_factor)

                # GNSS factor
                if self.gnss_init_t1 > 0:
                    for i in range(t0,t1):
                        if self.state.gnss_valid[i]:
                            p = np.matmul(trans.Cen(self.ten0).T, self.state.gnss_position[i] - self.ten0)
                            n0pbg = self.state.wTbs[i].rotation().rotate(self.tbg)
                            p = p - n0pbg
                            gnss_factor = gtsam.GPSFactor(X(i), p,\
                                          gtsam.noiseModel.Robust.Create(\
                                                      gtsam.noiseModel.mEstimator.Cauchy(0.08),\
                                          gtsam.noiseModel.Diagonal.Sigmas(np.array([1.0,1.0,5.0]))))
                            self.cur_graph.push_back(gnss_factor)
                
                # Odo factor
                for i in range(t0,t1):
                    if self.state.odo_valid[i]:
                        vb = self.state.odo_vel[i]
                        odo_factor = gtsam.VelFactor(X(i),V(i),vb,gtsam.noiseModel.Diagonal.Sigmas(np.array([2.0,2.0,2.0])))
                        self.cur_graph.push_back(odo_factor)

                """ multi-sensor DBA iterations """
                for iter in range(2):
                    if iter > 0:
                        self.cur_graph.resize(self.cur_graph.size()-1)
                    bacore.hessian(H,v) # camera frame
                    Hgg = gtsam.BA2GTSAM(H,v,self.Tbc)
                    Hg = Hgg[0:(t1-t0)*6,0:(t1-t0)*6]
                    vg = Hgg[0:(t1-t0)*6,(t1-t0)*6]

                    initial = gtsam.Values()
                    for i in range(t0,t1):
                        initial.insert(X(i), self.state.wTbs[i]) # the indice need to be handled
                    initial_vis = copy.deepcopy(initial)
                    vis_factor = CustomHessianFactor(initial_vis,Hg,vg)
                    self.cur_graph.push_back(vis_factor)
                    
                    if not self.ignore_imu:
                        for i in range(t0,t1):
                            initial.insert(B(i),self.state.bs[i])
                            initial.insert(V(i),self.state.vs[i])

                    optimizer = gtsam.LevenbergMarquardtOptimizer(self.cur_graph, initial, params)
                    self.cur_result = optimizer.optimize()

                    # retraction and depth update
                    for i in range(t0,t1):
                        p0 = initial.atPose3(X(i))
                        p1 = self.cur_result.atPose3(X(i))
                        xi = gtsam.Pose3.Logmap(p0.inverse()*p1)
                        dx[(i-t0)*6:(i-t0)*6+6] = torch.tensor(xi)
                        if not self.ignore_imu:
                            self.state.bs[i] = self.cur_result.atConstantBias(B(i))
                            self.state.vs[i] = self.cur_result.atVector(V(i))
                        self.state.wTbs[i] = self.cur_result.atPose3(X(i))
                    dx = torch.tensor(gtsam.GTSAM2BA(dx,self.Tbc))
                    dx_dz = bacore.retract(dx)
                del bacore
            self.disps.clamp_(min=0.001)


================================================
FILE: dbaf/droid_net.py
================================================
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
from modules.extractor import BasicEncoder
from modules.corr import CorrBlock
from modules.gru import ConvGRU
from modules.clipping import GradientClip
from lietorch import SE3
from geom.ba import BA
import geom.projective_ops as pops
from geom.graph_utils import graph_to_edge_list, keyframe_indicies
from torch_scatter import scatter_mean
import time

def cvx_upsample(data, mask):
    """ upsample pixel-wise transformation field """
    batch, ht, wd, dim = data.shape
    data = data.permute(0, 3, 1, 2)
    mask = mask.view(batch, 1, 9, 8, 8, ht, wd)
    mask = torch.softmax(mask, dim=2)

    up_data = F.unfold(data, [3,3], padding=1)
    up_data = up_data.view(batch, dim, 9, 1, 1, ht, wd)

    up_data = torch.sum(mask * up_data, dim=2)
    up_data = up_data.permute(0, 4, 2, 5, 3, 1)
    up_data = up_data.reshape(batch, 8*ht, 8*wd, dim)

    return up_data

def upsample_disp(disp, mask):
    batch, num, ht, wd = disp.shape
    disp = disp.view(batch*num, ht, wd, 1)
    mask = mask.view(batch*num, -1, ht, wd)
    return cvx_upsample(disp, mask).view(batch, num, 8*ht, 8*wd)


class GraphAgg(nn.Module):
    def __init__(self):
        super(GraphAgg, self).__init__()
        self.conv1 = nn.Conv2d(128, 128, 3, padding=1)
        self.conv2 = nn.Conv2d(128, 128, 3, padding=1)
        self.relu = nn.ReLU(inplace=True)

        self.eta = nn.Sequential(
            nn.Conv2d(128, 1, 3, padding=1),
            GradientClip(),
            nn.Softplus())

        self.upmask = nn.Sequential(
            nn.Conv2d(128, 8*8*9, 1, padding=0))

    def forward(self, net, ii):
        batch, num, ch, ht, wd = net.shape
        net = net.view(batch*num, ch, ht, wd)

        _, ix = torch.unique(ii, return_inverse=True)
        net = self.relu(self.conv1(net))

        net = net.view(batch, num, 128, ht, wd)
        net = scatter_mean(net, ix, dim=1)
        net = net.view(-1, 128, ht, wd)

        net = self.relu(self.conv2(net))

        eta = self.eta(net).view(batch, -1, ht, wd)
        upmask = self.upmask(net).view(batch, -1, 8*8*9, ht, wd)

        return .01 * eta, upmask


class UpdateModule(nn.Module):
    def __init__(self):
        super(UpdateModule, self).__init__()
        cor_planes = 4 * (2*3 + 1)**2

        self.corr_encoder = nn.Sequential(
            nn.Conv2d(cor_planes, 128, 1, padding=0),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 128, 3, padding=1),
            nn.ReLU(inplace=True))

        self.flow_encoder = nn.Sequential(
            nn.Conv2d(4, 128, 7, padding=3),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 64, 3, padding=1),
            nn.ReLU(inplace=True))

        self.weight = nn.Sequential(
            nn.Conv2d(128, 128, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 2, 3, padding=1),
            GradientClip(),
            nn.Sigmoid())

        self.delta = nn.Sequential(
            nn.Conv2d(128, 128, 3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(128, 2, 3, padding=1),
            GradientClip())

        self.gru = ConvGRU(128, 128+128+64)
        self.agg = GraphAgg()

    def forward(self, net, inp, corr, flow=None, ii=None, jj=None, upsample = False):
        """ RaftSLAM update operator """
        batch, num, ch, ht, wd = net.shape
        if flow is None:
            flow = torch.zeros(batch, num, 4, ht, wd, device=net.device)

        output_dim = (batch, num, -1, ht, wd)
        net = net.view(batch*num, -1, ht, wd)
        inp = inp.view(batch*num, -1, ht, wd)
        corr = corr.view(batch*num, -1, ht, wd) 
        flow = flow.view(batch*num, -1, ht, wd) 

        corr = self.corr_encoder(corr)
        flow = self.flow_encoder(flow)
        net = self.gru(net, inp, corr, flow)

        ### update variables ###
        delta = self.delta(net).view(*output_dim)
        weight = self.weight(net).view(*output_dim)

        delta = delta.permute(0,1,3,4,2)[...,:2].contiguous()
        weight = weight.permute(0,1,3,4,2)[...,:2].contiguous()

        net = net.view(*output_dim)

        if ii is not None:
            ### ATTENTION!!!! ###
            # We found this useless for VIO performance, thus disable it to save computation.
            # Feel free to re-enable it.
            if upsample:
                eta, upmask = self.agg(net, ii.to(net.device))
                return net, delta, weight, eta, upmask
            else:
                return net, delta, weight, None, None
        else:
            return net, delta, weight


class DroidNet(nn.Module):
    def __init__(self):
        super(DroidNet, self).__init__()
        self.fnet = BasicEncoder(output_dim=128, norm_fn='instance')
        self.cnet = BasicEncoder(output_dim=256, norm_fn='none')
        self.update = UpdateModule()


    def extract_features(self, images):
        """ run feeature extraction networks """

        # normalize images
        images = images[:, :, [2,1,0]] / 255.0
        mean = torch.as_tensor([0.485, 0.456, 0.406], device=images.device)
        std = torch.as_tensor([0.229, 0.224, 0.225], device=images.device)
        images = images.sub_(mean[:, None, None]).div_(std[:, None, None])

        fmaps = self.fnet(images)
        net = self.cnet(images)
        
        net, inp = net.split([128,128], dim=2)
        net = torch.tanh(net)
        inp = torch.relu(inp)
        return fmaps, net, inp


    def forward(self, Gs, images, disps, intrinsics, graph=None, num_steps=12, fixedp=2):
        """ Estimates SE3 or Sim3 between pair of frames """

        u = keyframe_indicies(graph)
        ii, jj, kk = graph_to_edge_list(graph)

        ii = ii.to(device=images.device, dtype=torch.long)
        jj = jj.to(device=images.device, dtype=torch.long)

        fmaps, net, inp = self.extract_features(images)
        net, inp = net[:,ii], inp[:,ii]
        corr_fn = CorrBlock(fmaps[:,ii], fmaps[:,jj], num_levels=4, radius=3)

        ht, wd = images.shape[-2:]
        coords0 = pops.coords_grid(ht//8, wd//8, device=images.device)
        
        coords1, _ = pops.projective_transform(Gs, disps, intrinsics, ii, jj)
        target = coords1.clone()

        Gs_list, disp_list, residual_list = [], [], []
        for step in range(num_steps):
            Gs = Gs.detach()
            disps = disps.detach()
            coords1 = coords1.detach()
            target = target.detach()

            # extract motion features
            corr = corr_fn(coords1)
            resd = target - coords1
            flow = coords1 - coords0

            motion = torch.cat([flow, resd], dim=-1)
            motion = motion.permute(0,1,4,2,3).clamp(-64.0, 64.0)

            net, delta, weight, eta, upmask = \
                self.update(net, inp, corr, motion, ii, jj)

            target = coords1 + delta

            for i in range(2):
                Gs, disps = BA(target, weight, eta, Gs, disps, intrinsics, ii, jj, fixedp=2)

            coords1, valid_mask = pops.projective_transform(Gs, disps, intrinsics, ii, jj)
            residual = (target - coords1)

            Gs_list.append(Gs)
            disp_list.append(upsample_disp(disps, upmask))
            residual_list.append(valid_mask * residual)


        return Gs_list, disp_list, residual_list


================================================
FILE: dbaf/geoFunc/__init__.py
================================================


================================================
FILE: dbaf/geoFunc/const_value.py
================================================
import math

pi=math.pi
a = 6378137
finv = 298.257223563

================================================
FILE: dbaf/geoFunc/trans.py
================================================
import math
from math import atan2, sin, cos
from . import const_value
import numpy as np
from scipy.spatial.transform import Rotation

def cart2geod(Xinput):
    X=Xinput[0]
    Y=Xinput[1]
    Z=Xinput[2]

    tolsq = 1e-10
    maxit = 10

    rtd   = 180/const_value.pi

    esq = (2-1/const_value.finv) / const_value.finv
    
    oneesq = 1-esq
    P=math.sqrt(X*X+Y*Y)

    if P > 1e-20:
        dlambda = math.atan2(Y,X) *rtd
    else:
        dlambda = 0

    if dlambda <0:
        dlambda = dlambda +360
    
    r=math.sqrt(P*P+Z*Z)

    if r>1e-20:
        sinphi=Z/r
    else :
        sinphi=0
    
    dphi = math.asin(sinphi)

    if r<1e-20:
        h=0
        return
    
    h = r-const_value.a*(1-sinphi*sinphi/const_value.finv)

    for i in range(maxit):
        sinphi = math.sin(dphi)
        cosphi = math.cos(dphi)

        N_phi = const_value.a/math.sqrt(1-esq*sinphi*sinphi)

        dP =P -(N_phi+h)*cosphi
        dZ=Z-(N_phi*oneesq+h)*sinphi

        h=h+(sinphi*dZ+cosphi*dP)
        dphi =dphi+(cosphi*dZ - sinphi*dP)/(N_phi+h)

        if dP*dP + dZ*dZ<tolsq:
            break

        if i==maxit-1:
            print('sth. wrong in cart2geod.')

    dphi=dphi*rtd
    geod=[]
    geod.append(dphi)
    geod.append(dlambda)
    geod.append(h)
    # print(geod)
    return geod

def cart2enu(X, dx):
    
    dtr=const_value.pi/180

    geod = cart2geod(X)
    # print(geod)
    cl = math.cos(geod[1]*dtr)
    sl = math.sin(geod[1]*dtr)
    cb = math.cos(geod[0]*dtr)
    sb = math.sin(geod[0]*dtr)

    east = -sl*   dx[0] +cl*   dx[1]+0
    north= -sb*cl*dx[0] -sb*sl*dx[1]+cb*dx[2]
    up   =  cb*cl*dx[0] +cb*sl*dx[1]+sb*dx[2]

    enu=[]
    enu.append(east)
    enu.append(north)
    enu.append(up)
    return enu

def enu2cart(X, enu):
    
    dtr=const_value.pi/180

    geod = cart2geod(X)
    # print(geod)
    cl = math.cos(geod[1]*dtr)
    sl = math.sin(geod[1]*dtr)
    cb = math.cos(geod[0]*dtr)
    sb = math.sin(geod[0]*dtr)

    #east = -sl*   dx[0] +cl*   dx[1]+0
    #north= -sb*cl*dx[0] -sb*sl*dx[1]+cb*dx[2]
    #up   =  cb*cl*dx[0] +cb*sl*dx[1]+sb*dx[2]

    dx0 = -sl*enu[0]-sb*cl*enu[1]+cb*cl*enu[2]
    dx1 =  cl*enu[0]-sb*sl*enu[1]+cb*sl*enu[2]
    dx2 =          0+   cb*enu[1]+   sb*enu[2]

    dx=[]
    dx.append(dx0)
    dx.append(dx1)
    dx.append(dx2)
    return dx

def hhmmss2sec(hhmmss):
    elem = hhmmss.split(':')
    sec = float(elem[0])*3600+float(elem[1])*60+float(elem[2])
    return sec

def Cen(X):
    dtr=const_value.pi/180

    geod = cart2geod(X)
    # print(geod)
    cl = math.cos(geod[1]*dtr)
    sl = math.sin(geod[1]*dtr)
    cb = math.cos(geod[0]*dtr)
    sb = math.sin(geod[0]*dtr)

    M = np.array([[-sl,cl,0],[-sb*cl,-sb*sl,cb],[cb*cl,cb*sl,sb]]).T
    return M

def rad2deg(l):
    ll = []
    for i in range(len(l)):
        ll.append(l[i]*180/math.pi)
    return ll

def deg2rad(l):
    ll = []
    for i in range(len(l)):
        ll.append(l[i]/180*math.pi)
    return ll

def m2att(R):
    att=[0,0,0]

    att[0] = math.asin(R[2, 1])
    att[1] = math.atan2(-R[2, 0], R[2, 2])
    att[2] = math.atan2(-R[0, 1], R[1, 1])

    return att

def att2m(att):
    sp = math.sin(att[0])
    cp=math.cos(att[0])
    sr = math.sin(att[1])
    cr =math.cos(att[1])
    sy=math.sin(att[2])
    cy= math.cos(att[2])
    R=np.array([[cy*cr - sy*sp*sr, -sy*cp, cy*sr + sy*sp*cr],\
        [sy*cr + cy*sp*sr, cy*cp, sy*sr - cy*sp*cr],\
            [-cp*sr, sp, cp*cr]])
    return R

def q2att(qnb):
    q0 = qnb[0]
    q1 = qnb[1]
    q2 = qnb[2]
    q3 = qnb[3]
    q11 = q0*q0
    q12 = q0*q1
    q13 = q0*q2
    q14 = q0*q3
    q22 = q1*q1
    q23 = q1*q2
    q24 = q1*q3
    q33 = q2*q2
    q34 = q2*q3
    q44 = q3*q3

    att=[0,0,0]
    att[0] = math.asin(2 * (q34 + q12))
    att[1] = math.atan2(-2 * (q24 - q13), q11 - q22 - q33 + q44)
    att[2] = math.atan2(-2 * (q23 - q14), q11 - q22 + q33 - q44)
    return att

def q2R(qnb):
    return att2m(q2att(qnb))

def alignRt(xyz0,xyz1):
    if len(xyz0)!=len(xyz1):
        raise Exception()
    N = len(xyz0)
    p1 = np.array([0.0,0.0,0.0])
    p2 = np.array([0.0,0.0,0.0])
    for i in range(N):
        p1 += np.array(xyz0[i])
        p2 += np.array(xyz1[i])
    p1 /= N
    p2 /= N

    W = np.zeros([3,3])
    for j in range(N):
        q1 = np.array(xyz0[j]) - p1
        q2 = np.array(xyz1[j]) - p2
        W += np.matmul(q1.reshape(3,1),q2.reshape(1,3))
    U, sigma, VT = np.linalg.svd(W)
    R= np.matmul(U,VT)
    t=p1-np.matmul(R,p2)
    return R,t

def R2ypr(R):
    n = R[0]
    o = R[1]
    a = R[2]

    y = atan2(n[1], n[0])
    p = atan2(-n[2], n[0] * cos(y) + n[1] * sin(y))
    r = atan2(a[0] * sin(y) - a[1] * cos(y), -o[0] * sin(y) + o[1] * cos(y))
    return np.array([y,p,r])

def ypr2R(ypr):
    y = ypr[0]
    p = ypr[1]
    r = ypr[2]

    Rz = np.array([[cos(y),-sin(y),0],[sin(y),cos(y),0],[0,0,1]])
    Ry = np.array([[cos(p),0,sin(p)],[0,1,0],[-sin(p),0,cos(p)]])
    Rx = np.array([[1,0,0],[0,cos(r),-sin(r)],[0,sin(r),cos(r)]])
        
    return np.matmul(np.matmul(Rz,Ry),Rx)

def FromTwoVectors(a,b):
    v0 = a/np.linalg.norm(a)
    v1 = b/np.linalg.norm(b)
    c = np.dot(v1,v0)
    axis = np.cross(v0,v1)
    s = math.sqrt((1+c)*2)
    invs = 1/s
    vec = axis*invs
    w = s* 0.5
    return Rotation.from_quat(np.array([vec[0],vec[1],vec[2],w])).as_matrix()




================================================
FILE: dbaf/geom/__init__.py
================================================


================================================
FILE: dbaf/geom/ba.py
================================================
import lietorch
import torch
import torch.nn.functional as F

from .chol import block_solve, schur_solve
import geom.projective_ops as pops
from torch_scatter import scatter_sum

# utility functions for scattering ops
def safe_scatter_add_mat(A, ii, jj, n, m):
    v = (ii >= 0) & (jj >= 0) & (ii < n) & (jj < m)
    return scatter_sum(A[:,v], ii[v]*m + jj[v], dim=1, dim_size=n*m)

def safe_scatter_add_vec(b, ii, n):
    v = (ii >= 0) & (ii < n)
    return scatter_sum(b[:,v], ii[v], dim=1, dim_size=n)

# apply retraction operator to inv-depth maps
def disp_retr(disps, dz, ii):
    ii = ii.to(device=dz.device)
    return disps + scatter_sum(dz, ii, dim=1, dim_size=disps.shape[1])

# apply retraction operator to poses
def pose_retr(poses, dx, ii):
    ii = ii.to(device=dx.device)
    return poses.retr(scatter_sum(dx, ii, dim=1, dim_size=poses.shape[1]))


def BA(target, weight, eta, poses, disps, intrinsics, ii, jj, fixedp=1, rig=1):
    """ Full Bundle Adjustment """

    B, P, ht, wd = disps.shape
    N = ii.shape[0]
    D = poses.manifold_dim

    ### 1: commput
Download .txt
gitextract_ny3kcvri/

├── .gitignore
├── .gitmodules
├── LICENSE
├── README.md
├── batch_kitti360.py
├── batch_subt.py
├── batch_tumvi.py
├── batch_whu.py
├── calib/
│   ├── 0412.txt
│   ├── 0412new.txt
│   ├── 1012.txt
│   ├── barn.txt
│   ├── carla.txt
│   ├── eth.txt
│   ├── euroc.txt
│   ├── handheld.txt
│   ├── kitti_360.txt
│   ├── subt.txt
│   ├── tartan.txt
│   ├── tum3.txt
│   └── tumvi.txt
├── dataset/
│   ├── euroc_to_hdf5.py
│   ├── kitti360_to_hdf5.py
│   └── tumvi_to_hdf5.py
├── dbaf/
│   ├── covisible_graph.py
│   ├── data_readers/
│   │   ├── __init__.py
│   │   ├── augmentation.py
│   │   ├── base.py
│   │   ├── factory.py
│   │   ├── rgbd_utils.py
│   │   ├── stream.py
│   │   ├── tartan.py
│   │   └── tartan_test.txt
│   ├── dbaf.py
│   ├── dbaf_frontend.py
│   ├── depth_video.py
│   ├── droid_net.py
│   ├── geoFunc/
│   │   ├── __init__.py
│   │   ├── const_value.py
│   │   └── trans.py
│   ├── geom/
│   │   ├── __init__.py
│   │   ├── ba.py
│   │   ├── chol.py
│   │   ├── graph_utils.py
│   │   ├── losses.py
│   │   └── projective_ops.py
│   ├── modules/
│   │   ├── __init__.py
│   │   ├── clipping.py
│   │   ├── corr.py
│   │   ├── extractor.py
│   │   └── gru.py
│   ├── motion_filter.py
│   └── multi_sensor.py
├── demo_vio_kitti360.py
├── demo_vio_subt.py
├── demo_vio_tumvi.py
├── demo_vio_whu.py
├── evaluation_scripts/
│   ├── batch_tumvi.py
│   ├── evaluate_kitti.py
│   └── evaluate_tumvi.py
├── results/
│   └── PLACEHOLDER
├── setup.py
├── src/
│   ├── altcorr_kernel.cu
│   ├── bacore.h
│   ├── correlation_kernels.cu
│   ├── droid.cpp
│   └── droid_kernels.cu
└── visualization/
    ├── check_reconstruction_kitti.py
    ├── check_reconstruction_kitti_animation.py
    ├── check_reconstruction_tumvi.py
    └── check_reconstruction_tumvi_animation.py
Download .txt
SYMBOL INDEX (260 symbols across 38 files)

FILE: dataset/euroc_to_hdf5.py
  function show_image (line 11) | def show_image(image):
  function image_stream (line 16) | def image_stream(imagedir, imagestamp, h5path, calib, stride):

FILE: dataset/kitti360_to_hdf5.py
  function show_image (line 11) | def show_image(image):
  function image_stream (line 16) | def image_stream(imagedir, imagestamp, h5path, calib, stride):

FILE: dataset/tumvi_to_hdf5.py
  function show_image (line 11) | def show_image(image):
  function image_stream (line 16) | def image_stream(imagedir, imagestamp, h5path, calib, stride):

FILE: dbaf/covisible_graph.py
  class CovisibleGraph (line 15) | class CovisibleGraph:
    method __init__ (line 16) | def __init__(self, video: DepthVideo, update_op, device="cuda:0", corr...
    method __filter_repeated_edges (line 61) | def __filter_repeated_edges(self, ii, jj):
    method print_edges (line 74) | def print_edges(self):
    method filter_edges (line 88) | def filter_edges(self):
    method clear_edges (line 97) | def clear_edges(self):
    method add_factors (line 103) | def add_factors(self, ii, jj, remove=False):
    method rm_factors (line 152) | def rm_factors(self, mask, store=False):
    method rm_keyframe (line 180) | def rm_keyframe(self, ix):
    method update (line 214) | def update(self, t0=None, t1=None, itrs=2, use_inactive=False, EP=1e-7...
    method add_neighborhood_factors (line 344) | def add_neighborhood_factors(self, t0, t1, r=3):
    method add_proximity_factors (line 357) | def add_proximity_factors(self, t0=0, t1=0, rad=2, nms=2, beta=0.25, t...

FILE: dbaf/data_readers/augmentation.py
  class RGBDAugmentor (line 7) | class RGBDAugmentor:
    method __init__ (line 10) | def __init__(self, crop_size):
    method spatial_transform (line 20) | def spatial_transform(self, images, depths, poses, intrinsics):
    method color_transform (line 49) | def color_transform(self, images):
    method __call__ (line 56) | def __call__(self, images, poses, depths, intrinsics):

FILE: dbaf/data_readers/base.py
  class RGBDDataset (line 19) | class RGBDDataset(data.Dataset):
    method __init__ (line 20) | def __init__(self, name, datapath, n_frames=4, crop_size=[384,512], fm...
    method _build_dataset_index (line 50) | def _build_dataset_index(self):
    method image_read (line 62) | def image_read(image_file):
    method depth_read (line 66) | def depth_read(depth_file):
    method build_frame_graph (line 69) | def build_frame_graph(self, poses, depths, intrinsics, f=16, max_flow=...
    method __getitem__ (line 94) | def __getitem__(self, index):
    method __len__ (line 152) | def __len__(self):
    method __imul__ (line 155) | def __imul__(self, x):

FILE: dbaf/data_readers/factory.py
  function dataset_factory (line 17) | def dataset_factory(dataset_list, **kwargs):
  function create_datastream (line 34) | def create_datastream(dataset_path, **kwargs):
  function create_imagestream (line 62) | def create_imagestream(dataset_path, **kwargs):
  function create_stereostream (line 69) | def create_stereostream(dataset_path, **kwargs):
  function create_rgbdstream (line 76) | def create_rgbdstream(dataset_path, **kwargs):

FILE: dbaf/data_readers/rgbd_utils.py
  function parse_list (line 11) | def parse_list(filepath, skiprows=0):
  function associate_frames (line 16) | def associate_frames(tstamp_image, tstamp_depth, tstamp_pose, max_dt=1.0):
  function loadtum (line 35) | def loadtum(datapath, frame_rate=-1):
  function all_pairs_distance_matrix (line 91) | def all_pairs_distance_matrix(poses, beta=2.5):
  function pose_matrix_to_quaternion (line 100) | def pose_matrix_to_quaternion(pose):
  function compute_distance_matrix_flow (line 105) | def compute_distance_matrix_flow(poses, disps, intrinsics):
  function compute_distance_matrix_flow2 (line 145) | def compute_distance_matrix_flow2(poses, disps, intrinsics, beta=0.4):

FILE: dbaf/data_readers/stream.py
  class RGBDStream (line 18) | class RGBDStream(data.Dataset):
    method __init__ (line 19) | def __init__(self, datapath, frame_rate=-1, image_size=[384,512], crop...
    method image_read (line 27) | def image_read(image_file):
    method depth_read (line 31) | def depth_read(depth_file):
    method __len__ (line 34) | def __len__(self):
    method __getitem__ (line 37) | def __getitem__(self, index):
  class ImageStream (line 75) | class ImageStream(data.Dataset):
    method __init__ (line 76) | def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512]):
    method __len__ (line 93) | def __len__(self):
    method image_read (line 97) | def image_read(imfile):
    method __getitem__ (line 100) | def __getitem__(self, index):
  class StereoStream (line 127) | class StereoStream(data.Dataset):
    method __init__ (line 128) | def __init__(self, datapath, intrinsics, rate=1, image_size=[384,512],
    method __len__ (line 150) | def __len__(self):
    method image_read (line 154) | def image_read(imfile, imap=None):
    method __getitem__ (line 160) | def __getitem__(self, index):

FILE: dbaf/data_readers/tartan.py
  class TartanAir (line 18) | class TartanAir(RGBDDataset):
    method __init__ (line 23) | def __init__(self, mode='training', **kwargs):
    method is_test_scene (line 29) | def is_test_scene(scene):
    method _build_dataset (line 33) | def _build_dataset(self):
    method calib_read (line 58) | def calib_read():
    method image_read (line 62) | def image_read(image_file):
    method depth_read (line 66) | def depth_read(depth_file):
  class TartanAirStream (line 73) | class TartanAirStream(RGBDStream):
    method __init__ (line 74) | def __init__(self, datapath, **kwargs):
    method _build_dataset_index (line 77) | def _build_dataset_index(self):
    method calib_read (line 100) | def calib_read(datapath):
    method image_read (line 104) | def image_read(image_file):
  class TartanAirTestStream (line 108) | class TartanAirTestStream(RGBDStream):
    method __init__ (line 109) | def __init__(self, datapath, **kwargs):
    method _build_dataset_index (line 112) | def _build_dataset_index(self):
    method calib_read (line 133) | def calib_read(datapath):
    method image_read (line 137) | def image_read(image_file):

FILE: dbaf/dbaf.py
  class DBAFusion (line 16) | class DBAFusion:
    method __init__ (line 17) | def __init__(self, args):
    method load_weights (line 34) | def load_weights(self, weights):
    method track (line 50) | def track(self, tstamp, image, depth=None, intrinsics=None):
    method terminate (line 60) | def terminate(self, stream=None):
    method save_vis_easy (line 64) | def save_vis_easy(self):

FILE: dbaf/dbaf_frontend.py
  class DBAFusionFrontend (line 16) | class DBAFusionFrontend:
    method __init__ (line 17) | def __init__(self, net, video, args):
    method get_pose_ref (line 85) | def get_pose_ref(self, tt:float):
    method __rollup (line 89) | def __rollup(self, roll):
    method __update (line 153) | def __update(self):
    method init_IMU (line 377) | def init_IMU(self):
    method init_VI (line 434) | def init_VI(self):
    method init_GNSS (line 517) | def init_GNSS(self):
    method VisualIMUAlignment (line 606) | def VisualIMUAlignment(self, t0, t1, ignore_lever, disable_scale = Fal...
    method __initialize (line 816) | def __initialize(self):
    method __call__ (line 853) | def __call__(self):

FILE: dbaf/depth_video.py
  function BA2GTSAM (line 20) | def BA2GTSAM(H: np.ndarray, v: np.ndarray, Tbc: gtsam.Pose3):
  function CustomHessianFactor (line 31) | def CustomHessianFactor(values: gtsam.Values, H: np.ndarray, v: np.ndarr...
  class DepthVideo (line 40) | class DepthVideo:
    method __init__ (line 41) | def __init__(self, image_size=[480, 640], buffer=1024, save_pkl = Fals...
    method get_lock (line 126) | def get_lock(self):
    method __item_setter (line 129) | def __item_setter(self, index, item):
    method __setitem__ (line 161) | def __setitem__(self, index, item):
    method __getitem__ (line 165) | def __getitem__(self, index):
    method append (line 183) | def append(self, *item):
    method format_indicies (line 191) | def format_indicies(ii, jj):
    method upsample (line 205) | def upsample(self, ix, mask):
    method normalize (line 211) | def normalize(self):
    method reproject (line 221) | def reproject(self, ii, jj):
    method reproject_comp (line 231) | def reproject_comp(self, ii, jj, xyz_comp):
    method distance (line 240) | def distance(self, ii=None, jj=None, beta=0.3, bidirectional=True):
    method rm_new_gnss (line 272) | def rm_new_gnss(self, t1):
    method set_prior (line 307) | def set_prior(self, t0, t1):
    method ba (line 323) | def ba(self, target, weight, eta, ii, jj, t0=1, t1=None, itrs=2, lm=1e...

FILE: dbaf/droid_net.py
  function cvx_upsample (line 17) | def cvx_upsample(data, mask):
  function upsample_disp (line 33) | def upsample_disp(disp, mask):
  class GraphAgg (line 40) | class GraphAgg(nn.Module):
    method __init__ (line 41) | def __init__(self):
    method forward (line 55) | def forward(self, net, ii):
  class UpdateModule (line 74) | class UpdateModule(nn.Module):
    method __init__ (line 75) | def __init__(self):
    method forward (line 107) | def forward(self, net, inp, corr, flow=None, ii=None, jj=None, upsampl...
  class DroidNet (line 145) | class DroidNet(nn.Module):
    method __init__ (line 146) | def __init__(self):
    method extract_features (line 153) | def extract_features(self, images):
    method forward (line 171) | def forward(self, Gs, images, disps, intrinsics, graph=None, num_steps...

FILE: dbaf/geoFunc/trans.py
  function cart2geod (line 7) | def cart2geod(Xinput):
  function cart2enu (line 71) | def cart2enu(X, dx):
  function enu2cart (line 92) | def enu2cart(X, enu):
  function hhmmss2sec (line 117) | def hhmmss2sec(hhmmss):
  function Cen (line 122) | def Cen(X):
  function rad2deg (line 135) | def rad2deg(l):
  function deg2rad (line 141) | def deg2rad(l):
  function m2att (line 147) | def m2att(R):
  function att2m (line 156) | def att2m(att):
  function q2att (line 168) | def q2att(qnb):
  function q2R (line 190) | def q2R(qnb):
  function alignRt (line 193) | def alignRt(xyz0,xyz1):
  function R2ypr (line 215) | def R2ypr(R):
  function ypr2R (line 225) | def ypr2R(ypr):
  function FromTwoVectors (line 236) | def FromTwoVectors(a,b):

FILE: dbaf/geom/ba.py
  function safe_scatter_add_mat (line 10) | def safe_scatter_add_mat(A, ii, jj, n, m):
  function safe_scatter_add_vec (line 14) | def safe_scatter_add_vec(b, ii, n):
  function disp_retr (line 19) | def disp_retr(disps, dz, ii):
  function pose_retr (line 24) | def pose_retr(poses, dx, ii):
  function BA (line 29) | def BA(target, weight, eta, poses, disps, intrinsics, ii, jj, fixedp=1, ...
  function MoBA (line 107) | def MoBA(target, weight, eta, poses, disps, intrinsics, ii, jj, fixedp=1...

FILE: dbaf/geom/chol.py
  class CholeskySolver (line 5) | class CholeskySolver(torch.autograd.Function):
    method forward (line 7) | def forward(ctx, H, b):
    method backward (line 22) | def backward(ctx, grad_x):
  function block_solve (line 32) | def block_solve(H, b, ep=0.1, lm=0.0001):
  function schur_solve (line 46) | def schur_solve(H, E, C, v, w, ep=0.1, lm=0.0001, sless=False):

FILE: dbaf/geom/graph_utils.py
  function graph_to_edge_list (line 10) | def graph_to_edge_list(graph):
  function keyframe_indicies (line 23) | def keyframe_indicies(graph):
  function meshgrid (line 26) | def meshgrid(m, n, device='cuda'):
  function neighbourhood_graph (line 30) | def neighbourhood_graph(n, r):
  function build_frame_graph (line 37) | def build_frame_graph(poses, disps, intrinsics, num=16, thresh=24.0, r=2):
  function build_frame_graph_v2 (line 72) | def build_frame_graph_v2(poses, disps, intrinsics, num=16, thresh=24.0, ...

FILE: dbaf/geom/losses.py
  function pose_metrics (line 9) | def pose_metrics(dE):
  function fit_scale (line 21) | def fit_scale(Ps, Gs):
  function geodesic_loss (line 30) | def geodesic_loss(Ps, Gs, graph, gamma=0.9, do_scale=True):
  function residual_loss (line 77) | def residual_loss(residuals, gamma=0.9):
  function flow_loss (line 89) | def flow_loss(Ps, disps, poses_est, disps_est, intrinsics, graph, gamma=...

FILE: dbaf/geom/projective_ops.py
  function extract_intrinsics (line 8) | def extract_intrinsics(intrinsics):
  function coords_grid (line 11) | def coords_grid(ht, wd, **kwargs):
  function iproj (line 18) | def iproj(disps, intrinsics, jacobian=False):
  function proj (line 39) | def proj(Xs, intrinsics, jacobian=False, return_depth=False):
  function actp (line 67) | def actp(Gij, X0, jacobian=False):
  function projective_transform (line 96) | def projective_transform(poses, depths, intrinsics, ii, jj, jacobian=Fal...
  function projective_transform_comp (line 127) | def projective_transform_comp(poses, depths, intrinsics, ii, jj, xyz_com...
  function induced_flow (line 160) | def induced_flow(poses, disps, intrinsics, ii, jj):

FILE: dbaf/modules/clipping.py
  class GradClip (line 7) | class GradClip(torch.autograd.Function):
    method forward (line 9) | def forward(ctx, x):
    method backward (line 13) | def backward(ctx, grad_x):
  class GradientClip (line 19) | class GradientClip(nn.Module):
    method __init__ (line 20) | def __init__(self):
    method forward (line 23) | def forward(self, x):

FILE: dbaf/modules/corr.py
  class CorrSampler (line 6) | class CorrSampler(torch.autograd.Function):
    method forward (line 9) | def forward(ctx, volume, coords, radius):
    method backward (line 16) | def backward(ctx, grad_output):
  class CorrBlock (line 23) | class CorrBlock:
    method __init__ (line 24) | def __init__(self, fmap1, fmap2, num_levels=4, radius=3):
    method __call__ (line 40) | def __call__(self, coords):
    method cat (line 52) | def cat(self, other):
    method __getitem__ (line 57) | def __getitem__(self, index):
    method corr (line 64) | def corr(fmap1, fmap2):
  class CorrLayer (line 74) | class CorrLayer(torch.autograd.Function):
    method forward (line 76) | def forward(ctx, fmap1, fmap2, coords, r):
    method backward (line 83) | def backward(ctx, grad_corr):
  class AltCorrBlock (line 91) | class AltCorrBlock:
    method __init__ (line 92) | def __init__(self, fmaps, num_levels=4, radius=3):
    method corr_fn (line 106) | def corr_fn(self, coords, ii, jj):
    method __call__ (line 128) | def __call__(self, coords, ii, jj):

FILE: dbaf/modules/extractor.py
  class ResidualBlock (line 6) | class ResidualBlock(nn.Module):
    method __init__ (line 7) | def __init__(self, in_planes, planes, norm_fn='group', stride=1):
    method forward (line 47) | def forward(self, x):
  class BottleneckBlock (line 58) | class BottleneckBlock(nn.Module):
    method __init__ (line 59) | def __init__(self, in_planes, planes, norm_fn='group', stride=1):
    method forward (line 104) | def forward(self, x):
  class BasicEncoder (line 118) | class BasicEncoder(nn.Module):
    method __init__ (line 119) | def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0, multi...
    method _make_layer (line 175) | def _make_layer(self, dim, stride=1):
    method forward (line 183) | def forward(self, x):

FILE: dbaf/modules/gru.py
  class ConvGRU (line 5) | class ConvGRU(nn.Module):
    method __init__ (line 6) | def __init__(self, h_planes=128, i_planes=128):
    method forward (line 19) | def forward(self, net, *inputs):

FILE: dbaf/motion_filter.py
  class MotionFilter (line 12) | class MotionFilter:
    method __init__ (line 15) | def __init__(self, net, video, thresh=2.5, device="cuda:0"):
    method __context_encoder (line 33) | def __context_encoder(self, image):
    method context_encoder (line 39) | def context_encoder(self, image):
    method __feature_encoder (line 45) | def __feature_encoder(self, image):
    method feature_encoder (line 50) | def feature_encoder(self, image):
    method track (line 56) | def track(self, tstamp, image, depth=None, intrinsics=None):

FILE: dbaf/multi_sensor.py
  class MultiSensorState (line 7) | class MultiSensorState:
    method __init__ (line 8) | def __init__(self):
    method set_imu_params (line 32) | def set_imu_params(self, noise = None):
    method init_first_state (line 71) | def init_first_state(self,t,pos,R,vel):
    method append_imu (line 86) | def append_imu(self, t, measuredAcc, measuredOmega):
    method append_imu_temp (line 105) | def append_imu_temp(self, t, measuredAcc, measuredOmega, predict_pose ...
    method append_img (line 114) | def append_img(self, t):
    method append_gnss (line 138) | def append_gnss(self,t,pos):
    method append_odo (line 145) | def append_odo(self,t,vel):
    method predict (line 152) | def predict(self):

FILE: demo_vio_kitti360.py
  function show_image (line 20) | def show_image(image):
  function image_stream (line 25) | def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride):

FILE: demo_vio_subt.py
  function show_image (line 19) | def show_image(image):
  function image_stream (line 24) | def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride):

FILE: demo_vio_tumvi.py
  function show_image (line 19) | def show_image(image):
  function image_stream (line 24) | def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride):

FILE: demo_vio_whu.py
  function show_image (line 19) | def show_image(image):
  function image_stream (line 24) | def image_stream(imagedir, imagestamp, enable_h5, h5path, calib, stride):

FILE: evaluation_scripts/evaluate_kitti.py
  function ape (line 25) | def ape(traj_ref: PosePath3D, traj_est: PosePath3D,

FILE: evaluation_scripts/evaluate_tumvi.py
  function ape (line 43) | def ape(traj_ref: PosePath3D, traj_est: PosePath3D,

FILE: src/bacore.h
  function class (line 4) | class BACore

FILE: src/droid.cpp
  function ba (line 109) | std::vector<torch::Tensor> ba(
  function ba_extend (line 140) | std::vector<torch::Tensor> ba_extend(
  function frame_distance (line 181) | torch::Tensor frame_distance(
  function projmap (line 200) | std::vector<torch::Tensor> projmap(
  function iproj (line 218) | torch::Tensor iproj(
  function corr_index_forward (line 231) | std::vector<torch::Tensor> corr_index_forward(
  function corr_index_backward (line 241) | std::vector<torch::Tensor> corr_index_backward(
  function altcorr_forward (line 254) | std::vector<torch::Tensor> altcorr_forward(
  function altcorr_backward (line 266) | std::vector<torch::Tensor> altcorr_backward(
  function depth_filter (line 281) | torch::Tensor depth_filter(
  function PYBIND11_MODULE (line 297) | PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {

FILE: visualization/check_reconstruction_kitti.py
  function create_camera_actor (line 24) | def create_camera_actor(g, scale=0.05):
  function create_point_actor (line 34) | def create_point_actor(points, colors):
  function str2array (line 44) | def str2array(ss):
  function key_action_callback (line 62) | def key_action_callback(vis, action, mods):
  function save_callback (line 70) | def save_callback(vis, action, mods):

FILE: visualization/check_reconstruction_kitti_animation.py
  function create_camera_actor (line 25) | def create_camera_actor(g, scale=0.05):
  function create_point_actor (line 35) | def create_point_actor(points, colors):
  function str2array (line 45) | def str2array(ss):
  function key_action_callback (line 63) | def key_action_callback(vis, action, mods):

FILE: visualization/check_reconstruction_tumvi.py
  function create_camera_actor (line 24) | def create_camera_actor(g, scale=0.05):
  function create_point_actor (line 34) | def create_point_actor(points, colors):
  function str2array (line 44) | def str2array(ss):
  function key_action_callback (line 63) | def key_action_callback(vis, action, mods):

FILE: visualization/check_reconstruction_tumvi_animation.py
  function create_camera_actor (line 25) | def create_camera_actor(g, scale=0.05):
  function create_point_actor (line 35) | def create_point_actor(points, colors):
  function str2array (line 45) | def str2array(ss):
  function key_action_callback (line 63) | def key_action_callback(vis, action, mods):
Condensed preview — 71 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (404K chars).
[
  {
    "path": ".gitignore",
    "chars": 2158,
    "preview": "a# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packag"
  },
  {
    "path": ".gitmodules",
    "chars": 211,
    "preview": "[submodule \"thirdparty/lietorch\"]\n\tpath = thirdparty/lietorch\n\turl = https://github.com/princeton-vl/lietorch\n[submodule"
  },
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 8162,
    "preview": "# DBA-Fusion\n\n>Tightly Integrating Deep Dense Visual Bundle Adjustment with Multiple Sensors for Large-Scale  Localizati"
  },
  {
    "path": "batch_kitti360.py",
    "chars": 1123,
    "preview": "import os\nimport subprocess\n\nfor i in ['0000','0002','0003','0004','0005','0006','0009','0010']:\n    p = subprocess.Pope"
  },
  {
    "path": "batch_subt.py",
    "chars": 846,
    "preview": "import os\nimport subprocess\n\nfor i in [\\\n    # 'Handheld1_Folder',\\\n    'Handheld2_Folder',\\\n      ]:\n    p = subprocess"
  },
  {
    "path": "batch_tumvi.py",
    "chars": 1267,
    "preview": "import os\nimport subprocess\n\nfor i in [\\\n    'outdoors1',\\\n    'outdoors2',\\\n    'outdoors3',\\\n    'outdoors4',\\\n    'ou"
  },
  {
    "path": "batch_whu.py",
    "chars": 2782,
    "preview": "import os\nimport subprocess\n\n# VIO\np = subprocess.Popen(\"python demo_vio_whu.py\" +\\\n    \" --imagedir=/home/zhouyuxuan/da"
  },
  {
    "path": "calib/0412.txt",
    "chars": 51,
    "preview": "889.32868436 889.32868436 515.73648834 202.43873596"
  },
  {
    "path": "calib/0412new.txt",
    "chars": 83,
    "preview": "885.839465 882.512623 505.509972 389.860117 -0.125551 0.065179 -0.000074 -0.000698\n"
  },
  {
    "path": "calib/1012.txt",
    "chars": 97,
    "preview": "890.21388839 889.56330572 512.88196119 381.38486858 -0.13095809 0.06640391 -0.00094794 0.0003389\n"
  },
  {
    "path": "calib/barn.txt",
    "chars": 67,
    "preview": "1161.545689 1161.545689 960.000000 540.000000 -0.025158 0.0 0.0 0.0"
  },
  {
    "path": "calib/carla.txt",
    "chars": 25,
    "preview": "886.8100 886.8100 512 256"
  },
  {
    "path": "calib/eth.txt",
    "chars": 62,
    "preview": "726.21081542969 726.21081542969 359.2048034668 202.47247314453"
  },
  {
    "path": "calib/euroc.txt",
    "chars": 80,
    "preview": "458.654 457.296 367.215 248.375 -0.28340811 0.07395907 0.00019359 1.76187114e-05"
  },
  {
    "path": "calib/handheld.txt",
    "chars": 155,
    "preview": "531.0895358407821 530.9183032386885 511.3708876141611 399.1276554093305 -0.3367182787437319 0.10679061024072911 0.000305"
  },
  {
    "path": "calib/kitti_360.txt",
    "chars": 91,
    "preview": "788.629315 786.382230 687.158398 317.752196 -0.344441 0.141678 0.000414 -0.000222 -0.029608"
  },
  {
    "path": "calib/subt.txt",
    "chars": 177,
    "preview": "758.3153257832925 676.6492212772476 318.27111164892506 239.79816832491474 1.583106303248484 -0.059098218173967695 0.1793"
  },
  {
    "path": "calib/tartan.txt",
    "chars": 23,
    "preview": "320.0 320.0 320.0 240.0"
  },
  {
    "path": "calib/tum3.txt",
    "chars": 23,
    "preview": "535.4 539.2 320.1 247.6"
  },
  {
    "path": "calib/tumvi.txt",
    "chars": 163,
    "preview": "190.97847715128717 190.9733070521226 254.93170605935475 256.8974428996504 0.0034823894022493434 0.0007150348452162257 -0"
  },
  {
    "path": "dataset/euroc_to_hdf5.py",
    "chars": 2685,
    "preview": "from tqdm import tqdm\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport argparse\n\nimport h5py\nimport pickle\n\nd"
  },
  {
    "path": "dataset/kitti360_to_hdf5.py",
    "chars": 2489,
    "preview": "from tqdm import tqdm\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport argparse\n\nimport h5py\nimport pickle\n\nd"
  },
  {
    "path": "dataset/tumvi_to_hdf5.py",
    "chars": 2671,
    "preview": "from tqdm import tqdm\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport argparse\n\nimport h5py\nimport pickle\n\nd"
  },
  {
    "path": "dbaf/covisible_graph.py",
    "chars": 18019,
    "preview": "import torch\nimport lietorch\nimport numpy as np\n\nimport matplotlib.pyplot as plt\nfrom lietorch import SE3\nfrom modules.c"
  },
  {
    "path": "dbaf/data_readers/__init__.py",
    "chars": 1,
    "preview": "\n"
  },
  {
    "path": "dbaf/data_readers/augmentation.py",
    "chars": 2243,
    "preview": "import torch\nimport torchvision.transforms as transforms\nimport numpy as np\nimport torch.nn.functional as F\n\n\nclass RGBD"
  },
  {
    "path": "dbaf/data_readers/base.py",
    "chars": 5181,
    "preview": "\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport torch.nn.functional as F\n\nimport csv\nimport os\ni"
  },
  {
    "path": "dbaf/data_readers/factory.py",
    "chars": 2458,
    "preview": "\nimport pickle\nimport os\nimport os.path as osp\n\n# RGBD-Dataset\nfrom .tartan import TartanAir\n\nfrom .stream import ImageS"
  },
  {
    "path": "dbaf/data_readers/rgbd_utils.py",
    "chars": 6453,
    "preview": "import numpy as np\nimport os.path as osp\n\nimport torch\nfrom lietorch import SE3\n\nimport geom.projective_ops as pops\nfrom"
  },
  {
    "path": "dbaf/data_readers/stream.py",
    "chars": 7658,
    "preview": "\nimport numpy as np\nimport torch\nimport torch.utils.data as data\nimport torch.nn.functional as F\n\nimport csv\nimport os\ni"
  },
  {
    "path": "dbaf/data_readers/tartan.py",
    "chars": 4468,
    "preview": "\nimport numpy as np\nimport torch\nimport glob\nimport cv2\nimport os\nimport os.path as osp\n\nfrom lietorch import SE3\nfrom ."
  },
  {
    "path": "dbaf/data_readers/tartan_test.txt",
    "chars": 1098,
    "preview": "abandonedfactory/abandonedfactory/Easy/P011\nabandonedfactory/abandonedfactory/Hard/P011\nabandonedfactory_night/abandoned"
  },
  {
    "path": "dbaf/dbaf.py",
    "chars": 6167,
    "preview": "import torch\nimport lietorch\nimport numpy as np\nfrom droid_net import DroidNet\nfrom depth_video import DepthVideo\nfrom m"
  },
  {
    "path": "dbaf/dbaf_frontend.py",
    "chars": 39895,
    "preview": "import torch\nimport torchvision\nimport numpy as np\n\nfrom lietorch import SE3, SO3\nfrom covisible_graph import CovisibleG"
  },
  {
    "path": "dbaf/depth_video.py",
    "chars": 26297,
    "preview": "import numpy as np\nimport torch\nimport lietorch\nimport droid_backends\n\nfrom torch.multiprocessing import Process, Queue,"
  },
  {
    "path": "dbaf/droid_net.py",
    "chars": 7399,
    "preview": "import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom collections import OrderedDic"
  },
  {
    "path": "dbaf/geoFunc/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "dbaf/geoFunc/const_value.py",
    "chars": 60,
    "preview": "import math\r\n\r\npi=math.pi\r\na = 6378137\r\nfinv = 298.257223563"
  },
  {
    "path": "dbaf/geoFunc/trans.py",
    "chars": 5595,
    "preview": "import math\r\nfrom math import atan2, sin, cos\r\nfrom . import const_value\r\nimport numpy as np\r\nfrom scipy.spatial.transfo"
  },
  {
    "path": "dbaf/geom/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "dbaf/geom/ba.py",
    "chars": 4687,
    "preview": "import lietorch\nimport torch\nimport torch.nn.functional as F\n\nfrom .chol import block_solve, schur_solve\nimport geom.pro"
  },
  {
    "path": "dbaf/geom/chol.py",
    "chars": 1827,
    "preview": "import torch\nimport torch.nn.functional as F\nimport geom.projective_ops as pops\n\nclass CholeskySolver(torch.autograd.Fun"
  },
  {
    "path": "dbaf/geom/graph_utils.py",
    "chars": 2860,
    "preview": "\nimport torch\nimport numpy as np\nfrom collections import OrderedDict\n\nimport lietorch\nfrom data_readers.rgbd_utils impor"
  },
  {
    "path": "dbaf/geom/losses.py",
    "chars": 3262,
    "preview": "from collections import OrderedDict\nimport numpy as np\nimport torch\nfrom lietorch import SO3, SE3, Sim3\nfrom .graph_util"
  },
  {
    "path": "dbaf/geom/projective_ops.py",
    "chars": 5069,
    "preview": "import torch\nimport torch.nn.functional as F\n\nfrom lietorch import SE3, Sim3\n\nMIN_DEPTH = 0.2\n\ndef extract_intrinsics(in"
  },
  {
    "path": "dbaf/modules/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "dbaf/modules/clipping.py",
    "chars": 580,
    "preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nGRAD_CLIP = .01\n\nclass GradClip(torch.autograd.Funct"
  },
  {
    "path": "dbaf/modules/corr.py",
    "chars": 4671,
    "preview": "import torch\nimport torch.nn.functional as F\n\nimport droid_backends\n\nclass CorrSampler(torch.autograd.Function):\n\n    @s"
  },
  {
    "path": "dbaf/modules/extractor.py",
    "chars": 6798,
    "preview": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass ResidualBlock(nn.Module):\n    def __init__(se"
  },
  {
    "path": "dbaf/modules/gru.py",
    "chars": 1276,
    "preview": "import torch\nimport torch.nn as nn\n\n\nclass ConvGRU(nn.Module):\n    def __init__(self, h_planes=128, i_planes=128):\n     "
  },
  {
    "path": "dbaf/motion_filter.py",
    "chars": 3549,
    "preview": "import cv2\nimport torch\nimport lietorch\n\nfrom collections import OrderedDict\nfrom droid_net import DroidNet\n\nimport geom"
  },
  {
    "path": "dbaf/multi_sensor.py",
    "chars": 6752,
    "preview": "import numpy as np\nimport gtsam\nimport math\n\nGRAVITY = 9.807\n\nclass MultiSensorState:\n    def __init__(self):\n        se"
  },
  {
    "path": "demo_vio_kitti360.py",
    "chars": 8837,
    "preview": "import sys\nsys.path.append('dbaf')\nsys.path.append('dbaf/geoFunc')\n\nfrom tqdm import tqdm\nimport numpy as np\nimport torc"
  },
  {
    "path": "demo_vio_subt.py",
    "chars": 9320,
    "preview": "import sys\nsys.path.append('dbaf')\n\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport ar"
  },
  {
    "path": "demo_vio_tumvi.py",
    "chars": 9190,
    "preview": "import sys\nsys.path.append('dbaf')\n\nfrom tqdm import tqdm\nimport numpy as np\nimport torch\nimport cv2\nimport os\nimport ar"
  },
  {
    "path": "demo_vio_whu.py",
    "chars": 10060,
    "preview": "import sys\nsys.path.append('dbaf')\nsys.path.append('dbaf/geoFunc')\nfrom tqdm import tqdm\nimport numpy as np\nimport torch"
  },
  {
    "path": "evaluation_scripts/batch_tumvi.py",
    "chars": 362,
    "preview": "import subprocess\n\nfor seq in ['magistrale1','magistrale2','magistrale3','magistrale4','magistrale5','magistrale6',\\\n   "
  },
  {
    "path": "evaluation_scripts/evaluate_kitti.py",
    "chars": 8766,
    "preview": "import argparse\nimport logging\nimport typing\n\nimport numpy as np\n\nimport evo.common_ape_rpe as common\nfrom evo.core impo"
  },
  {
    "path": "evaluation_scripts/evaluate_tumvi.py",
    "chars": 7923,
    "preview": "import argparse\nimport logging\nimport typing\n\nimport numpy as np\n\nimport evo.common_ape_rpe as common\nfrom evo.core impo"
  },
  {
    "path": "results/PLACEHOLDER",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "setup.py",
    "chars": 2220,
    "preview": "from setuptools import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\nimport os.path as osp\n"
  },
  {
    "path": "src/altcorr_kernel.cu",
    "chars": 11307,
    "preview": "#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n#include <cuda_fp16.h>\n#inclu"
  },
  {
    "path": "src/bacore.h",
    "chars": 1513,
    "preview": "#include <torch/extension.h>\n#include <vector>\n\nclass BACore\n{\npublic:\n  BACore(){}\n  ~BACore(){}\npublic:\n  void init(to"
  },
  {
    "path": "src/correlation_kernels.cu",
    "chars": 5216,
    "preview": "#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n#include <cuda_fp16.h>\n#inclu"
  },
  {
    "path": "src/droid.cpp",
    "chars": 7503,
    "preview": "#include <torch/extension.h>\n#include <vector>\n\n#include \"bacore.h\"\n\n// CUDA forward declarations\nstd::vector<torch::Ten"
  },
  {
    "path": "src/droid_kernels.cu",
    "chars": 56217,
    "preview": "#include <torch/extension.h>\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <cuda_runtime.h>\n\n#include <vector>\n#i"
  },
  {
    "path": "visualization/check_reconstruction_kitti.py",
    "chars": 3051,
    "preview": "import numpy as np\nimport cv2\nimport open3d as o3d\nimport matplotlib.pyplot as plt\nfrom lietorch import SO3, SE3, Sim3\nf"
  },
  {
    "path": "visualization/check_reconstruction_kitti_animation.py",
    "chars": 3399,
    "preview": "import numpy as np\nimport cv2\nimport open3d as o3d\nimport matplotlib.pyplot as plt\nfrom lietorch import SO3, SE3, Sim3\nf"
  },
  {
    "path": "visualization/check_reconstruction_tumvi.py",
    "chars": 3024,
    "preview": "import numpy as np\nimport cv2\nimport open3d as o3d\nimport matplotlib.pyplot as plt\nfrom lietorch import SO3, SE3, Sim3\nf"
  },
  {
    "path": "visualization/check_reconstruction_tumvi_animation.py",
    "chars": 3915,
    "preview": "import numpy as np\nimport cv2\nimport open3d as o3d\nimport matplotlib.pyplot as plt\nfrom lietorch import SO3, SE3, Sim3\nf"
  }
]

About this extraction

This page contains the full source code of the GREAT-WHU/DBA-Fusion GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 71 files (377.7 KB), approximately 112.5k tokens, and a symbol index with 260 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!