[
  {
    "path": ".gitignore",
    "content": "# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n#  Usually these files are written by a python script from a template\n#  before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n\n# vscode\n.vscode\n\n# experiments\n/experiments"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# RAVEN\n\nThis repo contains code for our CVPR 2019 paper.\n\n[RAVEN: A Dataset for <u>R</u>elational and <u>A</u>nalogical <u>V</u>isual r<u>E</u>aso<u>N</u>ing](http://wellyzhang.github.io/attach/cvpr19zhang.pdf)  \nChi Zhang*, Feng Gao*, Baoxiong Jia, Yixin Zhu, Song-Chun Zhu  \n*Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)*, 2019   \n(* indicates equal contribution.)\n\nDramatic progress has been witnessed in basic vision tasks involving low-level perception, such as object recognition, detection, and tracking. Unfortunately, there is still an enormous performance gap between artificial vision systems and human intelligence in terms of higher-level vision problems, especially ones involving reasoning. Earlier attempts in equipping machines with high-level reasoning have hovered around Visual Question Answering (VQA), one typical task associating vision and language understanding. In this work, we propose a new dataset, built in the context of Raven's Progressive Matrices (RPM) and aimed at lifting machine intelligence by associating vision with structural, relational, and analogical reasoning in a hierarchical representation. Unlike previous works in measuring abstract reasoning using RPM, we establish a semantic link between vision and reasoning by providing structure representation. This addition enables a new type of abstract reasoning by jointly operating on the structure representation. Machine reasoning ability using modern computer vision is evaluated in this newly proposed dataset. Additionally, we also provide human performance as a reference. Finally, we show consistent improvement across all models by incorporating a simple neural module that combines visual understanding and structure reasoning.\n\n![framework](http://wellyzhang.github.io/img/in-post/RAVEN/process.jpg)\n\n# Dataset\n\nThe dataset is generated using the attributed stochastic image grammar. An example is shown below.\n\n![grammar](http://wellyzhang.github.io/img/in-post/RAVEN/prologue.jpg)\n\nThe grammatical design makes the dataset flexible and extendable. In total, we come up with 7 different figural configurations. \n\n![configurations](http://wellyzhang.github.io/img/in-post/RAVEN/peek_view.png)\n\nThe dataset formatting document is in ```assets/README.md```. To download the dataset, please check [our project page](http://wellyzhang.github.io/project/raven.html#dataset).\n\n# Performance\n\nWe show performance of models in the following table. For details, please check our [paper](http://wellyzhang.github.io/attach/cvpr19zhang.pdf).\n\n\n| Method     | Acc        | Center     | 2x2Grid    | 3x3Grid    | L-R        | U-D        | O-IC       | O-IG       |\n| :---       | :---:      | :---:      | :---:      | :---:      | :---:      | :---:      | :---:      | :---:      |\n| LSTM       | 13.07%     | 13.19%     | 14.13%     | 13.69%     | 12.84%     | 12.35%     | 12.15%     | 12.99%     |\n| WReN       | 14.69%     | 13.09%     | 28.62%     | 28.27%     | 7.49%      | 6.34%      | 8.38%      | 10.56%     |\n| CNN        | 36.97%     | 33.58%     | 30.30%     | 33.53%     | 39.43%     | 41.26%     | 43.20%     | 37.54%     |\n| ResNet     | 53.43%     | 52.82%     | 41.86%     | 44.29%     | 58.77%     | 60.16%     | 63.19%     | 53.12%     |\n| LSTM+DRT   | 13.96%     | 14.29%     | 15.08%     | 14.09%     | 13.79%     | 13.24%     | 13.99%     | 13.29%     |\n| WReN+DRT   | 15.02%     | 15.38%     | 23.26%     | 29.51%     | 6.99%      | 8.43%      | 8.93%      | 12.35%     |\n| CNN+DRT    | 39.42%     | 37.30%     | 30.06%     | 34.57%     | 45.49%     | 45.54%     | 45.93%     | 37.54%     |\n| ResNet+DRT | **59.56%** | **58.08%** | **46.53%** | **50.40%** | **65.82%** | **67.11%** | **69.09%** | **60.11%** |\n| Human      | 84.41%     | 95.45%     | 81.82%     | 79.55%     | 86.36%     | 81.81%     | 86.36%     | 81.81%     |\n| Solver     | 100%       | 100%       | 100%       | 100%       | 100%       | 100%       | 100%       | 100%       |\n\n\n# Dependencies\n\n**Important**\n* Python 2.7\n* OpenCV\n* PyTorch\n* CUDA and cuDNN expected\n\nSee ```requirements.txt``` for a full list of packages required.\n\n# Usage\n\n## Dataset Generation\n\nCode to generate the dataset resides in the ```src/dataset``` folder. To generate a dataset, run\n\n```\npython src/dataset/main.py --num-samples <number of samples per configuration> --save-dir <directory to save the dataset>\n```\n\nCheck the ```main.py``` file for a full list of arguments you can adjust.\n\n## Benchmarking\n\nCode to benchmark the dataset resides in ```src/model```. To run the code, first put ```assets/embedding.npy``` in the dataset folder as specified in the ```src/model/utility/dataset_utility.py```. Then run\n\n```\npython src/model/main.py --model <model name> --path <path to the dataset>\n```\n\nYou can check the ```main.py``` file for a full list of arguments. This repo only supports ```Resnet18_MLP```, ```CNN_MLP```, and ```CNN_LSTM```. For WReN, please check the implementation in [the WReN repo](https://github.com/Fen9/WReN).\n\nNote that for batch processing, we implement the DRT as a maximum tree of all possible tree structures and prune the branches during training based on an indicator.\n\n# Citation\n\nIf you find the paper and/or the code helpful, please cite us.\n\n```\n@inproceedings{zhang2019raven, \n    title={RAVEN: A Dataset for Relational and Analogical Visual rEasoNing}, \n    author={Zhang, Chi and Gao, Feng and Jia, Baoxiong and Zhu, Yixin and Zhu, Song-Chun}, \n    booktitle={Proceedings of the IEEE Conference on Computer Vision and Pattern Recognition (CVPR)}, \n    year={2019}\n}\n```\n\n# Acknowledgement\n\nWe'd like to express our gratitude towards all the colleagues and anonymous reviewers for helping us improve the paper. The project is impossible to finish without the following open-source implementation.\n\n* [WReN](https://github.com/Fen9/WReN)\n"
  },
  {
    "path": "assets/README.md",
    "content": "# Dataset Format\n\nThe dataset folder is organized as follows:\n\n```\ncenter_single/\n    RAVEN_0_train.npz\n    RAVEN_0_train.xml\n    ...\n    RAVEN_6_val.npz\n    RAVEN_6_val.xml\n    ...\n    RAVEN_8_test.npz\n    RAVEN_8_test.xml\n    ...\ndistribute_four/\n    ...\ndistribute_nine/\n    ...\nin_center_single_out_center_single/\n    ...\nin_distribute_four_out_center_single/\n    ...\nleft_center_single_right_center_single/\n    ...\nup_center_single_down_center_single/\n    ...\n```\n\nNote that each npz file comes with an xml file.\n\nThese 7 folders correspond to the 7 figure configurations in the paper. Specifically,\n\n* Center = center_single\n* 2x2Grid = distribute_four\n* 3x3Grid = distribute_nine\n* Left-Right = left_center_single_right_center_single\n* Up-Down = up_center_single_down_center_single\n* Out-InCenter = in_center_single_out_center_single\n* Out-InGrid = in_distribute_four_out_center_single\n\n## Naming\n\nYou might notice that the actual naming in this dataset is slightly different from what's reported in our paper. This is mostly due to the fact that things like **2x2** or **3x3** do not have corresponding word vectors. They are now **distribute_four** and **distribute_nine**. To make the paper concise, we also remove certain adjectives. **Center** was **Center_Single** and sometimes came with a component name. \n\nAs described in the paper, embeddings for each of them are obtained from pre-trained GloVe vectors and held fixed during training.\n\n## NPZ file\n\nEach npz file contains the following:\n\n* image: a (16, 160, 160) array where all 16 figures in each problem are stacked on the first dimension. Note that first 8 figures compose the problem matrix and the last 8 figures are choices.\n* target: the index of the correct answer in the answer set. Note that it starts from 0 and you should offset it by 8 if you want to retrieve it from the image array.\n* structure: the tree structure annotation for the problem. It's serialized into a sequence using pre-order traversal.\n* meta_matrix: similar to that in PGM. Detailed ordering could be found in ```src/dataset/const.py```.\n* meta_target: bitwise-or of meta_matrix on all rows. \n* meta_structure: it's similar to meta_matrix. Detailed ordering is in ```src/dataset/const.py```.\n\n## XML file\n\nEach xml file contains the following:\n\n* Context panels and choice panels: each Panel could be further decomposed into Struct, Component, Layout, and Entity.\n  * Each layer comes with its name and id if necessary.\n  * Layout has its own attributes, whose values are indices into the value set (see also ```src/dataset/const.py```), except Position. Position is a list of slots entities could occupy, denoted by center and width/height. \n  * Entity's attributes follow the same annotation. The bbox is retrieved from the Position array in its parent Layout and the real_bbox is the actual bounding box, denoted by center and width/height. The mask is encoded using the run-length encoding. To decode it, use the ```rle_decode``` function in ```src/dataset/api.py```.\n* Rules: rules are divided into groups, each of which applies to the corresponding component with the same id number. \n  * ```attr``` could be ```Number/Position``` when the rule is ```Constant``` as these two attributes are deeply coupled.\n  * When there is a rule on ```Number``` or ```Position```, we omit the rule on the other attribute, as it should be assumed **as is**, *i.e.*, following the rule on the other (could remain unchanged).\n  * Therefore, each rule group has 4 rules."
  },
  {
    "path": "requirements.txt",
    "content": "numpy\nscipy\nmatplotlib\npillow\nscikit-image\nopencv-contrib-python\ntqdm\ntorch\ntorchvision"
  },
  {
    "path": "src/dataset/AoT.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport copy\n\nimport numpy as np\nfrom scipy.misc import comb\n\nfrom Attribute import Angle, Color, Number, Position, Size, Type, Uniformity\nfrom constraints import rule_constraint\n\n\nclass AoTNode(object):\n    \"\"\"Superclass of AoT. \n    \"\"\"\n\n    levels_next = {\"Root\": \"Structure\",\n                   \"Structure\": \"Component\",\n                   \"Component\": \"Layout\",\n                   \"Layout\": \"Entity\"}\n\n    def __init__(self, name, level, node_type, is_pg=False):\n        self.name = name\n        self.level = level\n        self.node_type = node_type\n        self.children = []\n        self.is_pg = is_pg\n    \n    def insert(self, node):\n        \"\"\"Used for public.\n        Arguments:\n            node(AoTNode): a node to insert\n        \"\"\"\n        assert isinstance(node, AoTNode)\n        assert self.node_type != \"leaf\"\n        assert node.level == self.levels_next[self.level]\n        self.children.append(node)\n    \n    def _insert(self, node):\n        \"\"\"Used for private.\n        Arguments:\n            node(AoTNode): a node to insert\n        \"\"\"\n        assert isinstance(node, AoTNode)\n        assert self.node_type != \"leaf\"\n        assert node.level == self.levels_next[self.level]\n        self.children.append(node)\n    \n    def _resample(self, change_number):\n        \"\"\"Resample the layout. If the number of entities change, resample also the \n        position distribution; otherwise only resample each attribute for each entity.\n        Arugments:\n            change_number(bool): whether to the number has been reset\n        \"\"\"\n        assert self.is_pg\n        if self.node_type == \"and\":\n            for child in self.children:\n                child._resample(change_number)\n        else:\n            self.children[0]._resample(change_number)\n\n    def __repr__(self):\n        return self.level + \".\" + self.name\n    \n    def __str__(self):\n        return self.level + \".\" + self.name\n\n\nclass Root(AoTNode):\n\n    def __init__(self, name, is_pg=False):\n        super(Root, self).__init__(name, level=\"Root\", node_type=\"or\", is_pg=is_pg)\n    \n    def sample(self):\n        \"\"\"The function returns a separate AoT that is correctly parsed.\n        Note that a new node is needed so that modification does not alter settings\n        in the original tree.\n        Returns:\n            new_node(Root): a newly instantiated node\n        \"\"\"\n        if self.is_pg:\n            raise ValueError(\"Could not sample on a PG\")\n        new_node = Root(self.name, True)\n        selected = np.random.choice(self.children)\n        new_node.insert(selected._sample())\n        return new_node\n\n    def resample(self, change_number=False):\n        self._resample(change_number)\n\n    def prune(self, rule_groups):\n        \"\"\"Prune the AoT such that all branches satisfy the constraints. \n        Arguments:\n            rule_groups(list of list of Rule): each list of Rule applies to a component\n        Returns:\n            new_node(Root): a newly instantiated node with branches all satisfying the constraints;\n                None if no branches satisfy all the constraints\n        \"\"\"\n        new_node = Root(self.name)\n        for structure in self.children:\n            if len(structure.children) == len(rule_groups):\n                new_child = structure._prune(rule_groups)\n                if new_child is not None:\n                    new_node.insert(new_child)\n        # during real execution, this should never happens\n        if len(new_node.children) == 0:\n            new_node = None\n        return new_node\n\n    def prepare(self):\n        \"\"\"This function prepares the AoT for rendering.\n        Returns:\n            structure.name(str): used for rendering structure\n            entities(list of Entity): used for rendering each entity\n        \"\"\"\n        assert self.is_pg\n        assert self.level == \"Root\"\n        structure = self.children[0]\n        components = []\n        for child in structure.children:\n            components.append(child)\n        entities = []\n        for component in components:\n            for child in component.children[0].children:\n                entities.append(child)\n        return structure.name, entities\n    \n    def sample_new(self, component_idx, attr_name, min_level, max_level, root):\n        \"\"\"Sample a new configuration. This is used for generating answers.\n        Arguments:\n            component_idx(int): the component we will sample\n            attr_name(str): name of the attribute to sample\n            min_level(int): lower bound of value level for the attribute\n            max_level(int): upper bound of value level for the attribute\n            root(AoTNode): the answer AoT, used for storing previous value levels for each attribute\n        \"\"\"\n        assert self.is_pg\n        self.children[0]._sample_new(component_idx, attr_name, min_level, max_level, root.children[0])\n\n\nclass Structure(AoTNode):\n\n    def __init__(self, name, is_pg=False):\n        super(Structure, self).__init__(name, level=\"Structure\", node_type=\"and\", is_pg=is_pg)\n    \n    def _sample(self):\n        if self.is_pg:\n            raise ValueError(\"Could not sample on a PG\")\n        new_node = Structure(self.name, True)\n        for child in self.children:\n            new_node.insert(child._sample())\n        return new_node\n    \n    def _prune(self, rule_groups):\n        new_node = Structure(self.name)\n        for i in range(len(self.children)):\n            child = self.children[i]\n            # if any of the components fails to satisfy the constraint\n            # the structure could not be chosen\n            new_child = child._prune(rule_groups[i])\n            if new_child is None:\n                return None\n            new_node.insert(new_child)\n        return new_node\n    \n    def _sample_new(self, component_idx, attr_name, min_level, max_level, structure):\n        self.children[component_idx]._sample_new(attr_name, min_level, max_level, structure.children[component_idx])\n        \n\nclass Component(AoTNode):\n\n    def __init__(self, name, is_pg=False):\n        super(Component, self).__init__(name, level=\"Component\", node_type=\"or\", is_pg=is_pg)\n\n    def _sample(self):\n        if self.is_pg:\n            raise ValueError(\"Could not sample on a PG\")\n        new_node = Component(self.name, True)\n        selected = np.random.choice(self.children)\n        new_node.insert(selected._sample())\n        return new_node\n\n    def _prune(self, rule_group):\n        new_node = Component(self.name)\n        for child in self.children:\n            new_child = child._update_constraint(rule_group)\n            if new_child is not None:\n                new_node.insert(new_child)\n        if len(new_node.children) == 0:\n            new_node = None\n        return new_node\n    \n    def _sample_new(self, attr_name, min_level, max_level, component):\n        self.children[0]._sample_new(attr_name, min_level, max_level, component.children[0])\n\n\nclass Layout(AoTNode):\n    \"\"\"Layout is the highest level of the hierarchy that has attributes (Number, Position and Uniformity).\n    To copy a Layout, please use deepcopy such that newly instantiated and separated attributes are created.\n    \"\"\"\n\n    def __init__(self, name, layout_constraint, entity_constraint, \n                             orig_layout_constraint=None, orig_entity_constraint=None, \n                             sample_new_num_count=None, is_pg=False):\n        super(Layout, self).__init__(name, level=\"Layout\", node_type=\"and\", is_pg=is_pg)\n        self.layout_constraint = layout_constraint\n        self.entity_constraint = entity_constraint\n        self.number = Number(min_level=layout_constraint[\"Number\"][0], max_level=layout_constraint[\"Number\"][1])\n        self.position = Position(pos_type=layout_constraint[\"Position\"][0], pos_list=layout_constraint[\"Position\"][1])\n        self.uniformity = Uniformity(min_level=layout_constraint[\"Uni\"][0], max_level=layout_constraint[\"Uni\"][1])\n        self.number.sample()\n        self.position.sample(self.number.get_value())\n        self.uniformity.sample()\n        # store initial layout_constraint and entity_constraint for answer generation\n        if orig_layout_constraint is None:\n            self.orig_layout_constraint = copy.deepcopy(self.layout_constraint)\n        else:\n            self.orig_layout_constraint = orig_layout_constraint\n        if orig_entity_constraint is None:\n            self.orig_entity_constraint = copy.deepcopy(self.entity_constraint)\n        else:\n            self.orig_entity_constraint = orig_entity_constraint\n        if sample_new_num_count is None:\n            self.sample_new_num_count = dict()\n            most_num = len(self.position.values)\n            for i in range(layout_constraint[\"Number\"][0], layout_constraint[\"Number\"][1] + 1):\n                self.sample_new_num_count[i] = [comb(most_num, i + 1), []]\n        else:\n            self.sample_new_num_count = sample_new_num_count\n\n    def add_new(self, *bboxes):\n        \"\"\"Add new entities into this level.\n        Arguments:\n            *bboxes(tuple of bbox): bboxes of new entities\n        \"\"\"\n        name = self.number.get_value()\n        uni = self.uniformity.get_value()\n        for i in range(len(bboxes)):\n            name += i\n            bbox = bboxes[i]\n            new_entity = copy.deepcopy(self.children[0])\n            new_entity.name = str(name)\n            new_entity.bbox = bbox\n            if not uni:\n                new_entity.resample()\n            self._insert(new_entity)\n    \n    def resample(self, change_number=False):\n        self._resample(change_number)\n            \n    def _sample(self):\n        \"\"\"Though Layout is an \"and\" node, we do not enumerate all possible configurations, but rather\n        we treat it as a sampling process such that different configurtions are sampled. After the\n        sampling, the lower level Entities are instantiated.\n        Returns:\n            new_node(Layout): a separated node with independent attributes\n        \"\"\"\n        pos = self.position.get_value()\n        new_node = copy.deepcopy(self)\n        new_node.is_pg = True\n        if self.uniformity.get_value():\n            node = Entity(name=str(0), bbox=pos[0], entity_constraint=self.entity_constraint)\n            new_node._insert(node)\n            for i in range(1, len(pos)):\n                bbox = pos[i]\n                node = copy.deepcopy(node)\n                node.name = str(i)\n                node.bbox = bbox\n                new_node._insert(node)\n        else:\n            for i in range(len(pos)):\n                bbox = pos[i]\n                node = Entity(name=str(i), bbox=bbox, entity_constraint=self.entity_constraint)\n                new_node._insert(node)\n        return new_node\n        \n    def _resample(self, change_number):\n        \"\"\"Resample each attribute for every child.\n        This function is called across rows.\n        Arguments:\n            change_number(bool): whether to resample a number\n        \"\"\"\n        if change_number:\n            self.number.sample()\n        del self.children[:]\n        self.position.sample(self.number.get_value())\n        pos = self.position.get_value()\n        if self.uniformity.get_value():\n            node = Entity(name=str(0), bbox=pos[0], entity_constraint=self.entity_constraint)\n            self._insert(node)\n            for i in range(1, len(pos)):\n                bbox = pos[i]\n                node = copy.deepcopy(node)\n                node.name = str(i)\n                node.bbox = bbox\n                self._insert(node)\n        else:\n            for i in range(len(pos)):\n                bbox = pos[i]\n                node = Entity(name=str(i), bbox=bbox, entity_constraint=self.entity_constraint)\n                self._insert(node)\n\n    def _update_constraint(self, rule_group):\n        \"\"\"Update the constraint of the layout. If one constraint is not satisfied, return None \n        such that this structure is disgarded.\n        Arguments:\n            rule_group(list of Rule): all rules to apply to this layout\n        Returns:\n            Layout(Layout): a new Layout node with independent attributes\n        \"\"\"        \n        num_min = self.layout_constraint[\"Number\"][0]\n        num_max = self.layout_constraint[\"Number\"][1]\n        uni_min = self.layout_constraint[\"Uni\"][0]\n        uni_max = self.layout_constraint[\"Uni\"][1]\n        type_min = self.entity_constraint[\"Type\"][0]\n        type_max = self.entity_constraint[\"Type\"][1]\n        size_min = self.entity_constraint[\"Size\"][0]\n        size_max = self.entity_constraint[\"Size\"][1]\n        color_min = self.entity_constraint[\"Color\"][0]\n        color_max = self.entity_constraint[\"Color\"][1]\n        new_constraints = rule_constraint(rule_group, num_min, num_max, \n                                                      uni_min, uni_max,\n                                                      type_min, type_max,\n                                                      size_min, size_max,\n                                                      color_min, color_max)\n        new_layout_constraint, new_entity_constraint = new_constraints\n        new_num_min = new_layout_constraint[\"Number\"][0]\n        new_num_max = new_layout_constraint[\"Number\"][1]\n        if new_num_min > new_num_max:\n            return None\n        new_uni_min = new_layout_constraint[\"Uni\"][0]\n        new_uni_max = new_layout_constraint[\"Uni\"][1]\n        if new_uni_min > new_uni_max:\n            return None\n        new_type_min = new_entity_constraint[\"Type\"][0]\n        new_type_max = new_entity_constraint[\"Type\"][1]\n        if new_type_min > new_type_max:\n            return None\n        new_size_min = new_entity_constraint[\"Size\"][0]\n        new_size_max = new_entity_constraint[\"Size\"][1]\n        if new_size_min > new_size_max:\n            return None\n        new_color_min = new_entity_constraint[\"Color\"][0]\n        new_color_max = new_entity_constraint[\"Color\"][1]                                    \n        if new_color_min > new_color_max:\n            return None\n\n        new_layout_constraint = copy.deepcopy(self.layout_constraint)\n        new_layout_constraint[\"Number\"][:] = [new_num_min, new_num_max]\n        new_layout_constraint[\"Uni\"][:] = [new_uni_min, new_uni_max]\n        \n        new_entity_constraint = copy.deepcopy(self.entity_constraint)\n        new_entity_constraint[\"Type\"][:] = [new_type_min, new_type_max]\n        new_entity_constraint[\"Size\"][:] = [new_size_min, new_size_max]\n        new_entity_constraint[\"Color\"][:] = [new_color_min, new_color_max]\n        return Layout(self.name, new_layout_constraint, new_entity_constraint,\n                                 self.orig_layout_constraint, self.orig_entity_constraint,\n                                 self.sample_new_num_count)\n    \n    def reset_constraint(self, attr):\n        attr_name = attr.lower()\n        instance = getattr(self, attr_name)\n        instance.min_level = self.layout_constraint[attr][0]\n        instance.max_level = self.layout_constraint[attr][1]\n    \n    def _sample_new(self, attr_name, min_level, max_level, layout):\n        if attr_name == \"Number\":\n            while True:\n                value_level = self.number.sample_new(min_level, max_level)\n                if layout.sample_new_num_count[value_level][0] == 0:\n                    continue\n                new_num = self.number.get_value(value_level)\n                new_value_idx = self.position.sample_new(new_num)\n                set_new_value_idx = set(new_value_idx)\n                if set_new_value_idx not in layout.sample_new_num_count[value_level][1]:\n                    layout.sample_new_num_count[value_level][0] -= 1\n                    layout.sample_new_num_count[value_level][1].append(set_new_value_idx)\n                    break\n            self.number.set_value_level(value_level)\n            self.position.set_value_idx(new_value_idx)\n            pos = self.position.get_value()\n            del self.children[:]\n            for i in range(len(pos)):\n                bbox = pos[i]\n                node = Entity(name=str(i), bbox=bbox, entity_constraint=self.entity_constraint)\n                self._insert(node)\n        elif attr_name == \"Position\":\n            new_value_idx = self.position.sample_new(self.number.get_value())\n            layout.position.previous_values.append(new_value_idx)\n            self.position.set_value_idx(new_value_idx)\n            pos = self.position.get_value()\n            for i in range(len(pos)):\n                bbox = pos[i]\n                self.children[i].bbox = bbox\n        elif attr_name == \"Type\":\n            for index in range(len(self.children)):\n                new_value_level = self.children[index].type.sample_new(min_level, max_level)\n                self.children[index].type.set_value_level(new_value_level)\n                layout.children[index].type.previous_values.append(new_value_level)\n        elif attr_name == \"Size\":\n            for index in range(len(self.children)):\n                new_value_level = self.children[index].size.sample_new(min_level, max_level)\n                self.children[index].size.set_value_level(new_value_level)\n                layout.children[index].size.previous_values.append(new_value_level)\n        elif attr_name == \"Color\":\n            for index in range(len(self.children)):\n                new_value_level = self.children[index].color.sample_new(min_level, max_level)\n                self.children[index].color.set_value_level(new_value_level)\n                layout.children[index].color.previous_values.append(new_value_level)\n        else:\n            raise ValueError(\"Unsupported operation\")\n\n\nclass Entity(AoTNode):\n\n    def __init__(self, name, bbox, entity_constraint):\n        super(Entity, self).__init__(name, level=\"Entity\", node_type=\"leaf\", is_pg=True)\n        # Attributes\n        # Sample each attribute such that the value lies in the admissible range\n        # Otherwise, random sample\n        self.entity_constraint = entity_constraint\n        self.bbox = bbox\n        self.type = Type(min_level=entity_constraint[\"Type\"][0], max_level=entity_constraint[\"Type\"][1])\n        self.type.sample()\n        self.size = Size(min_level=entity_constraint[\"Size\"][0], max_level=entity_constraint[\"Size\"][1])\n        self.size.sample()\n        self.color = Color(min_level=entity_constraint[\"Color\"][0], max_level=entity_constraint[\"Color\"][1])\n        self.color.sample()\n        self.angle = Angle(min_level=entity_constraint[\"Angle\"][0], max_level=entity_constraint[\"Angle\"][1])\n        self.angle.sample()\n    \n    def reset_constraint(self, attr, min_level, max_level):\n        attr_name = attr.lower()\n        self.entity_constraint[attr][:] = [min_level, max_level]\n        instance = getattr(self, attr_name)\n        instance.min_level = min_level\n        instance.max_level = max_level\n\n    def resample(self):\n        self.type.sample()\n        self.size.sample()\n        self.color.sample()\n        self.angle.sample()\n"
  },
  {
    "path": "src/dataset/Attribute.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\nfrom const import (ANGLE_MAX, ANGLE_MIN, ANGLE_VALUES, COLOR_MAX, COLOR_MIN,\n                   COLOR_VALUES, NUM_MAX, NUM_MIN, NUM_VALUES, SIZE_MAX,\n                   SIZE_MIN, SIZE_VALUES, TYPE_MAX, TYPE_MIN, TYPE_VALUES,\n                   UNI_MAX, UNI_MIN, UNI_VALUES)\n\n\nclass Attribute(object):\n    \"\"\"Super-class for all attributes. This should not be instantiated.\n    In the sub-class, each attribute should have a pre-defined value set\n    and a member to indicate the index in the value set. This design enables\n    setting a value by modifying the index only. Also, each instance should \n    come with value index boundaries, set as min_level and max_level. Boundaries\n    are good when we want to set constraints on the value set.\n\n    Before accessing the value, we should sample a value level by calling\n    the sample function.\n    \"\"\"\n\n    def __init__(self, name):\n        self.name = name\n        self.level = \"Attribute\"\n        # memory to store previous values\n        self.previous_values = []\n\n    def sample(self):\n        pass\n    \n    def get_value(self):\n        pass\n    \n    def set_value(self):\n        pass\n    \n    def __repr__(self):\n        return self.level + \".\" + self.name\n    \n    def __str__(self):\n        return self.level + \".\" + self.name\n\n\nclass Number(Attribute):\n\n    def __init__(self, min_level=NUM_MIN, max_level=NUM_MAX):\n        super(Number, self).__init__(\"Number\")\n        self.value_level = 0\n        self.values = NUM_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n\n    def sample(self, min_level=NUM_MIN, max_level=NUM_MAX):\n        # min_level: min level index\n        # max_level: max level index\n        min_level = max(self.min_level, min_level)\n        max_level = min(self.max_level, max_level)\n        self.value_level = np.random.choice(range(min_level, max_level + 1))\n\n    def sample_new(self, min_level=None, max_level=None, previous_values=None):\n        \"\"\"Sample new values for generating the answer set.\n        Returns:\n            new_idx(int): a new value_level\n        \"\"\"\n        if min_level is None or max_level is None:\n            values = range(self.min_level, self.max_level + 1)\n        else:\n            values = range(min_level, max_level + 1)\n        if not previous_values:\n            available = set(values) - set(self.previous_values) - set([self.value_level])\n        else:\n            available = set(values) - set(previous_values) - set([self.value_level])\n        new_idx = np.random.choice(list(available))\n        return new_idx\n    \n    def get_value_level(self):\n        return self.value_level\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n\n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Type(Attribute):\n\n    def __init__(self, min_level=TYPE_MIN, max_level=TYPE_MAX):\n        super(Type, self).__init__(\"Type\")\n        self.value_level = 0\n        self.values = TYPE_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n    \n    def sample(self, min_level=TYPE_MIN, max_level=TYPE_MAX):\n        min_level = max(self.min_level, min_level)\n        max_level = min(self.max_level, max_level)\n        self.value_level = np.random.choice(range(min_level, max_level + 1))\n\n    def sample_new(self, min_level=None, max_level=None, previous_values=None):\n        if min_level is None or max_level is None:\n            values = range(self.min_level, self.max_level + 1)\n        else:\n            values = range(min_level, max_level + 1)\n        if not previous_values:\n            available = set(values) - set(self.previous_values) - set([self.value_level])\n        else:\n            available = set(values) - set(previous_values) - set([self.value_level])\n        new_idx = np.random.choice(list(available))\n        return new_idx\n\n    def get_value_level(self):\n        return self.value_level\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n    \n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Size(Attribute):\n\n    def __init__(self, min_level=SIZE_MIN, max_level=SIZE_MAX):\n        super(Size, self).__init__(\"Size\")\n        self.value_level = 3\n        self.values = SIZE_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n\n    def sample(self, min_level=SIZE_MIN, max_level=SIZE_MAX):\n        min_level = max(self.min_level, min_level)\n        max_level = min(self.max_level, max_level)\n        self.value_level = np.random.choice(range(min_level, max_level + 1))   \n\n    def sample_new(self, min_level=None, max_level=None, previous_values=None):\n        if min_level is None or max_level is None:\n            values = range(self.min_level, self.max_level + 1)\n        else:\n            values = range(min_level, max_level + 1)\n        if not previous_values:\n            available = set(values) - set(self.previous_values) - set([self.value_level])\n        else:\n            available = set(values) - set(previous_values) - set([self.value_level])\n        new_idx = np.random.choice(list(available))\n        return new_idx\n\n    def get_value_level(self):\n        return self.value_level\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n\n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Color(Attribute):\n\n    def __init__(self, min_level=COLOR_MIN, max_level=COLOR_MAX):\n        super(Color, self).__init__(\"Color\")\n        self.value_level = 0\n        self.values = COLOR_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n\n    def sample(self, min_level=COLOR_MIN, max_level=COLOR_MAX):\n        min_level = max(self.min_level, min_level)\n        max_level = min(self.max_level, max_level)\n        self.value_level = np.random.choice(range(min_level, max_level + 1))\n\n    def sample_new(self, min_level=None, max_level=None, previous_values=None):\n        if min_level is None or max_level is None:\n            values = range(self.min_level, self.max_level + 1)\n        else:\n            values = range(min_level, max_level + 1)\n        if not previous_values:\n            available = set(values) - set(self.previous_values) - set([self.value_level])\n        else:\n            available = set(values) - set(previous_values) - set([self.value_level])\n        new_idx = np.random.choice(list(available))\n        return new_idx\n\n    def get_value_level(self):\n        return self.value_level\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n\n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Angle(Attribute):\n\n    def __init__(self, min_level=ANGLE_MIN, max_level=ANGLE_MAX):\n        super(Angle, self).__init__(\"Angle\")\n        self.value_level = 3\n        self.values = ANGLE_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n\n    def sample(self, min_level=ANGLE_MIN, max_level=ANGLE_MAX):\n        min_level = max(self.min_level, min_level)\n        max_level = min(self.max_level, max_level)\n        self.value_level = np.random.choice(range(min_level, max_level + 1))\n\n    def sample_new(self, min_level=None, max_level=None, previous_values=None):\n        if min_level is None or max_level is None:\n            values = range(self.min_level, self.max_level + 1)\n        else:\n            values = range(min_level, max_level + 1)\n        if not previous_values:\n            available = set(values) - set(self.previous_values) - set([self.value_level])\n        else:\n            available = set(values) - set(previous_values) - set([self.value_level])\n        new_idx = np.random.choice(list(available))\n        return new_idx\n\n    def get_value_level(self):\n        return self.value_level\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n    \n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Uniformity(Attribute):\n\n    def __init__(self, min_level=UNI_MIN, max_level=UNI_MAX):\n        super(Uniformity, self).__init__(\"Uniformity\")\n        self.value_level = 0\n        self.values = UNI_VALUES\n        self.min_level = min_level\n        self.max_level = max_level\n    \n    def sample(self):\n        self.value_level = np.random.choice(range(self.min_level, self.max_level + 1))\n    \n    def sample_new(self):\n        # Should not resample uniformity\n        pass\n    \n    def set_value_level(self, value_level):\n        self.value_level = value_level\n    \n    def get_value_level(self):\n        return self.value_level\n\n    def get_value(self, value_level=None):\n        if value_level is None:\n            value_level = self.value_level\n        return self.values[value_level]\n\n\nclass Position(Attribute):\n    \"\"\"Position is a special case. There are the planar position and \n    the angular position. Planar position allows translation in the plane\n    while angular Position performs roration around an axis penperdicular to the plane.\n    \"\"\"\n\n    def __init__(self, pos_type, pos_list):\n        \"\"\"Instantiate the Position attribute by passing a position type\n        and a pre-defined position distribution on the plane. This attribute\n        is strongly coupled with Number and hence value index boundaries are \n        not needed.\n        Arguments:\n            pos_type(str): either \"planar\" or \"angular\n            pos_list(list of list of numbers): actual distribution on the plane\n        \"\"\"\n        super(Position, self).__init__(\"Position\")\n        # planar: [x_c, y_c, max_w, max_h]\n        # angular: [x_c, y_c, max_w, max_h, x_r, y_r, omega]\n        assert pos_type in (\"planar\", \"angular\")\n        self.pos_type = pos_type\n        self.values = pos_list\n        self.value_idx = None\n\n    def sample(self, num):\n        \"\"\"Sample multiple positions at the same time.\n        Arguments:\n            num(int): the number of positions to sample\n        \"\"\"\n        length = len(self.values)\n        assert num <= length\n        self.value_idx = np.random.choice(range(length), num, False)\n    \n    def sample_new(self, num, previous_values=None):\n        # Here sample new relies on probability\n        length = len(self.values)\n        if not previous_values:\n            constraints = self.previous_values\n        else:\n            constraints = previous_values\n        while True:\n            finished = True\n            new_value_idx = np.random.choice(length, num, False)\n            if set(new_value_idx) == set(self.value_idx):\n                continue\n            for previous_value in constraints:\n                if set(new_value_idx) == set(previous_value):\n                    finished = False\n                    break\n            if finished:\n                break\n        return new_value_idx\n\n    def sample_add(self, num):\n        \"\"\"Sample additional number of positions.\n        Arguments:\n            num(int): the number of additional positions to sample\n        Returns:\n            ret(tuple of position): new positions to add to the layout\n        \"\"\"\n        ret = []\n        available = set(range(len(self.values))) - set(self.value_idx)\n        idxes_2_add = np.random.choice(list(available), num, False)\n        for index in idxes_2_add:\n            self.value_idx = np.insert(self.value_idx, 0, index)\n            ret.append(self.values[index])\n        return ret\n    \n    def get_value_idx(self):\n        return self.value_idx\n    \n    def set_value_idx(self, value_idx):\n        # Note that after sampling self.value_idx is a Numpy array\n        self.value_idx = value_idx\n\n    def get_value(self, value_idx=None):\n        if value_idx is None:\n            value_idx = self.value_idx\n        ret = []\n        for idx in value_idx:\n            ret.append(self.values[idx])\n        return ret\n    \n    def remove(self, bbox):\n        # Note that after sampling self.value_idx is a Numpy array\n        idx = self.values.index(bbox)\n        np_idx = np.where(self.value_idx == idx)[0][0]\n        self.value_idx = np.delete(self.value_idx, np_idx)\n        "
  },
  {
    "path": "src/dataset/Rule.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport copy\n\nimport numpy as np\n\nfrom const import COLOR_MAX, COLOR_MIN\n\n\ndef Rule_Wrapper(name, attr, param, component_idx):\n    ret = None\n    if name == \"Constant\":\n        ret = Constant(name, attr, param, component_idx)\n    elif name == \"Progression\":\n        ret = Progression(name, attr, param, component_idx)\n    elif name == \"Arithmetic\":\n        ret = Arithmetic(name, attr, param, component_idx)\n    elif name == \"Distribute_Three\":\n        ret = Distribute_Three(name, attr, param, component_idx)\n    else:\n        raise ValueError(\"Unsupported Rule\")\n    return ret \n\n\nclass Rule(object):\n    \"\"\"General API for a rule.\n    Priority order: Rule on Number/Position always comes first\n    \"\"\"\n    \n    def __init__(self, name, attr, params, component_idx=0):\n        \"\"\"Instantiate a rule by its name, attribute, paramter list and the component it applies to.\n        Each rule should be applied to all entities in a component.\n        Arguments:\n            name(str): pre-defined name of the rule\n            attr(str): pre-defined name of the attribute\n            params(list): a list of possible parameters for it to sample\n            component_idx(int): the index of the component to apply the rule\n        \"\"\"\n        self.name = name\n        self.attr = attr\n        self.params = params\n        self.component_idx = component_idx\n        self.value = 0\n        self.sample()\n    \n    def sample(self):\n        \"\"\"Sample a parameter from the parameter list.\n        \"\"\"\n        if self.params is not None:\n            self.value = np.random.choice(self.params)\n    \n    def apply_rule(self, aot, in_aot=None):\n        \"\"\"Apply the rule to a component in the AoT.\n        Arguments:\n            aot(AoTNode): an AoT for reference\n            in_aot(AoTNode): an AoT to apply the rule\n        Returns:\n            second_aot(AoTNode): a modified AoT\n        \"\"\"\n        # Root -> Structure -> Component -> Layout -> Entity\n        pass\n\n\nclass Constant(Rule):\n    \"\"\"Unary operator. Nothing changes.\n    \"\"\"\n\n    def __init__(self, name, attr, param, component_idx):\n        super(Constant, self).__init__(name, attr, param, component_idx)\n    \n    def apply_rule(self, aot, in_aot=None):\n        if in_aot is None:\n            in_aot = aot\n        return copy.deepcopy(in_aot)\n\n\nclass Progression(Rule):\n    \"\"\"Unary operator. Attribute difference on two consequetive Panels remains the same.\n    \"\"\"\n\n    def __init__(self, name, attr, param, component_idx):\n        super(Progression, self).__init__(name, attr, param, component_idx)\n        # Flag to trigger consistency of the attribute in the first column\n        self.first_col = True\n\n    def apply_rule(self, aot, in_aot=None):\n        current_layout = aot.children[0].children[self.component_idx].children[0]\n        if in_aot is None:\n            in_aot = aot\n        second_aot = copy.deepcopy(in_aot)\n        second_layout = second_aot.children[0].children[self.component_idx].children[0]\n        if self.attr == \"Number\":\n            second_layout.number.set_value_level(second_layout.number.get_value_level() + self.value)\n            second_layout.position.sample(second_layout.number.get_value())\n            pos = second_layout.position.get_value()\n            del second_layout.children[:]\n            for i in range(len(pos)):\n                entity = copy.deepcopy(current_layout.children[0])\n                entity.name = str(i)\n                entity.bbox = pos[i]\n                if not current_layout.uniformity.get_value():\n                    entity.resample()\n                second_layout.insert(entity)\n        elif self.attr == \"Position\":\n            second_pos_idx = (second_layout.position.get_value_idx() + self.value) % len(second_layout.position.values)\n            second_layout.position.set_value_idx(second_pos_idx)\n            second_bbox = second_layout.position.get_value()\n            for i in range(len(second_bbox)):\n                second_layout.children[i].bbox = second_bbox[i]\n        elif self.attr == \"Type\":\n            old_value_level = current_layout.children[0].type.get_value_level()\n            # enforce value consistency\n            if self.first_col and not current_layout.uniformity.get_value():\n                for entity in current_layout.children:\n                    entity.type.set_value_level(old_value_level)\n            for entity in second_layout.children:\n                entity.type.set_value_level(old_value_level + self.value)\n        elif self.attr == \"Size\":\n            old_value_level = current_layout.children[0].size.get_value_level()\n            # enforce value consistency\n            if self.first_col and not current_layout.uniformity.get_value():\n                for entity in current_layout.children:\n                    entity.size.set_value_level(old_value_level)\n            for entity in second_layout.children:\n                entity.size.set_value_level(old_value_level + self.value)\n        elif self.attr == \"Color\":\n            old_value_level = current_layout.children[0].color.get_value_level()\n            # enforce value consistency\n            if self.first_col and not current_layout.uniformity.get_value():\n                for entity in current_layout.children:\n                    entity.color.set_value_level(old_value_level)\n            for entity in second_layout.children:\n                entity.color.set_value_level(old_value_level + self.value)\n        else:\n            raise ValueError(\"Unsupported attriubute\")\n        self.first_col = not self.first_col\n        return second_aot\n\n\nclass Arithmetic(Rule):\n    \"\"\"Binary operator. Basically: Panel_3 = Panel_1 + Panel_2.\n    For Position: + means SET_UNION and - SET_DIFF.\n    \"\"\"\n\n    def __init__(self, name, attr, param, component_idx):\n        super(Arithmetic, self).__init__(name, attr, param, component_idx)\n        self.memory = []\n        self.color_count = 0\n        self.color_white_alarm = False\n    \n    def apply_rule(self, aot, in_aot=None):\n        current_layout = aot.children[0].children[self.component_idx].children[0]\n        if in_aot is None:\n            in_aot = aot\n        second_aot = copy.deepcopy(in_aot)\n        second_layout = second_aot.children[0].children[self.component_idx].children[0]\n        if self.attr == \"Number\":\n            # the third col\n            if len(self.memory) > 0:\n                first_layout_number_level = self.memory.pop()\n                if self.value > 0:\n                    total = first_layout_number_level + 1 + current_layout.number.get_value()\n                else:\n                    total = first_layout_number_level + 1 - current_layout.number.get_value()\n                second_layout.number.set_value_level(total - 1)\n            # the second col\n            else:\n                old_value_level = current_layout.number.get_value_level()\n                self.memory.append(old_value_level)\n                if self.value > 0:\n                    num_max_level_orig = sum(current_layout.layout_constraint[\"Number\"]) + 1\n                    new_num_max_level = num_max_level_orig - old_value_level - 1\n                    second_layout.layout_constraint[\"Number\"][1] = new_num_max_level\n                else:\n                    num_min_level_orig = (second_layout.layout_constraint[\"Number\"][0] - 1) / 2\n                    new_num_max_level = old_value_level - num_min_level_orig - 1\n                    second_layout.layout_constraint[\"Number\"][:] = [num_min_level_orig, new_num_max_level]\n                second_layout.reset_constraint(\"Number\")\n                second_layout.number.sample()\n            second_layout.position.sample(second_layout.number.get_value())\n            pos = second_layout.position.get_value()\n            del second_layout.children[:]\n            for i in range(len(pos)):\n                entity = copy.deepcopy(current_layout.children[0])\n                entity.name = str(i)\n                entity.bbox = pos[i]\n                if not current_layout.uniformity.get_value():\n                    entity.resample()\n                second_layout.insert(entity)\n        elif self.attr == \"Position\":\n            # ADD is interpreted as SET_UNION; SUB is interpreted as SET_DIFF\n            # the third col\n            if len(self.memory) > 0:\n                first_layout_value_idx = self.memory.pop()\n                if self.value > 0:\n                    new_pos_idx = set(first_layout_value_idx) | set(current_layout.position.get_value_idx())\n                else:\n                    new_pos_idx = set(first_layout_value_idx) - set(current_layout.position.get_value_idx())\n                second_layout.number.set_value_level(len(new_pos_idx) - 1)\n                second_layout.position.set_value_idx(np.array(list(new_pos_idx)))\n            # the second col\n            else:\n                current_layout_value_idx = current_layout.position.get_value_idx()\n                self.memory.append(current_layout_value_idx)\n                while True:\n                    second_layout.number.sample()\n                    second_layout.position.sample(second_layout.number.get_value())\n                    # if UNION, not a subset; otherwise not clearly a union\n                    if self.value > 0:\n                        if not (set(current_layout_value_idx) >= set(second_layout.position.get_value_idx())):\n                            break\n                    # if DIFF, not a subset; otherwise no entities left\n                    else:\n                        if not (set(current_layout_value_idx) <= set(second_layout.position.get_value_idx())):\n                            break\n            pos = second_layout.position.get_value()\n            del second_layout.children[:]\n            for i in range(len(pos)):\n                entity = copy.deepcopy(current_layout.children[0])\n                entity.name = str(i)\n                entity.bbox = pos[i]\n                if not current_layout.uniformity.get_value():\n                    entity.resample()\n                second_layout.insert(entity)\n        elif self.attr == \"Size\":\n            if len(self.memory) > 0:\n                first_layout_size_level = self.memory.pop()\n                if self.value > 0:\n                    new_size_value_level = first_layout_size_level + \\\n                                           current_layout.children[0].size.get_value_level() + 1\n                else:\n                    new_size_value_level = first_layout_size_level - \\\n                                           current_layout.children[0].size.get_value_level() - 1\n                for entity in second_layout.children:\n                    entity.size.set_value_level(new_size_value_level)\n            else:\n                # make sure of value consistency\n                old_value_level = current_layout.children[0].size.get_value_level()\n                self.memory.append(old_value_level)\n                if not current_layout.uniformity.get_value():\n                    for entity in current_layout.children:\n                        entity.size.set_value_level(old_value_level)\n                if self.value > 0:\n                    size_max_level_orig = sum(current_layout.entity_constraint[\"Size\"]) + 1\n                    new_size_max_level = size_max_level_orig - old_value_level - 1\n                    # deepcopy breaks the link of constraints between Layout and Entity\n                    # Need to reset each attribute\n                    second_layout.entity_constraint[\"Size\"][1] = new_size_max_level\n                else:\n                    size_min_level_orig = (current_layout.entity_constraint[\"Size\"][0] - 1) / 2\n                    new_size_max_level = old_value_level - size_min_level_orig - 1\n                    second_layout.entity_constraint[\"Size\"] = [size_min_level_orig, new_size_max_level]\n                new_size_min_level, new_size_max_level = second_layout.entity_constraint[\"Size\"]\n                the_child = second_layout.children[0]\n                the_child.reset_constraint(\"Size\", new_size_min_level, new_size_max_level)\n                the_child.size.sample()\n                new_size_value_level = the_child.size.get_value_level()\n                for idx in range(1, len(second_layout.children)):\n                    entity = second_layout.children[idx]\n                    entity.reset_constraint(\"Size\", new_size_min_level, new_size_max_level)\n                    entity.size.set_value_level(new_size_value_level)\n        elif self.attr == \"Color\":\n            self.color_count += 1\n            if len(self.memory) > 0:\n                first_layout_color_level = self.memory.pop()\n                if self.value > 0:\n                    new_color_value_level = first_layout_color_level + \\\n                                            current_layout.children[0].color.get_value_level()\n                else:\n                    new_color_value_level = first_layout_color_level - \\\n                                            current_layout.children[0].color.get_value_level()\n                for entity in second_layout.children:\n                    entity.color.set_value_level(new_color_value_level)\n            else:\n                # Logic here: C_12 and C_22 could not be both 0, otherwise it's impossible to distinguish + and -\n                # If C_12 == 0, we set an alarm\n                # Under this alarm, if C_21 == MAX and ADD rule, then resample C_21 to ensure C_22 could be other than 0\n                # Similarly, if C_21 == 0 and SUB rule, then resample C_21 to ensure C_22 could be other than 0\n                # Finally, loop until C_22 is not 0\n\n                # make sure of value consistency\n                old_value_level = current_layout.children[0].color.get_value_level()\n                # the third time you apply this rule and find C_21 == MAX/0 if +/-\n                reset_current_layout = False\n                if self.color_count == 3 and self.color_white_alarm:\n                    if self.value > 0 and old_value_level == COLOR_MAX:\n                        old_value_level = current_layout.children[0].color.sample_new()\n                        reset_current_layout = True\n                    if self.value < 0 and old_value_level == COLOR_MIN:\n                        old_value_level = current_layout.children[0].color.sample_new()\n                        reset_current_layout = True\n                self.memory.append(old_value_level)\n                if reset_current_layout or not current_layout.uniformity.get_value():\n                    for entity in current_layout.children:\n                        entity.color.set_value_level(old_value_level)\n                if self.value > 0:\n                    color_max_level_orig = sum(current_layout.entity_constraint[\"Color\"])\n                    new_color_max_level = color_max_level_orig - old_value_level\n                    second_layout.entity_constraint[\"Color\"][1] = new_color_max_level\n                else:\n                    color_min_level_orig = second_layout.entity_constraint[\"Color\"][0] / 2\n                    new_color_max_level = old_value_level\n                    second_layout.entity_constraint[\"Color\"][:] = [color_min_level_orig, new_color_max_level]\n                new_color_min_level, new_color_max_level = second_layout.entity_constraint[\"Color\"]\n                the_child = second_layout.children[0]\n                the_child.reset_constraint(\"Color\", new_color_min_level, new_color_max_level)\n                the_child.color.sample()\n                new_color_value_level = the_child.color.get_value_level()\n                # the first time you apply this rule and get C_12 == 0\n                # set the alarm\n                if self.color_count == 1:\n                    self.color_white_alarm = (new_color_value_level == 0)\n                if self.color_count == 3 and self.color_white_alarm and new_color_value_level == 0:\n                    new_color_value_level = the_child.color.sample_new()\n                    the_child.color.set_value_level(new_color_value_level)\n                for idx in range(1, len(second_layout.children)):\n                    entity = second_layout.children[idx]\n                    entity.reset_constraint(\"Color\", new_color_min_level, new_color_max_level)\n                    entity.color.set_value_level(new_color_value_level)\n        else:\n            raise ValueError(\"Unsupported attriubute\")\n        return second_aot\n\n\nclass Distribute_Three(Rule):\n    \"\"\"Ternay operator. Three values across the columns form a fixed set.\n    \"\"\"\n\n    def __init__(self, name, attr, param, component_idx):\n        super(Distribute_Three, self).__init__(name, attr, param, component_idx)\n        self.value_levels = []\n        self.count = 0\n\n    def apply_rule(self, aot, in_aot=None):\n        current_layout = aot.children[0].children[self.component_idx].children[0]\n        if in_aot is None:\n            in_aot = aot\n        second_aot = copy.deepcopy(in_aot)\n        second_layout = second_aot.children[0].children[self.component_idx].children[0]\n        if self.attr == \"Number\":\n            if self.count == 0:\n                all_value_levels = range(current_layout.layout_constraint[\"Number\"][0], \n                                         current_layout.layout_constraint[\"Number\"][1] + 1)\n                current_value_level = current_layout.number.get_value_level()\n                idx = all_value_levels.index(current_value_level)\n                all_value_levels.pop(idx)\n                three_value_levels = np.random.choice(all_value_levels, 2, False)\n                three_value_levels = np.insert(three_value_levels, 0, current_value_level)\n                self.value_levels.append(three_value_levels[[0, 1, 2]])\n                if np.random.uniform() >= 0.5:\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                else:\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                second_layout.number.set_value_level(self.value_levels[0][1])\n            else:\n                row, col = divmod(self.count, 2)\n                if col == 0:\n                    current_layout.number.set_value_level(self.value_levels[row][0])\n                    current_layout.resample()\n                    second_aot = copy.deepcopy(aot)\n                    second_layout = second_aot.children[0].children[self.component_idx].children[0]\n                    second_layout.number.set_value_level(self.value_levels[row][1])\n                else:\n                    second_layout.number.set_value_level(self.value_levels[row][2])\n            second_layout.position.sample(second_layout.number.get_value())\n            pos = second_layout.position.get_value()\n            del second_layout.children[:]\n            for i in range(len(pos)):\n                entity = copy.deepcopy(current_layout.children[0])\n                entity.name = str(i)\n                entity.bbox = pos[i]\n                if not current_layout.uniformity.get_value():\n                    entity.resample()\n                second_layout.insert(entity)\n            self.count = (self.count + 1) % 6\n        elif self.attr == \"Position\":\n            if self.count == 0:\n                # sample new does not change value_level/value_idx\n                num = current_layout.number.get_value()\n                pos_0 = current_layout.position.get_value_idx()\n                pos_1 = current_layout.position.sample_new(num)\n                pos_2 = current_layout.position.sample_new(num, [pos_1])\n                three_value_levels = np.array([pos_0, pos_1, pos_2])\n                self.value_levels.append(three_value_levels[[0, 1, 2]])\n                if np.random.uniform() >= 0.5:\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                else:\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                second_layout.position.set_value_idx(self.value_levels[0][1])\n            else:\n                row, col = divmod(self.count, 2)\n                if col == 0:\n                    current_layout.number.set_value_level(len(self.value_levels[row][0]) - 1)\n                    current_layout.resample()\n                    current_layout.position.set_value_idx(self.value_levels[row][0])\n                    pos = current_layout.position.get_value()\n                    for i in range(len(pos)):\n                        entity = current_layout.children[i]\n                        entity.bbox = pos[i]\n                    second_aot = copy.deepcopy(aot)\n                    second_layout = second_aot.children[0].children[self.component_idx].children[0]\n                    second_layout.position.set_value_idx(self.value_levels[row][1])            \n                else:\n                    second_layout.position.set_value_idx(self.value_levels[row][2])\n            pos = second_layout.position.get_value()\n            for i in range(len(pos)):\n                entity = second_layout.children[i]\n                entity.bbox = pos[i]\n            self.count = (self.count + 1) % 6\n        elif self.attr == \"Type\":\n            if self.count == 0:\n                all_value_levels = range(current_layout.entity_constraint[\"Type\"][0], \n                                         current_layout.entity_constraint[\"Type\"][1] + 1)\n                # if np.random.uniform() >= 0.5 and 0 not in all_value_levels:\n                #     all_value_levels.insert(0, 0)\n                three_value_levels = np.random.choice(all_value_levels, 3, False)\n                np.random.shuffle(three_value_levels) \n                self.value_levels.append(three_value_levels[[0, 1, 2]])\n                if np.random.uniform() >= 0.5:\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                else:\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                for entity in current_layout.children:\n                    entity.type.set_value_level(self.value_levels[0][0])\n                for entity in second_layout.children:\n                    entity.type.set_value_level(self.value_levels[0][1])\n            else:\n                row, col = divmod(self.count, 2)\n                if col == 0:\n                    value_level = self.value_levels[row][0]\n                    for entity in current_layout.children:\n                        entity.type.set_value_level(value_level)\n                    value_level = self.value_levels[row][1]\n                    for entity in second_layout.children:\n                        entity.type.set_value_level(value_level)\n                else:\n                    value_level = self.value_levels[row][2]\n                    for entity in second_layout.children:\n                        entity.type.set_value_level(value_level)\n            self.count = (self.count + 1) % 6\n        elif self.attr == \"Size\":\n            if self.count == 0:\n                all_value_levels = range(current_layout.entity_constraint[\"Size\"][0], \n                                         current_layout.entity_constraint[\"Size\"][1] + 1)\n                three_value_levels = np.random.choice(all_value_levels, 3, False) \n                self.value_levels.append(three_value_levels[[0, 1, 2]])\n                if np.random.uniform() >= 0.5:\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                else:\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                for entity in current_layout.children:\n                    entity.size.set_value_level(self.value_levels[0][0])\n                for entity in second_layout.children:\n                    entity.size.set_value_level(self.value_levels[0][1])\n            else:\n                row, col = divmod(self.count, 2)\n                if col == 0:\n                    value_level = self.value_levels[row][0]\n                    for entity in current_layout.children:\n                        entity.size.set_value_level(value_level)\n                    value_level = self.value_levels[row][1]\n                    for entity in second_layout.children:\n                        entity.size.set_value_level(value_level)\n                else:\n                    value_level = self.value_levels[row][2]\n                    for entity in second_layout.children:\n                        entity.size.set_value_level(value_level)\n            self.count = (self.count + 1) % 6\n        elif self.attr == \"Color\":\n            if self.count == 0:\n                all_value_levels = range(current_layout.entity_constraint[\"Color\"][0], \n                                         current_layout.entity_constraint[\"Color\"][1] + 1)\n                three_value_levels = np.random.choice(all_value_levels, 3, False) \n                self.value_levels.append(three_value_levels[[0, 1, 2]])\n                if np.random.uniform() >= 0.5:\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                else:\n                    self.value_levels.append(three_value_levels[[2, 0, 1]])\n                    self.value_levels.append(three_value_levels[[1, 2, 0]])\n                for entity in current_layout.children:\n                    entity.color.set_value_level(self.value_levels[0][0])\n                for entity in second_layout.children:\n                    entity.color.set_value_level(self.value_levels[0][1])\n            else:\n                row, col = divmod(self.count, 2)\n                if col == 0:\n                    value_level = self.value_levels[row][0]\n                    for entity in current_layout.children:\n                        entity.color.set_value_level(value_level)\n                    value_level = self.value_levels[row][1]\n                    for entity in second_layout.children:\n                        entity.color.set_value_level(value_level)\n                else:\n                    value_level = self.value_levels[row][2]\n                    for entity in second_layout.children:\n                        entity.color.set_value_level(value_level)\n            self.count = (self.count + 1) % 6\n        else:\n            raise ValueError(\"Unsupported attriubute\")\n        return second_aot\n"
  },
  {
    "path": "src/dataset/__init__.py",
    "content": "\"\"\" RAVEN dataset generation code\n\nAuthor: Chi Zhang\nData: 05/14/2019\nContact: chi.zhang@ucla.edu\n\"\"\""
  },
  {
    "path": "src/dataset/api.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport xml.etree.ElementTree as ET\n\nimport cv2\nimport numpy as np\nfrom const import DEFAULT_WIDTH, IMAGE_SIZE\nfrom rendering import render_entity\n\n\nclass Bunch:\n    \"\"\"Dummy class\"\"\"\n    def __init__(self, **kwds):\n        self.__dict__.update(kwds)\n\n\ndef get_real_bbox(entity_bbox, entity_type, entity_size, entity_angle):\n    assert entity_type != \"none\"\n    center = (int(entity_bbox[1] * IMAGE_SIZE), int(entity_bbox[0] * IMAGE_SIZE))\n    M = cv2.getRotationMatrix2D(center, entity_angle, 1)\n    unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n    delta = DEFAULT_WIDTH * 1.5 / IMAGE_SIZE\n    if entity_type == \"circle\":\n        radius = unit * entity_size\n        real_bbox = [center[1] * 1.0 / IMAGE_SIZE, center[0] * 1.0 / IMAGE_SIZE, 2 * radius / IMAGE_SIZE + delta, 2 * radius / IMAGE_SIZE + delta]\n    else:\n        if entity_type == \"triangle\":\n            dl = int(unit * entity_size)\n            homo_pts = np.array([[center[0], center[1] - dl, 1], \n                                 [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0), 1], \n                                 [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0), 1]], \n                                np.int32)\n        if entity_type == \"square\":\n            dl = int(unit / 2 * np.sqrt(2) * entity_size)\n            homo_pts = np.array([[center[0] - dl, center[1] - dl, 1],\n                                 [center[0] - dl, center[1] + dl, 1], \n                                 [center[0] + dl, center[1] + dl, 1], \n                                 [center[0] + dl, center[1] - dl, 1]],\n                                np.int32)\n        if entity_type == \"pentagon\":\n            dl = int(unit * entity_size)\n            homo_pts = np.array([[center[0], center[1] - dl, 1],\n                                 [center[0] - int(dl * np.cos(np.pi / 10)), center[1] - int(dl * np.sin(np.pi / 10)), 1],\n                                 [center[0] - int(dl * np.sin(np.pi / 5)), center[1] + int(dl * np.cos(np.pi / 5)), 1],\n                                 [center[0] + int(dl * np.sin(np.pi / 5)), center[1] + int(dl * np.cos(np.pi / 5)), 1],\n                                 [center[0] + int(dl * np.cos(np.pi / 10)), center[1] - int(dl * np.sin(np.pi / 10)), 1]],\n                                np.int32)\n        if entity_type == \"hexagon\":\n            dl = int(unit * entity_size)\n            homo_pts = np.array([[center[0], center[1] - dl, 1],\n                                 [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] - int(dl / 2.0), 1],\n                                 [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0), 1],\n                                 [center[0], center[1] + dl, 1],\n                                 [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0), 1],\n                                 [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] - int(dl / 2.0), 1]],\n                                np.int32)\n        after_pts = np.dot(M, homo_pts.T)\n        min_x = min(after_pts[1, :]) / IMAGE_SIZE\n        max_x = max(after_pts[1, :]) / IMAGE_SIZE\n        min_y = min(after_pts[0, :]) / IMAGE_SIZE\n        max_y = max(after_pts[0, :]) / IMAGE_SIZE\n        real_bbox = [(min_x + max_x) / 2, (min_y + max_y) / 2, max_x - min_x + delta, max_y - min_y + delta] \n    return list(np.round(real_bbox, 4))\n\n\ndef get_mask(entity_bbox, entity_type, entity_size, entity_angle):\n    dummy_entity = Bunch()\n    dummy_entity.bbox = entity_bbox\n    dummy_entity.type = Bunch(get_value=lambda : entity_type)\n    dummy_entity.size = Bunch(get_value=lambda : entity_size)\n    dummy_entity.color = Bunch(get_value=lambda : 0)\n    dummy_entity.angle = Bunch(get_value=lambda : entity_angle)\n    mask = render_entity(dummy_entity) / 255\n    return mask\n\n\n# ref: https://www.kaggle.com/stainsby/fast-tested-rle\n# ref: https://www.kaggle.com/paulorzp/run-length-encode-and-decode\ndef rle_encode(img):\n    '''\n    img: numpy array, 1 - mask, 0 - background\n    Returns run length as string formated\n    '''\n    pixels = img.flatten()\n    pixels = np.concatenate([[0], pixels, [0]])\n    runs = np.where(pixels[1:] != pixels[:-1])[0] + 1\n    runs[1::2] -= runs[::2]\n    return \"[\" + \",\".join(str(x) for x in runs) + \"]\"\n \n\ndef rle_decode(mask_rle, shape):\n    '''\n    mask_rle: run-length as string formated (start length)\n    shape: (height,width) of array to return \n    Returns numpy array, 1 - mask, 0 - background\n    '''\n    s = mask_rle[1:-1].split(\",\")\n    starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n    starts -= 1\n    ends = starts + lengths\n    img = np.zeros(shape[0] * shape[1], dtype=np.uint8)\n    for lo, hi in zip(starts, ends):\n        img[lo:hi] = 1\n    return img.reshape(shape)\n"
  },
  {
    "path": "src/dataset/build_tree.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nfrom AoT import Component, Layout, Root, Structure\nfrom constraints import (gen_entity_constraint, gen_layout_constraint,\n                         rule_constraint)\n\n\ndef build_center_single():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # Singleton struct\n    struct = Structure(\"Singleton\")\n\n    # Singleton comp\n    comp = Component(\"Grid\")\n\n    # Center_Single layout\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.5, 0.5, 1, 1)], \n                                              num_min=0, \n                                              num_max=0)\n    layout = Layout(\"Center_Single\", layout_constraint, entity_constraint)\n    comp.insert(layout)\n\n    struct.insert(comp)\n    root.insert(struct)\n\n    return root\n\n\ndef build_distribute_four():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # Singleton struct\n    struct = Structure(\"Singleton\")\n\n    # Singleton comp\n    comp = Component(\"Grid\")\n\n    # Distribute_Four\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\",\n                                              [(0.25, 0.25, 0.5, 0.5),\n                                               (0.25, 0.75, 0.5, 0.5),\n                                               (0.75, 0.25, 0.5, 0.5),\n                                               (0.75, 0.75, 0.5, 0.5)],\n                                              num_min=0,\n                                              num_max=3)\n    layout = Layout(\"Distribute_Four\", layout_constraint, entity_constraint)\n    comp.insert(layout)\n\n    struct.insert(comp)\n    root.insert(struct)\n\n    return root\n\n\ndef build_distribute_nine():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # Singleton struct\n    struct = Structure(\"Singleton\")\n\n    # Singleton comp\n    comp = Component(\"Grid\")\n\n    # Distribute_Nine\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.16, 0.16, 0.33, 0.33),\n                                               (0.16, 0.5, 0.33, 0.33),\n                                               (0.16, 0.83, 0.33, 0.33),\n                                               (0.5, 0.16, 0.33, 0.33),\n                                               (0.5, 0.5, 0.33, 0.33),\n                                               (0.5, 0.83, 0.33, 0.33),\n                                               (0.83, 0.16, 0.33, 0.33),\n                                               (0.83, 0.5, 0.33, 0.33),\n                                               (0.83, 0.83, 0.33, 0.33)],\n                                              num_min=0,\n                                              num_max=8)\n    layout = Layout(\"Distribute_Nine\", layout_constraint, entity_constraint)\n    comp.insert(layout)\n\n    struct.insert(comp)\n    root.insert(struct)\n    \n    return root\n\n\ndef build_left_center_single_right_center_single():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # Left-Right Structure\n    struct = Structure(\"Left_Right\")\n\n    # Left Component\n    comp_left = Component(\"Left\")\n\n    # Left_Center_Single\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.5, 0.25, 0.5, 0.5)], \n                                              num_min=0, \n                                              num_max=0)\n    layout = Layout(\"Left_Center_Single\", layout_constraint, entity_constraint)\n    comp_left.insert(layout)\n\n    # Right Component\n    comp_right = Component(\"Right\")\n\n    # Right_Center_Single\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.5, 0.75, 0.5, 0.5)], \n                                              num_min=0, \n                                              num_max=0)\n    layout = Layout(\"Right_Center_Single\", layout_constraint, entity_constraint)\n    comp_right.insert(layout)\n\n    struct.insert(comp_left)\n    struct.insert(comp_right)\n    root.insert(struct)\n    \n    return root\n\n\ndef build_up_center_single_down_center_single():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # Up-Down Structure\n    struct = Structure(\"Up_Down\")\n\n    # Left Component\n    comp_up = Component(\"Up\")\n\n    # Up_Center_Single\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.25, 0.5, 0.5, 0.5)], \n                                              num_min=0, \n                                              num_max=0)\n    layout = Layout(\"Up_Center_Single\", layout_constraint, entity_constraint)\n    comp_up.insert(layout)\n\n    # Down Component\n    comp_down = Component(\"Down\")\n\n    # Down_Center_Single\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\", \n                                              [(0.75, 0.5, 0.5, 0.5)], \n                                              num_min=0, \n                                              num_max=0)\n    layout = Layout(\"Down_Center_Single\", layout_constraint, entity_constraint)\n    comp_down.insert(layout)\n\n    struct.insert(comp_up)\n    struct.insert(comp_down)\n    root.insert(struct)\n    \n    return root\n\n\ndef build_in_center_single_out_center_single():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # In-Out Structure\n    struct = Structure(\"Out_In\")\n\n    # Out Component \n    comp_out = Component(\"Out\")\n\n    # Out_One\n    entity_constraint = gen_entity_constraint(type_min=1, \n                                              size_min=3,\n                                              color_max=0)\n    layout_constraint = gen_layout_constraint(\"planar\",\n                                              [(0.5, 0.5, 1, 1)],\n                                              num_min=0,\n                                              num_max=0)\n    layout = Layout(\"Out_Center_Single\", layout_constraint, entity_constraint)\n    comp_out.insert(layout)\n\n    # In Component\n    comp_in = Component(\"In\")\n\n    # In_Center_Single\n    entity_constraint = gen_entity_constraint(type_min=1)\n    layout_constraint = gen_layout_constraint(\"planar\",\n                                              [(0.5, 0.5, 0.33, 0.33)],\n                                              num_min=0,\n                                              num_max=0)\n    layout = Layout(\"In_Center_Single\", layout_constraint, entity_constraint)\n    comp_in.insert(layout)\n\n    struct.insert(comp_out)\n    struct.insert(comp_in)\n    root.insert(struct)\n\n    return root\n\n\ndef build_in_distribute_four_out_center_single():\n    # Build AoT here\n    root = Root(\"Scene\")\n\n    # In-Out Structure\n    struct = Structure(\"Out_In\")\n\n    # Out Component \n    comp_out = Component(\"Out\")\n\n    # Out_One\n    entity_constraint = gen_entity_constraint(type_min=1, \n                                              size_min=3,\n                                              color_max=0)\n    layout_constraint = gen_layout_constraint(\"planar\",\n                                              [(0.5, 0.5, 1, 1)],\n                                              num_min=0,\n                                              num_max=0)\n    layout = Layout(\"Out_Center_Single\", layout_constraint, entity_constraint)\n    comp_out.insert(layout)\n\n    # In Component\n    comp_in = Component(\"In\")\n\n    # In_Four\n    entity_constraint = gen_entity_constraint(type_min=1, size_min=2)\n    layout_constraint = gen_layout_constraint(\"planar\",\n                                              [(0.42, 0.42, 0.15, 0.15),\n                                               (0.42, 0.58, 0.15, 0.15),\n                                               (0.58, 0.42, 0.15, 0.15),\n                                               (0.58, 0.58, 0.15, 0.15)],\n                                              num_min=0,\n                                              num_max=3)\n    layout = Layout(\"In_Distribute_Four\", layout_constraint, entity_constraint)\n    comp_in.insert(layout)\n\n    struct.insert(comp_out)\n    struct.insert(comp_in)\n    root.insert(struct)\n\n    return root"
  },
  {
    "path": "src/dataset/const.py",
    "content": "# -*- coding: utf-8 -*-\n\n\n# Maximum number of components in a RPM\nMAX_COMPONENTS = 2\n\n# Canvas parameters\nIMAGE_SIZE = 160\nCENTER = (IMAGE_SIZE / 2, IMAGE_SIZE / 2)\nDEFAULT_RADIUS = IMAGE_SIZE / 4\nDEFAULT_WIDTH = 2\n\n# Attribute parameters\n# Number\nNUM_VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nNUM_MIN = 0\nNUM_MAX = len(NUM_VALUES) - 1\n\n# Uniformity\nUNI_VALUES = [False, False, False, True]\nUNI_MIN = 0\nUNI_MAX = len(UNI_VALUES) - 1\n\n# Type\nTYPE_VALUES = [\"none\", \"triangle\", \"square\", \"pentagon\", \"hexagon\", \"circle\"]\nTYPE_MIN = 0\nTYPE_MAX = len(TYPE_VALUES) - 1\n\n# Size\nSIZE_VALUES = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nSIZE_MIN = 0\nSIZE_MAX = len(SIZE_VALUES) - 1\n\n# Color\nCOLOR_VALUES = [255, 224, 196, 168, 140, 112, 84, 56, 28, 0]\nCOLOR_MIN = 0\nCOLOR_MAX = len(COLOR_VALUES) - 1\n\n# Angle: self-rotation\nANGLE_VALUES = [-135, -90, -45, 0, 45, 90, 135, 180]\nANGLE_MIN = 0\nANGLE_MAX = len(ANGLE_VALUES) - 1\n\nMETA_TARGET_FORMAT = [\"Constant\", \"Progression\", \"Arithmetic\", \"Distribute_Three\", \"Number\", \"Position\", \"Type\", \"Size\", \"Color\"]\nMETA_STRUCTURE_FORMAT = [\"Singleton\", \"Left_Right\", \"Up_Down\", \"Out_In\", \"Left\", \"Right\", \"Up\", \"Down\", \"Out\", \"In\", \"Grid\", \"Center_Single\", \"Distribute_Four\", \"Distribute_Nine\", \"Left_Center_Single\", \"Right_Center_Single\", \"Up_Center_Single\", \"Down_Center_Single\", \"Out_Center_Single\", \"In_Center_Single\", \"In_Distribute_Four\"]\n\n# Rule, Attr, Param\n# The design encodes rule priority order: Number/Position always comes first\n# Number and Position could not both be sampled\n# Progression on Number: Number on each Panel +1/2 or -1/2\n# Progression on Position: Entities on each Panel roll over the layout\n# Arithmetic on Number: Numeber on the third Panel = Number on first +/- Number on second (1 for + and -1 for -)\n# Arithmetic on Position: 1 for SET_UNION and -1 for SET_DIFF\n# Distribute_Three on Number: Three numbers through each row\n# Distribute_Three on Position: Three positions (same number) through each row\n# Constant on Number/Position: Nothing changes\n# Progression on Type: Type progression defined as the number of edges on each entity (Triangle, Square, Pentagon, Hexagon, Circle)\n# Distribute_Three on Type: Three types through each row\n# Constant on Type: Nothing changes\n# Progression on Size: Size on each entity +1/2 or -1/2\n# Arithmetic on Size: Size on the third Panel = Size on the first +/- Size on the second (1 for + and -1 for -)\n# Distribute_Three on Size: Three sizes through each row\n# Constant on Size: Nothing changes\n# Progression on Color: Color +1/2 or -1/2\n# Arithmetic on Color: Color on the third Panel = Color on the first +/- Color on the second (1 for + and -1 for -)\n# Distribute_Three on Color: Three colors through each row\n# Constant on Color: Nothing changes\n# Note that all rules on Type, Size and Color enforce value consistency in a panel\nRULE_ATTR = [[[\"Progression\", \"Number\", [-2, -1, 1, 2]], \n              [\"Progression\", \"Position\", [-2, -1, 1, 2]], \n              [\"Arithmetic\", \"Number\", [1, -1]],\n              [\"Arithmetic\", \"Position\", [1, -1]],\n              [\"Distribute_Three\", \"Number\", None],\n              [\"Distribute_Three\", \"Position\", None],\n              [\"Constant\", \"Number/Position\", None]],\n             [[\"Progression\", \"Type\", [-2, -1, 1, 2]],\n              [\"Distribute_Three\", \"Type\", None], \n              [\"Constant\", \"Type\", None]],\n             [[\"Progression\", \"Size\", [-2, -1, 1, 2]],\n              [\"Arithmetic\", \"Size\", [1, -1]],\n              [\"Distribute_Three\", \"Size\", None],\n              [\"Constant\", \"Size\", None]],\n             [[\"Progression\", \"Color\", [-2, -1, 1, 2]],\n              [\"Arithmetic\", \"Color\", [1, -1]],\n              [\"Distribute_Three\", \"Color\", None],\n              [\"Constant\", \"Color\", None]]]\n"
  },
  {
    "path": "src/dataset/constraints.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nfrom const import (ANGLE_MAX, ANGLE_MIN, COLOR_MAX, COLOR_MIN, NUM_MAX,\n                   NUM_MIN, SIZE_MAX, SIZE_MIN, TYPE_MAX, TYPE_MIN, UNI_MAX,\n                   UNI_MIN)\n\n\ndef gen_layout_constraint(pos_type, pos_list, \n                          num_min=NUM_MIN, num_max=NUM_MAX,\n                          uni_min=UNI_MIN, uni_max=UNI_MAX):\n    constraint = {\"Number\": [num_min, num_max],\n                  \"Position\": [pos_type, pos_list[:]],\n                  \"Uni\": [uni_min, uni_max]}\n    return constraint\n\n\ndef gen_entity_constraint(type_min=TYPE_MIN, type_max=TYPE_MAX, \n                          size_min=SIZE_MIN, size_max=SIZE_MAX, \n                          color_min=COLOR_MIN, color_max=COLOR_MAX,\n                          angle_min=ANGLE_MIN, angle_max=ANGLE_MAX):\n    constraint = {\"Type\": [type_min, type_max],\n                  \"Size\": [size_min, size_max],\n                  \"Color\": [color_min, color_max],\n                  \"Angle\": [angle_min, angle_max]}\n    return constraint\n\n\ndef rule_constraint(rule_list, num_min, num_max, \n                               uni_min, uni_max,\n                               type_min, type_max,\n                               size_min, size_max,\n                               color_min, color_max):\n    \"\"\"Generate constraints given the rules and the original constraints \n    from layout and entity. Note that each attribute has at most one rule\n    applied on it.\n    Arguments:\n        rule_list(ordered list of Rule): all rules applied to this layout\n        others (int): boundary levels for each attribute in a layout; note that\n            num_max + 1 == len(layout.position.values)\n    Returns:\n        layout_constraint(dict): a new layout constraint\n        entity_constraint(dict): a new entity constraint\n    \"\"\"\n    assert len(rule_list) > 0\n    for rule in rule_list:\n        if rule.name == \"Progression\":\n            # rule.value: add/sub how many levels\n            if rule.attr == \"Number\":\n                if rule.value > 0:\n                    num_max = num_max - rule.value * 2\n                else:\n                    num_min = num_min - rule.value * 2\n            if rule.attr == \"Position\":\n                # Progression here means moving in Layout slots in order\n                abs_value = abs(rule.value)\n                num_max = num_max - abs_value * 2\n            if rule.attr == \"Type\":\n                if rule.value > 0:\n                    type_max = type_max - rule.value * 2\n                else:\n                    type_min = type_min - rule.value * 2\n            if rule.attr == \"Size\":\n                if rule.value > 0:\n                    size_max = size_max - rule.value * 2\n                else:\n                    size_min = size_min - rule.value * 2\n            if rule.attr == \"Color\":\n                if rule.value > 0:\n                    color_max = color_max - rule.value * 2\n                else:\n                    color_min = color_min - rule.value * 2\n        if rule.name == \"Arithmetic\":\n            # rule.value > 0 if add col_0 + col_1\n            # rule.value < 0 if sub col_0 - col_1\n            if rule.attr == \"Number\":\n                if rule.value > 0:\n                    num_max = num_max - num_min - 1\n                else:\n                    num_min = 2 * num_min + 1\n            if rule.attr == \"Position\":\n                # SET_UNION\n                # at least two position configurations\n                if rule.value > 0:\n                    num_max = num_max - 1\n                # num_min makes sure of overlap\n                # at least two configurations\n                # SET_DIFF\n                else:\n                    num_min = (num_max + 2) / 2 - 1\n                    num_max = num_max - 1\n            if rule.attr == \"Size\":\n                if rule.value > 0:\n                    size_max = size_max - size_min - 1\n                else:\n                    size_min = 2 * size_min + 1\n            if rule.attr == \"Color\":\n                # at least two different colors\n                if color_max - color_min < 1:\n                    color_max = color_min - 1\n                else:\n                    if rule.value > 0:\n                        color_max = color_max - color_min\n                    if rule.value < 0:\n                        color_min = 2 * color_min\n        if rule.name == \"Distribute_Three\":\n            # if less than 3 values, invalidate it\n            if rule.attr == \"Number\":\n                if num_max - num_min + 1 < 3:\n                    num_max = num_min - 1\n            if rule.attr == \"Position\":\n                # max number allowed in the layout should be >= 3\n                if num_max + 1 < 3:\n                    num_max = num_min - 1\n                # num_max + 1 == len(layout.position.values)\n                # C_{num_max + 1}^{num_value} >= 3\n                # C_{num_max + 1} = num_max + 1 >= 3\n                # hence only need to constrain num_max: num_max = num_max - 1\n                # Check Yang Hui’s Triangle (Pascal's Triangle): https://www.varsitytutors.com/hotmath/hotmath_help/topics/yang-huis-triangle\n                else:\n                    num_max = num_max - 1\n            if rule.attr == \"Type\":\n                if type_max - type_min + 1 < 3:\n                    type_max = type_min - 1\n            if rule.attr == \"Size\":\n                if size_max - size_min + 1 < 3:\n                    size_max = size_min - 1\n            if rule.attr == \"Color\":\n                if color_max - color_min + 1 < 3:\n                    color_max = color_min - 1\n        \n    return gen_layout_constraint(None, [], \n                                 num_min, num_max, \n                                 uni_min, uni_max), \\\n           gen_entity_constraint(type_min, type_max, \n                                 size_min, size_max, \n                                 color_min, color_max)\n"
  },
  {
    "path": "src/dataset/main.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport argparse\nimport copy\nimport os\nimport random\nimport sys\n\nimport numpy as np\nfrom tqdm import trange\n\nfrom build_tree import (build_center_single, build_distribute_four,\n                        build_distribute_nine,\n                        build_in_center_single_out_center_single,\n                        build_in_distribute_four_out_center_single,\n                        build_left_center_single_right_center_single,\n                        build_up_center_single_down_center_single)\nfrom const import IMAGE_SIZE, RULE_ATTR\nfrom rendering import (generate_matrix, generate_matrix_answer, imsave, imshow,\n                       render_panel)\nfrom Rule import Rule_Wrapper\nfrom sampling import sample_attr, sample_attr_avail, sample_rules\nfrom serialize import dom_problem, serialize_aot, serialize_rules\nfrom solver import solve\n\n\ndef merge_component(dst_aot, src_aot, component_idx):\n    src_component = src_aot.children[0].children[component_idx]\n    dst_aot.children[0].children[component_idx] = src_component\n\n\ndef fuse(args, all_configs):\n    random.seed(args.seed)\n    np.random.seed(args.seed)\n\n    acc = 0\n    for k in trange(args.num_samples * len(all_configs)):\n        if k < args.num_samples * (1 - args.val - args.test):\n            set_name = \"train\"\n        elif k < args.num_samples * (1 - args.test):\n            set_name = \"val\"\n        else:\n            set_name = \"test\"\n        \n        tree_name = random.choice(all_configs.keys())\n        root = all_configs[tree_name]\n        while True:\n            rule_groups = sample_rules()\n            new_root = root.prune(rule_groups)    \n            if new_root is not None:\n                break\n        \n        start_node = new_root.sample()\n\n        row_1_1 = copy.deepcopy(start_node)\n        for l in range(len(rule_groups)):\n            rule_group = rule_groups[l]\n            rule_num_pos = rule_group[0]\n            row_1_2 = rule_num_pos.apply_rule(row_1_1)\n            row_1_3 = rule_num_pos.apply_rule(row_1_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_1_2 = rule.apply_rule(row_1_1, row_1_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_1_3 = rule.apply_rule(row_1_2, row_1_3)\n            if l == 0:\n                to_merge = [row_1_1, row_1_2, row_1_3]\n            else:\n                merge_component(to_merge[1], row_1_2, l)\n                merge_component(to_merge[2], row_1_3, l)\n        row_1_1, row_1_2, row_1_3 = to_merge\n\n        row_2_1 = copy.deepcopy(start_node)\n        row_2_1.resample(True)\n        for l in range(len(rule_groups)):\n            rule_group = rule_groups[l]\n            rule_num_pos = rule_group[0]\n            row_2_2 = rule_num_pos.apply_rule(row_2_1)\n            row_2_3 = rule_num_pos.apply_rule(row_2_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_2_2 = rule.apply_rule(row_2_1, row_2_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_2_3 = rule.apply_rule(row_2_2, row_2_3)\n            if l == 0:\n                to_merge = [row_2_1, row_2_2, row_2_3]\n            else:\n                merge_component(to_merge[1], row_2_2, l)\n                merge_component(to_merge[2], row_2_3, l)\n        row_2_1, row_2_2, row_2_3 = to_merge\n\n        row_3_1 = copy.deepcopy(start_node)\n        row_3_1.resample(True)\n        for l in range(len(rule_groups)):\n            rule_group = rule_groups[l]\n            rule_num_pos = rule_group[0]\n            row_3_2 = rule_num_pos.apply_rule(row_3_1)\n            row_3_3 = rule_num_pos.apply_rule(row_3_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_3_2 = rule.apply_rule(row_3_1, row_3_2)\n            for i in range(1, len(rule_group)):\n                rule = rule_group[i]\n                row_3_3 = rule.apply_rule(row_3_2, row_3_3)\n            if l == 0:\n                to_merge = [row_3_1, row_3_2, row_3_3]\n            else:\n                merge_component(to_merge[1], row_3_2, l)\n                merge_component(to_merge[2], row_3_3, l)\n        row_3_1, row_3_2, row_3_3 = to_merge\n\n        imgs = [render_panel(row_1_1),\n                render_panel(row_1_2),\n                render_panel(row_1_3),\n                render_panel(row_2_1),\n                render_panel(row_2_2),\n                render_panel(row_2_3),\n                render_panel(row_3_1),\n                render_panel(row_3_2),\n                np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)]\n        context = [row_1_1, row_1_2, row_1_3, row_2_1, row_2_2, row_2_3, row_3_1, row_3_2]\n\n        modifiable_attr = sample_attr_avail(rule_groups, row_3_3)\n        answer_AoT = copy.deepcopy(row_3_3)\n        candidates = [answer_AoT]\n        for j in range(7):\n            component_idx, attr_name, min_level, max_level = sample_attr(modifiable_attr)\n            answer_j = copy.deepcopy(answer_AoT)\n            answer_j.sample_new(component_idx, attr_name, min_level, max_level, answer_AoT)\n            candidates.append(answer_j)\n\n        random.shuffle(candidates)\n        answers = []\n        for candidate in candidates:\n            answers.append(render_panel(candidate))\n        # imsave(generate_matrix_answer(imgs + answers), \"./experiments/fuse/{}.jpg\".format(k))\n\n        image = imgs[0:8] + answers\n        target = candidates.index(answer_AoT)\n        predicted = solve(rule_groups, context, candidates)\n        meta_matrix, meta_target = serialize_rules(rule_groups)\n        structure, meta_structure = serialize_aot(start_node)\n        np.savez(\"{}/RAVEN_{}_{}.npz\".format(args.save_dir, k, set_name), image=image, \n                                                                          target=target,\n                                                                          predict=predicted, \n                                                                          meta_matrix=meta_matrix,\n                                                                          meta_target=meta_target, \n                                                                          structure=structure,\n                                                                          meta_structure=meta_structure)\n        with open(\"{}/RAVEN_{}_{}.xml\".format(args.save_dir, k, set_name), \"w\") as f:\n            dom = dom_problem(context + candidates, rule_groups)\n            f.write(dom)\n        if target == predicted:\n            acc += 1\n    print \"Accuracy: {}\".format(float(acc) / (args.num_samples * len(all_configs)))\n\n\ndef separate(args, all_configs):\n    random.seed(args.seed)\n    np.random.seed(args.seed)\n\n    for key in all_configs.keys():\n        acc = 0\n        for k in trange(args.num_samples):\n            count_num = k % 10\n            if count_num < (10 - args.val - args.test):\n                set_name = \"train\"\n            elif count_num < (10 - args.test):\n                set_name = \"val\"\n            else:\n                set_name = \"test\"\n\n            root = all_configs[key]\n            while True:\n                rule_groups = sample_rules()\n                new_root = root.prune(rule_groups)    \n                if new_root is not None:\n                    break\n            \n            start_node = new_root.sample()\n\n            row_1_1 = copy.deepcopy(start_node)\n            for l in range(len(rule_groups)):\n                rule_group = rule_groups[l]\n                rule_num_pos = rule_group[0]\n                row_1_2 = rule_num_pos.apply_rule(row_1_1)\n                row_1_3 = rule_num_pos.apply_rule(row_1_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_1_2 = rule.apply_rule(row_1_1, row_1_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_1_3 = rule.apply_rule(row_1_2, row_1_3)\n                if l == 0:\n                    to_merge = [row_1_1, row_1_2, row_1_3]\n                else:\n                    merge_component(to_merge[1], row_1_2, l)\n                    merge_component(to_merge[2], row_1_3, l)\n            row_1_1, row_1_2, row_1_3 = to_merge\n\n            row_2_1 = copy.deepcopy(start_node)\n            row_2_1.resample(True)\n            for l in range(len(rule_groups)):\n                rule_group = rule_groups[l]\n                rule_num_pos = rule_group[0]\n                row_2_2 = rule_num_pos.apply_rule(row_2_1)\n                row_2_3 = rule_num_pos.apply_rule(row_2_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_2_2 = rule.apply_rule(row_2_1, row_2_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_2_3 = rule.apply_rule(row_2_2, row_2_3)\n                if l == 0:\n                    to_merge = [row_2_1, row_2_2, row_2_3]\n                else:\n                    merge_component(to_merge[1], row_2_2, l)\n                    merge_component(to_merge[2], row_2_3, l)\n            row_2_1, row_2_2, row_2_3 = to_merge\n\n            row_3_1 = copy.deepcopy(start_node)\n            row_3_1.resample(True)\n            for l in range(len(rule_groups)):\n                rule_group = rule_groups[l]\n                rule_num_pos = rule_group[0]\n                row_3_2 = rule_num_pos.apply_rule(row_3_1)\n                row_3_3 = rule_num_pos.apply_rule(row_3_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_3_2 = rule.apply_rule(row_3_1, row_3_2)\n                for i in range(1, len(rule_group)):\n                    rule = rule_group[i]\n                    row_3_3 = rule.apply_rule(row_3_2, row_3_3)\n                if l == 0:\n                    to_merge = [row_3_1, row_3_2, row_3_3]\n                else:\n                    merge_component(to_merge[1], row_3_2, l)\n                    merge_component(to_merge[2], row_3_3, l)\n            row_3_1, row_3_2, row_3_3 = to_merge\n\n            imgs = [render_panel(row_1_1),\n                    render_panel(row_1_2),\n                    render_panel(row_1_3),\n                    render_panel(row_2_1),\n                    render_panel(row_2_2),\n                    render_panel(row_2_3),\n                    render_panel(row_3_1),\n                    render_panel(row_3_2),\n                    np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)]\n            context = [row_1_1, row_1_2, row_1_3, row_2_1, row_2_2, row_2_3, row_3_1, row_3_2]\n            modifiable_attr = sample_attr_avail(rule_groups, row_3_3)\n            answer_AoT = copy.deepcopy(row_3_3)\n            candidates = [answer_AoT]\n            for j in range(7):\n                component_idx, attr_name, min_level, max_level = sample_attr(modifiable_attr)\n                answer_j = copy.deepcopy(answer_AoT)\n                answer_j.sample_new(component_idx, attr_name, min_level, max_level, answer_AoT)\n                candidates.append(answer_j)\n\n            random.shuffle(candidates)\n            answers = []\n            for candidate in candidates:\n                answers.append(render_panel(candidate))\n            # imsave(generate_matrix_answer(imgs + answers), \"./experiments/{}/{}.jpg\".format(key, k))    \n            \n            image = imgs[0:8] + answers\n            target = candidates.index(answer_AoT)\n            predicted = solve(rule_groups, context, candidates)\n            meta_matrix, meta_target = serialize_rules(rule_groups)\n            structure, meta_structure = serialize_aot(start_node)\n            np.savez(\"{}/{}/RAVEN_{}_{}.npz\".format(args.save_dir, key, k, set_name), image=image, \n                                                                                      target=target, \n                                                                                      predict=predicted,\n                                                                                      meta_matrix=meta_matrix,\n                                                                                      meta_target=meta_target, \n                                                                                      structure=structure,\n                                                                                      meta_structure=meta_structure)\n            with open(\"{}/{}/RAVEN_{}_{}.xml\".format(args.save_dir, key, k, set_name), \"w\") as f:\n                dom = dom_problem(context + candidates, rule_groups)\n                f.write(dom)\n            \n            if target == predicted:\n                acc += 1\n        print \"Accuracy of {}: {}\".format(key, float(acc) / args.num_samples)\n\n\ndef main():\n    main_arg_parser = argparse.ArgumentParser(description=\"parser for RAVEN\")\n    main_arg_parser.add_argument(\"--num-samples\", type=int, default=20000,\n                                 help=\"number of samples for each component configuration\")\n    main_arg_parser.add_argument(\"--save-dir\", type=str, default=\"~/Datasets/\",\n                                 help=\"path to folder where the generated dataset will be saved.\")\n    main_arg_parser.add_argument(\"--seed\", type=int, default=1234,\n                                 help=\"random seed for dataset generation\")\n    main_arg_parser.add_argument(\"--fuse\", type=int, default=0,\n                                 help=\"whether to fuse different configurations\")\n    main_arg_parser.add_argument(\"--val\", type=float, default=2,\n                                 help=\"the proportion of the size of validation set\")\n    main_arg_parser.add_argument(\"--test\", type=float, default=2,\n                                 help=\"the proportion of the size of test set\")                             \n    args = main_arg_parser.parse_args()\n\n    all_configs = {\"center_single\": build_center_single(),\n                   \"distribute_four\": build_distribute_four(),\n                   \"distribute_nine\": build_distribute_nine(),\n                   \"left_center_single_right_center_single\": build_left_center_single_right_center_single(),\n                   \"up_center_single_down_center_single\": build_up_center_single_down_center_single(),\n                   \"in_center_single_out_center_single\": build_in_center_single_out_center_single(),\n                   \"in_distribute_four_out_center_single\": build_in_distribute_four_out_center_single()}\n\n    if not os.path.exists(args.save_dir):\n        os.mkdir(args.save_dir)\n    if args.fuse:\n        if not os.path.exists(os.path.join(args.save_dir, \"fuse\")):\n            os.mkdir(os.path.join(args.save_dir, \"fuse\"))\n        fuse(args, all_configs)\n    else:\n        for key in all_configs.keys():\n            if not os.path.exists(os.path.join(args.save_dir, key)):\n                os.mkdir(os.path.join(args.save_dir, key))\n        separate(args, all_configs)\n    \n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/dataset/rendering.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport cv2\nimport numpy as np\nfrom PIL import Image\n\nfrom AoT import Root\nfrom const import CENTER, DEFAULT_WIDTH, IMAGE_SIZE\n\n\ndef imshow(array):\n    image = Image.fromarray(array)\n    image.show()\n\n\ndef imsave(array, filepath):\n    image = Image.fromarray(array)\n    image.save(filepath)\n\n\ndef generate_matrix(array_list):\n    # row-major array_list\n    assert len(array_list) <= 9\n    img_grid = np.zeros((IMAGE_SIZE * 3, IMAGE_SIZE * 3), np.uint8)\n    for idx in range(len(array_list)):\n        i, j = divmod(idx, 3)\n        img_grid[i * IMAGE_SIZE:(i + 1) * IMAGE_SIZE, j * IMAGE_SIZE:(j + 1) * IMAGE_SIZE] = array_list[idx]\n    # draw grid\n    for x in [0.33, 0.67]:\n        img_grid[int(x * IMAGE_SIZE * 3) - 1:int(x * IMAGE_SIZE * 3) + 1, :] = 0\n    for y in [0.33, 0.67]:\n        img_grid[:, int(y * IMAGE_SIZE * 3) - 1:int(y * IMAGE_SIZE * 3) + 1] = 0\n    return img_grid\n\n\ndef generate_answers(array_list):\n    assert len(array_list) <= 8\n    img_grid = np.zeros((IMAGE_SIZE * 2, IMAGE_SIZE * 4), np.uint8)\n    for idx in range(len(array_list)):\n        i, j = divmod(idx, 4)\n        img_grid[i * IMAGE_SIZE:(i + 1) * IMAGE_SIZE, j * IMAGE_SIZE:(j + 1) * IMAGE_SIZE] = array_list[idx]\n    # draw grid\n    for x in [0.5]:\n        img_grid[int(x * IMAGE_SIZE * 2) - 1:int(x * IMAGE_SIZE * 2) + 1, :] = 0\n    for y in [0.25, 0.5, 0.75]:\n        img_grid[:, int(y * IMAGE_SIZE * 4) - 1:int(y * IMAGE_SIZE * 4) + 1] = 0\n    return img_grid\n\n\ndef generate_matrix_answer(array_list):\n    # row-major array_list\n    assert len(array_list) <= 18\n    img_grid = np.zeros((IMAGE_SIZE * 6, IMAGE_SIZE * 3), np.uint8)\n    for idx in range(len(array_list)):\n        i, j = divmod(idx, 3)\n        img_grid[i * IMAGE_SIZE:(i + 1) * IMAGE_SIZE, j * IMAGE_SIZE:(j + 1) * IMAGE_SIZE] = array_list[idx]\n    # draw grid\n    for x in [0.33, 0.67, 1.00, 1.33, 1.67]:\n        img_grid[int(x * IMAGE_SIZE * 3), :] = 0\n    for y in [0.33, 0.67]:\n        img_grid[:, int(y * IMAGE_SIZE * 3)] = 0\n    return img_grid\n\n\ndef merge_matrix_answer(matrix, answer):\n    matrix_image = generate_matrix(matrix)\n    answer_image = generate_answers(answer)\n    img_grid = np.ones((IMAGE_SIZE * 5 + 20, IMAGE_SIZE * 4), np.uint8) * 255\n    img_grid[:IMAGE_SIZE * 3, int(0.5 * IMAGE_SIZE):int(3.5 * IMAGE_SIZE)] = matrix_image\n    img_grid[-(IMAGE_SIZE * 2):, :] = answer_image\n    return img_grid\n\ndef render_panel(root):\n    # Decompose the panel into a structure and its entities\n    assert isinstance(root, Root)\n    canvas = np.ones((IMAGE_SIZE, IMAGE_SIZE), np.uint8) * 255\n    structure, entities = root.prepare()\n    structure_img = render_structure(structure)\n    background = np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)\n    # note left components entities are in the lower layer\n    for entity in entities:\n        entity_img = render_entity(entity)\n        background = layer_add(background, entity_img)\n    background = layer_add(background, structure_img)\n    return canvas - background\n\n\ndef render_structure(structure_name):\n    ret = None\n    if structure_name == \"Left_Right\":\n        ret = np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)\n        ret[:, int(0.5 * IMAGE_SIZE)] = 255.0\n    elif structure_name == \"Up_Down\":\n        ret = np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)\n        ret[int(0.5 * IMAGE_SIZE), :] = 255.0\n    else:\n        ret = np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)\n    return ret\n\n\ndef render_entity(entity):\n    entity_bbox = entity.bbox\n    entity_type = entity.type.get_value()\n    entity_size = entity.size.get_value()\n    entity_color = entity.color.get_value()\n    entity_angle = entity.angle.get_value()\n    img = np.zeros((IMAGE_SIZE, IMAGE_SIZE), np.uint8)\n\n    # planar position: [x, y, w, h]\n    # angular position: [x, y, w, h, x_c, y_c, omega]\n    # center: (columns, rows)\n    center = (int(entity_bbox[1] * IMAGE_SIZE), int(entity_bbox[0] * IMAGE_SIZE))\n    if entity_type == \"triangle\":\n        unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n        dl = int(unit * entity_size)\n        pts = np.array([[center[0], center[1] - dl], \n                        [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0)], \n                        [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0)]], \n                       np.int32)\n        pts = pts.reshape((-1, 1, 2))\n        color = 255 - entity_color\n        width = DEFAULT_WIDTH\n        draw_triangle(img, pts, color, width)\n    elif entity_type == \"square\":\n        unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n        dl = int(unit / 2 * np.sqrt(2) * entity_size)\n        pt1 = (center[0] - dl, center[1] - dl)\n        pt2 = (center[0] + dl, center[1] + dl)\n        color = 255 - entity_color\n        width = DEFAULT_WIDTH\n        draw_square(img, pt1, pt2, color, width)\n    elif entity_type == \"pentagon\":\n        unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n        dl = int(unit * entity_size)\n        pts = np.array([[center[0], center[1] - dl],\n                        [center[0] - int(dl * np.cos(np.pi / 10)), center[1] - int(dl * np.sin(np.pi / 10))],\n                        [center[0] - int(dl * np.sin(np.pi / 5)), center[1] + int(dl * np.cos(np.pi / 5))],\n                        [center[0] + int(dl * np.sin(np.pi / 5)), center[1] + int(dl * np.cos(np.pi / 5))],\n                        [center[0] + int(dl * np.cos(np.pi / 10)), center[1] - int(dl * np.sin(np.pi / 10))]],\n                       np.int32)\n        pts = pts.reshape((-1, 1, 2))\n        color = 255 - entity_color\n        width = DEFAULT_WIDTH\n        draw_pentagon(img, pts, color, width)\n    elif entity_type == \"hexagon\":\n        unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n        dl = int(unit * entity_size)\n        pts = np.array([[center[0], center[1] - dl],\n                        [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] - int(dl / 2.0)],\n                        [center[0] - int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0)],\n                        [center[0], center[1] + dl],\n                        [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] + int(dl / 2.0)],\n                        [center[0] + int(dl / 2.0 * np.sqrt(3)), center[1] - int(dl / 2.0)]],\n                       np.int32)\n        pts = pts.reshape((-1, 1, 2))\n        color = 255 - entity_color\n        width = DEFAULT_WIDTH\n        draw_hexagon(img, pts, color, width)\n    elif entity_type == \"circle\":\n        # Minus because of the way we show the image. See: render_panel's return\n        color = 255 - entity_color\n        unit = min(entity_bbox[2], entity_bbox[3]) * IMAGE_SIZE / 2\n        radius = int(unit * entity_size)\n        width = DEFAULT_WIDTH\n        draw_circle(img, center, radius, color, width)\n    elif entity_type == \"none\":\n        pass\n    # angular\n    if len(entity_bbox) > 4:\n        # [x, y, w, h, x_c, y_c, omega]\n        entity_angle = entity_bbox[6]\n        center = (int(entity_bbox[5] * IMAGE_SIZE), int(entity_bbox[4] * IMAGE_SIZE))\n        img = rotate(img, entity_angle, center=center)\n    # planar \n    else:\n        img = rotate(img, entity_angle, center=center)\n    # img = shift(img, *entity_position)\n\n    return img\n\n\ndef shift(img, dx, dy):\n    M = np.array([[1, 0, dx], [0, 1, dy]], np.float32)\n    img = cv2.warpAffine(img, M, (IMAGE_SIZE, IMAGE_SIZE), flags=cv2.INTER_LINEAR)\n    return img\n\n\ndef rotate(img, angle, center=CENTER):\n    M = cv2.getRotationMatrix2D(center, angle, 1)\n    img = cv2.warpAffine(img, M, (IMAGE_SIZE, IMAGE_SIZE), flags=cv2.INTER_LINEAR)\n    return img\n\n\ndef scale(img, tx, ty, center=CENTER):\n    M = np.array([[tx, 0, center[0] * (1 - tx)], [0, ty, center[1] * (1 - ty)]], np.float32)\n    img = cv2.warpAffine(img, M, (IMAGE_SIZE, IMAGE_SIZE), flags=cv2.INTER_LINEAR)\n    return img\n\n\ndef layer_add(lower_layer_np, higher_layer_np):\n    # higher_layer_np is superimposed on lower_layer_np\n    # new_np = lower_layer_np.copy()\n    # lower_layer_np is modified\n    lower_layer_np[higher_layer_np > 0] = 0\n    return lower_layer_np + higher_layer_np\n\n\n# Draw primitives\ndef draw_triangle(img, pts, color, width):\n    # if filled\n    if color != 0:\n        # fill the interior\n        cv2.fillConvexPoly(img, pts, color)\n        # draw the edge\n        cv2.polylines(img, [pts], True, 255, width)\n    # if not filled\n    else:\n        cv2.polylines(img, [pts], True, 255, width)\n\n\ndef draw_square(img, pt1, pt2, color, width):\n    # if filled\n    if color != 0:\n        # fill the interior\n        cv2.rectangle(img,\n                      pt1,\n                      pt2,\n                      color, \n                      -1)\n        # draw the edge\n        cv2.rectangle(img, \n                      pt1,\n                      pt2,\n                      255,\n                      width)\n    # if not filled\n    else:\n        cv2.rectangle(img, \n                      pt1,\n                      pt2,\n                      255,\n                      width)\n\n\ndef draw_pentagon(img, pts, color, width):\n    # if filled\n    if color != 0:\n        # fill the interior\n        cv2.fillConvexPoly(img, pts, color)\n        # draw the edge\n        cv2.polylines(img, [pts], True, 255, width)\n    # if not filled\n    else:\n        cv2.polylines(img, [pts], True, 255, width)\n\n\ndef draw_hexagon(img, pts, color, width):\n    # if filled\n    if color != 0:\n        # fill the interior\n        cv2.fillConvexPoly(img, pts, color)\n        # draw the edge\n        cv2.polylines(img, [pts], True, 255, width)\n    # if not filled\n    else:\n        cv2.polylines(img, [pts], True, 255, width)\n\n\ndef draw_circle(img, center, radius, color, width):\n    # if filled\n    if color != 0:\n        # fill the interior\n        cv2.circle(img,\n                   center,\n                   radius,\n                   color,\n                   -1)\n        # draw the edge\n        cv2.circle(img,\n                   center,\n                   radius,\n                   255,\n                   width)\n    # if not filled\n    else:\n        cv2.circle(img,\n                   center,\n                   radius,\n                   255,\n                   width)\n"
  },
  {
    "path": "src/dataset/sampling.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\nfrom scipy.misc import comb\n\nfrom const import MAX_COMPONENTS, RULE_ATTR\nfrom Rule import Rule_Wrapper\n\n\ndef sample_rules():\n    \"\"\"First sample # components; for each component, sample a rule on each attribute.\n    \"\"\"\n    num_components = np.random.randint(1, MAX_COMPONENTS + 1)\n    all_rules = []\n    for i in range(num_components):\n        all_rules_component = []\n        for j in range(len(RULE_ATTR)):\n            idx = np.random.choice(len(RULE_ATTR[j]))\n            name_attr_param = RULE_ATTR[j][idx]\n            all_rules_component.append(Rule_Wrapper(name_attr_param[0], name_attr_param[1], name_attr_param[2], component_idx=i))\n        all_rules.append(all_rules_component)\n    return all_rules\n\n# pay attention to Position Arithmetic, new entities (resample)\ndef sample_attr_avail(rule_groups, row_3_3):\n    \"\"\"Sample available attributes whose values could be modified.\n    Arguments:\n        rule_groups(list of list of Rule): a list of rules to apply to the component\n        row_3_3(AoTNode): the answer AoT\n    Returns:\n        ret(list of list): [component_idx, attr, available_times, constraints]\n    \"\"\"\n    ret = []\n    for i in range(len(rule_groups)):\n        rule_group = rule_groups[i]\n        start_node_layout = row_3_3.children[0].children[i].children[0]\n        row_3_3_layout = row_3_3.children[0].children[i].children[0]\n        uni = row_3_3_layout.uniformity.get_value()\n        # Number/Position\n        # If Rule on Number: Only change Number\n        # If Rule on Position: Both Number and Position could be changed\n        rule = rule_group[0]\n        num = row_3_3_layout.number.get_value()\n        most_num = len(start_node_layout.position.values)\n        if rule.attr == \"Number\":\n            num_times = 0\n            min_level = start_node_layout.orig_layout_constraint[\"Number\"][0]\n            max_level = start_node_layout.orig_layout_constraint[\"Number\"][1]\n            for k in range(min_level, max_level + 1):\n                if k + 1 != num:\n                    num_times += comb(most_num, k + 1)\n            if num_times > 0:\n                ret.append([i, \"Number\", num_times, min_level, max_level])\n        # Constant or on Position\n        else:\n            num_times = 0\n            min_level = start_node_layout.orig_layout_constraint[\"Number\"][0]\n            max_level = start_node_layout.orig_layout_constraint[\"Number\"][1]\n            for k in range(min_level, max_level + 1):\n                if k + 1 != num:\n                    num_times += comb(most_num, k + 1)\n            if num_times > 0:\n                ret.append([i, \"Number\", num_times, min_level, max_level])\n            pos_times = comb(most_num, row_3_3_layout.number.get_value())\n            pos_times -= 1\n            if pos_times > 0:\n                ret.append([i, \"Position\", pos_times, None, None])\n        # Type, Size, Color\n        for j in range(1, len(rule_group)):\n            rule = rule_group[j]\n            rule_attr = rule.attr\n            min_level = start_node_layout.orig_entity_constraint[rule_attr][0]\n            max_level = start_node_layout.orig_entity_constraint[rule_attr][1] \n            if rule.name == \"Constant\":\n                if uni or rule_group[0].name == \"Constant\" or \\\n                          (rule_group[0].attr == \"Position\" and \n                          (rule_group[0].name == \"Progression\" or rule_group[0].name == \"Distribute_Three\")):\n                    times = max_level - min_level + 1\n                    times = times - 1\n                    if times > 0:\n                        ret.append([i, rule_attr, times, min_level, max_level])\n            else:\n                times = max_level - min_level + 1\n                times = times - 1\n                if times > 0:\n                    ret.append([i, rule_attr, times, min_level, max_level])\n    return ret\n\n\ndef sample_attr(attrs_list):\n    \"\"\"Given the attr_avail list, sample one attribute to modify the value.\n    If the available times becomes zero, delete it.\n    Arguments:\n        attrs_list(list of list): a flat component of available attributes \n            to change the values; consisting of different component indexes\n    \"\"\"\n    attr_idx = np.random.choice(len(attrs_list))\n    component_idx, attr_name, _, min_level, max_level = attrs_list[attr_idx]\n    attrs_list[attr_idx][2] -= 1\n    if attrs_list[attr_idx][2] == 0:\n        del attrs_list[attr_idx]\n    return component_idx, attr_name, min_level, max_level\n"
  },
  {
    "path": "src/dataset/serialize.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport json\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\n\nfrom const import META_STRUCTURE_FORMAT\nfrom api import get_real_bbox, get_mask, rle_encode\n\n\ndef n_tree_serialize(aot):\n    assert aot.is_pg\n    ret = \"\"\n    if aot.level == \"Layout\":\n        return aot.name + \"./\"\n    else:\n        ret += aot.name + \".\"\n        for child in aot.children:\n            x = n_tree_serialize(child)\n            ret += x\n            ret += \".\"\n        ret += \"/\"\n    return ret\n\n\ndef serialize_aot(aot):\n    \"\"\"Meta Structure format\n    META_STRUCTURE_FORMAT provided by const.py\n    \"\"\"    \n    n_tree = n_tree_serialize(aot)\n    meta_structure = np.zeros(len(META_STRUCTURE_FORMAT), np.uint8)\n    split = n_tree.split(\".\")\n    for node in split:\n        try:\n            node_index = META_STRUCTURE_FORMAT.index(node)\n            meta_structure[node_index] = 1\n        except ValueError:\n            continue\n    return split, meta_structure\n\n\ndef serialize_rules(rule_groups):\n    \"\"\"Meta matrix format\n    [\"Constant\", \"Progression\", \"Arithmetic\", \"Distribute_Three\", \"Number\", \"Position\", \"Type\", \"Size\", \"Color\"]\n    \"\"\"\n    meta_matrix = np.zeros((8, 9), np.uint8)\n    counter = 0\n    for rule_group in rule_groups:\n        for rule in rule_group:\n            if rule.name == \"Constant\":\n                meta_matrix[counter, 0] = 1\n            elif rule.name == \"Progression\":\n                meta_matrix[counter, 1] = 1\n            elif rule.name == \"Arithmetic\":\n                meta_matrix[counter, 2] = 1\n            else:\n                meta_matrix[counter, 3] = 1\n            if rule.attr == \"Number/Position\":\n                meta_matrix[counter, 4] = 1\n                meta_matrix[counter, 5] = 1\n            elif rule.attr == \"Number\":\n                meta_matrix[counter, 4] = 1\n            elif rule.attr == \"Position\":\n                meta_matrix[counter, 5] = 1\n            elif rule.attr == \"Type\":\n                meta_matrix[counter, 6] = 1\n            elif rule.attr == \"Size\":\n                meta_matrix[counter, 7] = 1\n            else:\n                meta_matrix[counter, 8] = 1\n            counter += 1\n    return meta_matrix, np.bitwise_or.reduce(meta_matrix)\n\n\ndef dom_problem(instances, rule_groups):\n    data = ET.Element(\"Data\")\n    panels = ET.SubElement(data, \"Panels\")\n    for i in range(len(instances)):\n        panel = instances[i]\n        panel_i = ET.SubElement(panels, \"Panel\")\n        struct = panel.children[0]\n        struct_i = ET.SubElement(panel_i, \"Struct\")\n        struct_i.set(\"name\", struct.name)\n        for j in range(len(struct.children)):\n            component = struct.children[j]\n            component_j = ET.SubElement(struct_i, \"Component\")\n            component_j.set(\"id\", str(j))\n            component_j.set(\"name\", component.name)\n            layout = component.children[0]\n            layout_k = ET.SubElement(component_j, \"Layout\")\n            layout_k.set(\"name\", layout.name)\n            layout_k.set(\"Number\", str(layout.number.get_value_level()))\n            layout_k.set(\"Position\", json.dumps(layout.position.values))\n            layout_k.set(\"Uniformity\", str(layout.uniformity.get_value_level()))\n            for l in range(len(layout.children)):\n                entity = layout.children[l]\n                entity_l = ET.SubElement(layout_k, \"Entity\")\n                entity_bbox = entity.bbox\n                entity_type = entity.type.get_value()\n                entity_size = entity.size.get_value()\n                entity_angle = entity.angle.get_value()\n                entity_l.set(\"bbox\", json.dumps(entity_bbox))\n                entity_l.set(\"real_bbox\", json.dumps(get_real_bbox(entity_bbox, entity_type, entity_size, entity_angle)))\n                entity_l.set(\"mask\", rle_encode(get_mask(entity_bbox, entity_type, entity_size, entity_angle)))\n                entity_l.set(\"Type\", str(entity.type.get_value_level()))\n                entity_l.set(\"Size\", str(entity.size.get_value_level()))\n                entity_l.set(\"Color\", str(entity.color.get_value_level()))\n                entity_l.set(\"Angle\", str(entity.angle.get_value_level()))\n    rules = ET.SubElement(data, \"Rules\")\n    for i in range(len(rule_groups)):\n        rule_group = rule_groups[i]\n        rule_group_i = ET.SubElement(rules, \"Rule_Group\")\n        rule_group_i.set(\"id\", str(i))\n        for rule in rule_group:\n            rule_j = ET.SubElement(rule_group_i, \"Rule\")\n            rule_j.set(\"name\", rule.name)\n            rule_j.set(\"attr\", rule.attr)\n    return ET.tostring(data)\n"
  },
  {
    "path": "src/dataset/solver.py",
    "content": "# -*- coding: utf-8 -*-\n\n\nimport numpy as np\n\n\ndef solve(rule_groups, context, candidates):\n    \"\"\"Search-based Heuristic Solver.\n    Arguments:\n        rule_groups(list of list of Rule): rules that apply to each component\n        context(list of AoTNode): a list of context AoTs in a row-major order;\n            should be of length 8\n        candidates(list of AoTNode): a list of candidate answer AoTs;\n            should be of length 8\n    Returns:\n        ans(int): index of the correct answer in the candidates\n    \"\"\"\n    satisfied = [0] * len(candidates)\n    for i in range(len(candidates)):\n        candidate = candidates[i]\n        # note that rule.component_idx should be the same as j\n        for j in range(len(rule_groups)):\n            rule_group = rule_groups[j]\n            rule_num_pos = rule_group[0]\n            satisfied[i] += check_num_pos(rule_num_pos, context, candidate)\n            regenerate = False\n            if rule_num_pos.attr == \"Number\" or rule_num_pos.name == \"Arithmetic\":\n                regenerate = True\n            rule_type = rule_group[1]\n            satisfied[i] += check_entity(rule_type, context, candidate, \"Type\", regenerate)\n            rule_size = rule_group[2]\n            satisfied[i] += check_entity(rule_size, context, candidate, \"Size\", regenerate)\n            rule_color = rule_group[3]\n            satisfied[i] += check_entity(rule_color, context, candidate, \"Color\", regenerate)\n    satisfied = np.array(satisfied)\n    answer_set = np.where(satisfied == max(satisfied))[0]\n    return np.random.choice(answer_set)\n\n\ndef check_num_pos(rule_num_pos, context, candidate):\n    \"\"\"Check whether Rule on layout attribute is satisfied.\n    Arguments:\n        rule_num_pos(Rule): the rule to check\n        context(list of AoTNode): the 8 context figures \n        candidate(AoTNode): the candidate AoT\n    Returns:\n        ret(int): 0 if failure, 1 if success\n    \"\"\"\n    ret = 0\n    component_idx = rule_num_pos.component_idx\n    row_3_1_layout = context[6].children[0].children[component_idx].children[0]\n    row_3_2_layout = context[7].children[0].children[component_idx].children[0]\n    candidate_layout = candidate.children[0].children[component_idx].children[0]\n    if rule_num_pos.name == \"Constant\":\n        set_row_3_1_pos = set(row_3_1_layout.position.get_value_idx())\n        set_row_3_2_pos = set(row_3_2_layout.position.get_value_idx())\n        set_candidate_pos = set(candidate_layout.position.get_value_idx())\n        # note that set equal only when len(Number) equal and content equal\n        if set_candidate_pos == set_row_3_1_pos and set_candidate_pos == set_row_3_2_pos:\n            ret = 1\n    elif rule_num_pos.name == \"Progression\":\n        if rule_num_pos.attr == \"Number\":\n            row_3_1_num = row_3_1_layout.number.get_value_level()\n            row_3_2_num = row_3_2_layout.number.get_value_level()\n            candidate_num = candidate_layout.number.get_value_level()\n            if row_3_2_num * 2 == row_3_1_num + candidate_num:\n                ret = 1\n        else:\n            row_3_1_pos = row_3_1_layout.position.get_value_idx()\n            row_3_2_pos = row_3_2_layout.position.get_value_idx()\n            candidate_pos = candidate_layout.position.get_value_idx()\n            most_num = len(candidate_layout.position.values)\n            diff = rule_num_pos.value\n            if (set((row_3_1_pos + diff) % most_num) == set(row_3_2_pos)) and \\\n               (set((row_3_2_pos + diff) % most_num) == set(candidate_pos)):\n               ret = 1\n    elif rule_num_pos.name == \"Arithmetic\":\n        mode = rule_num_pos.value\n        if rule_num_pos.attr == \"Number\":\n            row_3_1_num = row_3_1_layout.number.get_value()\n            row_3_2_num = row_3_2_layout.number.get_value()\n            candidate_num = candidate_layout.number.get_value()\n            if mode > 0 and (candidate_num == row_3_1_num + row_3_2_num):\n                ret = 1\n            if mode < 0 and (candidate_num == row_3_1_num - row_3_2_num):\n                ret = 1\n        else:\n            row_3_1_pos = row_3_1_layout.position.get_value_idx()\n            row_3_2_pos = row_3_2_layout.position.get_value_idx()\n            candidate_pos = candidate_layout.position.get_value_idx()\n            if mode > 0 and (set(candidate_pos) == set(row_3_1_pos) | set(row_3_2_pos)):\n                ret = 1\n            if mode < 0 and (set(candidate_pos) == set(row_3_1_pos) - set(row_3_2_pos)):\n                ret = 1\n    else:\n        three_values = rule_num_pos.value_levels[2]\n        if rule_num_pos.attr == \"Number\":\n            row_3_1_num = row_3_1_layout.number.get_value_level()\n            row_3_2_num = row_3_2_layout.number.get_value_level()\n            candidate_num = candidate_layout.number.get_value_level()\n            if row_3_1_num == three_values[0] and \\\n               row_3_2_num == three_values[1] and \\\n               candidate_num == three_values[2]:\n                ret = 1\n        else:\n            row_3_1_pos = row_3_1_layout.position.get_value_idx()\n            row_3_2_pos = row_3_2_layout.position.get_value_idx()\n            candidate_pos = candidate_layout.position.get_value_idx()\n            if set(row_3_1_pos) == set(three_values[0]) and \\\n               set(row_3_2_pos) == set(three_values[1]) and \\\n               set(candidate_pos) == set(three_values[2]):\n                ret = 1\n    return ret\n\n\ndef check_consistency(candidate, attr, component_idx):\n    candidate_layout = candidate.children[0].children[component_idx].children[0]\n    entity_0 = candidate_layout.children[0]\n    attr_name = attr.lower()\n    entity_0_value = getattr(entity_0, attr_name).get_value_level()\n    for i in range(1, len(candidate_layout.children)):\n        entity_i = candidate_layout.children[i]\n        entity_i_value = getattr(entity_i, attr_name).get_value_level()\n        if entity_i_value != entity_0_value:\n            return False\n    return True\n\n\ndef check_entity(rule, context, candidate, attr, regenerate):\n    \"\"\"Check whether Rule on entity attribute is satisfied.\n    Arguments:\n        rule(Rule): the rule to check\n        context(list of AoTNode): the 8 context figures \n        candidate(AoTNode): the candidate AoT\n        attr(str): attribute name\n    Returns:\n        ret(int): 0 if failure, 1 if success\n    \"\"\"\n    ret = 0\n    component_idx = rule.component_idx\n    row_3_1_layout = context[6].children[0].children[component_idx].children[0]\n    row_3_2_layout = context[7].children[0].children[component_idx].children[0]\n    candidate_layout = candidate.children[0].children[component_idx].children[0]\n    uni = candidate_layout.uniformity.get_value()\n    attr_name = attr.lower()\n    if rule.name == \"Constant\":\n        if uni:\n            if check_consistency(candidate, attr, component_idx):\n                if getattr(candidate_layout.children[0], attr_name).get_value_level() == \\\n                   getattr(row_3_2_layout.children[0], attr_name).get_value_level():\n                    ret = 1\n        else:\n            row_3_1_num = row_3_1_layout.number.get_value_level()\n            row_3_2_num = row_3_2_layout.number.get_value_level()\n            candidate_num = candidate_layout.number.get_value_level()\n            if (row_3_1_num == row_3_2_num) and (row_3_2_num == candidate_num):\n                if regenerate:\n                    ret = 1\n                else:\n                    flag = True\n                    for i in range(len(candidate_layout.children)):\n                        if not (getattr(candidate_layout.children[i], attr_name).get_value_level() == \n                                getattr(row_3_2_layout.children[i], attr_name).get_value_level()):\n                            flag = False\n                            break\n                    if flag:\n                        ret = 1\n            else:\n                ret = 1\n    elif rule.name == \"Progression\":\n        if check_consistency(candidate, attr, component_idx):\n            row_3_1_value = getattr(row_3_1_layout.children[0], attr_name).get_value_level()\n            row_3_2_value = getattr(row_3_2_layout.children[0], attr_name).get_value_level()\n            candidate_value = getattr(candidate_layout.children[0], attr_name).get_value_level()\n            if row_3_2_value * 2 == row_3_1_value + candidate_value:\n                ret = 1\n    elif rule.name == \"Arithmetic\":\n        if check_consistency(candidate, attr, component_idx):\n            row_3_1_value = getattr(row_3_1_layout.children[0], attr_name).get_value_level()\n            row_3_2_value = getattr(row_3_2_layout.children[0], attr_name).get_value_level()\n            candidate_value = getattr(candidate_layout.children[0], attr_name).get_value_level()\n            if rule.value > 0:\n                if attr == \"Color\":\n                    if candidate_value == row_3_1_value + row_3_2_value:\n                        ret = 1\n                else:\n                    if candidate_value == row_3_1_value + row_3_2_value + 1:\n                        ret = 1\n            if rule.value < 0:\n                if attr == \"Color\":\n                    if candidate_value == row_3_1_value - row_3_2_value:\n                        ret = 1\n                else:\n                    if candidate_value == row_3_1_value - row_3_2_value - 1:\n                        ret = 1                \n    else:\n        if check_consistency(candidate, attr, component_idx):\n            row_3_1_value = getattr(row_3_1_layout.children[0], attr_name).get_value_level()\n            row_3_2_value = getattr(row_3_2_layout.children[0], attr_name).get_value_level()\n            candidate_value = getattr(candidate_layout.children[0], attr_name).get_value_level()\n            three_values = rule.value_levels[2]\n            if row_3_1_value == three_values[0] and \\\n               row_3_2_value == three_values[1] and \\\n               candidate_value == three_values[2]:\n               ret = 1\n    return ret\n"
  },
  {
    "path": "src/model/__init__.py",
    "content": "\"\"\" RAVEN benchmarking code\n\nAuthor: Chi Zhang\nData: 05/14/2019\nContact: chi.zhang@ucla.edu\n\"\"\""
  },
  {
    "path": "src/model/basic_model.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass BasicModel(nn.Module):\n    def __init__(self, args):\n        super(BasicModel, self).__init__()\n        self.name = args.model\n    \n    def load_model(self, path, epoch):\n        state_dict = torch.load(path+'{}_epoch_{}.pth'.format(self.name, epoch))['state_dict']\n        self.load_state_dict(state_dict)\n\n    def save_model(self, path, epoch, acc, loss):\n        torch.save({'state_dict': self.state_dict(), 'acc': acc, 'loss': loss}, path+'{}_epoch_{}.pth'.format(self.name, epoch))\n\n    def compute_loss(self, output, target, meta_target, meta_structure):\n        pass\n\n    def train_(self, image, target, meta_target, meta_structure, embedding, indicator):\n        self.optimizer.zero_grad()\n        output = self(image, embedding, indicator)\n        loss = self.compute_loss(output, target, meta_target, meta_structure)\n        loss.backward()\n        self.optimizer.step()\n        pred = output[0].data.max(1)[1]\n        correct = pred.eq(target.data).cpu().sum().numpy()\n        accuracy = correct * 100.0 / target.size()[0]\n        return loss.item(), accuracy\n\n    def validate_(self, image, target, meta_target, meta_structure, embedding, indicator):\n        with torch.no_grad():\n            output = self(image, embedding, indicator)\n        loss = self.compute_loss(output, target, meta_target, meta_structure)\n        pred = output[0].data.max(1)[1]\n        correct = pred.eq(target.data).cpu().sum().numpy()\n        accuracy = correct * 100.0 / target.size()[0]\n        return loss.item(), accuracy\n\n    def test_(self, image, target, meta_target, meta_structure, embedding, indicator):\n        with torch.no_grad():\n            output = self(image, embedding, indicator)\n        pred = output[0].data.max(1)[1]\n        correct = pred.eq(target.data).cpu().sum().numpy()\n        accuracy = correct * 100.0 / target.size()[0]\n        return accuracy"
  },
  {
    "path": "src/model/cnn_lstm.py",
    "content": "import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom basic_model import BasicModel\nfrom fc_tree_net import FCTreeNet\n\nclass conv_module(nn.Module):\n    def __init__(self):\n        super(conv_module, self).__init__()\n        self.conv1 = nn.Conv2d(1, 16, kernel_size=3, stride=2)\n        self.batch_norm1 = nn.BatchNorm2d(16)\n        self.relu1 = nn.ReLU()\n        self.conv2 = nn.Conv2d(16, 16, kernel_size=3, stride=2)\n        self.batch_norm2 = nn.BatchNorm2d(16)\n        self.relu2 = nn.ReLU()\n        self.conv3 = nn.Conv2d(16, 16, kernel_size=3, stride=2)\n        self.batch_norm3 = nn.BatchNorm2d(16)\n        self.relu3 = nn.ReLU()\n        self.conv4 = nn.Conv2d(16, 16, kernel_size=3, stride=2)\n        self.batch_norm4 = nn.BatchNorm2d(16)\n        self.relu4 = nn.ReLU()\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.relu1(self.batch_norm1(x))\n        x = self.conv2(x)\n        x = self.relu2(self.batch_norm2(x))\n        x = self.conv3(x)\n        x = self.relu3(self.batch_norm3(x))\n        x = self.conv4(x)\n        x = self.relu4(self.batch_norm4(x))\n        return x.view(-1, 16, 16*4*4)\n\nclass lstm_module(nn.Module):\n    def __init__(self):\n        super(lstm_module, self).__init__()\n        self.lstm = nn.LSTM(input_size=16*4*4, hidden_size=96, num_layers=1)\n        self.dropout = nn.Dropout(0.5)\n        self.fc = nn.Linear(96, 8)\n\n    def forward(self, x):\n        x = x.permute(1, 0, 2)\n        hidden, _ = self.lstm(x)\n        score = self.fc(hidden[-1, :, :])\n        return score\n\nclass CNN_LSTM(BasicModel):\n    def __init__(self, args):\n        super(CNN_LSTM, self).__init__(args)\n        self.conv = conv_module()\n        self.lstm = lstm_module()\n        self.fc_tree_net = FCTreeNet(in_dim=300, img_dim=256)\n        self.optimizer = optim.Adam(self.parameters(), lr=args.lr, betas=(args.beta1, args.beta2), eps=args.epsilon)\n\n    def compute_loss(self, output, target, meta_target, meta_structure):\n        pred = output[0]\n        loss = F.cross_entropy(pred, target)\n        return loss\n\n    def forward(self, x, embedding, indicator):\n        alpha = 1.0\n        features = self.conv(x.view(-1, 1, 80, 80))\n        features_tree = self.fc_tree_net(features, embedding, indicator)\n        features_tree = features_tree.view(-1, 16, 256)\n        final_features = features + alpha * features_tree\n        score = self.lstm(final_features)\n        return score, None\n\n    "
  },
  {
    "path": "src/model/cnn_mlp.py",
    "content": "import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nfrom basic_model import BasicModel\nfrom fc_tree_net import FCTreeNet\n\nclass conv_module(nn.Module):\n    def __init__(self):\n        super(conv_module, self).__init__()\n        self.conv1 = nn.Conv2d(16, 32, kernel_size=3, stride=2)\n        self.batch_norm1 = nn.BatchNorm2d(32)\n        self.relu1 = nn.ReLU()\n        self.conv2 = nn.Conv2d(32, 32, kernel_size=3, stride=2)\n        self.batch_norm2 = nn.BatchNorm2d(32)\n        self.relu2 = nn.ReLU()\n        self.conv3 = nn.Conv2d(32, 32, kernel_size=3, stride=2)\n        self.batch_norm3 = nn.BatchNorm2d(32)\n        self.relu3 = nn.ReLU()\n        self.conv4 = nn.Conv2d(32, 32, kernel_size=3, stride=2)\n        self.batch_norm4 = nn.BatchNorm2d(32)\n        self.relu4 = nn.ReLU()\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.relu1(self.batch_norm1(x))\n        x = self.conv2(x)\n        x = self.relu2(self.batch_norm2(x))\n        x = self.conv3(x)\n        x = self.relu3(self.batch_norm3(x))\n        x = self.conv4(x)\n        x = self.relu4(self.batch_norm4(x))\n        return x.view(-1, 32*4*4)\n\nclass mlp_module(nn.Module):\n    def __init__(self):\n        super(mlp_module, self).__init__()\n        self.fc1 = nn.Linear(32*4*4, 512)\n        self.relu1 = nn.ReLU()\n        self.fc2 = nn.Linear(512, 8)\n        self.dropout = nn.Dropout(0.5)\n        \n    def forward(self, x):\n        x = self.relu1(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)\n        return x\n\nclass CNN_MLP(BasicModel):\n    def __init__(self, args):\n        super(CNN_MLP, self).__init__(args)\n        self.conv = conv_module()\n        self.mlp = mlp_module()\n        self.fc_tree_net = FCTreeNet(in_dim=300, img_dim=512)\n        self.optimizer = optim.Adam(self.parameters(), lr=args.lr, betas=(args.beta1, args.beta2), eps=args.epsilon)\n\n    def compute_loss(self, output, target, meta_target, meta_structure):\n        pred = output[0]\n        loss = F.cross_entropy(pred, target)\n        return loss\n\n    def forward(self, x, embedding, indicator):\n        alpha = 1.0\n        features = self.conv(x.view(-1, 16, 80, 80))\n        features_tree = features.view(-1, 1, 512)\n        features_tree = self.fc_tree_net(features_tree, embedding, indicator)\n        final_features = features + alpha * features_tree\n        score = self.mlp(final_features)\n        return score, None\n\n    "
  },
  {
    "path": "src/model/const/__init__.py",
    "content": "from const import *\n"
  },
  {
    "path": "src/model/const/const.py",
    "content": "# -*- coding: utf-8 -*-\n\n\n# Maximum number of components in a RPM\nMAX_COMPONENTS = 2\n\n# Canvas parameters\nIMAGE_SIZE = 160\nCENTER = (IMAGE_SIZE / 2, IMAGE_SIZE / 2)\nDEFAULT_RADIUS = IMAGE_SIZE / 4\nDEFAULT_WIDTH = 2\n\n# Attribute parameters\n# Number\nNUM_VALUES = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nNUM_MIN = 0\nNUM_MAX = len(NUM_VALUES) - 1\n\n# Uniformity\nUNI_VALUES = [False, False, False, True]\nUNI_MIN = 0\nUNI_MAX = len(UNI_VALUES) - 1\n\n# Type\nTYPE_VALUES = [\"none\", \"triangle\", \"square\", \"pentagon\", \"hexagon\", \"circle\"]\nTYPE_MIN = 0\nTYPE_MAX = len(TYPE_VALUES) - 1\n\n# Size\nSIZE_VALUES = [0.4, 0.5, 0.6, 0.7, 0.8, 0.9]\nSIZE_MIN = 0\nSIZE_MAX = len(SIZE_VALUES) - 1\n\n# Color\nCOLOR_VALUES = [255, 224, 196, 168, 140, 112, 84, 56, 28, 0]\nCOLOR_MIN = 0\nCOLOR_MAX = len(COLOR_VALUES) - 1\n\n# Angle: self-rotation\nANGLE_VALUES = [-135, -90, -45, 0, 45, 90, 135, 180]\nANGLE_MIN = 0\nANGLE_MAX = len(ANGLE_VALUES) - 1\n\nMETA_STRUCTURE_FORMAT = [\"Singleton\", \"Left_Right\", \"Up_Down\", \"Out_In\", \"Left\", \"Right\", \\\n                         \"Up\",\"Down\", \"Out\", \"In\", \"Grid\", \"Center_Single\", \"Distribute_Four\", \n                         \"Distribute_Nine\", \"Left_Center_Single\", \"Right_Center_Single\", \\\n                         \"Up_Center_Single\", \"Down_Center_Single\", \"Out_Center_Single\", \"In_Center_Single\", \"In_Distribute_Four\"]\n\n# Rule, Attr, Param\n# The design encodes rule priority order: Number/Position always comes first\n# Number and Position could not both be sampled\n# Progression on Number: Number on each Panel +1/2 or -1/2\n# Progression on Position: Entities on each Panel roll over the layout\n# Arithmetic on Number: Numeber on the third Panel = Number on first +/- Number on second (1 for + and -1 for -)\n# Arithmetic on Position: 1 for SET_UNION and -1 for SET_DIFF\n# Distribute_Three on Number: Three numbers through each row\n# Distribute_Three on Position: Three positions (same number) through each row\n# Constant on Number/Position: Nothing changes\n# Progression on Type: Type progression defined as the number of edges on each entity (Triangle, Square, Pentagon, Hexagon, Circle)\n# Distribute_Three on Type: Three types through each row\n# Constant on Type: Nothing changes\n# Progression on Size: Size on each entity +1/2 or -1/2\n# Arithmetic on Size: Size on the third Panel = Size on the first +/- Size on the second (1 for + and -1 for -)\n# Distribute_Three on Size: Three sizes through each row\n# Constant on Size: Nothing changes\n# Progression on Color: Color +1/2 or -1/2\n# Arithmetic on Color: Color on the third Panel = Color on the first +/- Color on the second (1 for + and -1 for -)\n# Distribute_Three on Color: Three colors through each row\n# Constant on Color: Nothing changes\n# Note that all rules on Type, Size and Color enforce value consistency in a panel\nRULE_ATTR = [[[\"Progression\", \"Number\", [-2, -1, 1, 2]], \n              [\"Progression\", \"Position\", [-2, -1, 1, 2]], \n              [\"Arithmetic\", \"Number\", [1, -1]],\n              [\"Arithmetic\", \"Position\", [1, -1]],\n              [\"Distribute_Three\", \"Number\", None],\n              [\"Distribute_Three\", \"Position\", None],\n              [\"Constant\", \"Number/Position\", None]],\n             [[\"Progression\", \"Type\", [-2, -1, 1, 2]],\n              [\"Distribute_Three\", \"Type\", None], \n              [\"Constant\", \"Type\", None]],\n             [[\"Progression\", \"Size\", [-2, -1, 1, 2]],\n              [\"Arithmetic\", \"Size\", [1, -1]],\n              [\"Distribute_Three\", \"Size\", None],\n              [\"Constant\", \"Size\", None]],\n             [[\"Progression\", \"Color\", [-2, -1, 1, 2]],\n              [\"Arithmetic\", \"Color\", [1, -1]],\n              [\"Distribute_Three\", \"Color\", None],\n              [\"Constant\", \"Color\", None]]]\n"
  },
  {
    "path": "src/model/fc_tree_net.py",
    "content": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass FCTreeNet(torch.nn.Module):\n    def __init__(self, in_dim=300, img_dim=256, use_cuda=True):\n        '''\n        initialization for TreeNet model, basically a ChildSumLSTM model\n        with non-linear activation embedding for different nodes in the AoG.\n        Shared weigths for all LSTM cells.\n        :param in_dim:      input feature dimension for word embedding (from string to vector space)\n        :param img_dim:     dimension of the input image feature, should be (panel_pair_number * img_feature_dim (e.g. 512 or 256))\n        '''\n        super(FCTreeNet, self).__init__()\n        self.in_dim = in_dim\n        self.img_dim = img_dim\n        self.fc = nn.Linear(self.in_dim, self.in_dim)\n        self.leaf = nn.Linear(self.in_dim + self.img_dim, self.img_dim)\n        self.middle = nn.Linear(self.in_dim + self.img_dim, self.img_dim)\n        self.merge = nn.Linear(self.in_dim + self.img_dim, self.img_dim)\n        self.root = nn.Linear(self.in_dim + self.img_dim, self.img_dim)\n\n        self.relu = nn.ReLU()\n\n    def forward(self, image_feature, input, indicator):\n        '''\n        Forward funciton for TreeNet model\n        :param input:\t\tinput should be (batch_size * 6 * input_word_embedding_dimension), got from the embedding vector\n        :param indicator:\tindicating whether the input is of structure with branches (batch_size * 1)\n        :param image_feature:   input dictionary for each node, primarily feature, for example (batch_size * 16 (panel_pair_number) * feature_dim (output from CNN))\n        :return:\n        '''\n        # image_feature = image_feature.view(-1, 16, image_feature.size(2))\n        input = self.fc(input.view(-1, input.size(-1)))\n        input = input.view(-1, 6, input.size(-1))\n        input = input.unsqueeze(1).repeat(1, image_feature.size(1), 1, 1)\n        indicator = indicator.unsqueeze(1).repeat(1, image_feature.size(1), 1).view(-1, 1)\n\n        leaf_left = input[:, :, 3, :].view(-1, input.size(-1))           # (batch_size * panel_pair_num) * input_word_embedding_dimension\n        leaf_right = input[:, :, 5, :].view(-1, input.size(-1))\n        inter_left = input[:, :, 2, :].view(-1, input.size(-1))\n        inter_right = input[:, :, 4, :].view(-1, input.size(-1))\n        merge = input[:, :, 1, :].view(-1, input.size(-1))\n        root = input[:, :, 0, :].view(-1, input.size(-1))\n        \n        # concating image_feature and word_embeddings for leaf node inputs\n        leaf_left = torch.cat((leaf_left, image_feature.view(-1, image_feature.size(-1))), dim=-1)\n        leaf_right = torch.cat((leaf_right, image_feature.view(-1, image_feature.size(-1))), dim=-1)\n\n        out_leaf_left = self.leaf(leaf_left)\n        out_leaf_right = self.leaf(leaf_right)\n\n        out_leaf_left = self.relu(out_leaf_left)\n        out_leaf_right = self.relu(out_leaf_right)\n\n        out_left = self.middle(torch.cat((inter_left, out_leaf_left), dim=-1))\n        out_right = self.middle(torch.cat((inter_right, out_leaf_right), dim=-1))\n\n        out_left = self.relu(out_left)\n        out_right = self.relu(out_right)\n\n        out_right = torch.mul(out_right, indicator)\n        merge_input = torch.cat((merge, out_left + out_right), dim=-1)\n        out_merge = self.merge(merge_input)\n\n        out_merge = self.relu(out_merge)\n\n        out_root = self.root(torch.cat((root, out_merge), dim=-1))\n        out_root = self.relu(out_root)\n        # size ((batch_size * panel_pair) * feature_dim)\n        return out_root\n        "
  },
  {
    "path": "src/model/main.py",
    "content": "import os\nimport numpy as np\nimport argparse\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\n\nfrom utility import dataset, ToTensor\nfrom cnn_mlp import CNN_MLP\nfrom cnn_lstm import CNN_LSTM\nfrom resnet18 import Resnet18_MLP\n\nparser = argparse.ArgumentParser(description='our_model')\nparser.add_argument('--model', type=str, default='Resnet18_MLP')\nparser.add_argument('--epochs', type=int, default=200)\nparser.add_argument('--batch_size', type=int, default=32)\nparser.add_argument('--seed', type=int, default=12345)\nparser.add_argument('--device', type=int, default=0)\nparser.add_argument('--load_workers', type=int, default=16)\nparser.add_argument('--resume', type=bool, default=False)\nparser.add_argument('--path', type=str, default='/home/chizhang/Datasets/RAVEN-10000/')\nparser.add_argument('--save', type=str, default='./experiments/checkpoint/')\nparser.add_argument('--img_size', type=int, default=224)\nparser.add_argument('--lr', type=float, default=1e-4)\nparser.add_argument('--beta1', type=float, default=0.9)\nparser.add_argument('--beta2', type=float, default=0.999)\nparser.add_argument('--epsilon', type=float, default=1e-8)\nparser.add_argument('--meta_alpha', type=float, default=0.0)\nparser.add_argument('--meta_beta', type=float, default=0.0)\n\n\nargs = parser.parse_args()\nargs.cuda = torch.cuda.is_available()\ntorch.cuda.set_device(args.device)\nif args.cuda:\n    torch.cuda.manual_seed(args.seed)\n\nif not os.path.exists(args.save):\n    os.makedirs(args.save)\n\ntrain = dataset(args.path, \"train\", args.img_size, transform=transforms.Compose([ToTensor()]))\nvalid = dataset(args.path, \"val\", args.img_size, transform=transforms.Compose([ToTensor()]))\ntest = dataset(args.path, \"test\", args.img_size, transform=transforms.Compose([ToTensor()]))\n\ntrainloader = DataLoader(train, batch_size=args.batch_size, shuffle=True, num_workers=16)\nvalidloader = DataLoader(valid, batch_size=args.batch_size, shuffle=False, num_workers=16)\ntestloader = DataLoader(test, batch_size=args.batch_size, shuffle=False, num_workers=16)\n\nif args.model == \"CNN_MLP\":\n    model = CNN_MLP(args)\nelif args.model == \"CNN_LSTM\":\n    model = CNN_LSTM(args)\nelif args.model == \"Resnet18_MLP\":\n    model = Resnet18_MLP(args)\n    \nif args.resume:\n    model.load_model(args.save, 0)\n    print('Loaded model')\nif args.cuda:\n    model = model.cuda()\n\ndef train(epoch):\n    model.train()\n    train_loss = 0\n    accuracy = 0\n\n    loss_all = 0.0\n    acc_all = 0.0\n    counter = 0\n    for batch_idx, (image, target, meta_target, meta_structure, embedding, indicator) in enumerate(trainloader):\n        counter += 1\n        if args.cuda:\n            image = image.cuda()\n            target = target.cuda()\n            meta_target = meta_target.cuda()\n            meta_structure = meta_structure.cuda()\n            embedding = embedding.cuda()\n            indicator = indicator.cuda()\n        loss, acc = model.train_(image, target, meta_target, meta_structure, embedding, indicator)\n        print('Train: Epoch:{}, Batch:{}, Loss:{:.6f}, Acc:{:.4f}.'.format(epoch, batch_idx, loss, acc))\n        loss_all += loss\n        acc_all += acc\n    if counter > 0:\n        print(\"Avg Training Loss: {:.6f}\".format(loss_all/float(counter)))\n\ndef validate(epoch):\n    model.eval()\n    val_loss = 0\n    accuracy = 0\n\n    loss_all = 0.0\n    acc_all = 0.0\n    counter = 0\n    for batch_idx, (image, target, meta_target, meta_structure, embedding, indicator) in enumerate(validloader):\n        counter += 1\n        if args.cuda:\n            image = image.cuda()\n            target = target.cuda()\n            meta_target = meta_target.cuda()\n            meta_structure = meta_structure.cuda()\n            embedding = embedding.cuda()\n            indicator = indicator.cuda()\n        loss, acc = model.validate_(image, target, meta_target, meta_structure, embedding, indicator)\n        # print('Validate: Epoch:{}, Batch:{}, Loss:{:.6f}, Acc:{:.4f}.'.format(epoch, batch_idx, loss, acc)) \n        loss_all += loss\n        acc_all += acc\n    if counter > 0:\n        print(\"Total Validation Loss: {:.6f}, Acc: {:.4f}\".format(loss_all/float(counter), acc_all/float(counter)))\n    return loss_all/float(counter), acc_all/float(counter)\n\ndef test(epoch):\n    model.eval()\n    accuracy = 0\n\n    acc_all = 0.0\n    counter = 0\n    for batch_idx, (image, target, meta_target, meta_structure, embedding, indicator) in enumerate(testloader):\n        counter += 1\n        if args.cuda:\n            image = image.cuda()\n            target = target.cuda()\n            meta_target = meta_target.cuda()\n            meta_structure = meta_structure.cuda()\n            embedding = embedding.cuda()\n            indicator = indicator.cuda()\n        acc = model.test_(image, target, meta_target, meta_structure, embedding, indicator)\n        # print('Test: Epoch:{}, Batch:{}, Acc:{:.4f}.'.format(epoch, batch_idx, acc))  \n        acc_all += acc\n    if counter > 0:\n        print(\"Total Testing Acc: {:.4f}\".format(acc_all / float(counter)))\n    return acc_all/float(counter)\n\ndef main():\n    for epoch in range(0, args.epochs):\n        train(epoch)\n        avg_loss, avg_acc = validate(epoch)\n        test(epoch)\n        model.save_model(args.save, epoch, avg_acc, avg_loss)\n\n\nif __name__ == '__main__':\n    main()"
  },
  {
    "path": "src/model/resnet18.py",
    "content": "import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torchvision.models as models\n\nfrom basic_model import BasicModel\nfrom fc_tree_net import FCTreeNet\n\nclass identity(nn.Module):\n    def __init__(self):\n        super(identity, self).__init__()\n    \n    def forward(self, x):\n        return x\n\nclass mlp_module(nn.Module):\n    def __init__(self):\n        super(mlp_module, self).__init__()\n        self.fc1 = nn.Linear(512, 512)\n        self.relu1 = nn.ReLU()\n        self.fc2 = nn.Linear(512, 8+9+21)\n        self.dropout = nn.Dropout(0.5)\n        \n    def forward(self, x):\n        x = self.relu1(self.fc1(x))\n        x = self.dropout(x)\n        x = self.fc2(x)\n        return x\n\nclass Resnet18_MLP(BasicModel):\n    def __init__(self, args):\n        super(Resnet18_MLP, self).__init__(args)\n        self.resnet18 = models.resnet18(pretrained=False)\n        self.resnet18.conv1 = nn.Conv2d(16, 64, kernel_size=7, stride=2, padding=3, bias=False)\n        self.resnet18.fc = identity()\n        self.mlp = mlp_module()\n        self.fc_tree_net = FCTreeNet(in_dim=300, img_dim=512)\n        self.optimizer = optim.Adam(self.parameters(), lr=args.lr, betas=(args.beta1, args.beta2), eps=args.epsilon)\n        self.meta_alpha = args.meta_alpha\n        self.meta_beta = args.meta_beta\n\n    def compute_loss(self, output, target, meta_target, meta_structure):\n        pred, meta_target_pred, meta_struct_pred = output[0], output[1], output[2]\n\n        target_loss = F.cross_entropy(pred, target)\n        meta_target_pred = torch.chunk(meta_target_pred, chunks=9, dim=1)\n        meta_target = torch.chunk(meta_target, chunks=9, dim=1)\n        meta_target_loss = 0.\n        for idx in range(0, 9):\n            meta_target_loss += F.binary_cross_entropy(F.sigmoid(meta_target_pred[idx]), meta_target[idx])\n\n        meta_struct_pred = torch.chunk(meta_struct_pred, chunks=21, dim=1)\n        meta_structure = torch.chunk(meta_structure, chunks=21, dim=1)\n        meta_struct_loss = 0.\n        for idx in range(0, 21):\n            meta_struct_loss += F.binary_cross_entropy(F.sigmoid(meta_struct_pred[idx]), meta_structure[idx])\n        loss = target_loss + self.meta_alpha*meta_struct_loss/21. + self.meta_beta*meta_target_loss/9.\n        return loss\n\n    def forward(self, x, embedding, indicator):\n        alpha = 1.0\n        features = self.resnet18(x.view(-1, 16, 224, 224))\n        features_tree = features.view(-1, 1, 512)\n        features_tree = self.fc_tree_net(features_tree, embedding, indicator)\n        final_features = features + alpha * features_tree\n        output = self.mlp(final_features)\n        pred = output[:,0:8]\n        meta_target_pred = output[:,8:17]\n        meta_struct_pred = output[:,17:38]\n        return pred, meta_target_pred, meta_struct_pred\n    "
  },
  {
    "path": "src/model/utility/__init__.py",
    "content": "from dataset_utility import *"
  },
  {
    "path": "src/model/utility/dataset_utility.py",
    "content": "import os\nimport glob\nimport numpy as np\nfrom scipy import misc\n\nimport torch\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, utils\n\n        \nclass ToTensor(object):\n    def __call__(self, sample):\n        return torch.tensor(sample, dtype=torch.float32)\n\nclass dataset(Dataset):\n    def __init__(self, root_dir, dataset_type, img_size, transform=None, shuffle=False):\n        self.root_dir = root_dir\n        self.transform = transform\n        self.file_names = [f for f in glob.glob(os.path.join(root_dir, \"*\", \"*.npz\")) \\\n                            if dataset_type in f]\n        self.img_size = img_size\n        self.embeddings = np.load(os.path.join(root_dir, 'embedding.npy'), allow_pickle=True)\n        self.shuffle = shuffle\n\n    def __len__(self):\n        return len(self.file_names)\n\n    def __getitem__(self, idx):\n        data_path = self.file_names[idx]\n        data = np.load(data_path)\n        image = data[\"image\"].reshape(16, 160, 160)\n        target = data[\"target\"]\n        structure = data[\"structure\"]\n        meta_target = data[\"meta_target\"]\n        meta_structure = data[\"meta_structure\"]\n\n        if self.shuffle:\n            context = image[:8, :, :]\n            choices = image[8:, :, :]\n            indices = range(8)\n            np.random.shuffle(indices)\n            new_target = indices.index(target)\n            new_choices = choices[indices, :, :]\n            image = np.concatenate((context, new_choices))\n            target = new_target\n        \n        resize_image = []\n        for idx in range(0, 16):\n            resize_image.append(misc.imresize(image[idx,:,:], (self.img_size, self.img_size)))\n        resize_image = np.stack(resize_image)\n        # image = resize(image, (16, 128, 128))\n        # meta_matrix = data[\"mata_matrix\"]\n\n        embedding = torch.zeros((6, 300), dtype=torch.float)\n        indicator = torch.zeros(1, dtype=torch.float)\n        element_idx = 0\n        for element in structure:\n            if element != '/':\n                embedding[element_idx, :] = torch.tensor(self.embeddings.item().get(element), dtype=torch.float)\n                element_idx += 1\n        if element_idx == 6:\n            indicator[0] = 1.\n        # if meta_target.dtype == np.int8:\n        #     meta_target = meta_target.astype(np.uint8)\n        # if meta_structure.dtype == np.int8:\n        #     meta_structure = meta_structure.astype(np.uint8)\n    \n        del data\n        if self.transform:\n            resize_image = self.transform(resize_image)\n            # meta_matrix = self.transform(meta_matrix)\n            target = torch.tensor(target, dtype=torch.long)\n            meta_target = self.transform(meta_target)\n            meta_structure = self.transform(meta_structure)\n            # meta_target = torch.tensor(meta_target, dtype=torch.long)\n        return resize_image, target, meta_target, meta_structure, embedding, indicator\n        \n"
  }
]