[
  {
    "path": ".gitignore",
    "content": "*.so\n*.egg-info/\n*.pyc\nbuild/\nlibs/\n.idea/\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "config/dagr-l-dsec.yaml",
    "content": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\ndataset: dsec\n\n# network\nradius: 0.01\ntime_window_us: 1000000\nmax_neighbors: 16\nn_nodes: 50000\n\nbatch_size: 64\n\nactivation: relu\nedge_attr_dim: 2\naggr: sum\nkernel_size: 5\npooling_aggr: max\n\nbase_width: 0.5\nafter_pool_width: 1\nnet_stem_width: 1\nyolo_stem_width: 1\nnum_scales: 2\n\n# learning\nweight_decay: 0.00001\nclip: 0.1\n\npooling_dim_at_output: 5x7\n\naug_trans: 0.1\naug_zoom: 1.5\naug_p_flip: 0.5\n\nimg_net: resnet18\n\nl_r: 0.0002\ntot_num_epochs: 801\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "config/dagr-l-ncaltech.yaml",
    "content": "path: \"/data/storage/daniel/aegnn\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\npooling_dim_at_output: 5x7\n\ntask: detection\ndataset: ncaltech101\n\n# network\nradius: 0.01\ntime_window_us: 1000000\nmax_neighbors: 16\nn_nodes: 50000\n\nbatch_size: 64\n\nactivation: relu\nedge_attr_dim: 2\naggr: sum\nkernel_size: 5\npooling_aggr: max\n\nbase_width: 0.5\nafter_pool_width: 1\nnet_stem_width: 1\nyolo_stem_width: 1\nnum_scales: 1\n\n# learning\nweight_decay: 0.00001\nclip: 0.1\n\naug_trans: 0.1\naug_p_flip: 0\naug_zoom: 1\nl_r: 0.001\ntot_num_epochs: 801"
  },
  {
    "path": "config/dagr-m-dsec.yaml",
    "content": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\ndataset: dsec\n\n# network\nradius: 0.01\ntime_window_us: 1000000\nmax_neighbors: 16\nn_nodes: 50000\n\nbatch_size: 64\n\nactivation: relu\nedge_attr_dim: 2\naggr: sum\nkernel_size: 5\npooling_aggr: max\n\nbase_width: 0.5\nafter_pool_width: 1\nnet_stem_width: 0.75\nyolo_stem_width: 0.75\nnum_scales: 2\n\n# learning\nweight_decay: 0.00001\nclip: 0.1\n\npooling_dim_at_output: 5x7\n\naug_trans: 0.1\naug_zoom: 1.5\naug_p_flip: 0.5\n\nimg_net: resnet18\n\nl_r: 0.0002\ntot_num_epochs: 801\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "config/dagr-n-dsec.yaml",
    "content": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\ndataset: dsec\n\n# network\nradius: 0.01\ntime_window_us: 1000000\nmax_neighbors: 16\nn_nodes: 50000\n\nbatch_size: 64\n\nactivation: relu\nedge_attr_dim: 2\naggr: sum\nkernel_size: 5\npooling_aggr: max\n\nbase_width: 0.5\nafter_pool_width: 1\nnet_stem_width: 0.25\nyolo_stem_width: 0.25\nnum_scales: 2\n\n# learning\nweight_decay: 0.00001\nclip: 0.1\n\npooling_dim_at_output: 5x7\n\naug_trans: 0.1\naug_zoom: 1.5\naug_p_flip: 0.5\n\nimg_net: resnet18\n\nl_r: 0.0002\ntot_num_epochs: 801\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "config/dagr-s-dsec.yaml",
    "content": "dataset_directory: \"/data/storage/daniel/aegnn/\"\noutput_directory: \"/data/storage/daniel/aegnn/logs\"\n\ntask: detection\ndataset: dsec\n\n# network\nradius: 0.01\ntime_window_us: 1000000\nmax_neighbors: 16\nn_nodes: 50000\n\nbatch_size: 64\n\nactivation: relu\nedge_attr_dim: 2\naggr: sum\nkernel_size: 5\npooling_aggr: max\n\nbase_width: 0.5\nafter_pool_width: 1\nnet_stem_width: 0.5\nyolo_stem_width: 0.5\nnum_scales: 2\n\n# learning\nweight_decay: 0.00001\nclip: 0.1\n\npooling_dim_at_output: 5x7\n\naug_trans: 0.1\naug_zoom: 1.5\naug_p_flip: 0.5\n\nimg_net: resnet18\n\nl_r: 0.0002\ntot_num_epochs: 801\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
  },
  {
    "path": "download_and_install_dependencies.sh",
    "content": "#! /usr/bin/env bash\nDAGR_DIR=$(pwd)\n\n# Download detectron2 for its fast mAP calculation function\nmkdir $DAGR_DIR/libs\ncd $DAGR_DIR/libs\ngit clone --no-checkout git@github.com:facebookresearch/detectron2.git\ncd $DAGR_DIR/libs/detectron2/\ngit checkout 32bd159d7263683e39bf4e87e5c4ac88bad2fd73\n\n# Download YOLOX\ncd $DAGR_DIR/libs\ngit clone --no-checkout git@github.com:Megvii-BaseDetection/YOLOX.git\ncd $DAGR_DIR/libs/YOLOX\ngit checkout 618fd8c08b2bc5fac9ffbb19a3b7e039ea0d5b9a\n\n# Download dsec-det\ncd $DAGR_DIR/libs\ngit clone git@github.com:uzh-rpg/dsec-det.git\ncd $DAGR_DIR/libs/dsec-det\ngit checkout 81e381dc0fc1b1a540a604a970a37de038abb83b\n\npip install -e $DAGR_DIR/libs/dsec-det\npip install -e $DAGR_DIR/libs/detectron2\npip install -e $DAGR_DIR/libs/YOLOX\npip install seaborn\n"
  },
  {
    "path": "download_example_data.sh",
    "content": "#! /usr/bin/env bash\nDAGR_DIR=$(pwd)\nDATA_DIR=$DAGR_DIR/data\n\nmkdir $DATA_DIR\nwget https://download.ifi.uzh.ch/rpg/dagr/data/dagr_s_50.pth -O $DATA_DIR/dagr_s_50.pth\n\nwget https://download.ifi.uzh.ch/rpg/dagr/data/DSEC_fragment.zip -O $DATA_DIR/DSEC_fragment.zip\nunzip $DATA_DIR/DSEC_fragment.zip -d $DATA_DIR\nrm -rf $DATA_DIR/DSEC_fragment.zip"
  },
  {
    "path": "install_env.sh",
    "content": "#! /usr/bin/env bash\n\nTORCH=$(python -c \"import torch; print(torch.__version__)\")\nCUDA=$(python -c \"import torch; print(torch.version.cuda)\")\nURL=https://data.pyg.org/whl/torch-${TORCH}+${CUDA}.html\n\npip install --no-cache-dir torch-scatter -f $URL;\npip install --no-cache-dir torch-cluster -f $URL;\npip install --no-cache-dir torch-spline-conv -f $URL;\npip install --no-cache-dir torch-sparse -f $URL;\npip install torch-geometric;\npip install wandb numba hdf5plugin plotly matplotlib pycocotools opencv-python scikit-video pandas ruamel.yaml\n"
  },
  {
    "path": "readme.md",
    "content": "# Low Latency Automotive Vision with Event Cameras\n\n<p align=\"center\">\n<a href=\"https://youtu.be/dwzGhMQCc4Y\">\n  <img src=\"assets/Nature_Gehrig_YouTube_cover_yt.jpg\" alt=\"DAGR\" width=\"500\"/>\n</a>\n</p>\n\nThis repository contains code from our 2024 Nature paper which can be accessed for free here [PDF Open Access](https://www.nature.com/articles/s41586-024-07409-w).\n**_Low Latency Automotive Vision with Event Cameras_** by [Daniel Gehrig](https://danielgehrig18.github.io/) and [Davide Scaramuzza](http://rpg.ifi.uzh.ch/people_scaramuzza.html). \nIf you use our code or refer to this project, please cite it using\n\n```bibtex\n@Article{Gehrig24nature,\n  author    = {Gehrig, Daniel and Scaramuzza, Davide},\n  title     = {Low Latency Automotive Vision with Event Cameras},\n  booktitle = {Nature},\n  year      = {2024}\n}\n```\n\n## Updates \n* Training code for N-Caltech101 and DSEC-DET have been open sourced. To train your model jump to the [training section](#training)\n\n## Installation\nFirst, download the github repository and its dependencies\n```bash\nWORK_DIR=/path/to/work/directory/\ncd $WORK_DIR\ngit clone git@github.com:uzh-rpg/dagr.git\nDAGR_DIR=$WORK_DIR/dagr\n\ncd $DAGR_DIR \n\n```\nThen start by installing the main libraries. Make sure Anaconda (or better Mamba), PyTorch, and CUDA is installed. \n```bash\ncd $DAGR_DIR\nconda create -y -n dagr python=3.8 \nconda activate dagr\nconda install -y setuptools==69.5.1 mkl==2024.0 pytorch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0 cudatoolkit=11.3 -c pytorch\n```\nThen install the pytorch-geometric libraries. This may take a while.\n```bash\nbash install_env.sh\n```\nThe above bash file will figure out the CUDA and Torch version, and install the appropriate pytorch-geometric packages.\nThen, download and install additional dependencies locally \n```bash\nbash download_and_install_dependencies.sh\nconda install -y h5py blosc-hdf5-plugin\n```\nFinally, install the dagr package\n```bash\npip install -e .\n```\n\n## Run Example\nAfter installing, you can download a data fragment, and checkpoint with \n```bash\nbash download_example_data.sh\n```\nThis will download a checkpoint and data fragment of DSEC-Detection on which you can test the code. \nOnce downloaded, run the following command\n```bash \nLOG_DIR=/path/to/log\nDEVICE=1\nCUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test_interframe.py --config config/dagr-s-dsec.yaml \\\n                                                                   --use_image \\\n                                                                   --img_net resnet50 \\\n                                                                   --checkpoint data/dagr_s_50.pth \\\n                                                                   --batch_size 8 \\\n                                                                   --dataset_directory data/DSEC_fragment \\\n                                                                   --no_eval \\                                                        \n                                                                   --output_directory $LOG_DIR\n```\nnote the wandb directory as `$WANDB_DIR` and then visualize the detections with \n```bash\npython scripts/visualize_detections.py --detections_folder $LOG_DIR/$WANDB_DIR \\\n                                       --dataset_directory data/DSEC_fragment/test \\\n                                       --vis_time_step_us 1000 \\ \n                                       --event_time_window_us 5000 \\\n                                       --sequence zurich_city_13_b\n```\n\n## Test on DSEC\nStart by downloading the DSEC dataset and the additional labelled data introduced in this work. \nTo do so, follow [these instructions](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec). They are based on the scripts \nof [dsec-det](https://github.com/uzh-rpg/dsec-det), which can be found in `libs/dsec-det/scripts`.\nTo continue, complete sections [Download DSEC](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec) until [Test Alignment](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#test-alignment). \nIf you already downloaded DSEC, make sure `$DSEC_ROOT` points to it, and instead start at section [Download DSEC-extra\n](https://github.com/uzh-rpg/dsec-det?tab=readme-ov-file#download-dsec-extra).  \n\nAfter downloading all the data, change back to $DAGR_DIR, and start by downsampling the events \n```bash\ncd $DAGR_DIR\nbash scripts/downsample_all_events.sh $DSEC_ROOT\n```\n\n### Running Evaluation\nThis repository implements three scripts for running evaluation of the model on DSEC-Det. \nThe first, evaluates the detection performance of the model after seeing one image, and the subsequent 50 milliseconds of events.\nTo run it, specify a device, and logging directory with  type \n```bash \nLOG_DIR=/path/to/log\nDEVICE=1\nCUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test.py --config config/dagr-s-dsec.yaml \\\n                                                        --use_image \\\n                                                        --img_net resnet50 \\\n                                                        --checkpoint data/dagr_s_50.pth \\\n                                                        --batch_size 8 \\\n                                                        --dataset_directory $DSEC_ROOT \\\n                                                        --output_directory $LOG_DIR\n```\nThen, to evaluate the number of FLOPS generated in asynchronous mode, run \n```bash \nLOG_DIR=/path/to/log\nDEVICE=1\nCUDA_VISIBLE_DEVICES=$DEVICE python scripts/count_flops.py --config config/eagr-s-dsec.yaml \\\n                                                           --use_image \\\n                                                           --img_net resnet50 \\\n                                                           --checkpoint data/dagr_s_50.pth \\\n                                                           --batch_size 8 \\\n                                                           --dataset_directory $DSEC_ROOT \\\n                                                           --output_directory $LOG_DIR\n```\nFinally, to evaluate the interframe detection performance of our method run\n```bash\nLOG_DIR=/path/to/log\nDEVICE=1\nCUDA_VISIBLE_DEVICES=$DEVICE python scripts/run_test_interframe.py --config config/eagr-s-dsec.yaml \\\n                                                                   --use_image \\\n                                                                   --img_net resnet50 \\\n                                                                   --checkpoint data/dagr_s_50.pth \\\n                                                                   --batch_size 8 \\\n                                                                   --dataset_directory $DSEC_ROOT \\\n                                                                   --output_directory $LOG_DIR \\\n                                                                   --num_interframe_steps 10\n```\nThis last script will write the high-rate detections from our method into the folder `$LOG_DIR/$WANDB_DIR`, \nwhere `$WANDB_DIR` is the automatically generated folder created by wandb. \nTo visualize the detections, use the following script: \n```bash\npython scripts/visualize_detections.py --detections_folder $LOG_DIR/$WANDB_DIR \\\n                                       --dataset_directory $DSEC_ROOT/test/ \\\n                                       --vis_time_step_us 1000 \\ \n                                       --event_time_window_us 5000 \\\n                                       --sequence zurich_city_13_b\n                                       \n```\nThis will start a visualization window showing the detections over a given sequence. If you want to save the detections \nto a video, use the `--write_to_output` flag, which will create a video in the folder `$LOG_DIR/$WANDB_DIR/visualization}`.  \n\n## Training \nTo train on N-Caltech101, download the files with\n\n```bash\nwget https://download.ifi.uzh.ch/rpg/dagr/data/ncaltech101.zip -P $DAGR_DIR/data/\ncd $DAGR_DIR/data/\nunzip ncaltech101.zip \nrm -rf ncaltech101.zip \n```\n\nThen run training with \n\n```bash\n\npython scripts/train_ncaltech101.py --config config/dagr-l-ncaltech.yaml \\\n                                    --exp_name ncaltech_l \\\n                                    --dataset_directory $DAGR_DIR/data/ \\\n                                    --output_directory $DAGR_DIR/logs/\n```\nTo train on DSEC, make a symlink to the data directory via \n```bash\nln -s $DSEC_ROOT $DAGR_DIR/data/dsec \n```\nThen run training with \n```bash\n\npython scripts/train_dsec.py --config config/dagr-s-dsec.yaml \\\n                             --exp_name dsec_s_50 \\\n                             --dataset_directory $DAGR_DIR/data/ \\\n                             --output_directory $DAGR_DIR/logs/ \\\n                             --use_image --img_net resnet50 --batch_size 32\n```\n"
  },
  {
    "path": "scripts/check_dataset.py",
    "content": ""
  },
  {
    "path": "scripts/count_flops.py",
    "content": "import os\nimport tqdm\nimport torch\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom torch_geometric.data import DataLoader\n\nfrom dagr.utils.args import FLOPS_FLAGS\nfrom dagr.utils.buffers import DictBuffer, format_data\n\nfrom dagr.data.augment import Augmentations\nfrom dagr.data.dsec_data import DSEC\n\nfrom dagr.model.networks.dagr import DAGR\n\nfrom dagr.asynchronous.evaluate_flops import evaluate_flops\n\n\nif __name__ == '__main__':\n    import torch_geometric\n    seed = 42\n    torch_geometric.seed.seed_everything(seed)\n    args = FLOPS_FLAGS()\n    assert \"checkpoint\" in args\n\n    project = f\"flops-{args.dataset}-{args.task}\"\n    pbar = tqdm.tqdm(total=4)\n\n    pbar.set_description(\"Loading dataset\")\n    dataset_path = args.dataset_directory / args.dataset\n    print(\"init datasets\")\n    dataset = DSEC(args.dataset_directory, \"test\", Augmentations.transform_testing, debug=True, min_bbox_diag=15, min_bbox_height=10)\n    loader = DataLoader(dataset, follow_batch=['bbox', \"bbox0\"], batch_size=args.batch_size, shuffle=False, num_workers=16)\n    pbar.update(1)\n\n    pbar.set_description(\"Initializing net\")\n    model = DAGR(args, height=dataset.height, width=dataset.width)\n    model = model.cuda()\n    model.eval()\n    pbar.update(1)\n\n    assert \"checkpoint\" in args\n    checkpoint = torch.load(args.checkpoint)\n    model.load_state_dict(checkpoint['ema'])\n    pbar.update(1)\n\n    model.cache_luts(radius=args.radius, height=dataset.height, width=dataset.width)\n\n    pbar.set_description(\"Computing FLOPS\")\n    buffer = DictBuffer()\n    args.output_directory.mkdir(parents=True, exist_ok=True)\n    pbar_flops = tqdm.tqdm(total=len(loader.dataset), desc=\"Computing FLOPS\")\n    for i, data in enumerate(loader):\n        data = data.cuda(non_blocking=True)\n        data = format_data(data)\n\n        flops_evaluation = evaluate_flops(model, data,\n                                          check_consistency=args.check_consistency,\n                                          return_all_samples=True, dense=args.dense)\n        if flops_evaluation is None:\n            continue\n\n        buffer.update(flops_evaluation['flops_per_layer'])\n        buffer.save(args.output_directory / \"flops_per_layer.pth\")\n        tot_flops = sum(buffer.compute().values())\n\n        pbar_flops.set_description(f\"Total FLOPS {tot_flops}\")\n        pbar_flops.update(1)\n\n    print(sum(buffer.compute().values()))\n    pbar.update(1)\n\n\n\n\n"
  },
  {
    "path": "scripts/downsample_all_events.sh",
    "content": "#!/bin/bash\n\nDSEC_ROOT=$1\nfor split in train test; do\n    for sequence in $DSEC_ROOT/$split/*/; do\n        infile=$sequence/events/left/events.h5\n        outfile=$sequence/events/left/events_2x.h5\n        python scripts/downsample_events.py --input_path $infile --output_path $outfile\n    done\ndone"
  },
  {
    "path": "scripts/downsample_events.py",
    "content": "import argparse\nimport tqdm\nimport hdf5plugin\nimport h5py\nimport weakref\nimport numba\n\nimport numpy as np\n\nfrom pathlib import Path\n\nfrom dsec_det.io import extract_from_h5_by_index, get_num_events\n\n\ndef _compression_opts():\n    compression_level = 1  # {0, ..., 9}\n    shuffle = 2  # {0: none, 1: byte, 2: bit}\n    # From https://github.com/Blosc/c-blosc/blob/7435f28dd08606bd51ab42b49b0e654547becac4/blosc/blosc.h#L66-L71\n    # define BLOSC_BLOSCLZ   0\n    # define BLOSC_LZ4       1\n    # define BLOSC_LZ4HC     2\n    # define BLOSC_SNAPPY    3\n    # define BLOSC_ZLIB      4\n    # define BLOSC_ZSTD      5\n    compressor_type = 5\n    compression_opts = (0, 0, 0, 0, compression_level, shuffle, compressor_type)\n    return compression_opts\n\n\nH5_BLOSC_COMPRESSION_FLAGS = dict(\n    compression=32001,\n    compression_opts=_compression_opts(),  # Blosc\n    chunks=True\n)\n\ndef create_ms_to_idx(t_us):\n    t_ms = t_us // 1000\n    x, counts = np.unique(t_ms, return_counts=True)\n    ms_to_idx = np.zeros(shape=(t_ms[-1] + 2,), dtype=\"uint64\")\n    ms_to_idx[x + 1] = counts\n    ms_to_idx = ms_to_idx[:-1].cumsum()\n    return ms_to_idx\n\nclass H5Writer:\n    def __init__(self, outfile):\n        assert not outfile.exists()\n\n        self.h5f = h5py.File(outfile, 'a')\n        self._finalizer = weakref.finalize(self, self.close_callback, self.h5f)\n\n        self.t_offset = None\n        self.num_events = 0\n\n        # create hdf5 datasets\n        shape = (2 ** 16,)\n        maxshape = (None,)\n\n        self.h5f.create_dataset(f'events/x', shape=shape, dtype='u2', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)\n        self.h5f.create_dataset(f'events/y', shape=shape, dtype='u2', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)\n        self.h5f.create_dataset(f'events/p', shape=shape, dtype='u1', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)\n        self.h5f.create_dataset(f'events/t', shape=shape, dtype='u4', maxshape=maxshape, **H5_BLOSC_COMPRESSION_FLAGS)\n\n    def create_ms_to_idx(self):\n        t_us = self.h5f['events/t'][()]\n        self.h5f.create_dataset(f'ms_to_idx', data=create_ms_to_idx(t_us), dtype='u8', **H5_BLOSC_COMPRESSION_FLAGS)\n\n    @staticmethod\n    def close_callback(h5f: h5py.File):\n        h5f.close()\n\n    def add_data(self, events):\n        if self.t_offset is None:\n            self.t_offset = events['t'][0]\n            self.h5f.create_dataset(f't_offset', data=self.t_offset, dtype='i8')\n\n        events['t'] -= self.t_offset\n        size = len(events['t'])\n        self.num_events += size\n\n        self.h5f[f'events/x'].resize(self.num_events, axis=0)\n        self.h5f[f'events/y'].resize(self.num_events, axis=0)\n        self.h5f[f'events/p'].resize(self.num_events, axis=0)\n        self.h5f[f'events/t'].resize(self.num_events, axis=0)\n\n        self.h5f[f'events/x'][self.num_events-size:self.num_events] = events['x']\n        self.h5f[f'events/y'][self.num_events-size:self.num_events] = events['y']\n        self.h5f[f'events/p'][self.num_events-size:self.num_events] = events['p']\n        self.h5f[f'events/t'][self.num_events-size:self.num_events] = events['t']\n\n\ndef downsample_events(events, input_height, input_width, output_height, output_width, change_map=None):\n    # this subsamples events if they were generated with cv2.INTER_AREA\n    if change_map is None:\n        change_map = np.zeros((output_height, output_width), dtype=\"float32\")\n\n    fx = int(input_width / output_width)\n    fy = int(input_height / output_height)\n\n    mask = np.zeros(shape=(len(events['t']),), dtype=\"bool\")\n    mask, change_map = _filter_events_resize(events['x'], events['y'], events['p'], mask, change_map, fx, fy)\n\n    events = {k: v[mask] for k, v in events.items()}\n    events['x'] = (events['x'] / fx).astype(\"uint16\")\n    events['y'] = (events['y'] / fy).astype(\"uint16\")\n\n    return events, change_map\n\n\n@numba.jit(nopython=True, cache=True)\ndef _filter_events_resize(x, y, p, mask, change_map, fx, fy):\n    # iterates through x,y,p of events, and increments cells of size fx x fy by 1/(fx*fy)\n    # if one of these cells reaches +-1, then reset the cell, and pass through that event.\n    # for memory reasons, this only returns the True/False for every event, indicating if\n    # the event was skipped or passed through.\n    for i in range(len(x)):\n        x_l = x[i] // fx\n        y_l = y[i] // fy\n        change_map[y_l, x_l] += p[i] * 1.0 / (fx * fy)\n\n        if np.abs(change_map[y_l, x_l]) >= 1:\n            mask[i] = True\n            change_map[y_l, x_l] -= p[i]\n\n    return mask, change_map\n\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\"\"\"Downsample events\"\"\")\n    parser.add_argument(\"--input_path\", type=Path, required=True, help=\"Path to input events.h5. \")\n    parser.add_argument(\"--output_path\", type=Path, required=True, help=\"Path where output events.h5 will be written.\")\n    parser.add_argument(\"--input_height\", type=int, default=480, help=\"Height of the input events resolution.\")\n    parser.add_argument(\"--input_width\", type=int, default=640, help=\"Width of the input events resolution\")\n    parser.add_argument(\"--output_height\", type=int, default=240, help=\"Height of the output events resolution.\")\n    parser.add_argument(\"--output_width\", type=int, default=320, help=\"Width of the output events resolution.\")\n    args = parser.parse_args()\n\n    num_events = get_num_events(args.input_path)\n    num_events_per_chunk = 100000\n    num_iterations = num_events // num_events_per_chunk\n\n    writer = H5Writer(args.output_path)\n\n    change_map = None\n    pbar = tqdm.tqdm(total=num_iterations+1)\n    for i in range(num_iterations):\n        events = extract_from_h5_by_index(args.input_path, i * num_events_per_chunk, (i+1) * num_events_per_chunk)\n        events['p'] = 2 * events['p'].astype(\"int8\") - 1\n        downsampled_events, change_map = downsample_events(events, change_map=change_map, input_height=args.input_height, input_width=args.input_width,\n                                                      output_height=args.output_height, output_width=args.output_width)\n        \n        events['p'] = ((events['p'] + 1)//2).astype(\"int8\")\n        writer.add_data(downsampled_events)\n        pbar.update(1)\n\n    events = extract_from_h5_by_index(args.input_path, num_iterations * num_events_per_chunk, num_events)\n    downsampled_events, change_map = downsample_events(events, change_map=change_map, input_height=args.input_height,\n                                                       input_width=args.input_width,\n                                                       output_height=args.output_height, output_width=args.output_width)\n    writer.add_data(downsampled_events)\n    pbar.update(1)\n\n    writer.create_ms_to_idx()\n\n\n\n\n"
  },
  {
    "path": "scripts/run_test.py",
    "content": "# avoid matlab error on server\nimport os\nimport torch\nimport wandb\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom torch_geometric.data import DataLoader\nfrom dagr.utils.args import FLAGS\n\nfrom dagr.data.dsec_data import DSEC\nfrom dagr.data.augment import Augmentations\n\nfrom dagr.model.networks.dagr import DAGR\nfrom dagr.model.networks.ema import ModelEMA\n\nfrom dagr.utils.logging import set_up_logging_directory, log_hparams\nfrom dagr.utils.testing import run_test_with_visualization\n\n\nif __name__ == '__main__':\n    import torch_geometric\n    import random\n    import numpy as np\n\n    seed = 42\n    torch_geometric.seed.seed_everything(seed)\n    torch.random.manual_seed(seed)\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n\n    args = FLAGS()\n\n    output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory)\n\n    project = f\"low_latency-{args.dataset}-{args.task}\"\n    print(f\"PROJECT: {project}\")\n    log_hparams(args)\n\n    print(\"init datasets\")\n    dataset_path = args.dataset_directory.parent / args.dataset\n\n    test_dataset = DSEC(args.dataset_directory, \"test\", Augmentations.transform_testing, debug=False, min_bbox_diag=15, min_bbox_height=10)\n\n    num_iters_per_epoch = 1\n\n    sampler = np.random.permutation(np.arange(len(test_dataset)))\n    test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)\n\n    print(\"init net\")\n    # load a dummy sample to get height, width\n    model = DAGR(args, height=test_dataset.height, width=test_dataset.width)\n    model = model.cuda()\n    ema = ModelEMA(model)\n\n    assert \"checkpoint\" in args\n    checkpoint = torch.load(args.checkpoint)\n    ema.ema.load_state_dict(checkpoint['ema'])\n    ema.ema.cache_luts(radius=args.radius, height=test_dataset.height, width=test_dataset.width)\n\n    with torch.no_grad():\n        metrics = run_test_with_visualization(test_loader, ema.ema, dataset=args.dataset)\n        log_data = {f\"testing/metric/{k}\": v for k, v in metrics.items()}\n        wandb.log(log_data)\n        print(metrics['mAP'])\n\n"
  },
  {
    "path": "scripts/run_test_interframe.py",
    "content": "import torch\nimport tqdm\nimport wandb\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nfrom torch_geometric.data import DataLoader\nfrom pprint import pprint\n\nfrom dagr.utils.logging import set_up_logging_directory, log_hparams\nfrom dagr.utils.args import FLAGS\nfrom dagr.utils.testing import run_test_with_visualization\n\nfrom dagr.data.augment import Augmentations\nfrom dagr.data.dsec_data import DSEC\n\nfrom dagr.model.networks.dagr import DAGR\nfrom dagr.model.networks.ema import ModelEMA\n\n\ndef to_npy(detections):\n    n_boxes = len(detections['boxes'])\n    dtype = np.dtype([('t', '<u8'), ('x', '<f4'), ('y', '<f4'), ('w', '<f4'), ('h', '<f4'), ('class_id', 'u1'), ('class_confidence', '<f4')])\n    data = np.zeros(shape=(n_boxes,), dtype=dtype)\n    data['t'] = detections['t']\n    data['x'] = detections['boxes'][:,0]\n    data['y'] = detections['boxes'][:,1]\n    data['w'] = detections['boxes'][:,2] - data['x']\n    data['h'] = detections['boxes'][:,3] - data['y']\n    data['class_id'] = detections['labels']\n    data['class_confidence'] = detections['scores']\n    return data\n\ndef save_detections(directory, detections):\n    sequence_detections_map = dict()\n    for d in tqdm.tqdm(detections, desc=\"compiling detections for saving...\"):\n        s = d['sequence']\n        if s not in sequence_detections_map:\n            sequence_detections_map[s] = to_npy(d)\n        else:\n            sequence_detections_map[s] = np.concatenate([sequence_detections_map[s], to_npy(d)])\n\n    for s, detections in sequence_detections_map.items():\n        detections = detections[detections['t'].argsort()]\n        np.save(directory / f\"detections_{s}.npy\", detections)\n\n\nif __name__ == '__main__':\n    import torch_geometric\n    import random\n    import numpy as np\n\n    seed = 42\n    torch_geometric.seed.seed_everything(seed)\n    torch.random.manual_seed(seed)\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n\n    args = FLAGS()\n\n    output_directory = set_up_logging_directory(args.dataset, args.task,  args.output_directory)\n    log_hparams(args)\n\n    print(\"init datasets\")\n    test_dataset = DSEC(root=args.dataset_directory, split=\"test\", transform=Augmentations.transform_testing,\n                        debug=False, min_bbox_diag=15, min_bbox_height=10, only_perfect_tracks=True,\n                        no_eval=args.no_eval)\n    test_loader = DataLoader(test_dataset, follow_batch=['bbox', \"bbox0\"], batch_size=args.batch_size, shuffle=False, num_workers=0, drop_last=True)\n\n    print(\"init net\")\n    model = DAGR(args, height=test_dataset.height, width=test_dataset.width)\n    model = model.cuda()\n    ema = ModelEMA(model)\n\n    assert \"checkpoint\" in args\n    checkpoint = torch.load(args.checkpoint)\n    ema.ema.load_state_dict(checkpoint['ema'])\n    ema.ema.cache_luts(radius=args.radius, height=test_dataset.height, width=test_dataset.width)\n\n    detections = []\n    with torch.no_grad():\n        for n_us in np.linspace(0, 50000, args.num_interframe_steps):\n            test_loader.dataset.set_num_us(int(n_us))\n            metrics, detections_one_offset = run_test_with_visualization(test_loader, ema.ema, dataset=args.dataset, name=wandb.run.name, compile_detections=True,\n                                                                         no_eval=args.no_eval)\n            detections.extend(detections_one_offset)\n\n            if metrics is not None:\n                pprint(f\"Time Window: {int(n_us)} ms \\t mAP: {metrics['mAP']}\")\n\n        save_detections(output_directory, detections)"
  },
  {
    "path": "scripts/train_dsec.py",
    "content": "# avoid matlab error on server\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nimport torch\nimport tqdm\nimport wandb\nfrom pathlib import Path\nimport argparse\n\nfrom torch_geometric.data import DataLoader\n\nfrom dagr.utils.logging import Checkpointer, set_up_logging_directory, log_hparams\nfrom dagr.utils.buffers import DetectionBuffer\nfrom dagr.utils.args import FLAGS\nfrom dagr.utils.learning_rate_scheduler import LRSchedule\n\nfrom dagr.data.augment import Augmentations\nfrom dagr.utils.buffers import format_data\nfrom dagr.data.dsec_data import DSEC\n\nfrom dagr.model.networks.dagr import DAGR\nfrom dagr.model.networks.ema import ModelEMA\n\n\ndef gradients_broken(model):\n    valid_gradients = True\n    for name, param in model.named_parameters():\n        if param.grad is not None:\n            # valid_gradients = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any())\n            valid_gradients = not (torch.isnan(param.grad).any())\n            if not valid_gradients:\n                break\n    return not valid_gradients\n\ndef fix_gradients(model):\n    for name, param in model.named_parameters():\n        if param.grad is not None:\n            param.grad = torch.nan_to_num(param.grad, nan=0.0)\n\n\ndef train(loader: DataLoader,\n          model: torch.nn.Module,\n          ema: ModelEMA,\n          scheduler: torch.optim.lr_scheduler.LambdaLR,\n          optimizer: torch.optim.Optimizer,\n          args: argparse.ArgumentParser,\n          run_name=\"\"):\n\n    model.train()\n\n    for i, data in enumerate(tqdm.tqdm(loader, desc=f\"Training {run_name}\")):\n        data = data.cuda(non_blocking=True)\n        data = format_data(data)\n\n        optimizer.zero_grad(set_to_none=True)\n\n        model_outputs = model(data)\n\n        loss_dict = {k: v for k, v in model_outputs.items() if \"loss\" in k}\n        loss = loss_dict.pop(\"total_loss\")\n\n        loss.backward()\n\n        torch.nn.utils.clip_grad_value_(model.parameters(), args.clip)\n\n        fix_gradients(model)\n\n        optimizer.step()\n        scheduler.step()\n\n        ema.update(model)\n\n        training_logs = {f\"training/loss/{k}\": v for k, v in loss_dict.items()}\n        wandb.log({\"training/loss\": loss.item(), \"training/lr\": scheduler.get_last_lr()[-1], **training_logs})\n\ndef run_test(loader: DataLoader,\n         model: torch.nn.Module,\n         dry_run_steps: int=-1,\n         dataset=\"gen1\"):\n\n    model.eval()\n\n    mapcalc = DetectionBuffer(height=loader.dataset.height, width=loader.dataset.width, classes=loader.dataset.classes)\n\n    for i, data in enumerate(tqdm.tqdm(loader)):\n        data = data.cuda()\n        data = format_data(data)\n\n        detections, targets = model(data)\n        if i % 10 == 0:\n            torch.cuda.empty_cache()\n\n        mapcalc.update(detections, targets, dataset, data.height[0], data.width[0])\n\n        if dry_run_steps > 0 and i == dry_run_steps:\n            break\n\n    torch.cuda.empty_cache()\n\n    return mapcalc\n\nif __name__ == '__main__':\n    import torch_geometric\n    import random\n    import numpy as np\n\n    seed = 42\n    torch_geometric.seed.seed_everything(seed)\n    torch.random.manual_seed(seed)\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n\n    args = FLAGS()\n\n    output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory, exp_name=args.exp_name)\n    log_hparams(args)\n\n    augmentations = Augmentations(args)\n\n    print(\"init datasets\")\n    dataset_path = args.dataset_directory / args.dataset\n\n    train_dataset = DSEC(root=dataset_path, split=\"train\", transform=augmentations.transform_training, debug=False,\n                         min_bbox_diag=15, min_bbox_height=10)\n    test_dataset = DSEC(root=dataset_path, split=\"val\", transform=augmentations.transform_testing, debug=False,\n                        min_bbox_diag=15, min_bbox_height=10)\n\n    train_loader = DataLoader(train_dataset, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=True)\n    num_iters_per_epoch = len(train_loader)\n\n    sampler = np.random.permutation(np.arange(len(test_dataset)))\n    test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)\n\n    print(\"init net\")\n    # load a dummy sample to get height, width\n    model = DAGR(args, height=test_dataset.height, width=test_dataset.width)\n\n    num_params = sum([np.prod(p.size()) for p in model.parameters()])\n    print(f\"Training with {num_params} number of parameters.\")\n\n    model = model.cuda()\n    ema = ModelEMA(model)\n\n    nominal_batch_size = 64\n    lr = args.l_r * np.sqrt(args.batch_size) / np.sqrt(nominal_batch_size)\n    optimizer = torch.optim.AdamW(list(model.parameters()), lr=lr, weight_decay=args.weight_decay)\n\n    lr_func = LRSchedule(warmup_epochs=.3,\n                         num_iters_per_epoch=num_iters_per_epoch,\n                         tot_num_epochs=args.tot_num_epochs)\n\n    lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer, lr_lambda=lr_func)\n\n    checkpointer = Checkpointer(output_directory=output_directory,\n                                model=model, optimizer=optimizer,\n                                scheduler=lr_scheduler, ema=ema,\n                                args=args)\n\n    start_epoch = checkpointer.restore_if_existing(output_directory, resume_from_best=False)\n\n    start_epoch = 0\n    if \"resume_checkpoint\" in args:\n        start_epoch = checkpointer.restore_checkpoint(args.resume_checkpoint, best=False)\n        print(f\"Resume from checkpoint at epoch {start_epoch}\")\n\n    with torch.no_grad():\n        mapcalc = run_test(test_loader, ema.ema, dry_run_steps=2, dataset=args.dataset)\n        mapcalc.compute()\n\n    print(\"starting to train\")\n    for epoch in range(start_epoch, args.tot_num_epochs):\n        train(train_loader, model, ema, lr_scheduler, optimizer, args, run_name=wandb.run.name)\n        checkpointer.checkpoint(epoch, name=f\"last_model\")\n\n        if epoch % 3 > 0:\n            continue\n\n        with torch.no_grad():\n            mapcalc = run_test(test_loader, ema.ema, dataset=args.dataset)\n            metrics = mapcalc.compute()\n            checkpointer.process(metrics, epoch)\n\n"
  },
  {
    "path": "scripts/train_ncaltech101.py",
    "content": "# avoid matlab error on server\nimport os\nos.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'\n\nimport torch\nimport tqdm\nimport wandb\nfrom pathlib import Path\nimport argparse\n\nfrom torch_geometric.data import DataLoader\n\nfrom dagr.utils.logging import Checkpointer, set_up_logging_directory, log_hparams\nfrom dagr.utils.buffers import DetectionBuffer\nfrom dagr.utils.args import FLAGS\nfrom dagr.utils.learning_rate_scheduler import LRSchedule\n\nfrom dagr.data.augment import Augmentations\nfrom dagr.utils.buffers import format_data\nfrom dagr.data.ncaltech101_data import NCaltech101\n\nfrom dagr.model.networks.dagr import DAGR\nfrom dagr.model.networks.ema import ModelEMA\n\ndef gradients_broken(model):\n    valid_gradients = True\n    for name, param in model.named_parameters():\n        if param.grad is not None:\n            # valid_gradients = not (torch.isnan(param.grad).any() or torch.isinf(param.grad).any())\n            valid_gradients = not (torch.isnan(param.grad).any())\n            if not valid_gradients:\n                break\n    return not valid_gradients\n\ndef fix_gradients(model):\n    for name, param in model.named_parameters():\n        if param.grad is not None:\n            param.grad = torch.nan_to_num(param.grad, nan=0.0)\n\n\ndef train(loader: DataLoader,\n          model: torch.nn.Module,\n          ema: ModelEMA,\n          scheduler: torch.optim.lr_scheduler.LambdaLR,\n          optimizer: torch.optim.Optimizer,\n          args: argparse.ArgumentParser,\n          run_name=\"\"):\n\n    model.train()\n\n    for i, data in enumerate(tqdm.tqdm(loader, desc=f\"Training {run_name}\")):\n        data = data.cuda(non_blocking=True)\n        data = format_data(data)\n\n        optimizer.zero_grad(set_to_none=True)\n\n        model_outputs = model(data)\n\n        loss_dict = {k: v for k, v in model_outputs.items() if \"loss\" in k}\n        loss = loss_dict.pop(\"total_loss\")\n\n        loss.backward()\n\n        torch.nn.utils.clip_grad_value_(model.parameters(), args.clip)\n\n        fix_gradients(model)\n\n        optimizer.step()\n        scheduler.step()\n\n        ema.update(model)\n\n        training_logs = {f\"training/loss/{k}\": v for k, v in loss_dict.items()}\n        wandb.log({\"training/loss\": loss.item(), \"training/lr\": scheduler.get_last_lr()[-1], **training_logs})\n\ndef run_test(loader: DataLoader,\n         model: torch.nn.Module,\n         dry_run_steps: int=-1,\n         dataset=\"gen1\"):\n\n    model.eval()\n\n    mapcalc = DetectionBuffer(height=loader.dataset.height, width=loader.dataset.width, classes=loader.dataset.classes)\n\n    for i, data in enumerate(tqdm.tqdm(loader)):\n        data = data.cuda()\n        data = format_data(data)\n\n        detections, targets = model(data)\n        if i % 10 == 0:\n            torch.cuda.empty_cache()\n\n        mapcalc.update(detections, targets, dataset, data.height[0], data.width[0])\n\n        if dry_run_steps > 0 and i == dry_run_steps:\n            break\n\n    torch.cuda.empty_cache()\n\n    return mapcalc\n\nif __name__ == '__main__':\n    import torch_geometric\n    import random\n    import numpy as np\n\n    seed = 42\n    torch_geometric.seed.seed_everything(seed)\n    torch.random.manual_seed(seed)\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n    random.seed(seed)\n\n    args = FLAGS()\n\n    output_directory = set_up_logging_directory(args.dataset, args.task, args.output_directory, exp_name=args.exp_name)\n    log_hparams(args)\n\n    augmentations = Augmentations(args)\n\n    print(\"init datasets\")\n    dataset_path = args.dataset_directory / args.dataset\n\n    train_dataset = NCaltech101(dataset_path, \"training\", augmentations.transform_training, num_events=args.n_nodes)\n    test_dataset = NCaltech101(dataset_path, \"validation\", augmentations.transform_testing, num_events=args.n_nodes)\n\n\n    train_loader = DataLoader(train_dataset, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=True, num_workers=4, drop_last=True)\n    num_iters_per_epoch = len(train_loader)\n\n    sampler = np.random.permutation(np.arange(len(test_dataset)))\n    test_loader = DataLoader(test_dataset, sampler=sampler, follow_batch=['bbox', 'bbox0'], batch_size=args.batch_size, shuffle=False, num_workers=4, drop_last=True)\n\n    print(\"init net\")\n    # load a dummy sample to get height, width\n    model = DAGR(args, height=test_dataset.height, width=test_dataset.width)\n\n    num_params = sum([np.prod(p.size()) for p in model.parameters()])\n    print(f\"Training with {num_params} number of parameters.\")\n\n    model = model.cuda()\n    ema = ModelEMA(model)\n\n    nominal_batch_size = 64\n    lr = args.l_r * np.sqrt(args.batch_size) / np.sqrt(nominal_batch_size)\n    optimizer = torch.optim.AdamW(list(model.parameters()), lr=lr, weight_decay=args.weight_decay)\n\n    lr_func = LRSchedule(warmup_epochs=.3,\n                         num_iters_per_epoch=num_iters_per_epoch,\n                         tot_num_epochs=args.tot_num_epochs)\n\n    lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer=optimizer, lr_lambda=lr_func)\n\n    checkpointer = Checkpointer(output_directory=output_directory,\n                                model=model, optimizer=optimizer,\n                                scheduler=lr_scheduler, ema=ema,\n                                args=args)\n\n    start_epoch = checkpointer.restore_if_existing(output_directory, resume_from_best=False)\n\n    start_epoch = 0\n    if \"resume_checkpoint\" in args:\n        start_epoch = checkpointer.restore_checkpoint(args.resume_checkpoint, best=False)\n        print(f\"Resume from checkpoint at epoch {start_epoch}\")\n\n    with torch.no_grad():\n        mapcalc = run_test(test_loader, ema.ema, dry_run_steps=2, dataset=args.dataset)\n        mapcalc.compute()\n\n    print(\"starting to train\")\n    for epoch in range(start_epoch, args.tot_num_epochs):\n        train(train_loader, model, ema, lr_scheduler, optimizer, args, run_name=wandb.run.name)\n        checkpointer.checkpoint(epoch, name=f\"last_model\")\n\n        if epoch % 3 > 0:\n            continue\n\n        with torch.no_grad():\n            mapcalc = run_test(test_loader, ema.ema, dataset=args.dataset)\n            metrics = mapcalc.compute()\n            checkpointer.process(metrics, epoch)\n\n"
  },
  {
    "path": "scripts/visualize_detections.py",
    "content": "import cv2\nimport argparse\n\nfrom pathlib import Path\nimport numpy as np\n\nfrom dsec_det.directory import DSECDirectory\nfrom dsec_det.io import extract_from_h5_by_timewindow, extract_image_by_index, load_start_and_end_time\nfrom dsec_det.preprocessing import compute_index\n\nfrom dagr.visualization.bbox_viz import draw_bbox_on_img\nfrom dagr.visualization.event_viz import draw_events_on_image\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\"\"\"Visualization script to show bounding boxes\"\"\")\n    parser.add_argument(\"--detections_folder\", help=\"Path to folder with detections.\", type=Path)\n    parser.add_argument(\"--dataset_directory\", help=\"Path to DSEC folder including which split.\", type=Path, default=\"/data/scratch1/daniel/datasets/DSEC_fragment/test\")\n    parser.add_argument(\"--vis_time_step_us\", help=\"Number of microseconds to step each iteration.\", type=int, default=1000)\n    parser.add_argument(\"--event_time_window_us\", help=\"Length of sliding event time window for visualization.\", type=int, default=5000)\n    parser.add_argument(\"--sequence\", help=\"Sequence to visualize. Must be an official DSEC sequence e.g. zurich_city_13_b\", default=\"zurich_city_13_b\", type=str)\n    parser.add_argument(\"--write_to_output\", help=\"Whether to save images in folder ${detections_folder}/visualization. Otherwise, just cv2.imshow is used.\", action=\"store_true\")\n    args = parser.parse_args()\n\n    assert args.dataset_directory.exists()\n    assert args.vis_time_step_us > 0\n    assert args.event_time_window_us > 0\n\n    if args.write_to_output:\n        assert (args.detections_folder / f\"detections_{args.sequence}.npy\").exists()\n        assert args.detections_folder.exists()\n        output_path = args.detections_folder / \"visualization\"\n        output_path.mkdir(parents=True, exist_ok=True)\n\n    dsec_directory = DSECDirectory(args.dataset_directory / args.sequence)\n\n    t0, t1 = load_start_and_end_time(dsec_directory)\n\n    vis_timestamps = np.arange(t0, t1, step=args.vis_time_step_us)\n    step_index_to_image_index = compute_index(dsec_directory.images.timestamps, vis_timestamps)\n\n    show_detections = args.detections_folder is not None\n\n    if not show_detections:\n        print(\"Did not specifiy detections. Just showing events and images.\")\n\n    if show_detections:\n        detections_file = args.detections_folder / f\"detections_{args.sequence}.npy\"\n        detections = np.load(detections_file)\n        detection_timestamps = np.unique(detections['t'])\n        step_index_to_boxes_index = compute_index(detection_timestamps, vis_timestamps)\n\n    scale = 2\n\n    for step, t in enumerate(vis_timestamps):\n\n        # find most recent image\n        image_index = step_index_to_image_index[step]\n        image = extract_image_by_index(dsec_directory.images.image_files_distorted, image_index)\n\n        # find events within time window [image_timestamps, t]\n        events = extract_from_h5_by_timewindow(dsec_directory.events.event_file, t-args.event_time_window_us, t)\n        image = draw_events_on_image(image, events['x'], events['y'], events['p'])\n\n        if show_detections:\n            # find most recent bounding boxes\n            boxes_index = step_index_to_boxes_index[step]\n            boxes_timestamp = detection_timestamps[boxes_index]\n            boxes = detections[detections['t'] == boxes_timestamp]\n\n            # draw them on one image\n            scale = 2\n            image = draw_bbox_on_img(image, scale*boxes['x'], scale*boxes['y'], scale*boxes['w'], scale*boxes[\"h\"],\n                                     boxes[\"class_id\"], boxes['class_confidence'], conf=0.3, nms=0.65)\n\n        if args.write_to_output:\n            cv2.imwrite(str(output_path / (\"%06d.png\" % step)), image)\n        else:\n            cv2.imshow(\"DSEC Det: Visualization\", image)\n            cv2.waitKey(3)\n\n"
  },
  {
    "path": "setup.py",
    "content": "from distutils.core import setup\nfrom torch.utils.cpp_extension import BuildExtension, CUDAExtension\n\nsetup(\n    name='dagr',\n    packages=['dagr'],\n    package_dir={'':'src'},\n    ext_modules=[\n        CUDAExtension(name='asy_tools',\n                      sources=['src/dagr/asynchronous/asy_tools/main.cu']),\n        CUDAExtension(name=\"ev_graph_cuda\",\n                      sources=['src/dagr/graph/ev_graph.cu'])\n    ],\n    cmdclass={\n        'build_ext': BuildExtension\n    }\n)\n"
  },
  {
    "path": "src/dagr/asynchronous/__init__.py",
    "content": "import logging\n\nimport torch.nn\nimport torch_geometric\nimport inspect\n\nfrom torch.nn import ModuleList\n\nfrom .conv import make_conv_asynchronous\nfrom .batch_norm import make_batch_norm_asynchronous\nfrom .linear import make_linear_asynchronous\nfrom .max_pool import make_max_pool_asynchronous\nfrom .cartesian import make_cartesian_asynchronous\n\nfrom .flops import compute_flops_from_module\n\nfrom dagr.model.layers.spline_conv import MySplineConv\nfrom dagr.model.layers.pooling import Pooling\nfrom dagr.model.layers.components import BatchNormData, Cartesian, Linear\n\n\n\nfrom torch_geometric.data import Data, Batch\nfrom typing import List\n\n\ndef is_data_or_data_list(ann):\n    return ann is Data or ann is Batch or ann is List[Data]\n\ndef make_model_synchronous(module: torch.nn.Module):\n    module.forward = module.sync_forward\n    module.asy_flops_log = []\n\n    for key, nn in module.named_modules():\n        if hasattr(nn, \"sync_forward\"):\n            nn.forward = nn.sync_forward\n            nn.asy_flops_log = []\n\n    return module\n\ndef make_model_asynchronous(module, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for graph convolutional layers.\n    By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning\n    and moving its weights and configuration. So, a convolutional layer can be converted by, for example:\n\n    ```\n    module = GCNConv(1, 2)\n    module = make_conv_asynchronous(module)\n    ```\n\n    :param module: convolutional module to transform.\n    :param grid_size: grid size (grid starting at 0, spanning to `grid_size`), >= `size` for pooling operations,\n                      e.g. the image size.\n    :param r: update radius around new events.\n    :param edge_attributes: function for computing edge attributes (default = None), assumed to be the same over\n                            all convolutional layers.\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n    assert isinstance(module, torch.nn.Module), \"module must be a `torch.nn.Module`\"\n    model_forward = module.forward\n    module.sync_forward = module.forward\n\n    module.asy_flops_log = [] if log_flops else None\n\n    # Make all layers asynchronous that have an implemented asynchronous function. Otherwise use\n    # the synchronous forward function.\n    for key, nn in module._modules.items():\n        nn_class_name = nn.__class__.__name__\n        logging.debug(f\"Making layer {key} of type {nn_class_name} asynchronous\")\n\n        if isinstance(nn, MySplineConv):\n            module._modules[key] = make_conv_asynchronous(nn, log_flops=log_flops)\n\n        elif isinstance(nn, Pooling):\n            module._modules[key] = make_max_pool_asynchronous(nn, log_flops=log_flops)\n\n        elif isinstance(nn, BatchNormData):\n            module._modules[key] = make_batch_norm_asynchronous(nn, log_flops=log_flops)\n\n        elif isinstance(nn, Cartesian):\n            module._modules[key] = make_cartesian_asynchronous(nn, log_flops=log_flops)\n\n        elif isinstance(nn, Linear):\n            module._modules[key] = make_linear_asynchronous(nn, log_flops=log_flops)\n\n        elif isinstance(nn, ModuleList):\n            module._modules[key] = make_model_asynchronous(nn, log_flops=log_flops)\n\n        else:\n            sign = inspect.signature(nn.forward)\n            first_arg = list(sign.parameters.values())[0]\n\n            if not is_data_or_data_list(first_arg.annotation):\n                continue\n\n            module._modules[key] = make_model_asynchronous(nn, log_flops=log_flops)\n            logging.debug(f\"Asynchronous module for {nn_class_name} is being made asynchronous recursively.\")\n\n    def async_forward(data: torch_geometric.data.Data, *args, **kwargs):\n        out = model_forward(data, *args, **kwargs)\n\n        if module.asy_flops_log is not None:\n            flops_count = [compute_flops_from_module(layer) for layer in module._modules.values()]\n            module.asy_flops_log.append(sum(flops_count))\n            logging.debug(f\"Model's modules update with overall {sum(flops_count)} flops\")\n\n        return out\n\n    module.forward = async_forward\n    return module\n\n\n__all__ = [\n    \"make_conv_asynchronous\",\n    \"make_linear_asynchronous\",\n    \"make_max_pool_asynchronous\",\n    \"make_model_asynchronous\"\n]\n"
  },
  {
    "path": "src/dagr/asynchronous/asy_tools/main.cu",
    "content": "#include <torch/extension.h>\n\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include <vector>\n\n\n#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n#define CHECK_DEVICE(x, y) AT_ASSERTM(x.device().index() == y.device().index(), #x \" and \" #y \" must be in same CUDA device\")\n\n\ntemplate <typename scalar_t>\n__global__ void masked_isdiff_kernel(\n  int64_t* __restrict__ indices,\n  const scalar_t* __restrict__ x_old,\n  const scalar_t* __restrict__ x_new,\n  int K, int C, float atol, float rtol\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K)\n    return;\n\n  // find out how many events to write, and what is the offset\n  int64_t temp = indices[lin_idx];\n  indices[lin_idx] = -1;\n  int offset = temp*C;\n  for (int i=0; i<C; i++) {\n    float input = x_old[offset + i];\n    float other = x_new[offset + i];\n    if (std::abs(input - other) > atol + rtol * other) {\n      indices[lin_idx] = temp;\n      break;\n    }\n  }\n}\n\ntemplate <typename scalar_t>\n__global__ void masked_inplace_BN_kernel(\n  const int64_t* __restrict__ indices,\n  const scalar_t* __restrict__ x,\n  scalar_t* __restrict__ x_out,\n  const scalar_t* __restrict__ running_mean,\n  const scalar_t* __restrict__ running_var,\n  const scalar_t* __restrict__ weight,\n  const scalar_t* __restrict__ bias,\n  int K, int C, float eps\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K*C)\n    return;\n\n  int i = lin_idx / C;\n  int c = lin_idx % C;\n\n  int x_lin_idx = C * indices[i] + c;\n  x_out[x_lin_idx] = (x[x_lin_idx] - running_mean[c]) / (sqrt(running_var[c] + eps)) * weight[c] + bias[c];\n}\n\nvoid masked_inplace_BN(\n    const torch::Tensor& indices,\n    const torch::Tensor& x,\n    torch::Tensor& x_out,\n    const torch::Tensor& running_mean,\n    const torch::Tensor& running_var,\n    const torch::Tensor& weight,\n    const torch::Tensor& bias,\n    float eps\n  )\n{\n  unsigned K = indices.size(0);\n  unsigned C = x.size(1);\n\n  unsigned threads = 256;\n  dim3 blocks((K*C + threads - 1) / threads, 1);\n\n  masked_inplace_BN_kernel<float><<<blocks, threads>>>(\n    indices.data<int64_t>(),\n    x.data<float>(),\n    x_out.data<float>(),\n    running_mean.data<float>(),\n    running_var.data<float>(),\n    weight.data<float>(),\n    bias.data<float>(), K, C, eps\n    );\n}\n\ntorch::Tensor masked_isdiff(\n    const torch::Tensor& indices, // N -> num events\n    const torch::Tensor& x_old,   // K -> num active pixels\n    const torch::Tensor& x_new,    // K -> num active pixels\n    float atol, float rtol\n  )\n{\n  CHECK_INPUT(indices);\n  CHECK_INPUT(x_old);\n  CHECK_INPUT(x_new);\n\n  CHECK_DEVICE(indices, x_old);\n  CHECK_DEVICE(indices, x_new);\n\n  unsigned K = indices.size(0);\n  unsigned C = x_old.size(1);\n\n  unsigned threads = 256;\n  dim3 blocks((K + threads - 1) / threads, 1);\n\n  masked_isdiff_kernel<float><<<blocks, threads>>>(\n      indices.data<int64_t>(),\n      x_old.data<float>(),\n      x_new.data<float>(),\n      K, C, atol, rtol\n    );\n\n  return indices.index({indices > -1});\n}\n\n\ntemplate <typename scalar_t>\n__global__ void masked_lin_kernel(\n  int64_t* __restrict__ indices,\n  const scalar_t* __restrict__ x_in,\n  scalar_t* __restrict__ x_out,\n  const scalar_t* __restrict__ weight,\n  const scalar_t* __restrict__ bias,\n  int K, int Cin, int Cout, bool add\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K*Cout)\n    return;\n\n  int i = lin_idx / Cout;\n  int cout = lin_idx % Cout;\n\n  int x_out_lin_idx = Cout * indices[i] + cout;\n  int x_int_lin_idx = Cin * indices[i];\n\n  if (!add)\n      x_out[x_out_lin_idx] = 0;\n\n  for (int cin=0; cin<Cin; cin++) {\n    x_out[x_out_lin_idx] += x_in[x_int_lin_idx + cin] * weight[cout*Cin + cin];\n  }\n  x_out[x_out_lin_idx] += bias[cout];\n}\n\ntemplate <typename scalar_t>\n__global__ void masked_lin_no_bias_kernel(\n  int64_t* __restrict__ indices,\n  const scalar_t* __restrict__ x_in,\n  scalar_t* __restrict__ x_out,\n  const scalar_t* __restrict__ weight,\n  int K, int Cin, int Cout, bool add\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K*Cout)\n    return;\n\n  int i = lin_idx / Cout;\n  int cout = lin_idx % Cout;\n\n  int x_out_lin_idx = Cout * indices[i] + cout;\n  int x_int_lin_idx = Cin * indices[i];\n\n  if (!add)\n      x_out[x_out_lin_idx] = 0;\n\n  for (int cin=0; cin<Cin; cin++) {\n    x_out[x_out_lin_idx] += x_in[x_int_lin_idx + cin] * weight[cout*Cin + cin];\n  }\n}\n\nvoid masked_lin_no_bias(\n    const torch::Tensor& indices,\n    const torch::Tensor& x_in,\n    torch::Tensor& x_out,\n    const torch::Tensor& weight,\n    bool add\n  )\n{\n  unsigned K = indices.size(0);\n  unsigned Cin = weight.size(1);\n  unsigned Cout = weight.size(0);\n\n  unsigned threads = 256;\n  dim3 blocks((K*Cout + threads - 1) / threads, 1);\n\n  masked_lin_no_bias_kernel<float><<<blocks, threads>>>(\n    indices.data<int64_t>(),\n    x_in.data<float>(),\n    x_out.data<float>(),\n    weight.data<float>(),\n    K, Cin, Cout, add);\n}\n\n\nvoid masked_lin(\n    const torch::Tensor& indices,\n    const torch::Tensor& x_in,\n    torch::Tensor& x_out,\n    const torch::Tensor& weight,\n    const torch::Tensor& bias,\n    bool add\n  )\n{\n  unsigned K = indices.size(0);\n  unsigned Cin = weight.size(1);\n  unsigned Cout = weight.size(0);\n\n  unsigned threads = 256;\n  dim3 blocks((K*Cout + threads - 1) / threads, 1);\n\n  masked_lin_kernel<float><<<blocks, threads>>>(\n    indices.data<int64_t>(),\n    x_in.data<float>(),\n    x_out.data<float>(),\n    weight.data<float>(),\n    bias.data<float>(), K, Cin, Cout, add);\n}\n\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n  m.def(\"masked_lin\", &masked_lin, \"Find edges from a queue of events.\");\n  m.def(\"masked_lin_no_bias\", &masked_lin_no_bias, \"Find edges from a queue of events.\");\n  m.def(\"masked_isdiff\", &masked_isdiff, \"Find edges from a queue of events.\");\n  m.def(\"masked_inplace_BN\", &masked_inplace_BN, \"Find edges from a queue of events.\");\n}\n"
  },
  {
    "path": "src/dagr/asynchronous/base/__init__.py",
    "content": ""
  },
  {
    "path": "src/dagr/asynchronous/base/base.py",
    "content": "from contextlib import contextmanager\nimport logging\n\n\ndef add_async_graph(module, log_flops: bool = False):\n    module.asy_graph = None\n    module.asy_flops_log = [] if log_flops else None\n    return module\n\n\ndef make_asynchronous(module, initialization_func, processing_func):\n    module.sync_forward = module.forward\n    def async_forward(*args, **kwargs):\n        with async_context(module, initialization_func, processing_func) as func:\n            output = func(module, *args, **kwargs)\n        return output\n    module.forward = async_forward\n    return module\n\n\n@contextmanager\ndef async_context(module, initialization_func, processing_func):\n    if module.asy_graph is None:\n        logging.debug(f\"Graph initialization of module {module}\")\n        yield initialization_func\n    else:\n        logging.debug(f\"Calling processing of module {module}\")\n        yield processing_func\n"
  },
  {
    "path": "src/dagr/asynchronous/base/utils.py",
    "content": "import torch\n\nfrom typing import Tuple\nimport asy_tools\n\n\ndef _efficient_cat(data_list):\n    data_list = [d for d in data_list if len(d) > 0]\n    if len(data_list) == 1:\n        return data_list[0]\n    return torch.cat(data_list)\n\ndef _efficient_cat_unique(data_list):\n    # first only keep elements that have len > 0\n    data_list_filt = [data for data in data_list if data.shape[0] > 0]\n    if len(data_list_filt) == 1:\n        return data_list_filt[0]\n    elif len(data_list_filt) == 0:\n        return data_list[0]\n    else:\n        return torch.cat(data_list_filt).unique()\n\ndef _to_hom(x, ones=None):\n    if ones is None or len(ones) < len(x):\n        ones = torch.ones_like(x[:,-1:])\n    else:\n        ones = ones[:len(x)]\n    return torch.cat([x, ones], dim=-1)\n\ndef _from_hom(x):\n    return x[:,:-1] / (x[:,-1:] + 1e-9)\n\ndef graph_new_nodes(old_data, new_data):\n    return torch.arange(old_data.x.shape[0], new_data.x.shape[0], device=new_data.x.device, dtype=torch.long)\n\ndef graph_changed_nodes(old_data, new_data) -> Tuple[torch.Tensor, torch.Tensor]:\n    len_x_old = old_data.x.shape[0]\n    len_pos_old = old_data.pos.shape[0]\n    x_new = new_data.x[:len_x_old] if len_x_old < new_data.x.shape[0] else new_data.x\n    pos_new = new_data.pos[:len_pos_old] if len_pos_old < new_data.pos.shape[0] else new_data.pos\n\n    diff_idx = asy_tools.masked_isdiff(new_data.diff_idx, x_new, old_data.x, 1e-8, 1e-5) if new_data.diff_idx.numel() > 0 else new_data.diff_idx\n    diff_pos_idx = asy_tools.masked_isdiff(new_data.diff_pos_idx, pos_new, old_data.pos, 1e-8, 1e-5) if new_data.diff_pos_idx.numel() > 0 else new_data.diff_pos_idx\n\n    return diff_idx, diff_pos_idx\n\ndef torch_isin(query, database):\n    if hasattr(torch, \"isin\"):\n        return torch.isin(query, database)\n    else:\n        return (query.view(1, -1) == database.view(-1, 1)).any(0)\n\ndef __remove_duplicate_from_A(a, b):\n    a_in_b = (a.view(2,1,-1) == b.view(2,-1,1)).all(0).any(0)\n    return a[:,~a_in_b]"
  },
  {
    "path": "src/dagr/asynchronous/batch_norm.py",
    "content": "import torch\nimport asy_tools\nfrom torch_geometric.nn.norm import BatchNorm\nimport torch.nn.functional as F\nfrom .base.base import make_asynchronous, add_async_graph\nfrom .base.utils import graph_changed_nodes, graph_new_nodes\n\n\ndef __sync_forward(m, x):\n    return F.batch_norm(x, m.running_mean, m.running_var, m.weight, m.bias, False, m.momentum, m.eps)\n\n\ndef __graph_initialization(module: BatchNorm, data) -> torch.Tensor:\n    module.asy_graph = data.clone()\n    module.graph_out = data.clone()\n    module.graph_out.x = __sync_forward(module.module, data.x)\n\n    # flops are not counted since BN can be fused with previous conv operator.\n    if module.asy_flops_log is not None:\n        flops = 0\n        module.asy_flops_log.append(flops)\n\n    return module.graph_out.clone()\n\ndef __graph_processing(module: BatchNorm, data) -> torch.Tensor:\n    \"\"\"Batch norms only execute simple normalization operation, which already is very efficient. The overhead\n    for looking for diff nodes would be much larger than computing the dense update.\n\n    However, a new node slightly changes the feature distribution and therefore all activations, when calling\n    the dense implementation. Therefore, we approximate the distribution with the initial distribution as\n    num_new_events << num_initial_events.\n    \"\"\"\n    if len(module.asy_graph.x) < len(data.x):\n        diff_idx = graph_new_nodes(module.asy_graph, data)\n        module.graph_out.x = torch.cat([module.graph_out.x, torch.zeros_like(data.x[:len(diff_idx)])])\n    else:\n        diff_idx, _ = graph_changed_nodes(module.asy_graph, data)\n\n    if data.diff_idx.numel()>0:\n        asy_tools.masked_inplace_BN(data.diff_idx, data.x,\n                                    module.graph_out.x,\n                                    module.module.running_mean,\n                                    module.module.running_var,\n                                    module.module.weight,\n                                    module.module.bias,\n                                    module.module.eps)\n\n    # If required, compute the flops of the asynchronous update operation.\n    if module.asy_flops_log is not None:\n        flops = 0\n        module.asy_flops_log.append(flops)\n\n    data.x = module.graph_out.x\n\n    return data\n\n\ndef __check_support(module):\n    return True\n\n\ndef make_batch_norm_asynchronous(module: BatchNorm, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for batch norm (1d) layers.\n    By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning\n    and moving its weights and configuration. So, a layer can be converted by, for example:\n\n    ```\n    module = BatchNorm(4)\n    module = make_batch_norm_asynchronous(module)\n    ```\n\n    :param module: batch norm module to transform.\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n    assert __check_support(module)\n    module = add_async_graph(module, log_flops=log_flops)\n    return make_asynchronous(module, __graph_initialization, __graph_processing)\n"
  },
  {
    "path": "src/dagr/asynchronous/cartesian.py",
    "content": "import torch\n\nfrom torch_geometric.nn.norm import BatchNorm\nfrom .base.base import make_asynchronous, add_async_graph\n\ndef __edge_attr(pos, edge_index, norm, max):\n    (row, col), pos = edge_index, pos\n\n    cart = pos[row] - pos[col]\n    cart = cart.view(-1, 1) if cart.dim() == 1 else cart\n\n    if norm and cart.numel() > 0:\n        max_value = cart.abs().max() if max is None else max\n        cart = cart / (2 * max_value) + 0.5\n\n    return cart\n\n\ndef __graph_initialization(module: BatchNorm, data) -> torch.Tensor:\n    module.asy_graph = data.clone()\n    module.graph_out = data.clone()\n    module.graph_out.edge_attr = __edge_attr(data.pos, data.edge_index, module.norm, module.max)\n\n    # flops are not counted since BN can be fused with previous conv operator.\n    if module.asy_flops_log is not None:\n        flops = 2 * len(module.graph_out.edge_attr)\n        module.asy_flops_log.append(flops)\n\n    return module.graph_out.clone()\n\n\ndef __graph_processing(module: BatchNorm, data) -> torch.Tensor:\n    \"\"\"Batch norms only execute simple normalization operation, which already is very efficient. The overhead\n    for looking for diff nodes would be much larger than computing the dense update.\n\n    However, a new node slightly changes the feature distribution and therefore all activations, when calling\n    the dense implementation. Therefore, we approximate the distribution with the initial distribution as\n    num_new_events << num_initial_events.\n    \"\"\"\n    module.graph_out.pos = torch.cat([module.asy_graph.pos, data.pos])\n    module.graph_out.x = torch.cat([module.asy_graph.x, data.x])\n    module.graph_out.edge_attr = __edge_attr(module.graph_out.pos, data.edge_index, module.norm, module.max)\n    module.graph_out.edge_index = data.edge_index\n\n    # flops are not counted since BN can be fused with previous conv operator.\n    if module.asy_flops_log is not None:\n        flops = 2 * len(module.graph_out.edge_attr)\n        module.asy_flops_log.append(flops)\n\n    if hasattr(data, \"diff_idx\"):\n        module.graph_out.diff_idx = data.diff_idx\n        module.graph_out.diff_pos_idx = data.diff_pos_idx\n\n    return module.graph_out\n\n\ndef __check_support(module):\n    return True\n\n\ndef make_cartesian_asynchronous(module: BatchNorm, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for cartesian layers.\n    By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning\n    and moving its weights and configuration. So, a layer can be converted by, for example:\n\n    ```\n    module = Cartesian()\n    module = make_cartesian_asynchronous(module)\n    ```\n\n    :param module: cartesian module to transform.\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n    assert __check_support(module)\n    module = add_async_graph(module, log_flops=log_flops)\n    return make_asynchronous(module, __graph_initialization, __graph_processing)"
  },
  {
    "path": "src/dagr/asynchronous/conv.py",
    "content": "import asy_tools\nimport torch\nimport torch_geometric.nn.conv\n\nfrom .base.base import make_asynchronous, add_async_graph\nfrom .base.utils import graph_new_nodes, graph_changed_nodes, _efficient_cat_unique, torch_isin\nfrom .flops import compute_flops_conv, compute_flops_cat\nfrom torch_scatter import scatter_sum\n\n\ndef __conv(x, edge_index, edge_attr, mask, nn):\n    if edge_index.numel() > 0:\n        x_j = x[edge_index[0, :], :]\n        phi = nn.message(x_j, edge_attr=edge_attr[:, :nn.dim])\n        y = nn.aggregate(phi, index=edge_index[1, :], ptr=None, dim_size=x.size()[0])\n    else:\n        y = torch.zeros(size=(x.shape[0], nn.out_channels), dtype=x.dtype, device=x.device)\n\n    if hasattr(nn, \"root_weight\") and nn.root_weight:\n        nn.lin_act = nn.lin(x)\n        y[mask] += nn.lin_act[mask]\n\n    if hasattr(nn, \"bias\") and nn.bias is not None:\n        y[mask] += nn.bias\n\n    return y\n\ndef __graph_initialization(module, data, *args, **kwargs):\n    module.asy_graph = data.clone()\n    module.graph_out = data.clone()\n\n    # Concat old and updated feature for output feature vector.\n    if hasattr(module.asy_graph, \"active_clusters\"):\n        mask = module.asy_graph.active_clusters\n        num_updated_elements = len(mask)\n    else:\n        mask = slice(None)\n        num_updated_elements = len(data.x)\n\n    module.graph_out.x = __conv(data.x, data.edge_index, data.edge_attr, mask, module)\n\n    # If required, compute the flops of the asynchronous update operation. Therefore, sum the flops for each node\n    # update, as they highly depend on the number of neighbors of this node.\n    if module.asy_flops_log is not None:\n        flops = compute_flops_conv(module, num_times_apply_bias_and_root=num_updated_elements, num_edges=data.edge_index.shape[1])\n        module.asy_flops_log.append(flops)\n\n    if hasattr(module, \"to_dense\"):\n        mask = module.graph_out.active_clusters\n        batch = module.graph_out.batch if module.graph_out.batch is None else module.graph_out.batch[mask]\n        if batch is None:\n            batch = torch.zeros(len(module.graph_out.pos[mask]), dtype=torch.long, device=data.x.device)\n        return module.to_dense(module.graph_out.x[mask],\n                               module.graph_out.pos[mask],\n                               module.graph_out.pooling,\n                               batch)\n\n    return module.graph_out.clone()\n\ndef __edges_with_src_node(node_idx, edge_index, edge_attr=None, node_idx_type=\"src\", return_changed_edges=False, return_mask=False):\n    if node_idx.numel() == 0:\n        outputs = [torch.empty(size=(2,0), dtype=torch.long, device=node_idx.device)]\n        if edge_attr is not None:\n            outputs.append(torch.empty(size=(0,3), dtype=edge_attr.dtype, device=edge_attr.device))\n        if return_mask:\n            outputs.append(torch.empty(size=(0,), dtype=torch.bool, device=node_idx.device))\n        if len(outputs) == 1:\n            outputs = outputs[0]\n        return outputs\n\n    if node_idx_type == \"src\":\n        mask = torch_isin(edge_index[0], node_idx)\n    elif node_idx_type == \"dst\":\n        mask = torch_isin(edge_index[1], node_idx)\n    elif node_idx_type == \"both\":\n        mask = torch_isin(edge_index[0], node_idx) | torch_isin(edge_index[1], node_idx)\n    else:\n        raise ValueError\n\n    output = [edge_index[:,mask]]\n    if edge_attr is not None:\n        output.append(edge_attr[mask])\n    if return_changed_edges:\n        output.append(mask.nonzero().ravel())\n    if return_mask:\n        output.append(mask.nonzero().ravel())\n    if len(output) == 1:\n        output = output[0]\n    return output\n\ndef find_only_x(idx_new_comp, idx_diff, pos_idx_diff, edge):\n    return idx_new_comp[torch_isin(idx_new_comp, idx_diff) & ~torch_isin(idx_new_comp, pos_idx_diff) & ~torch_isin(idx_new_comp, edge)]\n\ndef __graph_processing(module, data, *args, **kwargs):\n    \"\"\"Asynchronous graph update for graph convolutional layer.\n\n    After the initialization of the graph, only the nodes (and their receptive field) have to updated which either\n    have changed (different features) or have been added. Therefore, for updating the graph we have to first\n    compute the set of \"diff\" and \"new\" nodes to then do the convolutional message passing on this subgraph,\n    and add the resulting residuals to the graph.\n\n    :param x: graph nodes features.\n    \"\"\"\n    num_edges_image_feat = 0\n    num_edges = 0\n    num_times_apply_bias_and_root = 0\n    new_nodes = len(data.x) > len(module.asy_graph.x)\n\n    # first update the input graph\n    if new_nodes:\n        idx_new = graph_new_nodes(module.asy_graph, data)\n\n        module.asy_graph.x = torch.cat([module.asy_graph.x, data.x[idx_new]])\n        idx_new_comp = idx_new\n\n        # when new edges are added through added events, make sure to add them, otherwise only update the edge attributes\n        module.asy_graph.edge_index = torch.cat([module.asy_graph.edge_index, data.edge_index], dim=-1)\n        module.asy_graph.edge_attr = torch.cat([module.asy_graph.edge_attr, data.edge_attr], dim=0)\n\n        zero_row = torch.zeros(len(idx_new), module.out_channels, device=data.x.device)\n        module.graph_out.x = torch.cat([module.graph_out.x, zero_row])\n\n        data.diff_idx = idx_new_comp\n        pos_idx_diff = torch.zeros(size=(0,), dtype=torch.long, device=data.x.device)\n\n        if idx_new_comp.numel() > 0:\n            edge_index_new, edge_attr_new = data.edge_index, data.edge_attr\n            num_edges += edge_index_new.shape[1]\n    else:\n        idx_diff, pos_idx_diff = graph_changed_nodes(module.asy_graph, data)\n        idx_new_comp = _efficient_cat_unique([pos_idx_diff, idx_diff, data.edge_index[1].unique()])\n        data.diff_idx = idx_new_comp\n\n        if idx_new_comp.numel() > 0:\n            # find out dests of idx new, idx diff and pos_idx_diff\n            edge_index_update_message, mask  = __edges_with_src_node(idx_new_comp, module.asy_graph.edge_index, return_mask=True)\n            edge_attr_update_message = module.asy_graph.edge_attr[mask]\n            num_edges += edge_index_update_message.shape[1]\n            if hasattr(module.asy_graph, \"active_clusters\") and hasattr(data, \"_changed_attr\"):\n                module.asy_graph.edge_attr[data._changed_attr_indices] = data._changed_attr\n                edge_attr_update_message_new = module.asy_graph.edge_attr[mask]\n            else:\n                edge_attr_update_message_new = edge_attr_update_message\n\n        # when new edges are added through added events, make sure to add them, otherwise only update the edge attributes\n        if data.edge_index.numel() > 0:\n            module.asy_graph.edge_index = torch.cat([module.asy_graph.edge_index, data.edge_index], dim=-1)\n            module.asy_graph.edge_attr = torch.cat([module.asy_graph.edge_attr, data.edge_attr], dim=0)\n\n        if idx_new_comp.numel() > 0 and edge_index_update_message.numel() > 0:\n            # first compute update to y\n            x_old = module.asy_graph.x[edge_index_update_message[0], :]\n            phi_old = module.message(x_old, edge_attr=edge_attr_update_message)\n\n            # new messages\n            x_new = data.x[edge_index_update_message[0], :]\n            phi_new = module.message(x_new, edge_attr=edge_attr_update_message_new)\n            scatter_sum(phi_new-phi_old, index=edge_index_update_message[1],out=module.graph_out.x, dim=0, dim_size=len(module.graph_out.x))\n\n            data.diff_idx = _efficient_cat_unique([data.diff_idx, edge_index_update_message[1]])\n            num_edges += edge_index_update_message.shape[1]\n\n        only_x = find_only_x(idx_new_comp, idx_diff, pos_idx_diff, data.edge_index[1])\n        if only_x is not None and len(only_x) > 0:\n            idx_new_comp = idx_new_comp[~torch_isin(idx_new_comp, only_x)]\n            generalized_lin(module, data.x - module.asy_graph.x, module.graph_out.x, only_x)\n            num_times_apply_bias_and_root += len(only_x)\n\n        if idx_new_comp.numel() > 0:\n\n            # edge and attrs for newly computed\n            edge_index_new, edge_attr_new = __edges_with_src_node(idx_new_comp, edge_index=module.asy_graph.edge_index,\n                                                                  edge_attr=module.asy_graph.edge_attr,\n                                                                  node_idx_type=\"dst\")\n\n            edge_index_pos, _ = __edges_with_src_node(pos_idx_diff, edge_index=module.asy_graph.edge_index,\n                                                      edge_attr=module.asy_graph.edge_attr,\n                                                      node_idx_type=\"dst\")\n            num_edges_image_feat = edge_index_pos.shape[1]\n\n            num_edges += edge_index_new.shape[1]\n            module.graph_out.x[idx_new_comp] = 0\n\n    if idx_new_comp.numel() > 0:\n        if edge_index_new.shape[1] > 0:\n            num_edges += edge_index_new.shape[1]\n            # next compute all messages for computing new index\n            x_j = data.x[edge_index_new[0, :], :]\n            phi = module.message(x_j, edge_attr=edge_attr_new[:,:module.dim])\n            scatter_sum(phi, out=module.graph_out.x, index=edge_index_new[1], dim=0, dim_size=len(module.graph_out.x))\n\n        num_times_apply_bias_and_root += len(idx_new_comp)\n        generalized_lin(module, data.x, module.graph_out.x, idx_new_comp)\n\n    data.x = module.graph_out.x\n    data.diff_pos_idx = pos_idx_diff\n\n    # If required, compute the flops of the asynchronous update operation. Therefore, sum the flops for each node\n    # update, as they highly depend on the number of neighbors of this node.\n    if module.asy_flops_log is not None:\n        cat = hasattr(data, \"skipped\") and data.skipped\n        data.skipped = False\n        flops = compute_flops_conv(module, num_times_apply_bias_and_root=len(idx_new_comp), num_edges=num_edges,\n                                   concatenation=cat, num_image_channels=getattr(data, \"num_image_channels\", -1))\n\n        if cat:\n            flops += compute_flops_cat(module, num_edges=num_edges_image_feat,\n                                       num_times_apply_bias_and_root=num_times_apply_bias_and_root, num_image_channels=getattr(data, \"num_image_channels\", -1))\n\n\n        module.asy_flops_log.append(flops)\n\n    if hasattr(module, \"to_dense\"):\n        if pos_idx_diff.numel() > 0 or idx_new_comp.numel() > 0:\n            mask = data.active_clusters\n            batch = data.batch if data.batch is None else data.batch[mask]\n            if batch is None:\n                batch = torch.zeros(len(module.graph_out.pos[mask]), dtype=torch.long, device=data.x.device)\n\n            return module.to_dense(data.x[mask],\n                                   data.pos[mask],\n                                   data.pooling,\n                                   batch)\n        else:\n            return module.dense[:1]\n\n    return data\n\ndef generalized_lin(module, input, output, idx):\n    uses_bias = hasattr(module, \"bias\") and module.bias is not None\n    uses_weight = hasattr(module, \"root_weight\") and module.root_weight\n    if not uses_weight:\n        return\n\n    if uses_bias:\n        asy_tools.masked_lin(idx, input, output, module.lin.weight.data, module.bias.data, True)\n    else:\n        asy_tools.masked_lin_no_bias(idx, input, output, module.lin.weight.data, True)\n\ndef __check_support(module) -> bool:\n    if isinstance(module, torch_geometric.nn.conv.GCNConv):\n        if module.normalize is True:\n            raise NotImplementedError(\"GCNConvs with normalization are not yet supported!\")\n    return True\n\n\ndef make_conv_asynchronous(module, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for graph convolutional layers.\n    By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning\n    and moving its weights and configuration. So, a convolutional layer can be converted by, for example:\n\n    ```\n    module = GCNConv(1, 2)\n    module = make_conv_asynchronous(module)\n    ```\n\n    :param module: convolutional module to transform.\n    :param r: update radius around new events.\n    :param edge_attributes: function for computing edge attributes (default = None).\n    :param is_initial: layer initial layer of sequential or deeper (default = False).\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n    assert __check_support(module)\n\n    module = add_async_graph(module, log_flops=log_flops)\n    return make_asynchronous(module, __graph_initialization, __graph_processing)\n"
  },
  {
    "path": "src/dagr/asynchronous/evaluate_flops.py",
    "content": "import torch\n\nfrom torch_geometric.data import Batch, Data\nfrom typing import List, Tuple\nfrom collections import OrderedDict\n\nfrom . import make_model_asynchronous, make_model_synchronous\n\n\ndef split_data(data: Data, index: int)->Tuple[Data, Data]:\n    kwargs = dict(time_window=data.time_window, width=data.width, height=data.height)\n\n    if hasattr(data, \"image\"):\n        kwargs['image'] = data.image\n\n    data1 = Data(pos=data.pos[:index], x=data.x[:index], **kwargs)\n    data2 = Data(pos=data.pos[index:], x=data.x[index:], **kwargs)\n\n    if hasattr(data, \"pos_denorm\"):\n        data1.pos_denorm = data.pos_denorm[:index]\n        data2.pos_denorm = data.pos_denorm[index:]\n\n    return data1, data2\n\ndef forward_hook(inst, inp, out):\n    inp = inp[0]\n\n    if type(inp) is list:\n        inp = inp[0].clone()\n    elif type(inp) is tuple or type(inp) is dict:\n        return\n    else:\n        inp = inp.clone()\n\n    if type(out) is list:\n        out = out[0].clone()\n    elif type(out) is tuple or type(out) is dict:\n        return\n    else:\n        out = out.clone()\n\n    if not hasattr(inst, \"activations\"):\n        inst.activations = []\n\n    if type(inp) is torch.Tensor:\n        inp = inp if len(inp.shape) == 2 else inp[0]\n        inp = Data(x=inp)\n    if type(out) is torch.Tensor:\n        out = out if len(out.shape) == 2 else out[0]\n        out = Data(x=out)\n\n    if hasattr(inp, \"active_clusters\") and not hasattr(out, \"active_clusters\"):\n        out.active_clusters = inp.active_clusters\n    elif hasattr(out, \"active_clusters\") and not hasattr(inp, \"active_clusters\"):\n        inp.active_clusters = out.active_clusters\n\n    inp = _mask_if_possible(inp)\n    out = _mask_if_possible(out)\n\n    inst.activations.append((inp, out))\n\ndef _mask_if_possible(data):\n    mask = slice(None, None, None)\n    if hasattr(data,\"active_clusters\") and len(data.x) > data.active_clusters.max():\n        mask = data.active_clusters\n    masked = Data()\n    if hasattr(data, \"x\"):\n        masked.x = data.x[mask]\n    if hasattr(data, \"pos\") and data.pos is not None:\n        masked.pos = data.pos[mask]\n    if hasattr(data, \"edge_index\"):\n        masked.edge_index = data.edge_index\n        masked.edge_attr = data.edge_attr\n    return masked\n\ndef denorm(data):\n    denorm = torch.tensor([int(data.width), int(data.height), int(data.time_window)], device=data.pos.device)\n    data.pos_denorm = (denorm.view(1,-1) * data.pos + 1e-3).int()\n    data.batch = data.batch.int()\n    return data\n\ndef evaluate_flops(model: torch.nn.Module, batch: Data, dense=False,\n                   check_consistency=False,\n                   return_all_samples=False) -> OrderedDict:\n\n    flops_per_layer_batch = []\n\n    # for loop over batch\n    for i, data in enumerate(batch.to_data_list()):\n        events_initial, events_new = split_data(data, -1)\n\n        events_initial = Batch.from_data_list([events_initial])\n        events_new = Batch.from_data_list([events_new])\n        data = Batch.from_data_list([data])\n\n        # prepare data for fast inference\n        data = denorm(data)\n        events_new = denorm(events_new)\n        events_initial = denorm(events_initial)\n\n        # make a deep copy asynchronous version\n        handles = []\n        if check_consistency:\n            for m in model.modules():\n                handle = m.register_forward_hook(forward_hook)\n                handles.append(handle)\n\n            with torch.no_grad():\n                model.forward(data, reset=True, return_targets=False)\n\n        model = make_model_asynchronous(model, log_flops=True)\n\n        try:\n            with torch.no_grad():\n                model.forward(events_initial, reset=True, return_targets=False)\n                model.forward(events_new, reset=False, return_targets=False)\n\n        except Exception as e:\n            print(f\"Crashed at index {i} with message {e}\")\n            raise e\n\n        index = 0 if dense else 1\n        flops_per_layer = OrderedDict(\n            [\n                (name, module.asy_flops_log[index]) for name, module in model.named_modules() \\\n                if hasattr(module, \"asy_flops_log\") and module.asy_flops_log is not None and len(\n                module.asy_flops_log) > 0\n            ]\n        )\n\n        flops_per_layer = _filter_non_leaf_nodes(flops_per_layer)\n        flops_per_layer = _merge_to_level_flops(flops_per_layer, level=3)\n\n        if not check_consistency:\n            flops_per_layer_batch.append(flops_per_layer)\n\n        model = make_model_synchronous(model)\n\n        if check_consistency:\n            # tests if outputs from 0th and 2nd run are equal\n            max_mistake_x_layer, max_mistake_pos_layer, global_summary = test_and_compare_activations(model, runs=[0,2])\n            if max_mistake_x_layer[0] > 1e-3 or max_mistake_pos_layer[1] > 1e-3:\n                print(global_summary)\n                print(f\"AssertionError(Failed at index {i}.)\")\n            else:\n                flops_per_layer_batch.append(flops_per_layer)\n                print(global_summary)\n\n            for handle in handles:\n                handle.remove()\n            for m in model.modules():\n                if hasattr(m, \"activations\"):\n                    del m.activations\n\n    if len(flops_per_layer_batch) == 0:\n        return None\n\n    # global average\n    flops_per_layer = _merge_list_flops(flops_per_layer_batch)\n\n    output = {\"flops_per_layer\": flops_per_layer, \"total_flops\": sum(flops_per_layer.values())}\n    if return_all_samples:\n        output['flops_per_layer_batch'] = flops_per_layer_batch\n\n    return output\n\ndef _filter_non_leaf_nodes(flops_per_layer: OrderedDict)->OrderedDict:\n    filter_keys = []\n    for q_name in flops_per_layer:\n        for name in flops_per_layer:\n            if q_name in name and q_name != name:\n                filter_keys.append(q_name)\n                break\n    for f in filter_keys:\n        flops_per_layer.pop(f)\n    return flops_per_layer\n\ndef _merge_to_level_flops(flops_per_layer: OrderedDict, level=2)->OrderedDict:\n    known_flops = []\n    known_keys = []\n    for name, flops in flops_per_layer.items():\n        layers = name.split(\".\")\n        layers_up_to_level = \".\".join(layers[:level])\n        if layers_up_to_level not in known_keys:\n            known_keys.append(layers_up_to_level)\n            known_flops.append(0)\n        index = known_keys.index(layers_up_to_level)\n        known_flops[index] += flops\n\n    return OrderedDict(zip(known_keys, known_flops))\n\ndef _merge_list_flops(flops_per_layer_batch: List[OrderedDict])->OrderedDict:\n    return OrderedDict([(key, sum([f[key] for f in flops_per_layer_batch]) / len(flops_per_layer_batch)) for key in flops_per_layer_batch[0]])\n\ndef _summary(est, gt, prefix):\n    if len(est) != len(gt):\n        return \"\\tCannot compare since x do not have same length\\n\", None\n    max_diff, max_rel_diff, ind, max_ind = max_abs_diff(gt, est, threshold=1e-6)\n\n    summary = f\"\\t{prefix} MAX DIFF: {max_diff} MAX REL DIFF: {max_rel_diff}\\n\"\n    if ind.numel() > 0:\n        summary += f\"\\t{prefix} IND: {max_ind.cpu().numpy().ravel().tolist()}\\n\"\n    return summary, max_diff\n\n\ndef max_rel_diff(x, y, threshold=None):\n    return error_above_threshold((x-y).abs() / (x.abs()+1e-6), threshold)\n\ndef error_above_threshold(error, mag, threshold):\n    if threshold is None:\n        return error.max()\n    else:\n        error_ravel = error.ravel()\n        arg = error_ravel.argmax()\n        return error_ravel[arg], error_ravel[arg] / mag.ravel()[arg], (error > threshold).nonzero()[:,0].unique(), error.max(-1).values.argmax()\n\ndef max_abs_diff(x, y, threshold=None, alpha=0):\n    error = (x-y).abs()-x.abs()*alpha\n    return error_above_threshold(error, x.abs(), threshold)\n\ndef _print_summary_for_one(target, estimate, prefix=\"\"):\n    max_diff_pos = None\n    if type(target) is torch.Tensor:\n        summary, max_diff_x = _summary(target, estimate, prefix)\n    else:\n        summary = \"\"\n        if target.pos is not None and estimate.pos is not None:\n            sub_summary, max_diff_pos = _summary(target.pos[:,:2], estimate.pos[:,:2], f\"{prefix} POS\")\n            summary += sub_summary\n\n        sub_summary, max_diff_x = _summary(target.x, estimate.x, prefix=f\"{prefix} X\")\n        summary += sub_summary\n\n    return summary, max_diff_x, max_diff_pos\n\ndef print_summary_of_module(activations, runs=[0,2]):\n    target, estimate = [activations[i][1] for i in runs]\n    return _print_summary_for_one(target, estimate, \"OUT\")\n\ndef test_and_compare_activations(model, runs=[0,2]):\n    num_mistakes = []\n    global_summary = \"\"\n    for name, module in model.named_modules():\n        if not hasattr(module, \"activations\"):\n            continue\n        else:\n            if len(module.activations) <= max(runs):\n                continue\n\n            summary, max_diff_x, max_diff_pos = print_summary_of_module(module.activations, runs)\n            if max_diff_x is not None and max_diff_pos is not None:\n                num_mistakes.append([max_diff_x, max_diff_pos, name])\n            global_summary += f\"Inspecting {name}\\n{summary}\\n\\n\"\n\n    max_mistake_x_layer = max(num_mistakes, key=lambda x: x[0])\n    max_mistake_pos_layer = max(num_mistakes, key=lambda x: x[1])\n    global_summary += f\"Maximum mistakes: \\n\" \\\n                      f\"\\t{max_mistake_x_layer}\\n\" \\\n                      f\"\\t{max_mistake_pos_layer}\"\n\n    return max_mistake_x_layer, max_mistake_pos_layer, global_summary\n"
  },
  {
    "path": "src/dagr/asynchronous/flops/__init__.py",
    "content": "import logging\nfrom torch.nn import ModuleList\n\nfrom .conv import compute_flops_conv, compute_flops_cat\n\n\ndef compute_flops_from_module(module) -> int:\n    \"\"\"Compute flops from a GNN module (after the forward pass).\n\n    Generally, there are two cases. Either the module is an asynchronous module, then it should\n    have an `flops_log`, which contains the flops used for the last forward pass. Otherwise, the\n    layer's flops are computed from to the synchronous, dense update.\n\n    :param module: module to infer the flops from.\n    \"\"\"\n    module_name = module.__class__.__name__\n\n    if hasattr(module, \"asy_flops_log\") and module.asy_flops_log is not None:\n        assert type(module.asy_flops_log) == list, \"asyc. flops log must be a list\"\n        if type(module) is ModuleList:\n            flops = sum([compute_flops_from_module(layer) for layer in module._modules.values()])\n        else:\n            assert len(module.asy_flops_log) > 0, f\"asynchronous flops log is empty for module {module.__class__.__name__}\"\n            flops = module.asy_flops_log[-1]\n    else:\n        logging.debug(f\"Module {module_name} is not asynchronous, using flops = 0\")\n        return 0\n\n    logging.debug(f\"Module {module_name} adds {flops} flops\")\n    return flops\n\n\n__all__ = [\n    \"compute_flops_conv\",\n    \"compute_flops_from_module\"\n]\n"
  },
  {
    "path": "src/dagr/asynchronous/flops/conv.py",
    "content": "import torch\n\n\ndef compute_flops_conv(module: torch.nn.Module, num_times_apply_bias_and_root: int, num_edges: int, concatenation=False, num_image_channels=-1) -> int:\n    # Iterate over every different and every new node, and add the number of flops introduced\n    # by the node to the overall flops count of the layer.\n    ni = num_edges\n\n    m_in = module.in_channels\n\n    if concatenation:\n        m_in -= num_image_channels\n\n    m_out = module.out_channels\n\n    flops = ni * (2*m_in-1) * m_out\n\n    if hasattr(module, \"root_weight\") and module.root_weight:\n        flops += num_times_apply_bias_and_root * module.lin.weight.shape[0] * (2*module.lin.weight.shape[1]-1)\n\n    if hasattr(module, \"bias\") and module.bias is not None:\n        flops += num_times_apply_bias_and_root * module.lin.weight.shape[0]\n\n    return flops\n\n\ndef compute_flops_cat(module, num_edges, num_times_apply_bias_and_root, num_image_channels):\n    ni = num_edges\n    m_in = num_image_channels\n    m_out = module.out_channels\n\n    flops =  ni * (2 * m_in - 1) * m_out\n\n    if hasattr(module, \"root_weight\") and module.root_weight:\n        flops += num_times_apply_bias_and_root * module.lin.weight.shape[0] * (2*m_in-1)\n\n    return flops"
  },
  {
    "path": "src/dagr/asynchronous/linear.py",
    "content": "import numpy as np\nimport torch\nimport torch_geometric\nimport asy_tools\n\nfrom torch.nn import Linear\nimport torch.nn.functional as F\nfrom .base.base import make_asynchronous, add_async_graph\nfrom .base.utils import graph_new_nodes, graph_changed_nodes\n\n\ndef __graph_initialization(module: Linear, data) -> torch.Tensor:\n    mask = data.active_clusters if hasattr(data, \"active_clusters\") else slice(None, None, None)\n    x = data.x[mask]\n    weight = module.mlp.weight\n    bias = module.mlp.bias\n\n    y = torch.zeros(size=(len(data.x), weight.shape[0]), dtype=torch.float32, device=data.pos.device)\n    y[mask] = F.linear(x, weight, bias)\n\n    module.asy_graph = data.clone()\n    module.graph_out = torch_geometric.data.Data(x=y, pos=data.pos)\n    if hasattr(data, \"active_clusters\"):\n        module.graph_out.active_clusters = data.active_clusters\n\n    if module.asy_flops_log is not None:\n        flops = int(np.prod(x.size()) * y.size()[-1])\n        module.asy_flops_log.append(flops)\n\n    return module.graph_out.clone()\n\ndef __graph_processing(module: Linear, data) -> torch.Tensor:\n    if len(module.asy_graph.x) < len(data.x):\n        diff_idx = graph_new_nodes(module.asy_graph, data)\n        diff_pos_idx = diff_idx.clone()\n        module.graph_out.x = torch.cat([module.graph_out.x, torch.zeros_like(module.graph_out.x[:len(diff_idx)])])\n    else:\n        diff_idx, diff_pos_idx = graph_changed_nodes(module.asy_graph, data)\n\n    weight = module.mlp.weight\n    bias = module.mlp.bias\n\n    # Update the graph with the new values (only there where it has changed).\n    if diff_idx.numel() > 0:\n        if bias is not None:\n           asy_tools.masked_lin(diff_idx, data.x, module.graph_out.x, weight.data, bias.data, False)\n        else:\n           asy_tools.masked_lin_no_bias(diff_idx, data.x, module.graph_out.x, weight.data, False)\n\n    # If required, compute the flops of the asynchronous update operation.\n    if module.asy_flops_log is not None:\n        cin = weight.shape[1]\n        cat = hasattr(data, \"skipped\") and data.skipped\n        data.skipped = False\n\n        if cat:\n            cin -= data.num_image_channels\n\n        flops = diff_idx.numel() * int(weight.shape[0] * (2*cin-1))\n        flops += diff_idx.numel() * weight.shape[0]\n        module.asy_flops_log.append(flops)\n\n    data.diff_idx = diff_idx\n    data.diff_pos_idx = diff_pos_idx\n    data.x = module.graph_out.x\n\n    return data\n\ndef __check_support(module: Linear):\n    return True\n\n\ndef make_linear_asynchronous(module: Linear, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for linear layers.\n    By overwriting parts of the module asynchronous processing can be enabled without the need of re-learning\n    and moving its weights and configuration. So, a linear layer can be converted by, for example:\n\n    ```\n    module = Linear(4, 2)\n    module = make_linear_asynchronous(module)\n    ```\n\n    :param module: linear module to transform.\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n    assert __check_support(module)\n    module = add_async_graph(module, log_flops=log_flops)\n    return make_asynchronous(module, __graph_initialization, __graph_processing)\n"
  },
  {
    "path": "src/dagr/asynchronous/max_pool.py",
    "content": "import logging\nimport torch\n\nfrom torch_geometric.data import Data\nfrom torch_scatter import scatter_max, scatter_sum\n\nfrom .base.base import add_async_graph, make_asynchronous\nfrom .base.utils import graph_changed_nodes, graph_new_nodes, _efficient_cat_unique, torch_isin, _efficient_cat\nfrom .conv import __edges_with_src_node\nfrom .base.utils import _to_hom, _from_hom, __remove_duplicate_from_A\n\n\ndef pool_edge(cluster, edge_index, self_loop):\n    edge_index = cluster[edge_index]\n    if self_loop:\n        edge_index = edge_index.unique(dim=-1)\n    else:\n        edge_index = edge_index[:,edge_index[0]!=edge_index[1]].unique(dim=-1)\n\n    if len(edge_index) > 0:\n        return edge_index\n    return torch.zeros((2,0), dtype=torch.long, device=cluster.device)\n\n\ndef compute_attrs(transform, edge_index, pos):\n    return (pos[edge_index[0]] - pos[edge_index[1]])  /  (2 * transform.max) + 0.5\n\n\ndef __dense_process(module, data: Data, *args, **kwargs) -> Data:\n    # compute the cache to compute the output graph. This contains\n    # 1. the cluster assignment for each input feature -> dim num_input_nodes\n    # 2. the sum of positions for each feature in each cluster -> max_num_clusters\n    # 3. the count of positions for each feature -> max_num_clusters\n    # 4. which input nodes went to the computation of which output_node -> max_num_clusters x num_output\n    cluster_index = __get_global_cluster_index(module, pos=data.pos[:,:module.dim])\n    x, pos = data.x, data.pos\n    edge_index = pool_edge(cluster_index, data.edge_index, module.self_loop)\n\n    if hasattr(module.asy_graph, \"active_clusters\"):\n        active_cluster_index = cluster_index[module.asy_graph.active_clusters]\n        new_cluster_index = torch.full_like(cluster_index, fill_value=-1)\n        new_cluster_index[module.asy_graph.active_clusters] = active_cluster_index\n        cluster_index = new_cluster_index\n        x = x[module.asy_graph.active_clusters]\n        pos = pos[module.asy_graph.active_clusters]\n    else:\n        active_cluster_index = cluster_index\n\n    pos_hom = scatter_sum(_to_hom(pos[:,:module.dim]), active_cluster_index, dim=0, dim_size=module.num_grid_cells)\n    output_pos = _from_hom(pos_hom)\n\n    module.wh_inv = 1/ torch.Tensor([data.width[0], data.height[0]]).to(output_pos.device).view(1,-1)\n    output_pos[:,:2] = module.round_to_pixel(output_pos[:,:2], wh_inv=module.wh_inv)\n\n    active_clusters = torch.unique(active_cluster_index)\n\n    cache = Data(cluster_index=cluster_index, pos_hom=pos_hom)\n\n    if module.aggr == 'max':\n        output_x = torch.full(size=(module.num_grid_cells, x.shape[1]), fill_value=-torch.inf, device=x.device)\n        _, output_argmax = scatter_max(x, active_cluster_index, dim=0, out=output_x, dim_size=module.num_grid_cells)\n        cache.output_argmax = output_argmax\n    else:\n        x_hom = _to_hom(x)\n        cache.output_x_hom = scatter_sum(x_hom, active_cluster_index, dim=0, dim_size=module.num_grid_cells)\n        output_x = _from_hom(cache.output_x_hom)\n\n    module.ones = torch.ones_like(output_x[:,:1])\n\n    # construct output. This contains:\n    # the output graph -> has num_unique_clusters nodes\n    if module.keep_temporal_ordering:\n        t = pos[:, -1] if pos.shape[-1] > 2 else data.t_max[active_cluster_index]\n        output_t = torch.full(size=(module.num_grid_cells,), fill_value=-torch.inf, device=x.device)\n        t_max, _ = scatter_max(t, active_cluster_index, dim=0, out=output_t, dim_size=module.num_grid_cells)\n        if edge_index.shape[1] > 0:\n            t_src, t_dst = t_max[edge_index]\n            edge_index = edge_index[:, t_dst > t_src]\n\n    output_graph = Data(x=output_x,\n                        pos=output_pos,\n                        edge_index=edge_index,\n                        active_clusters=active_clusters,\n                        width=data.width,\n                        height=data.height)\n\n    if module.keep_temporal_ordering:\n        output_graph.t_max = output_t\n\n    if module.transform is not None:\n        output_graph = module.transform(output_graph)\n\n    return output_graph, cache\n\ndef __graph_initialization(module, data: Data, *args, **kwargs) -> Data:\n    \"\"\"Graph initialization for asynchronous update.\n\n    Both the input as well as the output graph have to be stored, in order to avoid repeated computation. The\n    input graph is used for spotting changed or new nodes (as for other asyn. layers), while the output graph\n    is compared to the set of diff & new nodes, in order to be updated. Depending on the type of pooling (max, mean,\n    average, etc) not only the output voxel feature have to be stored but also aggregations over all nodes in\n    one output voxel such as the sum or count.\n\n    Next to the features the node positions are averaged over all nodes in the voxel, as well. To do so,\n    position aggregations (count, sum) are stored and updated, too.\n    \"\"\"\n    module.asy_graph = data.clone()\n    module.graph_out, module.cache  = __dense_process(module, data)\n    module.graph_out.pooling = module.voxel_size\n\n    logging.debug(f\"Resulting in coarse graph {module.graph_out}\")\n\n    # Compute number of floating point operations (no cat, flatten, etc.).\n    if module.asy_flops_log is not None:\n        unique_clusters = len(module.graph_out.active_clusters)\n        flops = 6 * unique_clusters # pos and scatter with index\n        flops += module.graph_out.x.shape[1] * unique_clusters + module.graph_out.edge_index.numel()  # every edge has to be re-assigned\n        module.asy_flops_log.append(flops)\n\n    return module.graph_out.clone()\n\n#@profile\ndef __graph_process(module, data, *args, **kwargs) -> Data:\n    new_nodes = len(data.x) > len(module.asy_graph.x)\n\n    if new_nodes:\n        new_idx = graph_new_nodes(module.asy_graph, data)\n\n        module.asy_graph.x = torch.cat([module.asy_graph.x, data.x[new_idx]])\n        module.asy_graph.pos = torch.cat([module.asy_graph.pos, data.pos[new_idx]])\n\n        new_cluster_idx = __get_global_cluster_index(module, data.pos[new_idx, :module.dim])\n\n        # add to active clusters\n        if new_idx.numel() > 0:\n            module.graph_out.active_clusters = torch.cat([new_cluster_idx, module.graph_out.active_clusters]).sort().values.unique()\n\n        module.cache.cluster_index = torch.cat([module.cache.cluster_index, new_cluster_idx])\n        diff_pos_idx = new_idx\n        new_pos_hom = _to_hom(data.pos[new_idx, :module.dim], module.ones)\n        recomp_pos_new = new_cluster_idx\n        recomp_x_new = new_cluster_idx\n        if recomp_x_new.numel() > 0:\n            recomp_x_new = recomp_x_new#.clone()\n\n        num_diff_x = 0#len(diff_idx)\n        num_new = len(new_idx)\n        scatter_sum(new_pos_hom, new_cluster_idx, out=module.cache.pos_hom, dim=0)\n\n        if recomp_x_new.numel() > 0:\n            if module.aggr == \"max\":\n                mask = torch.cat([module.cache.output_argmax[recomp_x_new].ravel(), new_idx]).unique()\n            else:\n                mask = torch_isin(module.cache.cluster_index, recomp_x_new)\n\n    else:\n        num_new = 0\n\n        diff_idx, diff_pos_idx = graph_changed_nodes(module.asy_graph, data)\n        num_diff_x = len(diff_idx)\n\n        recomp_x_new = None\n        recomp_pos_new = None\n\n        if diff_pos_idx.numel()> 0:\n            inactive = torch_isin(diff_pos_idx, module.asy_graph.active_clusters)\n            old_pos = module.asy_graph.pos[diff_pos_idx[inactive], :module.dim]\n            module.asy_graph.pos[diff_pos_idx] = data.pos[diff_pos_idx]\n\n            old_pos_hom = _to_hom(old_pos, module.ones)\n            old_cluster_idx_pos = __get_global_cluster_index(module, old_pos)\n            new_pos_hom = _to_hom(data.pos[diff_pos_idx, :module.dim], module.ones)\n            all_pos = torch.cat([-old_pos_hom, new_pos_hom])\n            new_cluster_idx_pos = __get_global_cluster_index(module, data.pos[diff_pos_idx, :module.dim])\n            module.cache.cluster_index[diff_pos_idx] = new_cluster_idx_pos\n\n            recomp_x_new = new_cluster_idx_pos\n            recomp_pos_new = _efficient_cat([old_cluster_idx_pos, new_cluster_idx_pos])\n            # todo stupid bug, shallow copy could occur\n            if recomp_pos_new.numel()>0 and recomp_pos_new.data_ptr() == recomp_x_new.data_ptr():\n                recomp_pos_new = recomp_pos_new#.clone()\n            scatter_sum(all_pos, recomp_pos_new, out=module.cache.pos_hom, dim=0)\n\n        if diff_idx.numel() > 0:\n            cluster_idx_x = __get_global_cluster_index(module, module.asy_graph.pos[diff_idx, :module.dim])\n            recomp_x_new = cluster_idx_x if recomp_x_new is None else _efficient_cat_unique([recomp_x_new, cluster_idx_x])\n\n        if recomp_x_new is not None and recomp_x_new.numel() > 0:\n            mask = torch_isin(module.cache.cluster_index, recomp_x_new)\n            if module.aggr == \"max\":\n                module.graph_out.x[recomp_x_new] = -torch.inf\n\n    if recomp_x_new is not None and recomp_x_new.numel() > 0:\n        if module.aggr == \"max\":\n            scatter_max(data.x[mask], module.cache.cluster_index[mask], out=module.graph_out.x, dim=0)\n        else:\n            delta_x_hom = _to_hom(data.x[mask], module.ones) #\n            valid = ~torch.isinf(module.asy_graph.x[mask][:,0])\n            delta_x_hom[valid] -= _to_hom(module.asy_graph.x[mask][valid], module.ones)\n            scatter_sum(delta_x_hom, module.cache.cluster_index[mask], out=module.cache.output_x_hom, dim=0)\n            module.graph_out.x[recomp_x_new] = _from_hom(module.cache.output_x_hom[recomp_x_new])\n\n    # find the edges which are associated with changed positions since these need their attrs updated\n    # however, here we can only look at the x,y values. If only the third attr changes, then we don't need to do anything\n    if recomp_pos_new is not None and recomp_pos_new.numel() > 0:\n        # update pos with the updated positions\n        new_pos = _from_hom(module.cache.pos_hom[recomp_pos_new])\n        new_pos[:,:2] = module.round_to_pixel(new_pos[:,:2], wh_inv=module.wh_inv)\n        module.graph_out.pos[recomp_pos_new,:module.dim] = new_pos\n        update_edge_index, changed_edges = __edges_with_src_node(recomp_pos_new, module.graph_out.edge_index, node_idx_type=\"both\", return_changed_edges=True)\n        if module.transform is not None:\n            module.graph_out._changed_attr = compute_attrs(module.transform, update_edge_index, module.graph_out.pos)\n            module.graph_out._changed_attr_indices = changed_edges\n\n    # also handle edges which come from new connections at the input. These first need to be pooled\n    # then check if they are actually new.\n    if data.edge_index.numel() > 0:\n        coarse_edge_index = pool_edge(module.cache.cluster_index, data.edge_index, module.self_loop)\n        module.graph_out.edge_index = __remove_duplicate_from_A(coarse_edge_index, module.graph_out.edge_index)\n    else:\n        module.graph_out.edge_index = data.edge_index#torch.empty((2, 0), dtype=torch.long, device=data.x.device)\n\n    if module.transform is not None:\n        if module.graph_out.edge_index.numel() > 0:\n            module.graph_out.edge_attr = compute_attrs(module.transform, module.graph_out.edge_index, module.graph_out.pos)\n        else:\n            module.graph_out.edge_attr = data.edge_attr\n\n    module.graph_out.diff_idx = recomp_x_new.unique() if recomp_x_new is not None else diff_idx\n    module.graph_out.diff_pos_idx = recomp_pos_new.unique() if recomp_pos_new is not None else diff_pos_idx\n\n    if module.asy_flops_log is not None:\n        num_recomp_x = 0 if recomp_x_new is None else len(recomp_x_new)\n        num_recomp_pos = 0 if recomp_pos_new is None else len(recomp_pos_new)\n        flops = 0\n        flops += num_recomp_x * module.graph_out.x.shape[1]  # perform max\n        flops += num_recomp_pos                       # recompute pos\n        flops += 4 * len(diff_pos_idx)                        # subtract and add pos twice\n        flops += len(diff_pos_idx) + num_diff_x          # get cluster center for each index\n        flops += num_new * 2                             # add twice, also compute cluster center\n        module.asy_flops_log.append(flops)\n\n    return module.graph_out\n\ndef __get_global_cluster_index(module, pos) -> torch.LongTensor:\n    n_pos_dim = 2#pos.shape[1]\n    voxel_size = module.voxel_size[:n_pos_dim]#, device=pos.device)\n    pos_vertex = (pos[:,:2] / voxel_size).long()\n    x_v, y_v = pos_vertex.t()\n    grid_size = (1 / voxel_size + 1e-3).long()\n    cluster_idx = x_v + grid_size[0] * y_v\n    return cluster_idx\n\n\ndef make_max_pool_asynchronous(module, log_flops: bool = False):\n    \"\"\"Module converter from synchronous to asynchronous & sparse processing for graph max pooling layer.\n    By overwriting parts of the module asynchronous processing can be enabled without the need re-creating the\n    object. So, a max pooling layer can be converted by, for example:\n\n    ```\n    module = MaxPool([4, 4])\n    module = make_max_pool_asynchronous(module)\n    ```\n\n    :param module: standard max pooling module.\n    :param grid_size: grid size (grid starting at 0, spanning to `grid_size`), >= `size`.\n    :param r: update radius around new events.\n    :param log_flops: log flops of asynchronous update.\n    \"\"\"\n\n    module = add_async_graph(module, log_flops=log_flops)\n    module = make_asynchronous(module, __graph_initialization, __graph_process)\n    return module\n"
  },
  {
    "path": "src/dagr/data/augment.py",
    "content": "import torch\n\nfrom torch_geometric.transforms import BaseTransform\nfrom torch_geometric.data import Data\nfrom typing import List\n\nimport cv2\nimport numpy as np\nimport numba\nimport torch_geometric.transforms as T\n\n\n@numba.njit\ndef _add_event(x, y, xlim, ylim, p, i, count, pos, mask, threshold=1):\n    count[ylim, xlim] += float(p * (1 - abs(x - xlim)) * (1 - abs(y - ylim)))\n    pol = 1 if count[ylim, xlim] > 0 else -1\n\n    if pol * count[ylim, xlim] > threshold:\n        count[ylim, xlim] -= pol * threshold\n\n        mask[i] = True\n        pos[i, 0] = xlim\n        pos[i, 1] = ylim\n\n\n@numba.njit\ndef _subsample(pos: np.ndarray, polarity: np.ndarray, mask: np.ndarray, count: np.ndarray, threshold=1):\n    for i in range(len(pos)):\n        x, y = pos[i]\n        x0, x1 = int(x), int(x+1)\n        y0, y1 = int(y), int(y+1)\n\n        _add_event(x, y, x0, y0, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)\n        _add_event(x, y, x1, y0, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)\n        _add_event(x, y, x0, y1, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)\n        _add_event(x, y, x1, y1, polarity[i,0], i=i, count=count, pos=pos, mask=mask, threshold=threshold)\n\n\ndef _crop_events(data, left, right, not_crop_idx=None):\n    if not_crop_idx is None:\n        not_crop_idx = torch.all((data.pos >= left) & (data.pos <= right), dim=1)\n\n    data.x = data.x[not_crop_idx]\n    data.pos = data.pos[not_crop_idx]\n\n    if hasattr(data, \"t\"):\n        data.t = data.t[not_crop_idx]\n\n    return data\n\ndef _crop_image(image, left, right):\n    xmin, ymin = left\n    xmax, ymax = right\n    image[:ymin, :] = 0\n    image[ymax:, :] = 0\n    image[:, :xmin] = 0\n    image[:, xmax:] = 0\n    return image\n\ndef _resize_image(image, height, width, bg=None):\n\n    image = image[0].permute(1, 2, 0).numpy()\n    new_image = cv2.resize(image, (width, height), interpolation=cv2.INTER_NEAREST)\n\n    px = (new_image.shape[1] - image.shape[1])//2\n    py = (new_image.shape[0] - image.shape[0])//2\n\n    if px >= 0:\n        bg = new_image[py:py+image.shape[0], px:px+image.shape[1]]\n    else:\n        assert bg is not None\n        bg[-py:-py+new_image.shape[0], -px:-px+new_image.shape[1]] = new_image\n\n    bg = torch.from_numpy(bg).permute(2, 0, 1)[None]\n\n    return bg\n\ndef _crop_bbox(bbox: torch.Tensor, left: torch.Tensor, right: torch.Tensor):\n    bbox = bbox.clone()\n    bbox[:,2:4] += bbox[:,:2]\n    bbox[:,:2] = torch.clamp(bbox[:,:2], min=left, max=right)\n    bbox[:,2:4] = torch.clamp(bbox[:,2:4], min=left, max=right)\n    bbox[:,2:4] -= bbox[:,:2]\n    return bbox\n\ndef _scale_and_clip(x, scale):\n    return int(torch.clamp(x * scale, min=0, max=scale-1))\n\n\nclass RandomHFlip(BaseTransform):\n    def __init__(self, p: float):\n        self.p = p\n\n    def __call__(self, data: Data):\n        if torch.rand(1) > self.p:\n            return data\n\n        data.pos[:,0] = data.width - 1 - data.pos[:,0]\n\n        if hasattr(data, \"image\"):\n            image = data.image[0].permute(1,2,0).numpy()\n            image = np.ascontiguousarray(image[:,::-1])\n            image = torch.from_numpy(image).permute(2, 0, 1)[None]\n            data.image = image\n\n        if hasattr(data, \"bbox\"):\n            data.bbox[:, 0] = data.width - 1 - (data.bbox[:, 0] + data.bbox[:, 2])\n\n        if hasattr(data, \"bbox0\"):\n            data.bbox0[:, 0] = data.width - 1 - (data.bbox0[:, 0] + data.bbox0[:, 2])\n\n        return data\n\n\nclass Crop(BaseTransform):\n    r\"\"\"Crop with max and min values, has to be called before a graph is generated.\n\n    Args:\n        min (List[float]): min value per dimension\n        max (List[float]): max value per dimension\n    \"\"\"\n    def __init__(self, min: List[float], max: List[float]):\n        self.min = torch.as_tensor(min)\n        self.max = torch.as_tensor(max)\n\n    def init(self, height, width):\n        size = [width, height]\n        self.max = torch.IntTensor([_scale_and_clip(m, s) for m, s in zip(self.max, size)])\n        self.min = torch.IntTensor([_scale_and_clip(m, s) for m, s in zip(self.min, size)])\n\n    def __call__(self, data: Data):\n        data = _crop_events(data, self.min, self.max)\n\n        if hasattr(data, \"image\"):\n            data.image = _crop_image(data.image, self.min, self.max)\n\n        # crop bbox to dimension\n        if hasattr(data, \"bbox\"):\n            data.bbox = _crop_bbox(data.bbox, self.min, self.max)\n\n        if hasattr(data, \"bbox0\"):\n            data.bbox0 = _crop_bbox(data.bbox0, self.min, self.max)\n\n        return data\n\n\nclass RandomZoom(BaseTransform):\n    def __init__(self, zoom, subsample=False):\n        self.zoom = zoom\n        self.subsample = subsample\n        self.image = None\n\n        if subsample:\n            self._count = None\n\n    def _subsample(self, data, zoom, count):\n        pos_zoom = data.pos.numpy()\n\n        mask = np.zeros(len(data.pos), dtype=\"bool\")\n        _subsample(pos_zoom, data.x.numpy(), mask, count, threshold=1/(float(zoom)**2))\n\n        data.pos = torch.from_numpy(pos_zoom[mask].astype(\"int16\")) # implicit cast to int\n        data.x = data.x[mask]\n        if hasattr(data, \"t\"):\n            data.t = data.t[mask]\n\n        return data\n\n    def init(self, height, width):\n        self.image = np.zeros((height, width, 3), dtype=\"uint8\")\n        self._count = np.zeros((height + 1, width + 1), dtype=\"float32\")\n\n    def __call__(self, data):\n        zoom = torch.rand(1) * (self.zoom[1] - self.zoom[0]) + self.zoom[0]\n        width, height = int(np.ceil(data.width * zoom)), int(np.ceil(data.height * zoom))\n        H, W = self.image.shape[:2]\n\n        data.pos[:, 0] = ((data.pos[:, 0] - W // 2) * zoom + W // 2).to(torch.int16)\n        data.pos[:, 1] = ((data.pos[:, 1] - H // 2) * zoom + H // 2).to(torch.int16)\n\n        if self.subsample and zoom < 1:\n            data = self._subsample(data, float(zoom), count=self._count.copy())\n\n        if hasattr(data, \"image\"):\n            data.image = _resize_image(data.image, width=width, height=height, bg=self.image.copy() if zoom < 1 else None)\n\n        if hasattr(data, \"bbox\"):\n            data.bbox[:,2:4] *= zoom\n            data.bbox[:,0] = ((data.bbox[:,0] - W//2) * zoom + W//2)\n            data.bbox[:,1] = ((data.bbox[:,1] - H//2) * zoom + H//2)\n\n        if hasattr(data, \"bbox0\"):\n            data.bbox0[:,2:4] *= zoom\n            data.bbox0[:,0] = ((data.bbox0[:,0] - W//2) * zoom + W//2)\n            data.bbox0[:,1] = ((data.bbox0[:,1] - H//2) * zoom + H//2)\n\n        return data\n\n\nclass RandomCrop(BaseTransform):\n    r\"\"\"Random crop, assumes all pos values are in [0,1]\n\n    Args:\n        size (List[float]): crop size per dimension\n        dim (List[int]): dimension of the crop, default = [0,1]\n        p float: only to random crop with a probability of p\n    \"\"\"\n    def __init__(self, size: List[float] = [0.75, 0.75], dim: List[int]=[0,1], p=0.5):\n        self.size = torch.as_tensor(size)\n        self.dim = dim\n        self.p = p\n\n    def init(self, height, width):\n        size = torch.IntTensor([width, height])\n        self.size = torch.IntTensor([_scale_and_clip(s, ss) for s, ss in zip(self.size, size)])\n        self.left_max = size - self.size\n\n    def __call__(self, data: Data):\n        if torch.rand(1) > self.p:\n            return data\n\n        left = (torch.rand(len(self.dim)) * self.left_max).to(torch.int16)\n        right = left + self.size\n\n        data = _crop_events(data, left, right)\n\n        if hasattr(data, \"image\"):\n            data.image = _crop_image(data.image, left, right)\n\n        # crop bbox to new crop dimension\n        if hasattr(data, \"bbox\"):\n            data.bbox = _crop_bbox(data.bbox, left, right)\n\n        if hasattr(data, \"bbox0\"):\n            data.bbox0 = _crop_bbox(data.bbox0, left, right)\n\n        return data\n\n\nclass RandomTranslate(BaseTransform):\n    r\"\"\"Random crop, assumes all pos values are in [0,1]\n\n    Args:\n        size (float): crop size per dimension\n        dim (int): dimension of the crop, default = [0,1]\n    \"\"\"\n    def __init__(self, size: List[float]):\n        self.size = torch.as_tensor(size).float()\n        self.image = None\n\n    def init(self, height, width):\n        size = [width, height]\n        self.size = torch.IntTensor([_scale_and_clip(s, ss) for s, ss in zip(self.size, size)])\n        self.image = np.zeros((height + 2 * self.size[1], width + 2 * self.size[0], 3), dtype=\"uint8\")\n\n    def pad(self, image, bg):\n        px = (bg.shape[1] - image.shape[1])//2\n        py = (bg.shape[0] - image.shape[0])//2\n        bg[py:py + image.shape[0], px:px + image.shape[1]] = image\n        return bg\n\n    def __call__(self, data: Data):\n        move_px = (self.size * (torch.rand(len(self.size)) * 2 - 1)).to(torch.int16)\n        data.pos = data.pos + move_px\n\n        if hasattr(data, \"image\"):\n            image = data.image[0].permute(1, 2, 0).numpy()\n            image = self.pad(image, self.image.copy())\n            image = image[self.size[1]-move_px[1]:self.size[1]-move_px[1]+data.height, \\\n                          self.size[0]-move_px[0]:self.size[0]-move_px[0]+data.width]\n            data.image = torch.from_numpy(image).permute(2, 0, 1)[None]\n\n        if hasattr(data, \"bbox\"):\n            data.bbox[:,:2] += move_px\n\n        if hasattr(data, \"bbox0\"):\n            data.bbox0[:,:2] += move_px\n\n        return data\n\n\nclass Augmentations:\n    transform_testing = T.Compose([\n        Crop([0, 0], [1, 1]),\n    ])\n\n    def __init__(self, args):\n        self.transform_training = T.Compose([\n            RandomHFlip(p=args.aug_p_flip),\n            RandomCrop([0.75, 0.75], p=0.2),\n            RandomZoom(zoom=[1, args.aug_zoom], subsample=True),\n            RandomTranslate([args.aug_trans, args.aug_trans, 0]),\n            Crop([0, 0], [1, 1]),\n        ])\n\ndef init_transforms(transforms, height, width):\n    for t in transforms:\n        if hasattr(t, \"init\"):\n            t.init(height=height, width=width)"
  },
  {
    "path": "src/dagr/data/dsec_data.py",
    "content": "from pathlib import Path\nfrom typing import Optional, Callable\n\nfrom torch_geometric.data import Dataset\n\nimport numpy as np\nimport cv2\n\nimport torch\nfrom functools import lru_cache\n\nfrom dsec_det.dataset import DSECDet\n\nfrom dsec_det.io import yaml_file_to_dict\nfrom dagr.data.dsec_utils import filter_tracks, crop_tracks, rescale_tracks, compute_class_mapping, map_classes, filter_small_bboxes\nfrom dsec_det.directory import BaseDirectory\nfrom dagr.data.augment import init_transforms\nfrom dagr.data.utils import to_data\n\nfrom dagr.visualization.bbox_viz import draw_bbox_on_img\nfrom dagr.visualization.event_viz import draw_events_on_image\n\n\ndef tracks_to_array(tracks):\n    return np.stack([tracks['x'], tracks['y'], tracks['w'], tracks['h'], tracks['class_id']], axis=1)\n\n\n\ndef interpolate_tracks(detections_0, detections_1, t):\n    assert len(detections_1) == len(detections_0)\n    if len(detections_0) == 0:\n        return detections_1\n\n    t0 = detections_0['t'][0]\n    t1 = detections_1['t'][0]\n\n    assert t0 < t1\n\n    # need to sort detections\n    detections_0 = detections_0[detections_0['track_id'].argsort()]\n    detections_1 = detections_1[detections_1['track_id'].argsort()]\n\n    r = ( t - t0 ) / ( t1 - t0 )\n    detections_out = detections_0.copy()\n    for k in 'xywh':\n        detections_out[k] = detections_0[k] * (1 - r) + detections_1[k] * r\n\n    return detections_out\n\nclass EventDirectory(BaseDirectory):\n    @property\n    @lru_cache\n    def event_file(self):\n        return self.root / \"left/events_2x.h5\"\n\n\nclass DSEC(Dataset):\n    MAPPING = dict(pedestrian=\"pedestrian\", rider=None, car=\"car\", bus=\"car\", truck=\"car\", bicycle=None,\n                   motorcycle=None, train=None)\n    def __init__(self,\n                 root: Path,\n                 split: str,\n                 transform: Optional[Callable]=None,\n                 debug=False,\n                 min_bbox_diag=0,\n                 min_bbox_height=0,\n                 scale=2,\n                 cropped_height=430,\n                 only_perfect_tracks=False,\n                 demo=False,\n                 no_eval=False):\n\n        Dataset.__init__(self)\n\n        split_config = None\n        if not demo:\n            split_config = yaml_file_to_dict(Path(__file__).parent / \"dsec_split.yaml\")\n            assert split in split_config.keys(), f\"'{split}' not in {list(split_config.keys())}\"\n\n        self.dataset = DSECDet(root=root, split=split, sync=\"back\", debug=debug, split_config=split_config)\n\n        for directory in self.dataset.directories.values():\n            directory.events = EventDirectory(directory.events.root)\n\n        self.scale = scale\n        self.width = self.dataset.width // scale\n        self.height = cropped_height // scale\n        self.classes = (\"car\", \"pedestrian\")\n        self.time_window = 1000000\n        self.min_bbox_height = min_bbox_height\n        self.min_bbox_diag = min_bbox_diag\n        self.debug = debug\n        self.num_us = -1\n\n        self.class_remapping = compute_class_mapping(self.classes, self.dataset.classes, self.MAPPING)\n\n        if transform is not None and hasattr(transform, \"transforms\"):\n            init_transforms(transform.transforms, self.height, self.width)\n\n        self.transform = transform\n        self.no_eval = no_eval\n\n        if self.no_eval:\n            only_perfect_tracks = False\n\n        self.image_index_pairs, self.track_masks = filter_tracks(dataset=self.dataset, image_width=self.width,\n                                                                 image_height=self.height,\n                                                                 class_remapping=self.class_remapping,\n                                                                 min_bbox_height=min_bbox_height,\n                                                                 min_bbox_diag=min_bbox_diag,\n                                                                 only_perfect_tracks=only_perfect_tracks,\n                                                                 scale=scale)\n\n    def set_num_us(self, num_us):\n        self.num_us = num_us\n\n    def visualize_debug(self, index):\n        data = self.__getitem__(index)\n        image = data.image[0].permute(1,2,0).numpy()\n        p = data.x[:,0].numpy()\n        x, y = data.pos.t().numpy()\n        b_x, b_y, b_w, b_h, b_c = data.bbox.t().numpy()\n\n        image = draw_events_on_image(image, x, y, p)\n        image = draw_bbox_on_img(image, b_x, b_y, b_w, b_h,\n                                 b_c, np.ones_like(b_c), conf=0.3, nms=0.65)\n\n        cv2.imshow(f\"Debug {index}\", image)\n        cv2.waitKey(0)\n\n\n    def __len__(self):\n        return sum(len(d) for d in self.image_index_pairs.values())\n\n    def preprocess_detections(self, detections):\n        detections = rescale_tracks(detections, self.scale)\n        detections = crop_tracks(detections, self.width, self.height)\n        detections['class_id'], _ = map_classes(detections['class_id'], self.class_remapping)\n        return detections\n\n    def preprocess_events(self, events):\n        mask = events['y'] < self.height\n        events = {k: v[mask] for k, v in events.items()}\n        if len(events['t']) > 0:\n            events['t'] = self.time_window + events['t'] - events['t'][-1]\n        events['p'] = 2 * events['p'].reshape((-1,1)).astype(\"int8\") - 1\n        return events\n\n    def preprocess_image(self, image):\n        image = image[:self.scale * self.height]\n        image = cv2.resize(image, (self.width, self.height), interpolation=cv2.INTER_CUBIC)\n        image = torch.from_numpy(image).permute(2, 0, 1)\n        image = image.unsqueeze(0)\n        return image\n\n    def __getitem__(self, idx):\n        dataset, image_index_pairs, track_masks, idx = self.rel_index(idx)\n        image_index_0, image_index_1 = image_index_pairs[idx]\n        image_ts_0, image_ts_1 = dataset.images.timestamps[[image_index_0, image_index_1]]\n\n        detections_0 = self.dataset.get_tracks(image_index_0, mask=track_masks, directory_name=dataset.root.name)\n        detections_1 = self.dataset.get_tracks(image_index_1, mask=track_masks, directory_name=dataset.root.name)\n\n        detections_0 = self.preprocess_detections(detections_0)\n        detections_1 = self.preprocess_detections(detections_1)\n\n        image_0 = self.dataset.get_image(image_index_0, directory_name=dataset.root.name)\n        image_0 = self.preprocess_image(image_0)\n\n        events = self.dataset.get_events(image_index_0, directory_name=dataset.root.name)\n\n        if self.num_us >= 0:\n            image_ts_1 = image_ts_0 + self.num_us\n            events = {k: v[events['t'] < image_ts_1] for k, v in events.items()}\n            if not self.no_eval:\n                detections_1 = interpolate_tracks(detections_0, detections_1, image_ts_1)\n\n        # here, the timestamp of the events is no longer absolute\n        events = self.preprocess_events(events)\n\n        # convert to torch geometric data\n        data = to_data(**events, bbox=tracks_to_array(detections_1), bbox0=tracks_to_array(detections_0), t0=image_ts_0, t1=image_ts_1,\n                       width=self.width, height=self.height, time_window=self.time_window,\n                       image=image_0, sequence=str(dataset.root.name))\n\n        if self.transform is not None:\n            data = self.transform(data)\n\n        # remove bboxes if they have 0 width or height\n        mask = filter_small_bboxes(data.bbox[:, 2], data.bbox[:, 3], self.min_bbox_height, self.min_bbox_diag)\n        data.bbox = data.bbox[mask]\n        mask = filter_small_bboxes(data.bbox0[:, 2], data.bbox0[:, 3], self.min_bbox_height, self.min_bbox_diag)\n        data.bbox0 = data.bbox0[mask]\n\n        return data\n\n    def rel_index(self, idx):\n        for folder in self.dataset.subsequence_directories:\n            name = folder.name\n            image_index_pairs = self.image_index_pairs[name]\n            directory = self.dataset.directories[name]\n            track_mask = self.track_masks[name]\n            if idx < len(image_index_pairs):\n                return directory, image_index_pairs, track_mask, idx\n            idx -= len(image_index_pairs)\n        raise IndexError"
  },
  {
    "path": "src/dagr/data/dsec_split.yaml",
    "content": "train:\n  - thun_00_a\n  - interlaken_00_c\n  - interlaken_00_d\n  - interlaken_00_e\n  - interlaken_00_f\n  - interlaken_00_g\n  - zurich_city_00_a\n  - zurich_city_00_b\n  - zurich_city_01_a\n  - zurich_city_01_b\n  - zurich_city_01_c\n  - zurich_city_01_d\n  - zurich_city_01_e\n  - zurich_city_01_f\n  - zurich_city_02_a\n  - zurich_city_02_b\n  - zurich_city_02_c\n  - zurich_city_02_d\n  - zurich_city_02_e\n  - zurich_city_03_a\n  - zurich_city_04_a\n  - zurich_city_04_b\n  - zurich_city_04_c\n  - zurich_city_04_d\n  - zurich_city_04_e\n  - zurich_city_04_f\n  - zurich_city_05_a\n  - zurich_city_05_b\n  - zurich_city_06_a\n  - zurich_city_07_a\n  - zurich_city_08_a\n  - zurich_city_09_a\n  - zurich_city_09_b\n  - zurich_city_09_c\n  - zurich_city_09_d\n  - zurich_city_09_e\n  - zurich_city_10_a\n  - zurich_city_10_b\n  - zurich_city_11_a\n  - zurich_city_11_b\n  - zurich_city_11_c\nval:\n  - zurich_city_16_a\n  - zurich_city_17_a\n  - zurich_city_18_a\n  - zurich_city_19_a\n  - zurich_city_20_a\n  - zurich_city_21_a\ntest:\n  - thun_01_a\n  - thun_01_b\n  - thun_02_a\n  - interlaken_00_a\n  - interlaken_00_b\n  - interlaken_01_a\n  - zurich_city_12_a\n  - zurich_city_13_a\n  - zurich_city_13_b\n  - zurich_city_14_a\n  - zurich_city_14_b\n  - zurich_city_14_c\n  - zurich_city_15_a"
  },
  {
    "path": "src/dagr/data/dsec_utils.py",
    "content": "import numpy as np\nimport h5py\n\n\ndef construct_pairs(indices, n=2):\n    indices = np.sort(indices)\n    indices = np.stack([indices[i:i+1-n] for i in range(n-1)] + [indices[n-1:]])\n    mask = np.ones_like(indices[0]) > 0\n    for i, row in enumerate(indices):\n        mask = mask & (indices[0] + i == row)\n    indices = indices[...,mask].T\n    return indices\n\ndef rescale_tracks(tracks, scale):\n    tracks = tracks.copy()\n    for k in \"xywh\":\n        tracks[k] /= scale\n    return tracks\n\ndef crop_tracks(tracks, width, height):\n    tracks = tracks.copy()\n    x1, y1 = tracks['x'], tracks['y']\n    x2, y2 = x1 + tracks['w'], y1 + tracks['h']\n\n    x1 = np.clip(x1, 0, width-1)\n    x2 = np.clip(x2, 0, width-1)\n\n    y1 = np.clip(y1, 0, height-1)\n    y2 = np.clip(y2, 0, height-1)\n\n    tracks['x'] = x1\n    tracks['y'] = y1\n    tracks['w'] = x2-x1\n    tracks['h'] = y2-y1\n\n    return tracks\n\ndef map_classes(class_ids, old_to_new_mapping):\n    new_class_ids = old_to_new_mapping[class_ids]\n    mask = new_class_ids > -1\n    return new_class_ids, mask\n\ndef filter_small_bboxes(w, h, bbox_height=20, bbox_diag=30):\n    \"\"\"\n    Filter out tracks that are too small.\n    \"\"\"\n    diag = np.sqrt(h ** 2 + w ** 2)\n    return (diag > bbox_diag) & (w > bbox_height) & (h > bbox_height)\n\ndef filter_tracks(dataset, image_width, image_height, class_remapping, min_bbox_height=0, min_bbox_diag=0, scale=1, only_perfect_tracks=False):\n    image_index_pairs = {}\n    track_masks = {}\n\n    for directory_path in dataset.subsequence_directories:\n        tracks = dataset.directories[directory_path.name].tracks.tracks\n        image_timestamps = dataset.directories[directory_path.name].images.timestamps\n\n        tracks_rescaled = rescale_tracks(tracks, scale)\n        tracks_rescaled = crop_tracks(tracks_rescaled, image_width, image_height)\n\n        _, class_mask = map_classes(tracks_rescaled['class_id'], class_remapping)\n        size_mask = filter_small_bboxes(tracks_rescaled['w'], tracks_rescaled['h'], min_bbox_height, min_bbox_diag)\n        final_mask = size_mask & class_mask\n\n        # 1. stores indices of images which are valid, i.e. survived all filters above\n        valid_image_indices = np.unique(np.nonzero(np.isin(image_timestamps, tracks_rescaled[final_mask]['t']))[0])\n        valid_image_index_pairs = construct_pairs(valid_image_indices, 2)\n\n        if only_perfect_tracks:\n            valid_image_timestamp_brackets = image_timestamps[valid_image_index_pairs]\n            img_idx_to_track_idx = compute_img_idx_to_track_idx(tracks['t'], valid_image_timestamp_brackets)\n            mask = filter_by_only_perfect_tracks(tracks_rescaled, img_idx_to_track_idx, tracks_mask=final_mask)\n            valid_image_index_pairs = valid_image_index_pairs[mask]\n\n        image_index_pairs[directory_path.name] = valid_image_index_pairs\n        track_masks[directory_path.name] = final_mask\n\n    return image_index_pairs, track_masks\n\ndef _load_events(file, t0, num_events=None, num_us=None, height=None, time_window=None):\n    with h5py.File(file, 'r') as f:\n        ms = int((t0 - f['t_offset'][()]) / 1e3)\n        idx0 = int(f['ms_to_idx'][ms])\n\n        if num_events is not None:\n            idx1 = idx0 + num_events\n        if num_us is not None:\n            idx1 = int(f['ms_to_idx'][ms + int(num_us / 1e3)])\n\n        idx0, idx1 = sorted([idx0, idx1])\n        idx0 = idx0 if idx0 >= 0 else 0\n        idx1 = idx1 if idx1 >= 0 else 0\n\n        # load all events\n        events = {k: f[f'events/{k}'][idx0:idx1] for k in \"xytp\"}\n\n        tq = events['t'][-1] if idx1 > idx0 else f[f'events/t'][max([idx1 - 1, idx0])]\n\n        # cast to desired types\n        p = 2 * events[\"p\"][..., None].astype(\"int8\") - 1\n        t_ev = events['t'][..., None]\n        xy = np.stack([events['x'], events['y']], axis=-1).astype(\"int16\")\n\n        if time_window is not None:\n            t = (time_window - tq + t_ev).astype('int32')\n        else:\n            t = tq.copy()\n\n        # we have to add the offset here\n        tq += f['t_offset'][()]\n        tq = tq.astype(\"int64\")\n\n        # crop events to crop height\n        mask = (t[:, 0] > 0)\n        if height is not None:\n            mask &= (xy[:, 1] < height)\n\n        events = (xy[mask], t[mask], p[mask])\n\n        return events, tq\n\n\ndef filter_by_only_perfect_tracks(tracks, img_idx_to_track_idx, tracks_mask=None):\n    i0, i1 = img_idx_to_track_idx\n    mask = np.ones_like(i0[0]) > 0\n    for i in range(i0.shape[1]):\n        track = [tracks[i0[j][i]:i1[j][i]] for j in range(len(i0))]\n        if tracks_mask is not None:\n            track_mask = [tracks_mask[i0[j][i]:i1[j][i]] for j in range(len(i0))]\n            track = [t[m] for t, m in zip(track, track_mask)]\n        mask[i] = not is_invalid_track(track)\n    return mask\n\ndef is_invalid_track(track):\n    track = [tr[tr['track_id'].argsort()] for tr in track]\n\n    i_tr = track[0]\n    for c_tr in track[1:]:\n        if len(i_tr) != len(c_tr):\n            return True\n        if not (c_tr['track_id'] == i_tr['track_id']).all():\n            return True\n        iou = compute_iou(i_tr, c_tr)\n        min_iou = np.min(iou)\n        if min_iou < 0.10:\n            return True\n    else:\n        return False\n\ndef compute_iou(track0, track1):\n    x1, x2 = track0['x'], track0['x'] + track0['w']\n    y1, y2 = track0['y'], track0['y'] + track0['h']\n\n    x1g, x2g = track1['x'], track1['x'] + track1['w']\n    y1g, y2g = track1['y'], track1['y'] + track1['h']\n\n    # Intersection keypoints\n    xkis1 = np.max(np.stack([x1, x1g]), axis=0)\n    ykis1 = np.max(np.stack([y1, y1g]), axis=0)\n    xkis2 = np.min(np.stack([x2, x2g]), axis=0)\n    ykis2 = np.min(np.stack([y2, y2g]), axis=0)\n\n    intsct = np.zeros_like(x1)\n    mask = (ykis2 > ykis1) & (xkis2 > xkis1)\n    intsct[mask] = (xkis2[mask] - xkis1[mask]) * (ykis2[mask] - ykis1[mask])\n    union = (x2 - x1) * (y2 - y1) + (x2g - x1g) * (y2g - y1g) - intsct + 1e-9\n    iou = intsct / union\n\n    return iou\n\n\ndef compute_indices_for_contiguous_parts(x):\n    x, counts = np.unique(x, return_counts=True)\n    idx = np.concatenate([np.array([0]), counts]).cumsum()\n    return np.stack([idx[:-1], idx[1:]], axis=-1)\n\ndef _compute_img_idx_to_track_idx(t, t_query):\n    new_img_idx = compute_indices_for_contiguous_parts(t)\n    mask  = np.isin(np.unique(t), t_query)\n    new_img_idx = new_img_idx[mask].T\n    return new_img_idx\n\ndef compute_img_idx_to_track_idx(t, t_query):\n    return np.stack([_compute_img_idx_to_track_idx(t, t_q) for t_q in t_query.T])\n\ndef compute_class_mapping(classes, all_classes, mapping):\n    output_mapping = []\n    for i, c in enumerate(all_classes):\n        mapped_class = mapping[c]\n        output_mapping.append(classes.index(mapped_class) if mapped_class in classes else -1)\n    return np.array(output_mapping)\n"
  },
  {
    "path": "src/dagr/data/ncaltech101_data.py",
    "content": "import numpy as np\nimport torch\nimport hdf5plugin\nimport h5py\n\nfrom pathlib import Path\nfrom typing import Optional, Callable\nfrom torch.utils.data import Dataset\nfrom torch_geometric.data import Data\nfrom dagr.data.augment import init_transforms\nfrom dagr.data.utils import to_data\n\n\nclass NCaltech101(Dataset):\n\n    def __init__(self, root: Path, split, transform=Optional[Callable[[Data,], Data]], num_events: int=50000):\n        super().__init__()\n        self.load_dir = root / split\n        self.classes = sorted([d.name for d in self.load_dir.glob(\"*\")])\n        self.num_classes = len(self.classes)\n        self.files = sorted(list(self.load_dir.rglob(\"*.h5\")))\n        self.height = 180\n        self.width = 240\n        if transform is not None and hasattr(transform, \"transforms\"):\n            init_transforms(transform.transforms, self.height, self.width)\n        self.transform = transform\n        self.time_window = 1000000\n        self.num_events = num_events\n\n    def __len__(self):\n        return len(self.files)\n\n    def preprocess(self, data):\n        data.t -= (data.t[-1] - self.time_window + 1)\n        return data\n\n    def load_events(self, f_path):\n        return _load_events(f_path, self.num_events)\n\n    def __getitem__(self, idx):\n        f_path = self.files[idx]\n        target = self.classes.index(str(f_path.parent.name))\n\n        events = self.load_events(f_path)\n        data = to_data(**events,  bbox=self.load_bboxes(f_path, target),\n                       t0=events['t'][0], t1=events['t'], width=self.width, height=self.height,\n                       time_window=self.time_window)\n\n        data = self.preprocess(data)\n\n        data = self.transform(data) if self.transform is not None else data\n\n        if not hasattr(data, \"t\"):\n            data.t = data.pos[:, -1:]\n            data.pos = data.pos[:, :2].type(torch.int16)\n\n        return data\n\n    def load_bboxes(self, raw_file: Path, class_id):\n        rel_path = str(raw_file.relative_to(self.load_dir))\n        rel_path = rel_path.replace(\"image_\", \"annotation_\").replace(\".h5\", \".bin\")\n        annotation_file = self.load_dir / \"../annotations\" / rel_path\n        with annotation_file.open() as fh:\n            annotations = np.fromfile(fh, dtype=np.int16)\n            annotations = np.array(annotations[2:10])\n\n        return np.array([\n            annotations[0], annotations[1],  # upper-left corner\n            annotations[2] - annotations[0],  # width\n            annotations[5] - annotations[1],  # height\n            class_id,\n            1\n        ]).astype(\"float32\").reshape((1,-1))\n\ndef _load_events(f_path, num_events):\n    with h5py.File(str(f_path)) as fh:\n        fh = fh['events']\n        x = fh[\"x\"][-num_events:]\n        y = fh[\"y\"][-num_events:]\n        t = fh[\"t\"][-num_events:]\n        p = fh[\"p\"][-num_events:]\n    return dict(x=x, y=y, t=t, p=p)\n"
  },
  {
    "path": "src/dagr/data/utils.py",
    "content": "import numpy as np\nimport torch\nfrom torch_geometric.data import Data\n\n\ndef to_data(**kwargs):\n    # convert all tracks to correct format\n    for k, v in kwargs.items():\n        if k.startswith(\"bbox\"):\n            kwargs[k] = torch.from_numpy(v)\n\n    xy = np.stack([kwargs['x'], kwargs['y']], axis=-1).astype(\"int16\")\n    t = kwargs['t'].astype(\"int32\")\n    p = kwargs['p'].reshape((-1,1))\n\n    kwargs['x'] = torch.from_numpy(p)\n    kwargs['pos'] = torch.from_numpy(xy)\n    kwargs['t'] = torch.from_numpy(t)\n\n    return Data(**kwargs)"
  },
  {
    "path": "src/dagr/graph/ev_graph.cu",
    "content": "#include <torch/extension.h>\n\n#include <cuda.h>\n#include <cuda_runtime.h>\n#include \"spiral.h\"\n#include <vector>\n\n\n#define CHECK_CUDA(x) AT_ASSERTM(x.type().is_cuda(), #x \" must be a CUDA tensor\")\n#define CHECK_CONTIGUOUS(x) AT_ASSERTM(x.is_contiguous(), #x \" must be contiguous\")\n#define CHECK_INPUT(x) CHECK_CUDA(x); CHECK_CONTIGUOUS(x)\n#define CHECK_DEVICE(x, y) AT_ASSERTM(x.device().index() == y.device().index(), #x \" and \" #y \" must be in same CUDA device\")\n\n\n__global__ void fill_edges_cuda_kernel(\n  const int32_t* __restrict__ batch,\n  const int32_t* __restrict__ pos,\n  const int32_t* __restrict__ all_timestamps,\n  const int32_t* __restrict__ indices,\n  const int32_t* __restrict__ event_queue,\n        int64_t* __restrict__ edges,\n  //      int64_t* __restrict__ num_neighbors_array,\n  int B, int Q, int H, int W, int N, int K, float radius, float delta_t_us, int max_num_neighbors, int min_index\n)\n{\n  // linear index\n  const int event_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (event_idx >= N)\n    return;\n\n  int radius_int = radius;\n  int num_neighbors = 0;\n\n  int offset = event_idx * max_num_neighbors;\n\n  int b        = batch[event_idx];\n  int x        = pos[3 * event_idx + 0];\n  int y        = pos[3 * event_idx + 1];\n  int ts_event = pos[3 * event_idx + 2];\n\n  // first add self edge\n  edges[offset + num_neighbors + K * 0] = indices[event_idx]-min_index;\n  edges[offset + num_neighbors + K * 1] = indices[event_idx]-min_index;\n  num_neighbors++;\n\n  SpiralOut spiral;\n  for (int i=0; i<std::pow(2*radius_int+1, 2); i++) {\n    if (num_neighbors >= max_num_neighbors) break;\n    for (int q=0; q<Q; q++) {\n      int x_neighbor = x + spiral.x;\n      int y_neighbor = y + spiral.y;\n\n      // break if out of fov\n      if (!((x_neighbor >= 0) && (y_neighbor >= 0) && (x_neighbor < W) && (y_neighbor < H))) break;\n\n      int64_t queue_idx = x_neighbor + W * y_neighbor + H * W * q + H * W * Q * b;\n      int idx = event_queue[queue_idx];\n\n      // break if exceeded max num neighbors or no more events in queue\n      if (idx < min_index) break;\n\n      if (indices[event_idx] > idx) {\n          int32_t ts_neighbor = all_timestamps[idx-min_index];\n          int32_t dt_us = ts_event - ts_neighbor;\n\n          // if delta t is too large, no edge is added\n          if (dt_us > delta_t_us) continue;\n\n          edges[offset + num_neighbors + K * 0] = idx-min_index;\n          edges[offset + num_neighbors + K * 1] = indices[event_idx]-min_index;\n          num_neighbors++;\n          if (num_neighbors >= max_num_neighbors) break;\n      }\n    }\n    spiral.goNext();\n  }\n  //num_neighbors_array[event_idx] = num_neighbors;\n}\n\nvoid fill_edges_cuda(\n    const torch::Tensor& batch,      // N\n    const torch::Tensor& pos,      // N x 3\n    const torch::Tensor& all_timestamps, // N\n    const torch::Tensor& event_queue, // B x Q x H x W\n    const torch::Tensor& indices,     // N\n    const int max_num_neighbors,\n    const float radius,\n    const float delta_t_us,\n    torch::Tensor& edges,              // 2 x E\n    const int min_index\n  )\n{\n  CHECK_INPUT(batch);\n  CHECK_INPUT(pos);\n  CHECK_INPUT(event_queue);\n  CHECK_INPUT(all_timestamps);\n  CHECK_INPUT(edges);\n  CHECK_INPUT(indices);\n\n  CHECK_DEVICE(batch, event_queue);\n  CHECK_DEVICE(batch, pos);\n  CHECK_DEVICE(batch, edges);\n  CHECK_DEVICE(batch, indices);\n  CHECK_DEVICE(batch, all_timestamps);\n\n  unsigned N = batch.size(0);\n  unsigned B = event_queue.size(0);\n  unsigned Q = event_queue.size(1);\n  unsigned H = event_queue.size(2);\n  unsigned W = event_queue.size(3);\n  unsigned K = edges.size(1);\n\n  unsigned threads = 256;\n  dim3 blocks((N + threads - 1) / threads, 1);\n\n  fill_edges_cuda_kernel<<<blocks, threads>>>(\n      batch.data<int32_t>(),\n      pos.data<int32_t>(),\n      all_timestamps.data<int32_t>(),\n      indices.data<int32_t>(),\n      event_queue.data<int32_t>(),\n      edges.data<int64_t>(),\n      //num_neighbors.data<int64_t>(),\n      B, Q, H, W, N, K, radius, delta_t_us, max_num_neighbors, min_index\n    );\n}\n\ntemplate <typename scalar_t>\n__global__ void insert_in_queue_single_cuda_kernel(\n  const scalar_t* __restrict__ indices,\n  const scalar_t* __restrict__ events,\n  scalar_t* __restrict__ queue,\n  int B, int Q, int H, int W, int K\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K)\n    return;\n\n  // find out how many events to write, and what is the offset\n  int counts = 1;\n  int offset = 0;\n\n  // find out the x, y coords where to write the indices\n  int x = events[0];\n  int y = events[1];\n  int b = 0;\n\n  // write indices. break if queue size or counter is exceeded\n  for (int q=Q-1; q>=0; q--) {\n    int index = b * H * W * Q + q * H * W + y * W + x;\n    // for the current position, get the one at q - shift.\n    // if q - shift goes in the negative, take from indices instead\n    if (q >= counts) {\n      int shifted_index = b * H * W * Q + (q-counts) * H * W + y * W + x;\n      queue[index] = queue[shifted_index];\n    } else {\n      queue[index] = indices[offset + counts - 1 - q];\n    } \n  }\n}\n\n\ntemplate <typename scalar_t>\n__global__ void insert_in_queue_cuda_kernel(\n  const scalar_t* __restrict__ indices,\n  const scalar_t* __restrict__ unique_coords,\n  const scalar_t* __restrict__ cumsum_counts,\n  scalar_t* __restrict__ queue,\n  int B, int Q, int H, int W, int K\n)\n{\n  // linear index\n  const int lin_idx = blockIdx.x * blockDim.x + threadIdx.x;\n\n  // check that thread is not out of valid range\n  if (lin_idx >= K)\n    return;\n\n  // find out how many events to write, and what is the offset\n  int counts, offset;\n  if (lin_idx > 0) {\n    offset = cumsum_counts[lin_idx-1];\n    counts = cumsum_counts[lin_idx] - offset;\n  } else {\n    offset = 0;\n    counts = cumsum_counts[lin_idx];\n  }\n\n  // find out the x, y coords where to write the indices\n  int x = unique_coords[lin_idx] % W;\n  int y = ((unique_coords[lin_idx] - x)/ W) % H;\n  int b = unique_coords[lin_idx] / (W*H);\n\n  // write indices. break if queue size or counter is exceeded\n  for (int q=Q-1; q>=0; q--) {\n    int index = b * H * W * Q + q * H * W + y * W + x;\n    // for the current position, get the one at q - shift.\n    // if q - shift goes in the negative, take from indices instead\n    if (q >= counts) {\n      int shifted_index = b * H * W * Q + (q-counts) * H * W + y * W + x;\n      queue[index] = queue[shifted_index];\n    } else {\n      queue[index] = indices[offset + counts - 1 - q];\n    } \n  }\n}\n\n\ntorch::Tensor insert_in_queue_single_cuda(\n    const torch::Tensor& indices,       // 1\n    const torch::Tensor& events, // 4 x 1\n    const torch::Tensor& queue          // B x Q x H x W\n  )\n{\n  unsigned W = queue.size(3);\n  unsigned H = queue.size(2);\n  unsigned Q = queue.size(1);\n  unsigned B = queue.size(0);\n  unsigned K = 1;\n\n  unsigned threads = 256;\n  dim3 blocks((K + threads - 1) / threads, 1);\n\n  insert_in_queue_single_cuda_kernel<int32_t><<<blocks, threads>>>(\n      indices.data<int32_t>(),\n      events.data<int32_t>(),\n      queue.data<int32_t>(),\n      B, Q, H, W, K\n    );\n\n  return queue;\n}\n\n\ntorch::Tensor insert_in_queue_cuda(\n    const torch::Tensor& indices,       // N -> num events\n    const torch::Tensor& unique_coords, // K -> num active pixels\n    const torch::Tensor& cumsum_counts, // K -> num active pixels\n    const torch::Tensor& queue          // B x Q x H x W\n  )\n{\n  CHECK_INPUT(indices);\n  CHECK_INPUT(unique_coords);\n  CHECK_INPUT(cumsum_counts);\n  CHECK_INPUT(queue);\n\n  CHECK_DEVICE(indices, queue);\n  CHECK_DEVICE(indices, unique_coords);\n  CHECK_DEVICE(indices, cumsum_counts);\n  CHECK_DEVICE(indices, queue);\n\n  unsigned W = queue.size(3);\n  unsigned H = queue.size(2);\n  unsigned Q = queue.size(1);\n  unsigned B = queue.size(0);\n  unsigned K = unique_coords.size(0);\n\n  unsigned threads = 256;\n  dim3 blocks((K + threads - 1) / threads, 1);\n\n  insert_in_queue_cuda_kernel<int32_t><<<blocks, threads>>>(\n      indices.data<int32_t>(),\n      unique_coords.data<int32_t>(),\n      cumsum_counts.data<int32_t>(),\n      queue.data<int32_t>(),\n      B, Q, H, W, K\n    );\n\n  return queue;\n}\n\n\nPYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {\n  m.def(\"fill_edges_cuda\", &fill_edges_cuda, \"Find edges from a queue of events.\");\n  m.def(\"insert_in_queue_cuda\", &insert_in_queue_cuda, \"Insert events into queue.\");\n  m.def(\"insert_in_queue_single_cuda\", &insert_in_queue_single_cuda, \"Insert single events into queue.\");\n}\n"
  },
  {
    "path": "src/dagr/graph/ev_graph.py",
    "content": "import torch\nfrom .utils import _insert_events_into_queue, _search_for_edges\n\n\ndef move_to_cuda(func):\n    def wrapper(self, x, *args, **kwargs):\n        device = x.device\n        on_cpu = device == \"cpu\"\n        if on_cpu:\n            x = x.to(\"cuda\")\n        ret = func(self, x, *args, **kwargs)\n        if on_cpu:\n            ret = ret.cpu()\n        return ret\n    return wrapper\n        \n\nclass AsyncGraph:\n    def __init__(self, width=640,\n                 height=480,\n                 batch_size=1,\n                 max_num_neighbors=16,\n                 max_queue_size=512,\n                 radius=7, \n                 delta_t_us=600000):\n        self.radius = radius\n        self.delta_t_us = delta_t_us\n        self.event_queue = None\n\n        self.max_index = 0\n        self.min_index = 0\n        self.max_queue_size = max_queue_size\n        self.max_num_neighbors = max_num_neighbors\n        self.width = width\n        self.height = height\n        self.batch_size = batch_size\n        self.device = None\n\n        self.edges = torch.zeros((2,0), dtype=torch.long)\n        self.all_timestamps = torch.zeros((0,), dtype=torch.int32)\n        self.new_indices = None\n        self.edge_buffer = None\n        self.event_queue = None\n    \n    def initialize(self, n_ev, device):\n        self.edges = torch.zeros((2,0), dtype=torch.long, device=device)\n        self.all_timestamps = torch.zeros((0,), dtype=torch.int32, device=device)\n        self.new_indices = torch.arange(n_ev, dtype=torch.int32, device=device)\n        self.edge_buffer = torch.full((2, self.max_num_neighbors * n_ev), dtype=torch.int64, fill_value=-1, device=device)\n        self.event_queue = torch.full((self.batch_size, self.max_queue_size, self.height, self.width), fill_value=-1, device=device, dtype=torch.int32)\n\n    def reset(self):\n        self.edges = torch.zeros((2,0), dtype=torch.long, device=self.device)\n        self.all_timestamps = torch.zeros((0,), dtype=torch.int32, device=self.device)\n        self.max_index = 0\n        self.min_index = 0\n        if self.edge_buffer is not None:\n            self.edge_buffer.fill_(-1)\n        if self.event_queue is not None:\n            self.event_queue.fill_(-1)\n        \n    @move_to_cuda\n    def forward(self, batch, pos, collect_edges=True):\n        n_ev = len(batch)\n\n        if self.device is None:\n            self.device = batch.device\n            self.initialize(n_ev, self.device)\n\n        if len(batch) == 0:\n            return torch.zeros((2,0), device=self.device, dtype=torch.int32)\n\n        assert type(batch) is torch.Tensor and batch.dtype == torch.int32, [type(batch), batch.dtype]\n\n        self.all_timestamps = torch.cat([self.all_timestamps, pos[:,2]])\n\n        # insert events into queue, they have an ever growing index\n        if n_ev > len(self.new_indices):\n            self.new_indices = torch.arange(0, n_ev, dtype=torch.int32, device=self.device)\n            self.edge_buffer = torch.full((2, self.max_num_neighbors * n_ev), dtype=torch.int64, fill_value=-1, device=self.device)\n\n        indices = self.max_index + self.new_indices[:n_ev]\n        self.max_index += n_ev\n\n        self.event_queue = _insert_events_into_queue(batch, pos, indices=indices, queue=self.event_queue)\n\n        # read out edges from event queue, they need to correspond to indices\n        # from the current nodes\n        self.edge_buffer.fill_(-1)\n        edge_indices = _search_for_edges(batch, pos,\n                                         all_timestamps=self.all_timestamps.contiguous(),\n                                         indices=indices,\n                                         queue=self.event_queue,\n                                         max_num_neighbors=self.max_num_neighbors,\n                                         radius=self.radius,\n                                         delta_t_us=self.delta_t_us,\n                                         edges=self.edge_buffer,\n                                         min_index=self.min_index)\n        \n        if collect_edges:\n            self.edges = torch.cat([self.edges, edge_indices], dim=-1)\n\n        return edge_indices\n\n\nclass SlidingWindowGraph(AsyncGraph):\n    def __init__(self, width=640,\n                 height=480,\n                 batch_size=1,\n                 max_num_neighbors=16,\n                 max_queue_size=1024,\n                 radius=7, \n                 delta_t_us=600000):\n        AsyncGraph.__init__(self, width, height, batch_size, max_num_neighbors, \n                            max_queue_size, radius, delta_t_us)\n\n    @property\n    def init(self):\n        return len(self.all_timestamps) > 0\n\n    def delete_nodes(self, n_delete, delete_edges=True, return_edges=True):\n        # delete nodes\n        self.all_timestamps = self.all_timestamps[n_delete:]\n        self.min_index += n_delete\n\n        # the current edges do not correspond to\n        # the nodes anymore, so they need to be decremented\n        if delete_edges:\n            mask = (self.edges[0] < n_delete) | (self.edges[1] < n_delete)\n            deleted_edges = self.edges[:,mask].clone()\n            self.edges = self.edges[:,~mask]\n\n        self.edges.add_(-n_delete)\n\n        if delete_edges and return_edges:\n            return deleted_edges\n    \n    @move_to_cuda\n    def forward(self, batch, pos, return_node_counts=False, return_total_edges=False, delete_nodes=True, collect_edges=True):\n        n_delete = len(batch) if self.init else 0\n\n        # first find the interactions\n        edges = AsyncGraph.forward(self, batch, pos, collect_edges=collect_edges)\n\n        if return_total_edges:\n            total_edges = self.edges.clone()\n        \n        if return_node_counts:\n            tot_nodes = len(self.all_timestamps)\n\n        ret = [edges]\n\n        if delete_nodes:\n            deleted_edges = self.delete_nodes(n_delete)\n            ret.append(deleted_edges)\n\n        if return_total_edges:\n            ret.append(total_edges)\n\n        if return_node_counts:\n            ret.append([n_delete, len(batch), tot_nodes])\n\n        if len(ret) == 1:\n            ret = ret[0]\n\n        return ret\n"
  },
  {
    "path": "src/dagr/graph/spiral.h",
    "content": "class SpiralOut{\nprotected:\n    unsigned layer;\n    unsigned leg;\npublic:\n    int x, y; //read these as output from next, do not modify.\n    __device__ SpiralOut():layer(1),leg(0),x(0),y(0){}\n    __device__ void goNext(){\n        switch(leg){\n        case 0: ++x; if(x  == layer)  ++leg;                break;\n        case 1: ++y; if(y  == layer)  ++leg;                break;\n        case 2: --x; if(-x == layer)  ++leg;                break;\n        case 3: --y; if(-y == layer){ leg = 0; ++layer; }   break;\n        }\n    }\n};"
  },
  {
    "path": "src/dagr/graph/utils.py",
    "content": "import torch\nimport ev_graph_cuda\nfrom typing import Union\n\n\ndef _insert_events_into_queue(batch, pos, indices, queue: torch.LongTensor):\n    if len(batch) > 1:\n        height, width = queue.shape[-2:]\n        lin_coords = pos[:,0] + width * pos[:,1] + width*height*batch\n        sorted_lin_coords, sort_index = torch.sort(lin_coords, stable=True, descending=False)\n        sorted_indices = indices[sort_index].int()\n        unique_coords, unique_counter = torch.unique_consecutive(sorted_lin_coords, return_counts=True)\n        cumsum_counter = torch.cumsum(unique_counter, dim=0).int()\n        queue = ev_graph_cuda.insert_in_queue_cuda(sorted_indices, unique_coords, cumsum_counter, queue)\n    else:\n        queue = ev_graph_cuda.insert_in_queue_single_cuda(indices, pos, queue)\n\n    return queue\n\ndef _search_for_edges(batch, pos, all_timestamps, queue, indices, max_num_neighbors, radius, delta_t_us, edges, min_index):\n    ev_graph_cuda.fill_edges_cuda(batch, pos, all_timestamps, queue, indices, max_num_neighbors, radius, delta_t_us, edges, min_index)\n    edges = edges[:,(edges[1]>=0)]\n    return edges\n"
  },
  {
    "path": "src/dagr/model/layers/components.py",
    "content": "import torch\n\nfrom torch_geometric.nn import BatchNorm\nfrom torch_geometric.data import Data\n\nimport torch_geometric.transforms as T\n\n\nclass BatchNormData(BatchNorm):\n    def forward(self, data: Data):\n        data.x = BatchNorm.forward(self, data.x)\n        return data\n\n\nclass Linear(torch.nn.Module):\n    def __init__(self, ic, oc, bias=True):\n        torch.nn.Module.__init__(self)\n        self.mlp = torch.nn.Linear(ic, oc, bias=bias)\n\n    def forward(self, data: Data):\n        data.x = self.mlp(data.x)\n        return data\n\n\nclass Cartesian(torch.nn.Module):\n    def __init__(self, *args, **kwargs):\n        super().__init__()\n        T.Cartesian.__init__(self, *args, **kwargs)\n\n    def forward(self, data):\n        if data.edge_index.shape[1] > 0:\n            return T.Cartesian.__call__(self, data)\n        else:\n            data.edge_attr = torch.zeros((0, 3), dtype=data.x.dtype, device=data.x.device)\n            return data\n"
  },
  {
    "path": "src/dagr/model/layers/conv.py",
    "content": "import torch\n\nfrom torch_geometric.data import Data\n\nfrom dagr.model.layers.components import BatchNormData, Linear\nfrom dagr.model.layers.spline_conv import MySplineConv\nfrom dagr.model.utils import shallow_copy\n\n\nclass ConvBlock(torch.nn.Module):\n    def __init__(self, in_channels: int, out_channels: int, args, degree=1) -> None:\n        super(ConvBlock, self).__init__()\n        self.dim = args.edge_attr_dim\n        self.activation = getattr(torch.nn.functional, args.activation, torch.nn.functional.elu)\n        self.conv = MySplineConv(in_channels=in_channels,\n                                 out_channels=out_channels,\n                                 args=args,\n                                 bias=False,\n                                 degree=degree)\n\n        self.norm = BatchNormData(in_channels=out_channels)\n\n    def forward(self, data: Data) -> torch.Tensor:\n        data = self.conv(data)\n        data = self.norm(data)\n        data.x = self.activation(data.x)\n\n        return data\n\n\nclass ConvBlockWithSkip(torch.nn.Module):\n    def __init__(self, in_channel: int, out_channel: int, skip_in_channel: int, args) -> None:\n        super(ConvBlockWithSkip, self).__init__()\n        self.dim = args.edge_attr_dim\n\n        self.conv = MySplineConv(in_channels=in_channel,\n                                 out_channels=out_channel,\n                                 args=args,\n                                 bias=False)\n\n        self.activation = getattr(torch.nn.functional, args.activation, torch.nn.functional.elu)\n        self.norm = BatchNormData(in_channels=out_channel)\n\n        self.lin = Linear(skip_in_channel, out_channel, bias=False)\n        self.norm_skip = BatchNormData(in_channels=out_channel)\n\n    def forward(self, data: Data, data_skip: Data):\n        data = self.conv(data)\n\n        data_skip = self.lin(data_skip)\n        data_skip = self.norm_skip(data_skip)\n\n        data = self.norm(data)\n        data.x = self.activation(data.x + data_skip.x)\n\n        return data\n\n\nclass Layer(torch.nn.Module):\n    def __init__(self, in_channels: int, out_channels: int, args) -> None:\n        super(Layer, self).__init__()\n        self.in_channel = in_channels\n        self.out_channel = out_channels\n\n        self.conv_block1 = ConvBlock(in_channels, out_channels, args)\n        self.conv_block2 = ConvBlockWithSkip(out_channels, out_channels, in_channels, args=args)\n\n    def forward(self, data: Data) -> torch.Tensor:\n        data_skip = shallow_copy(data)\n        data = self.conv_block1(data)\n        output = self.conv_block2(data, data_skip)\n        return output\n"
  },
  {
    "path": "src/dagr/model/layers/ev_tgn.py",
    "content": "import torch\n\nfrom torch_geometric.data import Batch, Data\nfrom dagr.graph.ev_graph import SlidingWindowGraph\n\n\ndef _get_value_as_int(obj, key):\n    val = getattr(obj, key)\n    return val if type(val) is int else val[0]\n\ndef denormalize_pos(events):\n    if hasattr(events, \"pos_denorm\"):\n        return events.pos_denorm\n\n    denorm = torch.tensor([int(events.width[0]), int(events.height[0]), int(events.time_window[0])], device=events.pos.device)\n    return (denorm.view(1,-1) * events.pos + 1e-3).int()\n\n\nclass EV_TGN(torch.nn.Module):\n    def __init__(self, args):\n        torch.nn.Module.__init__(self)\n        self.radius = args.radius\n        self.max_neighbors = args.max_neighbors\n        self.max_queue_size = 128\n        self.graph_creators = None\n\n    def init_graph_creator(self, data):\n        delta_t_us = int(self.radius * _get_value_as_int(data, \"time_window\"))\n        radius = int(self.radius * _get_value_as_int(data, \"width\")+1)\n        batch_size = data.num_graphs\n        width = int(_get_value_as_int(data, \"width\"))\n        height = int(_get_value_as_int(data, \"height\"))\n        self.graph_creators = SlidingWindowGraph(width=width, height=height,\n                                                 max_num_neighbors=self.max_neighbors,\n                                                 max_queue_size=self.max_queue_size,\n                                                 batch_size=batch_size,\n                                                 radius=radius, delta_t_us=delta_t_us)\n\n    def forward(self, events: Data, reset=True):\n        if events.batch is None:\n            events = Batch.from_data_list([events])\n\n        # before we start, are the new events used to generate the graph, or are the new nodes attached to the network?\n        # if the first, then don't delete old events, if the second, delete as many events as are coming in.\n        if self.graph_creators is None:\n            self.init_graph_creator(events)\n        else:\n            if reset:\n                self.graph_creators.reset()\n\n        pos = denormalize_pos(events)\n        #pos = torch.cat([events.batch.view(-1,1), pos, events.x.int()], dim=1).int()\n        # properties of the edges\n        # src_i <= dst_i\n        # dst_i <= dst_j if i<j\n        events.edge_index = self.graph_creators.forward(events.batch.int(), pos, delete_nodes=False, collect_edges=reset)\n        events.edge_index = events.edge_index.long()\n\n        return events"
  },
  {
    "path": "src/dagr/model/layers/pooling.py",
    "content": "import torch\nimport torch_scatter\n\nfrom torch_cluster import grid_cluster\nfrom torch_geometric.nn.pool.avg_pool import _avg_pool_x\nfrom torch_geometric.nn.pool.pool import pool_pos\nfrom torch_geometric.data import Data, Batch\nfrom dagr.model.layers.components import BatchNormData\nfrom typing import List, Callable\n\n\ndef consecutive_cluster(src):\n    unique, inv, counts = torch.unique(src, sorted=True, return_inverse=True, return_counts=True)\n    perm = torch.arange(inv.size(0), dtype=inv.dtype, device=inv.device)\n    perm = inv.new_empty(unique.size(0)).scatter_(0, inv, perm)\n    return unique, inv, perm, counts\n\n\nclass Pooling(torch.nn.Module):\n    def __init__(self, size: List[float], width, height, batch_size, transform: Callable[[Data, ], Data], aggr: str = 'max', keep_temporal_ordering=False, dim=2, self_loop=False, in_channels=-1):\n        super(Pooling, self).__init__()\n        assert aggr in ['mean', 'max']\n        self.aggr = aggr\n        self.register_buffer(\"voxel_size\", torch.cat([size, torch.Tensor([1])]), persistent=False)\n\n        self.transform = transform\n        self.keep_temporal_ordering = keep_temporal_ordering\n        self.dim = dim\n\n        self.register_buffer(\"start\", torch.Tensor([0,0,0,0]), persistent=False)\n        self.register_buffer(\"end\", torch.Tensor([0.9999999,0.9999999,0.9999999,batch_size-1]), persistent=False)\n        self.register_buffer(\"wh_inv\", 1/torch.Tensor([[width, height]]), persistent=False)\n\n        self.max_num_voxels = batch_size * self.num_grid_cells\n        self.register_buffer(\"sorted_cluster\", torch.arange(self.max_num_voxels), persistent=False)\n\n        self.self_loop = self_loop\n\n        self.bn = None\n        if in_channels > 0:\n            self.bn = BatchNormData(in_channels)\n\n    @property\n    def num_grid_cells(self):\n        return (1/self.voxel_size+1e-3).int().prod()\n    \n    def round_to_pixel(self, pos, wh_inv):\n        torch.div(pos+1e-5, wh_inv, out=pos, rounding_mode='floor')\n        return pos * wh_inv\n\n    def forward(self, data: Data):\n        if data.x.shape[0] == 0:\n            return data\n\n        pos = torch.cat([data.pos, data.batch.float().view(-1,1)], dim=-1)\n        cluster = grid_cluster(pos, size=self.voxel_size, start=self.start, end=self.end)\n        unique_clusters, cluster, perm, _ = consecutive_cluster(cluster)\n        edge_index = cluster[data.edge_index]\n        if self.self_loop:\n            edge_index = edge_index.unique(dim=-1)\n        else:\n            edge_index = edge_index[:, edge_index[0]!=edge_index[1]]\n            if edge_index.shape[1] > 0:\n                edge_index = edge_index.unique(dim=-1)\n\n        batch = None if data.batch is None else data.batch[perm]\n        pos = None if data.pos is None else pool_pos(cluster, data.pos)\n\n        if self.keep_temporal_ordering:\n            t_max, _ = torch_scatter.scatter_max(data.pos[:,-1], cluster, dim=0)\n            t_src, t_dst = t_max[edge_index]\n            edge_index = edge_index[:, t_dst > t_src]\n\n        if self.aggr == 'max':\n            x, argmax = torch_scatter.scatter_max(data.x, cluster, dim=0)\n        else:\n            x = _avg_pool_x(cluster, data.x)\n\n        new_data = Batch(batch=batch, x=x, edge_index=edge_index, pos=pos)\n\n        if hasattr(data, \"height\"):\n            new_data.height = data.height\n            new_data.width = data.width\n\n        # round x and y coordinates to the center of the voxel grid\n        new_data.pos[:,:2] = self.round_to_pixel(new_data.pos[:,:2], wh_inv=self.wh_inv)\n\n        if self.transform is not None:\n            if new_data.edge_index.numel() > 0:\n                new_data = self.transform(new_data)\n            else:\n                new_data.edge_attr = torch.zeros(size=(0,pos.shape[1]), dtype=pos.dtype, device=pos.device)\n\n        if self.bn is not None:\n            new_data = self.bn(new_data)\n\n        return new_data\n"
  },
  {
    "path": "src/dagr/model/layers/spline_conv.py",
    "content": "import torch\n\nfrom torch_geometric.nn.conv import SplineConv\nfrom torch_geometric.data import Data\nfrom torch_geometric.transforms.to_sparse_tensor import ToSparseTensor\nfrom torch_spline_conv import spline_basis\n\n\nclass MySplineConv(SplineConv):\n    def __init__(self, in_channels, out_channels, args, bias=False, degree=1, **kwargs):\n        self.reproducible = True\n        self.to_sparse_tensor = ToSparseTensor(attr=\"edge_attr\", remove_edge_index=False)\n        super().__init__(in_channels=in_channels, out_channels=out_channels, bias=bias, degree=degree,\n                         dim=args.edge_attr_dim, aggr=args.aggr, kernel_size=args.kernel_size)\n\n    def init_lut(self, height, width, rx=None, Mx=None, ry=None, My=None):\n        # attr is assumed to be computed as attr = (x_i - x_j)/(2M) + 0.5\n        # where -r <= x_i - x_j <= r. So remapping to integers gives\n        # lut_index = 2M*attr - M + r. and 0 <= lut_index <= 2r\n\n        ry = ry or rx\n        My = My or Mx\n        self.attr_remapping_matrix = torch.Tensor([[2 * Mx * width,               0, - Mx * width + rx],\n                                                   [             0, 2 * My * height, - My * height + ry]])\n\n        # generate all possible dx, dy\n        dxy = torch.stack(torch.meshgrid(torch.arange(-rx, rx+1), torch.arange(-ry, ry+1))).float()\n        dxy[0] = dxy[0] / (2 * Mx * width) + 0.5\n        dxy[1] = dxy[1] / (2 * My * height) + 0.5\n        edge_attr = dxy.view((2,-1)).t()\n\n        bil_w, indices = spline_basis(edge_attr.to(self.weight.data.device), self.kernel_size, self.is_open_spline, self.degree)\n        lut_weights = (bil_w[...,None,None] * self.weight[indices]).sum(1)\n        _, cin, cout = lut_weights.shape\n        self.lut_weights = lut_weights.view((2 * rx + 1, 2 * ry + 1, cin, cout))\n\n        self.message = self.message_lut\n\n    def message_lut(self, x_j, edge_attr):\n        # index = (attr - 0.5) * 2 * M + r\n        dx_index = (edge_attr[:,0] * self.attr_remapping_matrix[0,0] + self.attr_remapping_matrix[0,-1]+1e-3).long()\n        dy_index = (edge_attr[:,1] * self.attr_remapping_matrix[1,1] + self.attr_remapping_matrix[1,-1]+1e-3).long()\n\n        weights = self.lut_weights[dx_index, dy_index] # N x C_out x C_in\n        x_out = torch.einsum(\"nio,ni->no\", weights, x_j)\n\n        return x_out\n\n    def forward(self, data: Data)->Data:\n        if self.reproducible:\n            # first check we already computed the adjacency matrix\n            if not hasattr(data, \"adj_t\"):\n                data.edge_attr = data.edge_attr[:,:self.dim]\n                data = self.to_sparse_tensor(data)\n            data.x = self._forward(data.x,\n                                  edge_index=data.adj_t)\n        else:\n            data.x = self._forward(data.x,\n                                  edge_index=data.edge_index,\n                                  edge_attr=data.edge_attr[:, :self.dim],\n                                  size=(data.x.shape[0], data.x.shape[0]))\n        return data\n\n    def _forward(self, x, edge_index, edge_attr=None, size=None):\n        \"\"\"\"\"\"\n        # propagate_type: (x: OptPairTensor, edge_attr: OptTensor)\n        if edge_index.numel() > 0:\n            out = self.propagate(edge_index, x=(x, x), edge_attr=edge_attr, size=size)\n        else:\n            out = torch.zeros((x.size(0), self.out_channels), dtype=x.dtype, device=x.device)\n\n        if x is not None and self.root_weight:\n            out += self.lin(x)\n\n        if self.bias is not None:\n            out += self.bias\n\n        return out\n\ndef to_dense(self, x, pos, pooling, batch=None, batch_size=None):\n    if hasattr(self, \"batch_size\"):\n        B = self.batch_size\n    elif batch_size is not None:\n        self.batch_size = batch_size\n        B = batch_size\n    elif batch is None:\n        batch = torch.zeros(size=(len(x),), dtype=torch.long, device=x.device)\n        B = 1\n        self.batch_size = B\n    else:\n        B = batch.max().item() + 1\n        self.batch_size = B\n\n    if not hasattr(self, \"dense\"):\n        W, H = (1 / pooling[:2] + 1e-3).long()\n        C = x.shape[-1]\n        self.dense = torch.zeros(size=(B, C, H, W), dtype=x.dtype, device=x.device)\n\n    est_x, est_y = (pos[:, :2] / pooling[:2]).t().long()\n\n    self.dense = self.dense.detach()\n    self.dense.zero_()\n\n    dense = self.dense[:B] if B < self.dense.shape[0] else self.dense\n    dense[batch.long(), :, est_y, est_x] = x\n\n    return dense\n\n\nclass SplineConvToDense(MySplineConv):\n    def forward(self, data: Data, batch_size: int=None)->torch.Tensor:\n        data = super().forward(data)\n        if data.batch is None:\n            data.batch = torch.zeros(len(data.x), dtype=torch.long, device=data.x.device)\n        return self.to_dense(data.x, data.pos, data.pooling, data.batch, batch_size=batch_size)\n\n    def to_dense(self, x, pos, pooling, batch=None, batch_size=None):\n        return to_dense(self, x, pos, pooling, batch, batch_size=batch_size)"
  },
  {
    "path": "src/dagr/model/networks/dagr.py",
    "content": "import torch\n\nimport torch.nn.functional as F\n\nfrom torch_geometric.data import Data\nfrom yolox.models import YOLOX, YOLOXHead, IOUloss\n\nfrom dagr.model.networks.net import Net\nfrom dagr.model.layers.spline_conv import SplineConvToDense\nfrom dagr.model.layers.conv import ConvBlock\nfrom dagr.model.utils import shallow_copy, init_subnetwork, voxel_size_to_params, postprocess_network_output, convert_to_evaluation_format, init_grid_and_stride, convert_to_training_format\n\n\nclass DAGR(YOLOX):\n    def __init__(self, args, height, width):\n        self.conf_threshold = 0.001\n        self.nms_threshold = 0.65\n\n        self.height = height\n        self.width = width\n\n        backbone = Net(args, height=height, width=width)\n        head = GNNHead(num_classes=backbone.num_classes,\n                       in_channels=backbone.out_channels,\n                       in_channels_cnn=backbone.out_channels_cnn,\n                       strides=backbone.strides,\n                       pretrain_cnn=args.pretrain_cnn,\n                       args=args)\n\n        super().__init__(backbone=backbone, head=head)\n\n        if \"img_net_checkpoint\" in args:\n            state_dict = torch.load(args.img_net_checkpoint)\n            init_subnetwork(self, state_dict['ema'], \"backbone.net.\", freeze=True)\n            init_subnetwork(self, state_dict['ema'], \"head.cnn_head.\")\n\n    def cache_luts(self, width, height, radius):\n        M = 2 * float(int(radius * width + 2) / width)\n        r = int(radius * width+1)\n        self.backbone.conv_block1.conv_block1.conv.init_lut(height=height, width=width, Mx=M, rx=r)\n        self.backbone.conv_block1.conv_block2.conv.init_lut(height=height, width=width, Mx=M, rx=r)\n\n        rx, ry, M = voxel_size_to_params(self.backbone.pool1, height, width)\n        self.backbone.layer2.conv_block1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.backbone.layer2.conv_block2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n        rx, ry, M = voxel_size_to_params(self.backbone.pool2, height, width)\n        self.backbone.layer3.conv_block1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.backbone.layer3.conv_block2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n        rx, ry, M = voxel_size_to_params(self.backbone.pool3, height, width)\n        self.backbone.layer4.conv_block1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.backbone.layer4.conv_block2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n        self.head.stem1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.head.cls_conv1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.head.reg_conv1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.head.cls_pred1.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.head.reg_pred1.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.head.obj_pred1.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n        rx, ry, M = voxel_size_to_params(self.backbone.pool4, height, width)\n        self.backbone.layer5.conv_block1.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n        self.backbone.layer5.conv_block2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n        if self.head.num_scales > 1:\n            self.head.stem2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n            self.head.cls_conv2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n            self.head.reg_conv2.conv.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n            self.head.cls_pred2.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n            self.head.reg_pred2.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n            self.head.obj_pred2.init_lut(height=height, width=width, Mx=M, rx=rx, ry=ry)\n\n    def forward(self, x: Data, reset=True, return_targets=True, filtering=True):\n        if not hasattr(self.head, \"output_sizes\"):\n            self.head.output_sizes = self.backbone.get_output_sizes()\n\n        if self.training:\n            targets = convert_to_training_format(x.bbox, x.bbox_batch, x.num_graphs)\n\n            if self.backbone.use_image:\n                targets0 = convert_to_training_format(x.bbox0, x.bbox0_batch, x.num_graphs)\n                targets = (targets, targets0)\n\n            # gt_target inputs need to be [l cx cy w h] in pixels\n            outputs = YOLOX.forward(self, x, targets)\n\n            return outputs\n\n        x.reset = reset\n\n        outputs = YOLOX.forward(self, x)\n\n        detections = postprocess_network_output(outputs, self.backbone.num_classes, self.conf_threshold, self.nms_threshold, filtering=filtering,\n                                                height=self.height, width=self.width)\n\n        ret = [detections]\n\n        if return_targets and hasattr(x, 'bbox'):\n            targets = convert_to_evaluation_format(x)\n            ret.append(targets)\n\n        return ret\n\n\nclass CNNHead(YOLOXHead):\n    def forward(self, xin):\n        outputs = dict(cls_output=[], reg_output=[], obj_output=[])\n\n        for k, (cls_conv, reg_conv, x) in enumerate(zip(self.cls_convs, self.reg_convs, xin)):\n            x = self.stems[k](x)\n            cls_x = x\n            reg_x = x\n\n            cls_feat = cls_conv(cls_x)\n            reg_feat = reg_conv(reg_x)\n\n            outputs[\"cls_output\"].append(self.cls_preds[k](cls_feat))\n            outputs[\"reg_output\"].append(self.reg_preds[k](reg_feat))\n            outputs[\"obj_output\"].append(self.obj_preds[k](reg_feat))\n\n        return outputs\n\n\nclass GNNHead(YOLOXHead):\n    def __init__(\n        self,\n        num_classes,\n        strides=[8, 16, 32],\n        in_channels=[256, 512, 1024],\n        in_channels_cnn=[256, 512, 1024],\n        act=\"silu\",\n        depthwise=False,\n        pretrain_cnn=False,\n        args=None\n    ):\n        YOLOXHead.__init__(self, num_classes, args.yolo_stem_width, strides, in_channels, act, depthwise)\n\n        self.pretrain_cnn = pretrain_cnn\n        self.num_scales = args.num_scales\n        self.use_image = args.use_image\n        self.batch_size = args.batch_size\n        self.no_events = args.no_events\n\n        self.in_channels = in_channels\n        self.n_anchors = 1\n        self.num_classes = num_classes\n\n        n_reg = max(in_channels)\n        self.stem1 = ConvBlock(in_channels=in_channels[0], out_channels=n_reg, args=args)\n        self.cls_conv1 = ConvBlock(in_channels=n_reg, out_channels=n_reg, args=args)\n        self.cls_pred1 = SplineConvToDense(in_channels=n_reg, out_channels=self.n_anchors * self.num_classes, bias=True, args=args)\n        self.reg_conv1 = ConvBlock(in_channels=n_reg, out_channels=n_reg, args=args)\n        self.reg_pred1 = SplineConvToDense(in_channels=n_reg, out_channels=4, bias=True, args=args)\n        self.obj_pred1 = SplineConvToDense(in_channels=n_reg, out_channels=self.n_anchors, bias=True, args=args)\n\n        if self.num_scales > 1:\n            self.stem2 = ConvBlock(in_channels=in_channels[1], out_channels=n_reg, args=args)\n            self.cls_conv2 = ConvBlock(in_channels=n_reg, out_channels=n_reg, args=args)\n            self.cls_pred2 = SplineConvToDense(in_channels=n_reg, out_channels=self.n_anchors * self.num_classes, bias=True, args=args)\n            self.reg_conv2 = ConvBlock(in_channels=n_reg, out_channels=n_reg, args=args)\n            self.reg_pred2 = SplineConvToDense(in_channels=n_reg, out_channels=4, bias=True, args=args)\n            self.obj_pred2 = SplineConvToDense(in_channels=n_reg, out_channels=self.n_anchors, bias=True, args=args)\n\n        if self.use_image:\n            self.cnn_head = CNNHead(num_classes=num_classes, strides=strides, in_channels=in_channels_cnn)\n\n        self.use_l1 = False\n        self.l1_loss = torch.nn.L1Loss(reduction=\"none\")\n        self.bcewithlog_loss = torch.nn.BCEWithLogitsLoss(reduction=\"none\")\n        self.iou_loss = IOUloss(reduction=\"none\")\n        self.strides = strides\n        self.grids = [torch.zeros(1)] * len(in_channels)\n\n        self.grid_cache = None\n        self.stride_cache = None\n        self.cache = []\n\n    def process_feature(self, x, stem, cls_conv, reg_conv, cls_pred, reg_pred, obj_pred, batch_size, cache):\n        x = stem(x)\n\n        cls_feat = cls_conv(shallow_copy(x))\n        reg_feat = reg_conv(x)\n\n        # we need to provide the batchsize, since sometimes it cannot be foudn from the data, especially when nodes=0\n        cls_output = cls_pred(cls_feat, batch_size=batch_size)\n        reg_output = reg_pred(shallow_copy(reg_feat), batch_size=batch_size)\n        obj_output = obj_pred(reg_feat, batch_size=batch_size)\n\n        return cls_output, reg_output, obj_output\n\n    def forward(self, xin: Data, labels=None, imgs=None):\n        # for events + image outputs\n        hybrid_out = dict(outputs=[], origin_preds=[], x_shifts=[], y_shifts=[], expanded_strides=[])\n        image_out = dict(outputs=[], origin_preds=[], x_shifts=[], y_shifts=[], expanded_strides=[])\n\n        if self.use_image:\n            xin, image_feat = xin\n\n            if labels is not None:\n                if self.use_image:\n                    labels, image_labels = labels\n\n            # resize image, and process with CNN\n            image_feat = [torch.nn.functional.interpolate(f, o) for f, o in zip(image_feat, self.output_sizes)]\n            out_cnn = self.cnn_head(image_feat)\n\n            # collect outputs from image alone, so the image network also learns to detect on its own.\n            for k in [0, 1]:\n                self.collect_outputs(out_cnn[\"cls_output\"][k],\n                                     out_cnn[\"reg_output\"][k],\n                                     out_cnn[\"obj_output\"][k],\n                                     k, self.strides[k], ret=image_out)\n\n        batch_size = len(out_cnn[\"cls_output\"][0]) if self.use_image else self.batch_size\n        cls_output, reg_output, obj_output = self.process_feature(xin[0], self.stem1, self.cls_conv1, self.reg_conv1,\n                                                        self.cls_pred1, self.reg_pred1, self.obj_pred1, batch_size=batch_size, cache=self.cache)\n\n        if self.use_image:\n            cls_output[:batch_size] += out_cnn[\"cls_output\"][0].detach()\n            reg_output[:batch_size] += out_cnn[\"reg_output\"][0].detach()\n            obj_output[:batch_size] += out_cnn[\"obj_output\"][0].detach()\n\n        self.collect_outputs(cls_output, reg_output, obj_output, 0, self.strides[0], ret=hybrid_out)\n\n        if self.num_scales > 1:\n            cls_output, reg_output, obj_output = self.process_feature(xin[1], self.stem2, self.cls_conv2,\n                                                                      self.reg_conv2, self.cls_pred2, self.reg_pred2,\n                                                                      self.obj_pred2, batch_size=batch_size, cache=self.cache)\n            if self.use_image:\n                batch_size = out_cnn[\"cls_output\"][0].shape[0]\n                cls_output[:batch_size] += out_cnn[\"cls_output\"][1].detach()\n                reg_output[:batch_size] += out_cnn[\"reg_output\"][1].detach()\n                obj_output[:batch_size] += out_cnn[\"obj_output\"][1].detach()\n\n            self.collect_outputs(cls_output, reg_output, obj_output, 1, self.strides[1], ret=hybrid_out)\n\n        if self.training:\n            # if we are only training the image detectors (pretraining),\n            # we only need to minimize the loss at detections from the image branch.\n            if self.use_image:\n                losses_image = self.get_losses(\n                    imgs,\n                    image_out['x_shifts'],\n                    image_out['y_shifts'],\n                    image_out['expanded_strides'],\n                    image_labels,\n                    torch.cat(image_out['outputs'], 1),\n                    image_out['origin_preds'],\n                    dtype=image_out['x_shifts'][0].dtype,\n                )\n\n                if not self.pretrain_cnn:\n                    losses_events  = self.get_losses(\n                    imgs,\n                    hybrid_out['x_shifts'],\n                    hybrid_out['y_shifts'],\n                    hybrid_out['expanded_strides'],\n                    labels,\n                    torch.cat(hybrid_out['outputs'], 1),\n                    hybrid_out['origin_preds'],\n                    dtype=xin[0].x.dtype,\n                )\n\n                    losses_image = list(losses_image)\n                    losses_events = list(losses_events)\n\n                    for i in range(5):\n                        losses_image[i] = losses_image[i] + losses_events[i]\n\n                return losses_image\n            else:\n                return self.get_losses(\n                    imgs,\n                    hybrid_out['x_shifts'],\n                    hybrid_out['y_shifts'],\n                    hybrid_out['expanded_strides'],\n                    labels,\n                    torch.cat(hybrid_out['outputs'], 1),\n                    hybrid_out['origin_preds'],\n                    dtype=xin[0].x.dtype,\n                )\n        else:\n            out = image_out['outputs'] if self.no_events else hybrid_out['outputs']\n\n            self.hw = [x.shape[-2:] for x in out]\n            # [batch, n_anchors_all, 85]\n            outputs = torch.cat([x.flatten(start_dim=2) for x in out], dim=2).permute(0, 2, 1)\n\n            return self.decode_outputs(outputs, dtype=out[0].type())\n\n    def collect_outputs(self, cls_output, reg_output, obj_output, k, stride_this_level, ret=None):\n        if self.training:\n            output = torch.cat([reg_output, obj_output, cls_output], 1)\n            output, grid = self.get_output_and_grid(output, k, stride_this_level, output.type())\n            ret['x_shifts'].append(grid[:, :, 0])\n            ret['y_shifts'].append(grid[:, :, 1])\n            ret['expanded_strides'].append(torch.zeros(1, grid.shape[1]).fill_(stride_this_level).type_as(output))\n        else:\n            output = torch.cat(\n                [reg_output, obj_output.sigmoid(), cls_output.sigmoid()], 1\n            )\n\n        ret['outputs'].append(output)\n\n    def decode_outputs(self, outputs, dtype):\n        if self.grid_cache is None:\n            self.grid_cache, self.stride_cache = init_grid_and_stride(self.hw, self.strides, dtype)\n\n        outputs[..., :2] = (outputs[..., :2] + self.grid_cache) * self.stride_cache\n        outputs[..., 2:4] = torch.exp(outputs[..., 2:4]) * self.stride_cache\n        return outputs\n\n"
  },
  {
    "path": "src/dagr/model/networks/ema.py",
    "content": "import torch\nimport math\nfrom copy import deepcopy\n\n\nclass ModelEMA:\n    \"\"\"\n    Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models\n    Keep a moving average of everything in the model state_dict (parameters and buffers).\n    This is intended to allow functionality like\n    https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage\n    A smoothed version of the weights is necessary for some training schemes to perform well.\n    This class is sensitive where it is initialized in the sequence of model init,\n    GPU assignment and distributed training wrappers.\n    \"\"\"\n\n    def __init__(self, model, decay=0.9999, updates=0):\n        \"\"\"\n        Args:\n            model (nn.Module): model to apply EMA.\n            decay (float): ema decay reate.\n            updates (int): counter of EMA updates.\n        \"\"\"\n        # Create EMA(FP32)\n        self.ema = deepcopy(model).eval()\n\n        try:\n            # if we do not do this, all the hooks will be activated for the other model, which will create\n            # a lot of memory usage\n            self.ema.backbone.net.remove_hooks()\n            self.ema.backbone.net.register_hooks()\n        except:\n            pass\n\n        self.updates = updates\n        # decay exponential ramp (to help early epochs)\n        self.decay = lambda x: decay * (1 - math.exp(-x / 2000))\n        for p in self.ema.parameters():\n            p.requires_grad_(False)\n\n    def update(self, model):\n        # Update EMA parameters\n        with torch.no_grad():\n            self.updates += 1\n            d = self.decay(self.updates)\n\n            msd = model.state_dict()\n            for k, v in self.ema.state_dict().items():\n                if v.dtype.is_floating_point:\n                    v *= d\n                    v += (1.0 - d) * msd[k].detach()\n"
  },
  {
    "path": "src/dagr/model/networks/net.py",
    "content": "import torch\n\nimport torch_geometric.transforms as T\n\nfrom torch_geometric.data import Data\nfrom dagr.model.layers.ev_tgn import EV_TGN\nfrom dagr.model.layers.pooling import Pooling\nfrom dagr.model.layers.conv import Layer\nfrom dagr.model.layers.components import Cartesian\nfrom dagr.model.networks.net_img import HookModule\nfrom dagr.model.utils import shallow_copy\nfrom torchvision.models import resnet18, resnet34, resnet50\n\n\ndef sampling_skip(data, image_feat):\n    image_feat_at_nodes = sample_features(data, image_feat)\n    return torch.cat((data.x, image_feat_at_nodes), dim=1)\n\ndef compute_pooling_at_each_layer(pooling_dim_at_output, num_layers):\n    py, px = map(int, pooling_dim_at_output.split(\"x\"))\n    pooling_base = torch.tensor([1.0 / px, 1.0 / py, 1.0 / 1])\n    poolings = []\n    for i in range(num_layers):\n        pooling = pooling_base / 2 ** (3 - i)\n        pooling[-1] = 1\n        poolings.append(pooling)\n    poolings = torch.stack(poolings)\n    return poolings\n\n\nclass Net(torch.nn.Module):\n    def __init__(self, args, height, width):\n        super().__init__()\n\n        channels = [1, int(args.base_width*32), int(args.after_pool_width*64),\n                    int(args.net_stem_width*128),\n                    int(args.net_stem_width*128),\n                    int(args.net_stem_width*128)]\n\n        self.out_channels_cnn = []\n        if args.use_image:\n            img_net = eval(args.img_net)\n            self.out_channels_cnn = [256, 256]\n            self.net = HookModule(img_net(pretrained=True),\n                                  input_channels=3,\n                                  height=height, width=width,\n                                  feature_layers=[\"conv1\", \"layer1\", \"layer2\", \"layer3\", \"layer4\"],\n                                  output_layers=[\"layer3\", \"layer4\"],\n                                  feature_channels=channels[1:],\n                                  output_channels=self.out_channels_cnn)\n\n        self.use_image = args.use_image\n        self.num_scales = args.num_scales\n\n        self.num_classes = dict(dsec=2, ncaltech101=100).get(args.dataset, 2)\n\n        self.events_to_graph = EV_TGN(args)\n\n        output_channels = channels[1:]\n        self.out_channels = output_channels[-2:]\n\n        input_channels = channels[:-1]\n        if self.use_image:\n            input_channels = [input_channels[i] + self.net.feature_channels[i] for i in range(len(input_channels))]\n\n        # parse x and y pooling dimensions at output\n        poolings = compute_pooling_at_each_layer(args.pooling_dim_at_output, num_layers=4)\n        max_vals_for_cartesian = 2*poolings[:,:2].max(-1).values\n        self.strides = torch.ceil(poolings[-2:,1] * height).numpy().astype(\"int32\").tolist()\n        self.strides = self.strides[-self.num_scales:]\n\n        effective_radius = 2*float(int(args.radius * width + 2) / width)\n        self.edge_attrs = Cartesian(norm=True, cat=False, max_value=effective_radius)\n\n        self.conv_block1 = Layer(2+input_channels[0], output_channels[0], args=args)\n\n        cart1 = T.Cartesian(norm=True, cat=False, max_value=2*effective_radius)\n        self.pool1 = Pooling(poolings[0], width=width, height=height, batch_size=args.batch_size,\n                             transform=cart1, aggr=args.pooling_aggr, keep_temporal_ordering=args.keep_temporal_ordering)\n\n        self.layer2 = Layer(input_channels[1]+2, output_channels[1], args=args)\n\n        cart2 = T.Cartesian(norm=True, cat=False, max_value=max_vals_for_cartesian[1])\n        self.pool2 = Pooling(poolings[1], width=width, height=height, batch_size=args.batch_size,\n                             transform=cart2, aggr=args.pooling_aggr, keep_temporal_ordering=args.keep_temporal_ordering)\n\n        self.layer3 = Layer(input_channels[2]+2, output_channels[2],  args=args)\n\n        cart3 = T.Cartesian(norm=True, cat=False, max_value=max_vals_for_cartesian[2])\n        self.pool3 = Pooling(poolings[2], width=width, height=height, batch_size=args.batch_size,\n                             transform=cart3, aggr=args.pooling_aggr, keep_temporal_ordering=args.keep_temporal_ordering)\n\n        self.layer4 = Layer(input_channels[3]+2, output_channels[3],  args=args)\n\n        cart4 = T.Cartesian(norm=True, cat=False, max_value=max_vals_for_cartesian[3])\n        self.pool4 = Pooling(poolings[3], width=width, height=height, batch_size=args.batch_size,\n                             transform=cart4, aggr='mean', keep_temporal_ordering=args.keep_temporal_ordering)\n\n        self.layer5 = Layer(input_channels[4]+2, output_channels[4],  args=args)\n\n        self.cache = []\n\n    def get_output_sizes(self):\n        poolings = [self.pool3.voxel_size[:2], self.pool4.voxel_size[:2]]\n        output_sizes = [(1 / p + 1e-3).cpu().int().numpy().tolist()[::-1] for p in poolings]\n        return output_sizes\n\n    def forward(self, data: Data, reset=True):\n        if self.use_image:\n            image_feat, image_outputs = self.net(data.image)\n\n        if hasattr(data, 'reset'):\n            reset = data.reset\n\n        data = self.events_to_graph(data, reset=reset)\n\n        if self.use_image:\n            data.x = sampling_skip(data, image_feat[0].detach())\n            data.skipped = True\n            data.num_image_channels = image_feat[0].shape[1]\n\n        data = self.edge_attrs(data)\n        data.edge_attr = torch.clamp(data.edge_attr, min=0, max=1)\n        rel_delta = data.pos[:, :2]\n        data.x = torch.cat((data.x, rel_delta), dim=1)\n        data = self.conv_block1(data)\n\n        if self.use_image:\n            data.x = sampling_skip(data, image_feat[1].detach())\n\n        data = self.pool1(data)\n\n        if self.use_image:\n            data.skipped = True\n            data.num_image_channels = image_feat[1].shape[1]\n\n        rel_delta = data.pos[:,:2]\n        data.x = torch.cat((data.x, rel_delta), dim=1)\n        data = self.layer2(data)\n\n        if self.use_image:\n            data.x = sampling_skip(data, image_feat[2].detach())\n\n        data = self.pool2(data)\n\n        if self.use_image:\n            data.skipped = True\n            data.num_image_channels = image_feat[2].shape[1]\n\n        rel_delta = data.pos[:,:2]\n        data.x = torch.cat((data.x, rel_delta), dim=1)\n        data = self.layer3(data)\n\n        if self.use_image:\n            data.x = sampling_skip(data, image_feat[3].detach())\n\n        data = self.pool3(data)\n\n        if self.use_image:\n            data.skipped = True\n            data.num_image_channels = image_feat[3].shape[1]\n\n        rel_delta = data.pos[:,:2]\n        data.x = torch.cat((data.x, rel_delta), dim=1)\n        data = self.layer4(data)\n\n        out3 = shallow_copy(data)\n        out3.pooling = self.pool3.voxel_size[:3]\n\n        if self.use_image:\n            data.x = sampling_skip(data, image_feat[4].detach())\n\n        data = self.pool4(data)\n\n        if self.use_image:\n            data.skipped = True\n            data.num_image_channels = image_feat[4].shape[1]\n\n        rel_delta = data.pos[:,:2]\n        data.x = torch.cat((data.x, rel_delta), dim=1)\n        data = self.layer5(data)\n\n        out4 = data\n        out4.pooling = self.pool4.voxel_size[:3]\n\n        output = [out3, out4]\n\n        if self.use_image:\n            return output[-self.num_scales:], image_outputs[-self.num_scales:]\n        return output[-self.num_scales:]\n\n\ndef sample_features(data, image_feat, image_sample_mode=\"bilinear\"):\n    if data.batch is None or len(data.batch) != len(data.pos):\n        data.batch = torch.zeros(len(data.pos), dtype=torch.long, device=data.x.device)\n    return _sample_features(data.pos[:,0] * data.width[0],\n                            data.pos[:,1] * data.height[0],\n                            data.batch.float(), image_feat,\n                            data.width[0],\n                            data.height[0],\n                            image_feat.shape[0],\n                            image_sample_mode)\n\ndef _sample_features(x, y, b, image_feat, width, height, batch_size, image_sample_mode):\n    x = 2 * x / (width - 1) - 1\n    y = 2 * y / (height - 1) - 1\n\n    batch_size = batch_size if batch_size > 1 else 2\n    b = 2 * b / (batch_size - 1) - 1\n\n    grid = torch.stack((x, y, b), dim=-1).view(1, 1, 1,-1, 3) # N x D_out x H_out x W_out x 3 (N=1, D_out=1, H_out=1)\n    image_feat = image_feat.permute(1,0,2,3).unsqueeze(0) # N x C x D x H x W (N=1)\n\n    image_feat_sampled = torch.nn.functional.grid_sample(image_feat,\n                                                         grid=grid,\n                                                         mode=image_sample_mode,\n                                                         align_corners=True) # N x C x H_out x W_out (H_out=1, N=1)\n\n    image_feat_sampled = image_feat_sampled.view(image_feat.shape[1], -1).t()\n\n    return image_feat_sampled\n\n\n\n\n"
  },
  {
    "path": "src/dagr/model/networks/net_img.py",
    "content": "import torch\n\n\nclass Layer(torch.nn.Module):\n    def __init__(self, input_channels, output_channels):\n        super(Layer, self).__init__()\n        self.conv1 = torch.nn.Conv2d(input_channels, output_channels, kernel_size=3, stride=1, padding=1)\n        self.bn1 = torch.nn.BatchNorm2d(output_channels)\n\n        self.conv2 = torch.nn.Conv2d(output_channels, output_channels, kernel_size=3, stride=1, padding=1)\n        self.bn2 = torch.nn.BatchNorm2d(output_channels)\n\n        self.dwc = torch.nn.Conv2d(input_channels, output_channels, kernel_size=1, stride=1, padding=0)\n        self.bn_skip = torch.nn.BatchNorm2d(output_channels)\n        self.act = torch.nn.ReLU()\n\n    def forward(self, x):\n        x_skip = x.clone()\n        x = self.act(self.bn1(self.conv1(x)))\n        x = self.bn2(self.conv2(x))\n        x = x + self.bn_skip(self.dwc(x_skip))\n        return self.act(x)\n\n\nclass ConvBlockDense(torch.nn.Module):\n    def __init__(self, in_channels, out_channels, bias=False, act=torch.nn.ReLU(), bn=True):\n        super(ConvBlockDense, self).__init__()\n        self.conv = torch.nn.Conv2d(in_channels, out_channels, bias=bias, kernel_size=3, stride=1, padding=1)\n        self.bn = torch.nn.BatchNorm2d(out_channels)\n        self.act = act\n        self.use_bn = bn\n\n    def forward(self, x):\n        x = self.conv(x)\n        if self.use_bn:\n            x = self.bn(x)\n        if self.act is not None:\n            x = self.act(x)\n        return x\n\n\nclass HookModule(torch.nn.Module):\n    \"\"\"\n    Define the module, then you can determine which features are extracted, and which outputs are extracted.\n    For each you can decide if they are mapped to a lower dimension or not.\n\n    \"\"\"\n    def __init__(self, module, height, width, input_channels=3, feature_layers=(), output_layers=(), feature_channels=None, output_channels=None):\n        torch.nn.Module.__init__(self)\n        self.module = module.cpu()\n\n        if input_channels != 3:\n            self.module.conv1 = torch.nn.Conv2d(in_channels=input_channels, out_channels=self.module.conv1.out_channels,\n                                                kernel_size=self.module.conv1.kernel_size,\n                                                padding=self.module.conv1.padding,\n                                                bias=False)\n\n        self.feature_layers = feature_layers\n        self.output_layers = output_layers\n\n        self.hooks = []\n        self.features = []\n        self.outputs = []\n        self.register_hooks()\n\n        self.feature_channels = []\n        self.output_channels = []\n        self.compute_channels_with_dummy(shape=(1, input_channels, height, width))\n\n        self.feature_dconv = torch.nn.ModuleList()\n        if feature_channels is not None:\n            assert len(feature_channels) == len(self.feature_channels)\n            self.feature_dconv = torch.nn.ModuleList(\n                [\n                    torch.nn.Conv2d(in_channels=cin, out_channels=cout, kernel_size=1, stride=1, padding=0)\n                    for cin, cout in zip(self.feature_channels, feature_channels)\n                ]\n            )\n            self.feature_channels = feature_channels\n\n        self.output_dconv = torch.nn.ModuleList()\n        if output_channels is not None:\n            assert len(output_channels) == len(self.output_channels)\n            self.output_dconv = torch.nn.ModuleList(\n                [\n                    torch.nn.Conv2d(in_channels=cin, out_channels=cout, kernel_size=1, stride=1, padding=0)\n                    for cin, cout in zip(self.output_channels, output_channels)\n                ]\n            )\n            self.output_channels = output_channels\n\n    def extract_layer(self, module, layer):\n        if len(layer) == 0:\n            return module\n        else:\n            return self.extract_layer(module._modules[layer[0]], layer[1:])\n\n    def compute_channels_with_dummy(self, shape):\n        dummy_input = torch.zeros(shape)\n        self.module.forward(dummy_input)\n        self.feature_channels = [f.shape[1] for f in self.features]\n        self.output_channels = [o.shape[1] for o in self.outputs]\n        self.features = []\n        self.outputs = []\n\n    def remove_hooks(self):\n        for h in self.hooks:\n            h.remove()\n\n    def register_hooks(self):\n        self.features = []\n        self.outputs = []\n        features_hook = lambda m, i, o: self.features.append(o)\n        outputs_hook = lambda m, i, o: self.outputs.append(o)\n        for l in self.feature_layers:\n            hook_id = self.extract_layer(self.module, l.split(\".\")).register_forward_hook(features_hook)\n            self.hooks.append(hook_id)\n        for l in self.output_layers:\n            hook_id = self.extract_layer(self.module, l.split(\".\")).register_forward_hook(outputs_hook)\n            self.hooks.append(hook_id)\n\n    def forward(self, x):\n        self.features = []\n        self.outputs = []\n        self.module(x)\n\n        features = self.features\n        if len(self.feature_dconv) > 0:\n            features = [dconv(f) for f, dconv in zip(self.features, self.feature_dconv)]\n\n        outputs = self.outputs\n        if len(self.output_dconv) > 0:\n            outputs = [dconv(o) for o, dconv in zip(self.outputs, self.output_dconv)]\n\n        return features, outputs"
  },
  {
    "path": "src/dagr/model/utils.py",
    "content": "import torchvision\nimport torch\n\nimport numpy as np\n\nfrom torch_geometric.data import Data\n\n\ndef init_subnetwork(net, state_dict, name=\"backbone.net.\", freeze=False):\n    assert name.endswith(\".\")\n\n    # get submodule\n    attrs = name.split(\".\")[:-1]\n    for attr in attrs:\n        net = getattr(net, attr)\n\n    # load weights and freeze\n    sub_state_dict = {k.replace(name, \"\"): v for k, v in state_dict.items() if name in k}\n    net.load_state_dict(sub_state_dict)\n\n    if freeze:\n        for param in net.parameters():\n            param.requires_grad = False\n\ndef batched_nms_coordinate_trick(boxes, scores, idxs, iou_threshold, width, height):\n    # adopted from torchvision nms, but faster\n    if boxes.numel() == 0:\n        return torch.empty((0,), dtype=torch.int64, device=boxes.device)\n    max_dim = max([width, height])\n    offsets = idxs * float(max_dim + 1)\n    boxes_for_nms = boxes + offsets[:, None]\n    keep = torchvision.ops.nms(boxes_for_nms, scores, iou_threshold)\n    return keep\n\ndef convert_to_evaluation_format(data):\n    targets = []\n    for d in data.to_data_list():\n        bbox = d.bbox.clone()\n        bbox[:,2:4] += bbox[:,:2]\n        targets.append({\n            \"boxes\": bbox[:,:4],\n            \"labels\": bbox[:, 4].long() # class 0 is background class\n        })\n    return targets\n\ndef convert_to_training_format(bbox, batch, batch_size):\n    max_detections = 100\n    targets = torch.zeros(size=(batch_size, max_detections, 5), dtype=torch.float32, device=bbox.device)\n    unique, counts = torch.unique(batch, return_counts=True)\n    counter = _sequential_counter(counts)\n\n    bbox = bbox.clone()\n    # xywhlc pix -> lcxcywh pix\n    bbox[:, :2] += bbox[:, 2:4] * .5\n    bbox = torch.roll(bbox[:, :5], dims=1, shifts=1)\n\n    targets[batch, counter] = bbox\n\n    return targets\n\ndef postprocess_network_output(prediction, num_classes, conf_thre=0.01, nms_thre=0.65, height=640, width=640, filtering=True):\n    prediction[..., :2] -= prediction[...,2:4] / 2 # cxcywh->xywh\n    prediction[..., 2:4] += prediction[...,:2]\n\n    output = []\n    for i, image_pred in enumerate(prediction):\n\n        # If none are remaining => process next image\n        if len(image_pred) == 0:\n            device = prediction.device\n            output.append({\n                \"boxes\": torch.zeros(0, 4, dtype=torch.float32, device=device),\n                \"scores\": torch.zeros(0, dtype=torch.float, device=device),\n                \"labels\": torch.zeros(0, dtype=torch.long, device=device)\n            })\n            continue\n\n        # Get score and class with highest confidence\n        class_conf, class_pred = torch.max(image_pred[:, 5: 5 + num_classes], 1, keepdim=True)\n        image_pred[:, 4:5] *= class_conf\n\n        conf_mask = (image_pred[:, 4] * class_conf.squeeze() >= conf_thre).squeeze()\n        # Detections ordered as (x1, y1, x2, y2, obj_conf, class_conf, class_pred)\n        detections = torch.cat((image_pred[:, :5], class_pred), 1)\n\n        if filtering:\n            detections = detections[conf_mask]\n\n        if len(detections) == 0:\n            device = prediction.device\n            output.append({\n                \"boxes\": torch.zeros(0, 4, dtype=torch.float32, device=device),\n                \"scores\": torch.zeros(0, dtype=torch.float, device=device),\n                \"labels\": torch.zeros(0, dtype=torch.long, device=device)\n            })\n            continue\n\n        nms_out_index = batched_nms_coordinate_trick(detections[:, :4], detections[:, 4], detections[:, 5],\n                                                      nms_thre, width=width, height=height)\n\n        if filtering:\n            detections = detections[nms_out_index]\n\n        output.append({\n            \"boxes\": detections[:, :4],\n            \"scores\": detections[:, 4],\n            \"labels\": detections[:, -1].long()\n        })\n\n    return output\n\ndef voxel_size_to_params(pooling_layer, height, width):\n    rx = int(np.ceil(2*pooling_layer.voxel_size[0].cpu().numpy() * width))\n    ry = int(np.ceil(2*pooling_layer.voxel_size[1].cpu().numpy() * height))\n    M = pooling_layer.transform.max\n    return rx, ry, M\n\n\ndef init_grid_and_stride(hw, strides, dtype):\n    grids = []\n    all_strides = []\n    for (hsize, wsize), stride in zip(hw, strides):\n        yv, xv = torch.meshgrid(torch.arange(hsize), torch.arange(wsize), indexing=\"ij\")\n        grid = torch.stack((xv, yv), 2).view(1, -1, 2)\n        grids.append(grid)\n        shape = grid.shape[:2]\n        all_strides.append(torch.full((*shape, 1), stride))\n\n    grid_cache = torch.cat(grids, dim=1).type(dtype)\n    stride_cache = torch.cat(all_strides, dim=1).type(dtype)\n\n    return grid_cache, stride_cache\n\ndef _sequential_counter(counts: torch.LongTensor):\n    \"\"\"\n    Returns a torch tensor which counts up for each count\n    Example: counts = [2,4,6,2,4] then the output will be\n    output = [0,1,0,1,2,3,0,1,2,3,4,5,0,1,0,1,2,3]\n    \"\"\"\n    assert counts.dtype == torch.long\n    assert len(counts.shape) > 0\n    assert (counts >= 0).all()\n\n    len_counter = counts.sum()\n    tensors_kwargs = dict(device=counts.device, dtype=torch.long)\n\n    # first construct delta function, which has value c_N at position sum_k=0^N c_k\n    delta = torch.zeros(size=(len_counter,), **tensors_kwargs)\n    x_coord = counts.cumsum(dim=0)\n    delta[x_coord[:-1]] = counts[:-1]\n\n    # next construct step function, and the result it a linear function minus this step function\n    step = delta.cumsum(dim=0)\n    counter = torch.arange(len_counter, **tensors_kwargs) - step\n\n    return counter\n\ndef shallow_copy(data):\n    out =  Data(x=data.x.clone(), edge_index=data.edge_index, edge_attr=data.edge_attr, pos=data.pos, batch=data.batch)\n    for key in [\"active_clusters\", \"_changed_attr\", \"_changed_attr_indices\",\"diff_idx\", \"diff_pos_idx\", \"pooling\", \"num_image_channels\", \"skipped\", \"pooled\"]:\n        if hasattr(data, key):\n            setattr(out, key, getattr(data, key))\n    for key in [\"diff_idx\", \"diff_pos_idx\"]:\n        if hasattr(data, key):\n            setattr(out, key, getattr(data, key).clone())\n    return out\n\n"
  },
  {
    "path": "src/dagr/utils/args.py",
    "content": "import argparse\nimport yaml\n\nfrom pathlib import Path\n\n\ndef BASE_FLAGS():\n    parser = argparse.ArgumentParser(\"\")\n    parser.add_argument('--dataset_directory', type=Path, default=argparse.SUPPRESS, help=\"Path to the directory containing the dataset.\")\n    parser.add_argument('--output_directory', type=Path, default=argparse.SUPPRESS, help=\"Path to the logging directory.\")\n    parser.add_argument(\"--checkpoint\", type=Path, default=argparse.SUPPRESS, help=\"Path to the directory containing the checkpoint.\")\n    parser.add_argument(\"--img_net\", default=argparse.SUPPRESS, type=str)\n    parser.add_argument(\"--img_net_checkpoint\", type=Path, default=argparse.SUPPRESS)\n\n    parser.add_argument(\"--config\", type=Path, default=\"../config/detection.yaml\")\n    parser.add_argument(\"--use_image\", action=\"store_true\")\n    parser.add_argument(\"--no_events\", action=\"store_true\")\n    parser.add_argument(\"--pretrain_cnn\", action=\"store_true\")\n    parser.add_argument(\"--keep_temporal_ordering\", action=\"store_true\")\n\n    # task params\n    parser.add_argument(\"--task\", default=argparse.SUPPRESS, type=str)\n    parser.add_argument(\"--dataset\", default=argparse.SUPPRESS, type=str)\n\n    # graph params\n    parser.add_argument('--radius', default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--time_window_us', default=argparse.SUPPRESS, type=int)\n    parser.add_argument('--max_neighbors', default=argparse.SUPPRESS, type=int)\n    parser.add_argument('--n_nodes', default=argparse.SUPPRESS, type=int)\n\n    # learning params\n    parser.add_argument('--batch_size', default=argparse.SUPPRESS, type=int)\n\n    # network params\n    parser.add_argument(\"--activation\", default=argparse.SUPPRESS, type=str, help=\"Can be one of ['Hardshrink', 'Hardsigmoid', 'Hardswish', 'ReLU', 'ReLU6', 'SoftShrink', 'HardTanh']\")\n    parser.add_argument(\"--edge_attr_dim\", default=argparse.SUPPRESS, type=int)\n    parser.add_argument(\"--aggr\", default=argparse.SUPPRESS, type=str)\n    parser.add_argument(\"--kernel_size\", default=argparse.SUPPRESS, type=int)\n    parser.add_argument(\"--pooling_aggr\", default=argparse.SUPPRESS, type=str)\n\n    parser.add_argument(\"--base_width\", default=argparse.SUPPRESS, type=float)\n    parser.add_argument(\"--after_pool_width\", default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--net_stem_width', default=argparse.SUPPRESS, type=float)\n    parser.add_argument(\"--yolo_stem_width\", default=argparse.SUPPRESS, type=float)\n    parser.add_argument(\"--num_scales\", default=argparse.SUPPRESS, type=int)\n    parser.add_argument('--pooling_dim_at_output', default=argparse.SUPPRESS)\n    parser.add_argument('--weight_decay', default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--clip', default=argparse.SUPPRESS, type=float)\n\n    parser.add_argument('--aug_p_flip', default=argparse.SUPPRESS, type=float)\n\n    return parser\n\ndef FLAGS():\n    parser = BASE_FLAGS()\n\n    # learning params\n    parser.add_argument('--aug_trans', default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--aug_zoom', default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--exp_name', default=argparse.SUPPRESS, type=str)\n    parser.add_argument('--l_r', default=argparse.SUPPRESS, type=float)\n    parser.add_argument('--no_eval', action=\"store_true\")\n    parser.add_argument('--tot_num_epochs', default=argparse.SUPPRESS, type=int)\n\n    parser.add_argument('--run_test', action=\"store_true\")\n\n    parser.add_argument('--num_interframe_steps', type=int, default=10)\n\n    args = parser.parse_args()\n\n    if args.config != \"\":\n        args = parse_config(args, args.config)\n\n    args.dataset_directory = Path(args.dataset_directory)\n    args.output_directory = Path(args.output_directory)\n\n    if \"checkpoint\" in args:\n        args.checkpoint = Path(args.checkpoint)\n\n    return args\n\ndef FLOPS_FLAGS():\n    parser = BASE_FLAGS()\n\n    # for flop eval\n    parser.add_argument(\"--check_consistency\", action=\"store_true\")\n    parser.add_argument(\"--dense\", action=\"store_true\")\n\n    # for runtime eval\n    args = parser.parse_args()\n\n    if args.config != \"\":\n        args = parse_config(args, args.config)\n\n    args.dataset_directory = Path(args.dataset_directory)\n    args.output_directory = Path(args.output_directory)\n\n    if \"checkpoint\" in args:\n        args.checkpoint = Path(args.checkpoint)\n\n    return args\n\n\ndef parse_config(args: argparse.ArgumentParser, config: Path):\n    with config.open() as f:\n        config = yaml.load(f, Loader=yaml.SafeLoader)\n        for k, v in config.items():\n            if k not in args:\n                setattr(args, k, v)\n        return args\n"
  },
  {
    "path": "src/dagr/utils/buffers.py",
    "content": "import numpy as np\nimport torch\n\nfrom typing import List, Dict\nfrom pathlib import Path\n\nfrom .coco_eval import evaluate_detection\n\n\ndef diag_filter(bbox, height: int, width: int, min_box_diagonal: int = 30, min_box_side: int = 20):\n    bbox[..., 0::2] = torch.clamp(bbox[..., 0::2], 0, width - 1)\n    bbox[..., 1::2] = torch.clamp(bbox[..., 1::2], 0, height - 1)\n    w, h = (bbox[..., 2:] - bbox[..., :2]).t()\n    diag = torch.sqrt(w ** 2 + h ** 2)\n    mask = (diag > min_box_diagonal) & (w > min_box_side) & (h > min_box_side)\n    return mask\n\n\ndef filter_bboxes(detections: List[Dict[str, torch.Tensor]], height: int, width: int, min_box_diagonal: int = 30,\n                  min_box_side: int = 20):\n    filtered_bboxes = []\n    for d in detections:\n        bbox = d[\"boxes\"]\n\n        # first clamp boxes to image\n        mask = diag_filter(bbox, height, width, min_box_diagonal, min_box_side)\n        bbox = {k: v[mask] for k, v in d.items()}\n\n        filtered_bboxes.append(bbox)\n\n    return filtered_bboxes\n\ndef format_data(data, normalizer=None):\n    if normalizer is None:\n        normalizer = torch.stack([data.width[0], data.height[0], data.time_window[0]], dim=-1)\n\n    if hasattr(data, \"image\"):\n        data.image = data.image.float() / 255.0\n\n    data.pos = torch.cat([data.pos, data.t.view((-1,1))], dim=-1)\n    data.t = None\n    data.x = data.x.float()\n    data.pos = data.pos / normalizer\n    return data\n\ndef bbox_t_to_ndarray(bbox, t):\n    dtype = [('t', '<u8'), ('x', '<f4'), ('y', '<f4'), ('w', '<f4'), ('h', '<f4'), ('class_id', 'u1')]\n    if len(bbox) == 3:\n        dtype.append(('class_confidence', '<f4'))\n\n    boxes = bbox['boxes'].numpy()\n    labels = bbox['labels'].numpy()\n\n    output = np.zeros(shape=(len(boxes),), dtype=dtype)\n    output['t'] = t\n    output['x'] = boxes[:, 0]\n    output['y'] = boxes[:, 1]\n    output['w'] = boxes[:, 2] - boxes[:, 0]\n    output['h'] = boxes[:, 3] - boxes[:, 1]\n    output['class_id'] = labels\n\n    if len(bbox) == 3:\n        output['class_confidence'] = bbox[\"scores\"].numpy()\n\n    return output\n\n\ndef compile(detections, sequences, timestamps):\n    output = {}\n    for det, s, t in zip(detections, sequences, timestamps):\n        if s not in output:\n            output[s] = []\n        output[s].append(bbox_t_to_ndarray(det, t))\n\n    if len(output) > 0:\n        output = {k: np.concatenate(v) for k, v in output.items() if len(v) > 0}\n\n    return output\n\ndef to_cpu(data_list: List[Dict[str, torch.Tensor]]):\n    return [{k: v.cpu() for k, v in d.items()} for d in data_list]\n\nclass Buffer:\n    def __init__(self):\n        self.buffer = []\n\n    def extend(self, elements: List[Dict[str, torch.Tensor]]):\n        self.buffer.extend(to_cpu(elements))\n\n    def clear(self):\n        self.buffer.clear()\n\n    def __iter__(self):\n        return iter(self.buffer)\n\n    def __next__(self):\n        return next(self.buffer)\n\n\n\nclass DetectionBuffer:\n    def __init__(self, height: int, width: int, classes: List[str]):\n        self.height = height\n        self.width = width\n        self.classes = classes\n        self.detections = Buffer()\n        self.ground_truth = Buffer()\n\n    def compile(self, sequences, timestamps):\n        detections = compile(self.detections, sequences, timestamps)\n        groundtruth = compile(self.ground_truth, sequences, timestamps)\n        return detections, groundtruth\n\n    def update(self, detections: List[Dict[str, torch.Tensor]], groundtruth: List[Dict[str, torch.Tensor]], dataset: str, height=None, width=None):\n        self.detections.extend(detections)\n        self.ground_truth.extend(groundtruth)\n\n    def compute(self)->Dict[str, float]:\n        output =  evaluate_detection(self.ground_truth.buffer, self.detections.buffer, height=self.height, width=self.width, classes=self.classes)\n        output = {k.replace(\"AP\", \"mAP\"): v for k, v in output.items()}\n        self.detections.clear()\n        self.ground_truth.clear()\n        return output\n\n\nclass DictBuffer:\n    def __init__(self):\n        self.running_mean = None\n        self.n = 0\n\n    def __recursive_mean(self, mn: float, s: float):\n        return self.n / (self.n + 1) * mn + s / (self.n + 1)\n\n    def update(self, dictionary: Dict[str, float]):\n        if self.running_mean is None:\n            self.running_mean = {k: 0 for k in dictionary}\n\n        self.running_mean = {k: self.__recursive_mean(self.running_mean[k], dictionary[k]) for k in dictionary}\n        self.n += 1\n\n    def save(self, path):\n        torch.save(self.running_mean, path)\n\n    def compute(self)->Dict[str, float]:\n        return self.running_mean\n\n"
  },
  {
    "path": "src/dagr/utils/coco_eval.py",
    "content": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport contextlib\nfrom pycocotools.coco import COCO\nfrom detectron2.evaluation.fast_eval_api import COCOeval_opt as COCOeval\n#from detectron2.evaluation.fast_eval_api import COCOeval\n\nimport numpy as np\nfrom typing import List, Dict, Tuple\nfrom torch import Tensor\n\nBBOX_DTYPE = np.dtype({'names':['t','x','y','w','h','class_id','track_id','class_confidence'], 'formats':['<i8','<f4','<f4','<f4','<f4','<u4','<u4','<f4'], 'offsets':[0,8,12,16,20,24,28,32], 'itemsize':40})\n\ndef _convert_to_coco_format(gt_boxes_list: List[Dict[str, Tensor]],\n                       dt_boxes_list: List[Dict[str, Tensor]],\n                       classes: str=(\"car\", \"pedestrian\"),\n                       height: int=240,\n                       width: int=304,\n                       time_tol: int=50000) -> Tuple[Dict, Dict]:\n    \"\"\"\n    Compute detection KPIs on list of boxes in the numpy format, using the COCO python API\n    https://github.com/cocodataset/cocoapi\n    KPIs are only computed on timestamps where there is actual at least one box\n    (fully empty frames are not considered)\n    :param gt_boxes_list: list of numpy array for GT boxes (one per file)\n    :param dt_boxes_list: list of numpy array for detected boxes\n    :param classes: iterable of classes names\n    :param height: int for box size statistics\n    :param width: int for box size statistics\n    :param time_tol: int size of the temporal window in micro seconds to look for a detection around a gt box\n    \"\"\"\n    flattened_gt = []\n    flattened_dt = []\n    for gt_boxes, dt_boxes in zip(gt_boxes_list, dt_boxes_list):\n        gt_boxes = _to_prophesee(gt_boxes)\n        dt_boxes = _to_prophesee(dt_boxes)\n\n        assert np.all(gt_boxes['t'][1:] >= gt_boxes['t'][:-1])\n        assert np.all(dt_boxes['t'][1:] >= dt_boxes['t'][:-1])\n\n        all_ts = np.unique(gt_boxes['t'])\n\n        gt_win, dt_win = _match_times(all_ts, gt_boxes, dt_boxes, time_tol)\n        flattened_gt = flattened_gt + gt_win\n        flattened_dt = flattened_dt + dt_win\n\n\n    num_detections = sum([d.size for d in flattened_dt])\n    if num_detections == 0:\n        # Corner case at the very beginning of the training.\n        print('no detections for evaluation found.')\n        return None\n\n    categories = [{\"id\": id + 1, \"name\": class_name, \"supercategory\": \"none\"}\n                  for id, class_name in enumerate(classes)]\n\n    return _to_coco_format(flattened_gt, flattened_dt, categories, height=height, width=width), len(flattened_gt)\n\n\n\ndef evaluate_detection(gt_boxes_list: List[Dict[str, Tensor]],\n                       dt_boxes_list: List[Dict[str, Tensor]],\n                       classes: str=(\"car\", \"pedestrian\"),\n                       height: int=240,\n                       width: int=304,\n                       time_tol: int=50000) -> Dict[str, float]:\n    \"\"\"\n    Compute detection KPIs on list of boxes in the numpy format, using the COCO python API\n    https://github.com/cocodataset/cocoapi\n    KPIs are only computed on timestamps where there is actual at least one box\n    (fully empty frames are not considered)\n    :param gt_boxes_list: list of numpy array for GT boxes (one per file)\n    :param dt_boxes_list: list of numpy array for detected boxes\n    :param classes: iterable of classes names\n    :param height: int for box size statistics\n    :param width: int for box size statistics\n    :param time_tol: int size of the temporal window in micro seconds to look for a detection around a gt box\n    \"\"\"\n    output = _convert_to_coco_format(gt_boxes_list,\n                                     dt_boxes_list,\n                                     classes,\n                                     height,\n                                     width,\n                                     time_tol)\n\n    if output is None:\n        out_keys = ('AP', 'AP_50', 'AP_75', 'AP_S', 'AP_M', 'AP_L')\n        return {k: 0 for k in out_keys}\n    else:\n        (dataset, results), num_gts = output\n        return _coco_eval(dataset, results, num_gts)\n\ndef _to_prophesee(det: Dict[str, Tensor]):\n    num_bboxes = len(det['boxes'])\n    out = np.zeros(shape=(num_bboxes,), dtype=BBOX_DTYPE)\n    det = {k: v.cpu().numpy() for k, v in det.items()}\n    x1, y1, x2, y2 = det['boxes'].T\n    out[\"x\"] = x1\n    out[\"y\"] = y1\n    out[\"w\"] = x2-x1\n    out[\"h\"] = y2-y1\n    out[\"class_id\"] = det[\"labels\"]\n    out[\"class_confidence\"] = det.get(\"scores\", np.ones(shape=(num_bboxes,), dtype=\"float32\"))\n    return out\n\ndef _match_times(all_ts, gt_boxes, dt_boxes, time_tol):\n    \"\"\"\n    match ground truth boxes and ground truth detections at all timestamps using a specified tolerance\n    return a list of boxes vectors\n    \"\"\"\n    gt_size = len(gt_boxes)\n    dt_size = len(dt_boxes)\n\n    windowed_gt = []\n    windowed_dt = []\n\n    low_gt, high_gt = 0, 0\n    low_dt, high_dt = 0, 0\n    for ts in all_ts:\n\n        while low_gt < gt_size and gt_boxes[low_gt]['t'] < ts:\n            low_gt += 1\n        # the high index is at least as big as the low one\n        high_gt = max(low_gt, high_gt)\n        while high_gt < gt_size and gt_boxes[high_gt]['t'] <= ts:\n            high_gt += 1\n\n        # detection are allowed to be inside a window around the right detection timestamp\n        low = ts - time_tol\n        high = ts + time_tol\n        while low_dt < dt_size and dt_boxes[low_dt]['t'] < low:\n            low_dt += 1\n        # the high index is at least as big as the low one\n        high_dt = max(low_dt, high_dt)\n        while high_dt < dt_size and dt_boxes[high_dt]['t'] <= high:\n            high_dt += 1\n\n        windowed_gt.append(gt_boxes[low_gt:high_gt])\n        windowed_dt.append(dt_boxes[low_dt:high_dt])\n\n    return windowed_gt, windowed_dt\n\n\ndef _coco_eval(dataset, results, num_gts):\n    \"\"\"simple helper function wrapping around COCO's Python API\n    :params:  gts iterable of numpy boxes for the ground truth\n    :params:  detections iterable of numpy boxes for the detections\n    :params:  height int\n    :params:  width int\n    :params:  labelmap iterable of class labels\n    \"\"\"\n\n\n    # Meaning: https://cocodataset.org/#detection-eval\n    out_keys = ('AP', 'AP_50', 'AP_75', 'AP_S', 'AP_M', 'AP_L')\n    out_dict = {k: 0.0 for k in out_keys}\n\n\n    coco_gt = COCO()\n    coco_gt.dataset = dataset\n    coco_gt.createIndex()\n    coco_pred = coco_gt.loadRes(results)\n\n    coco_eval = COCOeval(coco_gt, coco_pred, 'bbox')\n    coco_eval.params.imgIds = np.arange(1, num_gts + 1, dtype=int)\n    coco_eval.evaluate()\n    coco_eval.accumulate()\n\n    with open(os.devnull, 'w') as f, contextlib.redirect_stdout(f):\n        # info: https://stackoverflow.com/questions/8391411/how-to-block-calls-to-print\n        coco_eval.summarize()\n    for idx, key in enumerate(out_keys):\n        out_dict[key] = coco_eval.stats[idx]\n    return out_dict\n\n\n\ndef _to_coco_format(gts, detections, categories, height=240, width=304):\n    \"\"\"\n    utilitary function producing our data in a COCO usable format\n    \"\"\"\n    annotations = []\n    results = []\n    images = []\n\n    # to dictionary\n    for image_id, (gt, pred) in enumerate(zip(gts, detections)):\n        im_id = image_id + 1\n\n        images.append(\n            {\"date_captured\": \"2019\",\n             \"file_name\": \"n.a\",\n             \"id\": im_id,\n             \"license\": 1,\n             \"url\": \"\",\n             \"height\": height,\n             \"width\": width})\n\n        for bbox in gt:\n            x1, y1 = bbox['x'], bbox['y']\n            w, h = bbox['w'], bbox['h']\n            area = w * h\n\n            annotation = {\n                \"area\": float(area),\n                \"iscrowd\": False,\n                \"image_id\": im_id,\n                \"bbox\": [x1, y1, w, h],\n                \"category_id\": int(bbox['class_id']) + 1,\n                \"id\": len(annotations) + 1\n            }\n            annotations.append(annotation)\n\n        for bbox in pred:\n\n            image_result = {\n                'image_id': im_id,\n                'category_id': int(bbox['class_id']) + 1,\n                'score': float(bbox['class_confidence']),\n                'bbox': [bbox['x'], bbox['y'], bbox['w'], bbox['h']],\n            }\n            results.append(image_result)\n\n    dataset = {\"info\": {},\n               \"licenses\": [],\n               \"type\": 'instances',\n               \"images\": images,\n               \"annotations\": annotations,\n               \"categories\": categories}\n    return dataset, results\n"
  },
  {
    "path": "src/dagr/utils/learning_rate_scheduler.py",
    "content": "from functools import partial\nimport math\nfrom typing import List\n\nimport numpy as np\n\n\nclass LRSchedule:\n    def __init__(self,\n                 warmup_epochs: float,\n                 num_iters_per_epoch: int,\n                 tot_num_epochs: int,\n                 min_lr_ratio: float=0.05,\n                 warmup_lr_start: float=0,\n                 steps_at_iteration=[50000],\n                 reduction_at_step=0.5):\n\n        warmup_total_iters = num_iters_per_epoch * warmup_epochs\n        total_iters = tot_num_epochs * num_iters_per_epoch\n        no_aug_iters = 0\n        self.lr_func = partial(_yolox_warm_cos_lr, min_lr_ratio, total_iters, warmup_total_iters, warmup_lr_start, no_aug_iters, steps_at_iteration, reduction_at_step)\n\n    def __call__(self, *args, **kwargs)->float:\n        return self.lr_func(*args, **kwargs)\n\n\ndef _yolox_warm_cos_lr(\n    min_lr_ratio: float,\n    total_iters: int,\n    warmup_total_iters: int,\n    warmup_lr_start: float,\n    no_aug_iter: int,\n    steps_at_iteration: List[int],\n    reduction_at_step: float,\n    iters: int)->float:\n    \"\"\"Cosine learning rate with warm up.\"\"\"\n    min_lr = min_lr_ratio\n    if iters < warmup_total_iters:\n        # lr = (lr - warmup_lr_start) * iters / float(warmup_total_iters) + warmup_lr_start\n        lr = (1 - warmup_lr_start) * pow(iters / float(warmup_total_iters), 2) + warmup_lr_start\n    else:\n        lr = min_lr + 0.5 * (1 - min_lr) * (1.0 + math.cos(math.pi * (iters - warmup_total_iters) / (total_iters - warmup_total_iters - no_aug_iter)))\n\n    for step in steps_at_iteration:\n        if iters >= step:\n            lr *= reduction_at_step\n\n    return lr"
  },
  {
    "path": "src/dagr/utils/logging.py",
    "content": "import torch\nimport wandb\nimport os\n\nfrom typing import List, Dict, Optional\nfrom torch_geometric.data import Batch\nfrom pathlib import PosixPath\nfrom pprint import pprint\nfrom pathlib import Path\n\nfrom torch_geometric.data import Data\n\n\nclass Checkpointer:\n    def __init__(self, output_directory: Optional[Path] = None, args=None, optimizer=None, scheduler=None, ema=None, model=None):\n        self.optimizer = optimizer\n        self.scheduler = scheduler\n        self.ema = ema\n        self.model = model\n\n        self.mAP_max = 0\n        self.output_directory = output_directory\n        self.args = args\n\n    def restore_if_existing(self, folder, resume_from_best=False):\n        checkpoint = self.search_for_checkpoint(folder, best=resume_from_best)\n        if checkpoint is not None:\n            print(f\"Found existing checkpoint at {checkpoint}, resuming...\")\n            self.restore_checkpoint(folder, best=resume_from_best)\n\n    def mAP_from_checkpoint_name(self, checkpoint_name: Path):\n        return float(str(checkpoint_name).split(\"_\")[-1].split(\".pth\")[0])\n\n    def search_for_checkpoint(self, resume_checkpoint: Path, best=False):\n        checkpoints = list(resume_checkpoint.glob(\"*.pth\"))\n        if len(checkpoints) == 0:\n            return None\n\n        if not best:\n            if resume_checkpoint / \"last_model.pth\" in checkpoints:\n                return resume_checkpoint / \"last_model.pth\"\n\n        # remove \"last_model.pth\" from checkpoints\n        if resume_checkpoint / \"last_model.pth\" in checkpoints:\n            checkpoints.remove(resume_checkpoint / \"last_model.pth\")\n\n        checkpoints = sorted(checkpoints, key=lambda x: self.mAP_from_checkpoint_name(x.name))\n        return checkpoints[-1]\n\n\n    def restore_if_not_none(self, target, source):\n        if target is not None:\n            target.load_state_dict(source)\n\n    def restore_checkpoint(self, checkpoint_directory, best=False):\n        path = self.search_for_checkpoint(checkpoint_directory, best)\n        assert path is not None, \"No checkpoint found in {}\".format(checkpoint_directory)\n        print(\"Restoring checkpoint from {}\".format(path))\n        checkpoint = torch.load(path)\n\n        checkpoint['model'] = self.fix_checkpoint(checkpoint['model'])\n        checkpoint['ema'] = self.fix_checkpoint(checkpoint['ema'])\n\n        if self.ema is not None:\n            self.ema.ema.load_state_dict(checkpoint.get('ema', checkpoint['model']))\n            self.ema.updates = checkpoint.get('ema_updates', 0)\n        self.restore_if_not_none(self.model, checkpoint['model'])\n        self.restore_if_not_none(self.optimizer, checkpoint['optimizer'])\n        self.restore_if_not_none(self.scheduler, checkpoint['scheduler'])\n        return checkpoint['epoch']\n\n    def fix_checkpoint(self, state_dict):\n        return state_dict\n\n    def checkpoint(self, epoch: int, name: str=\"\"):\n        self.output_directory.mkdir(exist_ok=True, parents=True)\n\n        checkpoint = {\n            \"ema\": self.ema.ema.state_dict(),\n            \"ema_updates\": self.ema.updates,\n            \"model\": self.model.state_dict(),\n            \"optimizer\": self.optimizer.state_dict(),\n            \"scheduler\": self.scheduler.state_dict(),\n            \"epoch\": epoch,\n            \"args\": self.args\n        }\n\n        torch.save(checkpoint, self.output_directory / f\"{name}.pth\")\n\n    def process(self, data: Dict[str, float], epoch: int):\n        mAP = data['mAP']\n        data = {f\"validation/metric/{k}\": v for k, v in data.items()}\n        data['epoch'] = epoch\n        wandb.log(data)\n\n        if mAP > self.mAP_max:\n            self.checkpoint(epoch, name=f\"best_model_mAP_{mAP}\")\n            self.mAP_max = mAP\n\n\ndef set_up_logging_directory(dataset, task, output_directory, exp_name=\"temp\"):\n    project = f\"low_latency-{dataset}-{task}\"\n\n    output_directory = output_directory / dataset / task\n    output_directory.mkdir(parents=True, exist_ok=True)\n    wandb.init(project=project, id=exp_name, entity=\"danielgehrig18\", save_code=True, dir=str(output_directory))\n\n    name = wandb.run.id\n    output_directory = output_directory / name\n    output_directory.mkdir(parents=True, exist_ok=True)\n\n    return output_directory\n\ndef log_hparams(args):\n    hparams = {k: str(v) if type(v) is PosixPath else v for k, v in vars(args).items()}\n    pprint(hparams)\n    wandb.log(hparams)\n\ndef log_bboxes(data: Batch,\n               targets: List[Dict[str, torch.Tensor]],\n               detections: List[Dict[str, torch.Tensor]],\n               class_names: List[str],\n               bidx: int,\n               key: str):\n\n    gt_bbox = []\n    det_bbox = []\n    images = []\n    for b, datum in enumerate(data.to_data_list()):\n        image = visualize_events(datum)\n        image = torch.cat([image, image], dim=1)\n        images.append(image)\n\n        if len(detections) > 0:\n            det = detections[b]\n            det = torch.cat([det['boxes'], det['labels'].view(-1,1), det['scores'].view(-1,1)], dim=-1)\n            det[:, [0, 2]] += b * datum.width\n            det_bbox.append(det)\n\n        if len(targets) > 0:\n            tar = targets[b]\n            tar = torch.cat([tar['boxes'], tar['labels'].view(-1, 1), torch.ones_like(tar['labels'].view(-1, 1))], dim=-1)\n            tar[:, [0, 2]] += b * datum.width\n            tar[:, [1, 3]] += datum.height\n            gt_bbox.append(tar)\n\n        if b == bidx-1:\n            break\n\n    pred_bbox = torch.cat(det_bbox)\n    gt_bbox = torch.cat(gt_bbox)\n    images = torch.cat(images, dim=-1)\n\n    bidx = min([bidx, len(data)])\n\n    gt_bbox[:,[0,2]] /= (bidx * datum.width)\n    gt_bbox[:,[1,3]] /= (2 * datum.height)\n\n    pred_bbox[:,[0,2]] /= (bidx * datum.width)\n    pred_bbox[:,[1,3]] /= (2 * datum.height)\n\n    image = __convert_to_wandb_data(images.detach().float().cpu(),\n                                    gt_bbox.detach().cpu(),\n                                    pred_bbox.detach().cpu(),\n                                    class_names)\n\n    wandb.log({key: image})\n\ndef visualize_events(data: Data)->torch.Tensor:\n    x, y = data.pos[:,:2].long().t()\n    p = data.x[:,0].long()\n\n    if hasattr(data, \"image\"):\n        image = data.image[0].clone()\n    else:\n        image = torch.full(size=(3, data.height, data.width), fill_value=255, device=p.device, dtype=torch.uint8)\n\n    is_pos = p == 1\n    image[:, y[is_pos], x[is_pos]] = torch.tensor([[0],[0],[255]], dtype=torch.uint8, device=p.device)\n    image[:, y[~is_pos], x[~is_pos]] = torch.tensor([[255],[0],[0]], dtype=torch.uint8, device=p.device)\n\n    return image\n\ndef __convert_to_wandb_data(image: torch.Tensor, gt: torch.Tensor, p: torch.Tensor, class_names: List[str])->wandb.Image:\n    return wandb.Image(image, boxes={\n        \"predictions\": __parse_bboxes(p, class_names, suffix=\"P\"),\n        \"ground_truth\": __parse_bboxes(gt, class_names)\n    })\n\ndef __parse_bboxes(bboxes: torch.Tensor, class_names: List[str], suffix: str=\"GT\"):\n    # bbox N x 6 -> xyxycs\n    return {\n        \"box_data\": [__parse_bbox(bbox, class_names, suffix) for bbox in bboxes],\n        \"class_labels\": dict(enumerate(class_names))\n    }\n\ndef __parse_bbox(bbox: torch.Tensor, class_names: List[str], suffix: str=\"GT\"):\n    # bbox xyxycs\n    return {\n        \"position\": {\n            \"minX\": float(bbox[0]),\n            \"minY\": float(bbox[1]),\n            \"maxX\": float(bbox[2]),\n            \"maxY\": float(bbox[3])\n        },\n        \"class_id\": int(bbox[-2]),\n        \"scores\": {\n            \"object score\": float(bbox[-1])\n        },\n        \"bbox_caption\": f\"{suffix} - {class_names[int(bbox[-2])]}\"\n    }\n\n\n"
  },
  {
    "path": "src/dagr/utils/testing.py",
    "content": "import torch\nfrom dagr.utils.logging import log_bboxes\nfrom dagr.utils.buffers import DetectionBuffer, format_data\nimport tqdm\n\ndef to_npy(detections):\n    return [{k: v.cpu().numpy() for k, v in d.items()} for d in detections]\n\ndef format_detections(sequences, t, detections):\n    detections = to_npy(detections)\n    for i, det in enumerate(detections):\n        det['sequence'] = sequences[i]\n        det['t'] = t[i]\n    return detections\n\ndef run_test_with_visualization(loader, model, dataset: str, log_every_n_batch=-1, name=\"\", compile_detections=False,\n                                no_eval=False):\n    model.eval()\n\n    if not no_eval:\n        mapcalc = DetectionBuffer(height=loader.dataset.height, width=loader.dataset.width,\n                                  classes=loader.dataset.classes)\n\n    counter = 0\n    if compile_detections:\n        compiled_detections = []\n\n    for i, data in enumerate(tqdm.tqdm(loader, desc=f\"Testing {name}\")):\n        data = data.cuda(non_blocking=True)\n        data_for_visualization = data.clone()\n\n        data = format_data(data)\n        detections, targets = model(data.clone())\n\n        if compile_detections:\n            compiled_detections.extend(format_detections(data.sequence, data.t1, detections))\n\n        if log_every_n_batch > 0 and counter % log_every_n_batch == 0:\n            log_bboxes(data_for_visualization, targets=targets, detections=detections, bidx=4,\n                       class_names=loader.dataset.classes, key=\"testing/evaluated_bboxes\")\n\n        if not no_eval:\n            mapcalc.update(detections, targets, dataset, data.height[0], data.width[0])\n\n        if i % 5 == 0:\n            torch.cuda.empty_cache()\n\n        counter += 1\n\n    torch.cuda.empty_cache()\n\n    data = None\n    if not no_eval:\n        data = mapcalc.compute()\n\n    return (data, compiled_detections) if compile_detections else data"
  },
  {
    "path": "src/dagr/visualization/bbox_viz.py",
    "content": "import numpy as np\nimport cv2\nimport torchvision\nimport torch\n\n\n_COLORS = np.array([[0.000, 0.8, 0.1], [1, 0.67, 0.00]])\nclass_names = [\"car\", \"pedestrian\"]\n\n\ndef draw_bbox_on_img(img, x, y, w, h, labels, scores=None, conf=0.5, nms=0.45, label=\"\", linewidth=2):\n    if scores is not None:\n        mask = filter_boxes(x, y, w, h, labels, scores, conf, nms)\n        x = x[mask]\n        y = y[mask]\n        w = w[mask]\n        h = h[mask]\n        labels = labels[mask]\n        scores = scores[mask]\n\n    for i in range(len(x)):\n        if scores is not None and scores[i] < conf:\n            continue\n\n        x0 = int(x[i])\n        y0 = int(y[i])\n        x1 = int(x[i] + w[i])\n        y1 = int(y[i] + h[i])\n        cls_id = int(labels[i])\n\n        color = (_COLORS[cls_id] * 255).astype(np.uint8).tolist()\n\n        text = f\"{label}-{class_names[cls_id]}\"\n\n        if scores is not None:\n            text += f\":{scores[i] * 100: .1f}\"\n\n        txt_color = (0, 0, 0) if np.mean(_COLORS[cls_id]) > 0.5 else (255, 255, 255)\n        font = cv2.FONT_HERSHEY_SIMPLEX\n\n        txt_size = cv2.getTextSize(text, font, 0.4, 1)[0]\n        cv2.rectangle(img, (x0, y0), (x1, y1), color, linewidth)\n\n        txt_bk_color = (_COLORS[cls_id] * 255 * 0.7).astype(np.uint8).tolist()\n        txt_height = int(1.5*txt_size[1])\n        cv2.rectangle(\n            img,\n            (x0, y0 - txt_height),\n            (x0 + txt_size[0] + 1, y0 + 1),\n            txt_bk_color,\n            -1\n        )\n        cv2.putText(img, text, (x0, y0 + txt_size[1]-txt_height), font, 0.4, txt_color, thickness=1)\n    return img\n\ndef filter_boxes(x, y, w, h, labels, scores, conf, nms):\n    mask = scores > conf\n\n    x1, y1 = x + w, y + h\n    box_coords = np.stack([x, y, x1, y1], axis=-1)\n\n    nms_out_index = torchvision.ops.batched_nms(\n        torch.from_numpy(box_coords),\n        torch.from_numpy(np.ascontiguousarray(scores)),\n        torch.from_numpy(labels),\n        nms\n    )\n\n    nms_mask = np.ones_like(mask) == 0\n    nms_mask[nms_out_index] = True\n\n    return mask & nms_mask\n"
  },
  {
    "path": "src/dagr/visualization/event_viz.py",
    "content": "import numba\n\n@numba.jit(nopython=True)\ndef draw_events_on_image(img, x, y, p, alpha=0.5):\n    img_copy = img.copy()\n    for i in range(len(p)):\n        if y[i] < len(img):\n            img[y[i], x[i], :] = alpha * img_copy[y[i], x[i], :]\n            img[y[i], x[i], int(p[i])-1] += 255 * (1-alpha)\n    return img"
  }
]