[
  {
    "path": ".gitignore",
    "content": "## Core latex/pdflatex auxiliary files:\n*.aux\n*.lof\n*.log\n*.lot\n*.fls\n*.out\n*.toc\n*.fmt\n\n# python scripts\n*DS_Store*\n*.idea/*\n*.pyc\n*.ipynb_checkpoints*\n## Intermediate documents:\n*.dvi\n*-converted-to.*\n# these rules might exclude image files for figures etc.\n# *.ps\n# *.eps\n# *.pdf\n\n## Bibliography auxiliary files (bibtex/biblatex/biber):\n*.bbl\n*.bcf\n*.blg\n*-blx.aux\n*-blx.bib\n*.brf\n*.run.xml\n\n## Build tool auxiliary files:\n*.fdb_latexmk\n*.synctex\n*.synctex.gz\n*.synctex.gz(busy)\n*.pdfsync\n\n## Auxiliary and intermediate files from other packages:\n# algorithms\n*.alg\n*.loa\n\n# achemso\nacs-*.bib\n\n# amsthm\n*.thm\n\n# beamer\n*.nav\n*.snm\n*.vrb\n\n# cprotect\n*.cpt\n\n#(e)ledmac/(e)ledpar\n*.end\n*.[1-9]\n*.[1-9][0-9]\n*.[1-9][0-9][0-9]\n*.[1-9]R\n*.[1-9][0-9]R\n*.[1-9][0-9][0-9]R\n*.eledsec[1-9]\n*.eledsec[1-9]R\n*.eledsec[1-9][0-9]\n*.eledsec[1-9][0-9]R\n*.eledsec[1-9][0-9][0-9]\n*.eledsec[1-9][0-9][0-9]R\n\n# glossaries\n*.acn\n*.acr\n*.glg\n*.glo\n*.gls\n\n# gnuplottex\n*-gnuplottex-*\n\n# hyperref\n*.brf\n\n# knitr\n*-concordance.tex\n*.tikz\n*-tikzDictionary\n\n# listings\n*.lol\n\n# makeidx\n*.idx\n*.ilg\n*.ind\n*.ist\n\n# minitoc\n*.maf\n*.mtc\n*.mtc[0-9]\n*.mtc[1-9][0-9]\n\n# minted\n_minted*\n*.pyg\n\n# morewrites\n*.mw\n\n# mylatexformat\n*.fmt\n\n# nomencl\n*.nlo\n\n# sagetex\n*.sagetex.sage\n*.sagetex.py\n*.sagetex.scmd\n\n# sympy\n*.sout\n*.sympy\nsympy-plots-for-*.tex/\n\n# pdfcomment\n*.upa\n*.upb\n\n#pythontex\n*.pytxcode\npythontex-files-*/\n\n# Texpad\n.texpadtmp\n\n# TikZ & PGF\n*.dpth\n*.md5\n*.auxlock\n\n# todonotes\n*.tdo\n\n# xindy\n*.xdy\n\n# xypic precompiled matrices\n*.xyc\n\n# WinEdt\n*.bak\n*.sav\n\n# endfloat\n*.ttt\n*.fff\n\n# Latexian\nTSWLatexianTemp*\n\nsource/main.pdf\n\n.dropbox\n\n\n"
  },
  {
    "path": "LICENSE",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <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 <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <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<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "# Simulator\nThis simulator serves as the training and evaluation platform in the following work:\n\n\n> Efficient Large-Scale Fleet Management via Multi-Agent Deep Reinforcement Learning </br>\nKaixiang Lin, Renyu Zhao, Zhe Xu, Jiayu Zhou </br>\n[KDD 2018 Long presentation](https://arxiv.org/abs/1802.06444)\n\n### Prerequisites\n- Python 2\n\n### Run\n```\ncd ./tests/\npython run_example.py\n```\n \n### Docs\nPlease find more details of usage in [Wiki](https://github.com/illidanlab/Simulator/wiki)\n\n\n### References\nIf you find this work helpful in your research, please consider citing the following paper. The bibtex are listed below:\n```\n@article{lin2018efficient,\n  title={Efficient Large-Scale Fleet Management via Multi-Agent Deep Reinforcement Learning},\n  author={Lin, Kaixiang and Zhao, Renyu and Xu, Zhe and Zhou, Jiayu},\n  journal={arXiv preprint arXiv:1802.06444},\n  year={2018}\n}\n```\n"
  },
  {
    "path": "algorithm/IDQN.py",
    "content": "\nimport numpy as np\nimport tensorflow as tf\nimport random, os\nfrom alg_utility import *\n\n\nclass Estimator:\n    \"\"\" build Deep Q network\n    \"\"\"\n    def __init__(self,\n                 sess,\n                 action_dim,\n                 state_dim,\n                 env,\n                 scope=\"estimator\",\n                 summaries_dir=None):\n        self.sess = sess\n        self.n_valid_grid = env.n_valid_grids\n        self.action_dim = action_dim\n        self.state_dim = state_dim\n        self.M = env.M\n        self.N = env.N\n        self.scope = scope\n        self.T = 144\n        self.env = env\n\n        # Writes Tensorboard summaries to disk\n        self.summary_writer = None\n        with tf.variable_scope(scope):\n            # Build the graph\n            self._build_model()\n            if summaries_dir:\n                summary_dir = os.path.join(summaries_dir, \"summaries_{}\".format(scope))\n                if not os.path.exists(summary_dir):\n                    os.makedirs(summary_dir)\n                self.summary_writer = tf.summary.FileWriter(summary_dir)\n\n        self.neighbors_list = []\n        for idx, node_id in enumerate(env.target_grids):\n            neighbor_indices = env.nodes[node_id].layers_neighbors_id[0]  # index in env.nodes\n            neighbor_ids = [env.target_grids.index(env.nodes[item].get_node_index()) for item in neighbor_indices]\n            neighbor_ids.append(idx)\n            # index in env.target_grids == index in state\n            self.neighbors_list.append(neighbor_ids)\n\n        # compute valid action mask.\n        self.valid_action_mask = np.ones((self.n_valid_grid, self.action_dim))\n        self.valid_neighbor_node_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.nodes\n        self.valid_neighbor_grid_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.target_grids\n        for grid_idx, grid_id in enumerate(env.target_grids):\n            for neighbor_idx, neighbor in enumerate(self.env.nodes[grid_id].neighbors):\n                if neighbor is None:\n                    self.valid_action_mask[grid_idx, neighbor_idx] = 0\n                else:\n                    node_index = neighbor.get_node_index()  # node_index in env.nodes\n                    self.valid_neighbor_node_id[grid_idx, neighbor_idx] = node_index\n                    self.valid_neighbor_grid_id[grid_idx, neighbor_idx] = env.target_grids.index(node_index)\n\n            self.valid_neighbor_node_id[grid_idx, -1] = grid_id\n            self.valid_neighbor_grid_id[grid_idx, -1] = grid_idx\n\n\n\n    def _build_model(self):\n        trainable = True\n        self.state = X = tf.placeholder(shape=[None, self.state_dim], dtype=tf.float32, name=\"X\")\n\n        # The TD target value\n        self.y_pl = tf.placeholder(shape=[None], dtype=tf.float32, name=\"y\")\n\n        # action chosen\n        self.ACTION = tf.placeholder(tf.float32, [None, self.action_dim], 'action_chosen')\n\n        self.loss_lr = tf.placeholder(tf.float32, None, \"learning_rate\")\n\n        # 3 layers feed forward network.\n        l1 = tf.layers.dense(X, 128, tf.nn.elu, trainable=trainable)\n        l2 = tf.layers.dense(l1, 64, tf.nn.elu, trainable=trainable)\n        l3 = tf.layers.dense(l2, 32, tf.nn.elu, trainable=trainable)\n        self.qvalue = tf.layers.dense(l3, self.action_dim, tf.nn.elu, trainable=trainable)\n\n\n        # get the Q(s,a) for chosen action\n        self.action_predictions = tf.reduce_sum(self.qvalue * self.ACTION, axis=1)\n\n        self.losses = tf.squared_difference(self.y_pl, self.action_predictions)\n        self.loss = tf.reduce_mean(self.losses)\n\n        self.train_op = tf.train.AdamOptimizer(self.loss_lr).minimize(self.loss)\n\n        # Summaries for Tensorboard\n        self.summaries = tf.summary.merge([\n            tf.summary.scalar(\"loss\", self.loss),\n            tf.summary.histogram(\"loss_hist\", self.losses),\n            tf.summary.histogram(\"q_values_hist\", self.qvalue),\n            tf.summary.scalar(\"max_q_value\", tf.reduce_max(self.qvalue))\n        ])\n\n    def predict(self, s):\n        qvalues = self.sess.run(self.qvalue, {self.state: s})\n        max_qvalue = np.max(qvalues, axis=1)\n        return max_qvalue\n\n    def action(self, s, context, epsilon):\n        \"\"\" Compute Q(s, a) for all actions give states\n        :return:\n        \"\"\"\n        # A = np.ones(self.action_dim, dtype=float) * epsilon / self.action_dim\n        qvalues = self.sess.run(self.qvalue, {self.state: s})\n        action_idx = []            # go to which node, the index in nodes\n        action_idx_valid = []            #the index in env.target_grids\n        action_neighbor_idx = []\n        action_tuple_mat = np.zeros((len(self.env.nodes), len(self.env.nodes)))\n        action_tuple = []\n        action_starting_gridids = []\n\n        grid_ids = np.argmax(s[:, -self.n_valid_grid:], axis=1)  # starting grid of each sample\n        valid_probs = []\n\n        for idx, grid_valid_idx in enumerate(grid_ids):\n            curr_qvalue = qvalues[idx]\n            temp_qvalue = self.valid_action_mask[grid_valid_idx] * curr_qvalue\n\n            if np.sum(temp_qvalue) == 0:  # encourage exploration\n                temp_qvalue[self.valid_action_mask[grid_valid_idx]>0] = 1. / np.sum(self.valid_action_mask[grid_valid_idx])\n                action_prob = temp_qvalue / np.sum(temp_qvalue)\n                curr_action_indices = np.random.multinomial(int(context[idx]), action_prob)\n            else:\n                best_action = np.argmax(temp_qvalue)\n                action_prob = np.zeros(self.action_dim)\n                num_valid_action = np.count_nonzero(temp_qvalue)\n                action_prob[temp_qvalue > 0] = epsilon / float(num_valid_action)\n                action_prob[best_action] += 1 - epsilon\n                curr_action_indices = np.random.multinomial(int(context[idx]), action_prob)\n\n            valid_probs.append(action_prob)\n            start_node_id = self.env.target_grids[grid_valid_idx]\n            num_distinct_action = 0\n            for curr_action_idx, num_driver in enumerate(curr_action_indices):\n                if num_driver > 0:\n                    end_node_id = int(self.valid_neighbor_node_id[grid_valid_idx, curr_action_idx])\n\n                    action_idx.append(end_node_id)\n                    action_idx_valid.append(int(self.valid_neighbor_grid_id[grid_valid_idx, curr_action_idx]))\n                    action_neighbor_idx.append(curr_action_idx)\n                    action_tuple_mat[start_node_id, end_node_id] = num_driver\n                    num_distinct_action += 1\n            action_starting_gridids.append(num_distinct_action)\n\n        action_indices = np.where(action_tuple_mat > 0)\n        for xx, yy in zip(action_indices[0], action_indices[1]):\n            if xx != yy:\n                action_tuple.append((xx, yy, int(action_tuple_mat[xx, yy])))\n\n        return qvalues, action_idx, action_idx_valid, action_neighbor_idx, action_tuple, action_starting_gridids\n\n    def update(self, s, a, y, learning_rate, global_step):\n        \"\"\"\n        Updates the estimator towards the given targets.\n\n        Args:\n          s: State input of shape [batch_size, state_dim]\n          a: Chosen actions of shape [batch_size, action_dim], 0, 1 mask\n          y: Targets of shape [batch_size]\n\n        Returns:\n          The calculated loss on the batch.\n        \"\"\"\n        sess = self.sess\n        feed_dict = {self.state: s, self.y_pl: y, self.ACTION: a, self.loss_lr: learning_rate}\n        summaries, _, loss = sess.run([self.summaries, self.train_op, self.loss], feed_dict)\n\n        if self.summary_writer:\n            self.summary_writer.add_summary(summaries, global_step)\n        return loss\n\n\n\nclass stateProcessor:\n    \"\"\"\n        Process a raw global state into the states of grids.\n    \"\"\"\n\n    def __init__(self,\n                 target_id_states,\n                 target_grids,\n                 n_valid_grids):\n        self.target_id_states = target_id_states  # valid grid index for driver and order distribution.\n        self.target_grids = target_grids   # valid grid id [22, 24, ...]  504\n        self.n_valid_grids = n_valid_grids\n        self.T = 144\n        self.action_dim = 7\n        self.extend_state = True\n\n    def utility_conver_states(self, curr_state):\n        curr_s = np.array(curr_state).flatten()\n        curr_s_new = [curr_s[idx] for idx in self.target_id_states]\n        return np.array(curr_s_new)\n\n    def utility_conver_reward(self, reward_node):\n        reward_node_new = [reward_node[idx] for idx in self.target_grids]\n        return np.array(reward_node_new)\n\n    def reward_wrapper(self, info, curr_s):\n        \"\"\"\n        :param info: [node_reward(including neighbors), neighbor_reward]\n        :param curr_s:\n        :return:\n        \"\"\"\n\n        info_reward = info[0]\n        valid_nodes_reward = self.utility_conver_reward(info_reward[0])\n        devide = curr_s[:self.n_valid_grids]\n        devide[devide == 0] = 1\n        valid_nodes_reward = valid_nodes_reward/devide\n        return valid_nodes_reward\n\n    def compute_context(self, info):\n        # compute context\n        context = info.flatten()\n        context = [context[idx] for idx in self.target_grids]\n        return context\n\n    def utility_normalize_states(self, curr_s):\n        max_driver_num = np.max(curr_s[:self.n_valid_grids])\n        max_order_num = np.max(curr_s[self.n_valid_grids:])\n\n        curr_s_new = np.zeros_like(curr_s)\n        curr_s_new[:self.n_valid_grids] = curr_s[:self.n_valid_grids] / max_driver_num\n        curr_s_new[self.n_valid_grids:] = curr_s[self.n_valid_grids:] / max_order_num\n        return curr_s_new\n\n\n    def to_grid_states(self, curr_s, curr_city_time):\n        T = self.T\n\n        # curr_s = self.utility_conver_states(curr_state)\n        time_one_hot = np.zeros((T))\n        time_one_hot[curr_city_time % T] = 1\n        onehot_grid_id = np.eye(self.n_valid_grids)\n\n        s_grid = np.zeros((self.n_valid_grids, self.n_valid_grids * 3 + T))\n        s_grid[:, :self.n_valid_grids * 2] = np.stack([curr_s] * self.n_valid_grids)\n        s_grid[:, self.n_valid_grids * 2:self.n_valid_grids * 2 + T] = np.stack([time_one_hot] * self.n_valid_grids)\n        s_grid[:, -self.n_valid_grids:] = onehot_grid_id\n        return np.array(s_grid)\n\n    def to_grid_rewards(self, action_idx_valid, node_reward):\n        r_grid = []\n        for end_grid_id in action_idx_valid:\n            r_grid.append(node_reward[end_grid_id])\n\n        return np.array(r_grid)\n\n\n    def to_grid_next_states(self, s_grid, next_state, action_index, curr_city_time):\n        \"\"\"\n        :param s_grid:  batch_size x state_dimension\n        :param action_index: batch_size, end_valid_grid_id, next grid id.\n        :return:\n        \"\"\"\n        T = self.T\n        next_s = self.utility_normalize_states(self.utility_conver_states(next_state))\n\n        time_one_hot = np.zeros((T))\n        time_one_hot[curr_city_time % T] = 1\n\n        s_grid_next = np.zeros(s_grid.shape)\n        s_grid_next[:, :self.n_valid_grids*2] = next_s\n        s_grid_next[:, self.n_valid_grids*2:self.n_valid_grids*2+T] = time_one_hot\n\n        action_index = np.array(action_index) + self.n_valid_grids*2 + T\n        s_grid_next[np.arange(s_grid_next.shape[0]), action_index] = 1\n\n        return s_grid_next\n\n    def to_grid_state_for_training(self, s_grid, action_starting_gridids):\n        s_grid_new = []\n        for idx, num_extend in enumerate(action_starting_gridids):\n            temp_s = s_grid[idx]\n            s_grid_new += [temp_s] * num_extend\n        return np.array(s_grid_new)\n\n    def to_action_mat(self, action_neighbor_idx):\n        action_mat = np.zeros((len(action_neighbor_idx), self.action_dim))\n        action_mat[np.arange(action_mat.shape[0]), action_neighbor_idx] = 1\n        return action_mat\n\n\n\nclass ReplayMemory:\n    \"\"\" collect the experience and sample a batch for training networks.\n        without time ordering\n    \"\"\"\n    def __init__(self, memory_size, batch_size):\n        self.states = []\n        self.next_states = []\n        self.actions = []\n        self.rewards = []\n\n        self.batch_size = batch_size\n        self.memory_size = memory_size\n        self.current = 0\n        self.curr_lens = 0\n\n    def add(self, s, a, r, next_s):\n        if self.curr_lens == 0:\n            self.states = s\n            self.actions = a\n            self.rewards = r\n            self.next_states = next_s\n            self.curr_lens = self.states.shape[0]\n\n        elif self.curr_lens <= self.memory_size:\n            self.states = np.concatenate((self.states, s),axis=0)\n            self.next_states = np.concatenate((self.next_states, next_s), axis=0)\n            self.actions = np.concatenate((self.actions, a), axis=0)\n            self.rewards = np.concatenate((self.rewards, r), axis=0)\n            self.curr_lens = self.states.shape[0]\n        else:\n            new_sample_lens = s.shape[0]\n            index = random.randint(0, self.curr_lens - new_sample_lens)\n\n            self.states[index:(index + new_sample_lens)] = s\n            self.actions[index:(index + new_sample_lens)] = a\n            self.rewards[index:(index + new_sample_lens)] = r\n            self.next_states[index:(index + new_sample_lens)] = next_s\n\n    def sample(self):\n\n        if self.curr_lens <= self.batch_size:\n            return [self.states, self.actions, self.rewards, self.next_states]\n        indices = random.sample(range(0, self.curr_lens), self.batch_size)\n        batch_s = self.states[indices]\n        batch_a = self.actions[indices]\n        batch_r = self.rewards[indices]\n        batch_next_s = self.next_states[indices]\n        return [batch_s, batch_a, batch_r, batch_next_s]\n\n    def reset(self):\n        self.states = []\n        self.actions = []\n        self.rewards = []\n        self.next_states = []\n        self.curr_lens = 0\n\n\nclass ModelParametersCopier():\n    \"\"\"\n    Copy model parameters of one estimator to another.\n    \"\"\"\n\n    def __init__(self, estimator1, estimator2):\n        \"\"\"\n        Defines copy-work operation graph.\n        Args:\n          estimator1: Estimator to copy the paramters from\n          estimator2: Estimator to copy the parameters to\n        \"\"\"\n        e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)]\n        e1_params = sorted(e1_params, key=lambda v: v.name)\n        e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)]\n        e2_params = sorted(e2_params, key=lambda v: v.name)\n\n        self.update_ops = []\n        for e1_v, e2_v in zip(e1_params, e2_params):\n            op = e2_v.assign(e1_v)\n            self.update_ops.append(op)\n\n    def make(self, sess):\n        \"\"\"\n        Makes copy.\n        Args:\n            sess: Tensorflow session instance\n        \"\"\"\n        sess.run(self.update_ops)\n\n\n\n\n"
  },
  {
    "path": "algorithm/__init__.py",
    "content": ""
  },
  {
    "path": "algorithm/alg_utility.py",
    "content": "import tensorflow as tf\nimport numpy as np\n# import cvxpy as cvx\nfrom simulator.utilities import *\n\n\"\"\" Some of Following codes are modified from https://github.com/openai/baselines\n\"\"\"\ndef tfsum(x, axis=None, keepdims=False):\n    axis = None if axis is None else [axis]\n    return tf.reduce_sum(x, axis=axis, keepdims=keepdims)\n\nclass Pd(object):\n    \"\"\"\n    A particular probability distribution\n    \"\"\"\n\n    def mode(self):\n        raise NotImplementedError\n\n    def neglogp(self, x):\n        # Usually it's easier to define the negative logprob\n        raise NotImplementedError\n\n    def kl(self, other):\n        raise NotImplementedError\n\n    def entropy(self):\n        raise NotImplementedError\n\n    def sample(self):\n        raise NotImplementedError\n\n    def logp(self, x):\n        return - self.neglogp(x)\n\n\nclass DiagGaussianPd(Pd):\n    def __init__(self, mu, logstd):\n        self.mean = mu\n        self.logstd = logstd\n        self.std = tf.exp(logstd)\n\n    def mode(self):\n        return self.mean\n\n    def neglogp(self, x):\n        # axis = -1, sum over last dimension, first dimension is batch size\n        return 0.5 * tfsum(tf.square((x - self.mean) / self.std), axis=-1) \\\n               + 0.5 * np.log(2.0 * np.pi) * tf.to_float(tf.shape(x)[-1]) \\\n               + tfsum(self.logstd, axis=-1)\n\n    def sample(self):\n        return self.mean + self.std * tf.random_normal(tf.shape(self.mean))\n\n\n\ndef normalize_reward(discounted_epr):\n    reward_mean = np.mean(discounted_epr)\n    reward_std  = np.std(discounted_epr)\n    discounted_epr = (discounted_epr - reward_mean)/reward_std\n    return discounted_epr\n\n# def projection(Y, n, num_idle_driver):\n#     assert np.sum(Y) > num_idle_driver\n#     X = cvx.Variable(n)\n#     objective = cvx.Minimize(cvx.sum_squares(X - Y))\n#     constraints = [0 <= X,\n#                    num_idle_driver == cvx.sum_entries(X)]\n#     prob = cvx.Problem(objective, constraints)\n#\n#     # The optimal objective is returned by prob.solve().\n#     result = prob.solve()\n#     return X.value\n\n\ndef continuous_quadratic_knapsack(b, u, r):\n    \"\"\"\n    OBJECTIVE\n     min 1/2*||x||_2^2\n     s.t. b'*x = r, 0<= x <= u,  b > 0\n    \n    Related paper\n     [1] KC. Kiwiel. On linear-time algorithms for the continuous \n         quadratic knapsack problem, Journal of Optimization Theory \n         and Applications, 2007\n    Coding Reference: \n    https://github.com/jiayuzhou/MALSAR/blob/master/MALSAR/functions/CMTL/bsa_ihb.m\n    \"\"\"\n    n = len(b)\n    break_flag = 0 \n    t_l = np.zeros(n)\n    t_u = -u    # ( 0 - u)/1\n    t_L = -float('Inf')\n    t_U = float('Inf')\n    g_tL = 0\n    g_tU = 0\n    T = np.concatenate((t_l, t_u), axis=0)\n    n_iter = 0\n    while len(T) !=0:\n        n_iter += 1\n        g_t = 0\n        t_hat = np.median(T)\n\n        U_inds = np.where(t_hat < t_u)\n        M      = np.where((t_u <= t_hat) & (t_hat <= t_l))\n\n        if len(U_inds[0]) != 0: \n            g_t = g_t  + np.dot(b[U_inds], u[U_inds])\n\n        if len(M[0]) != 0:\n            g_t = g_t - np.dot(b[M], t_hat*b[M])  # a = 0   np.sum(b(M).*(a(M) - t_hat*b(M)))\n        if g_t > r:\n            t_L = t_hat\n            T = T[np.where(T > t_hat)]\n            g_tL = g_t \n        elif g_t < r:\n            t_U = t_hat\n            T = T[np.where(T < t_hat)]\n            g_tU = g_t\n        else:\n            t_star = t_hat\n            break_flag = 1\n            break\n            \n    if break_flag == 0:\n         t_star = t_L - (g_tL -r)*(t_U - t_L)/(g_tU - g_tL)\n    x_star = np.minimum(np.maximum(0, -t_star*b), u)\n    return x_star\n\n\ndef projection_fast(u, n, num_idle_driver):\n    b = np.ones((n))\n    r = np.sum(u) - num_idle_driver\n    x_star = continuous_quadratic_knapsack(b, u, r)\n    return u - x_star\n\n\ndef categorical_sample_split(logits, d=6):\n    \"\"\"\n    :param logits: sampling according to the probability exp(logits)\n    :param d: first dimension of logits. 6 in our case.\n    :return:\n    \"\"\"\n\n    value = [tf.multinomial(logits[i] - tf.reduce_max(logits[i], [1], keep_dims=True), 1)\n             for i in np.arange(d)\n             ]\n    return value\n\ndef fc(x, scope, nh, act=tf.nn.relu, init_scale=1.0):\n    with tf.variable_scope(scope):\n        nin = x.get_shape()[1].value\n        # w = tf.get_variable(\"w\", [nin, nh], initializer=ortho_init(init_scale))\n        w = tf.get_variable(\"w\", [nin, nh], initializer=tf.contrib.layers.xavier_initializer(uniform=True, seed=0))\n        b = tf.get_variable(\"b\", [nh], initializer=tf.constant_initializer(0.0))\n        z = tf.matmul(x, w)+b\n        h = act(z)\n        return h\n\n\ndef ortho_init(scale=1.0):\n    def _ortho_init(shape, dtype, partition_info=None):\n        #lasagne ortho init for tf\n        shape = tuple(shape)\n        if len(shape) == 2:\n            flat_shape = shape\n        elif len(shape) == 4: # assumes NHWC\n            flat_shape = (np.prod(shape[:-1]), shape[-1])\n        else:\n            raise NotImplementedError\n        np.random.seed(1)\n        a = np.random.normal(0.0, 1.0, flat_shape)\n        u, _, v = np.linalg.svd(a, full_matrices=False)\n        q = u if u.shape == flat_shape else v # pick the one with the correct shape\n        q = q.reshape(shape)\n        return (scale * q[:shape[0], :shape[1]]).astype(np.float32)\n    return _ortho_init\n\n\n##############################################################\n### utility function for tune DQN\n##############################################################\n\ndef get_target_ids_local(mapped_matrix_int_local):\n    row_inds, col_inds = np.where(mapped_matrix_int_local >= 0)\n\n    M_local, N_local = mapped_matrix_int_local.shape\n    target_ids_local  = []  # start from 0.\n    for x, y in zip(row_inds, col_inds):\n        node_id = ids_2dto1d(x, y, M_local, N_local)\n        target_ids_local.append(node_id)\n    return target_ids_local\n\ndef collision_action(action_tuple):\n    count = 0\n    action_set = set(())\n    for item in action_tuple:\n        if item[1] == -1:\n            continue\n        grid_id_key = str(item[0]) + \"-\" + str(item[1])\n        action_set.add(grid_id_key)\n        conflict_id_key = str(item[1]) + \"-\" + str(item[0])\n        if conflict_id_key in action_set:\n            count += 1\n    return count\n\ndef construct_grid_nodeid_mapping(target_ids_local, grid_ids_local):\n    node_mapping = {}\n    grid_mapping = {} #\n    for nodeid, gridid in zip(target_ids_local, grid_ids_local):\n        node_mapping[gridid] = nodeid\n        grid_mapping[nodeid] = gridid\n    return node_mapping, grid_mapping\n\ndef utility_conver_states(curr_s, target_id_states):\n    curr_s_new = [curr_s[idx] for idx in target_id_states]\n    return np.array(curr_s_new)\n\ndef utility_conver_reward(reward_node, target_id_states):\n    reward_node_new = [reward_node[idx] for idx in target_id_states]\n    return np.array(reward_node_new)\n\n##############################################################\n\n\ndef compute_sum_qtable(temp_qtable):\n    temp_q = 0\n    for item in temp_qtable:\n        for jj in item:\n            temp_q += np.sum(jj)\n\n    return temp_q"
  },
  {
    "path": "algorithm/cA2C.py",
    "content": "\n\nimport numpy as np\nimport tensorflow as tf\nimport random, os\nfrom alg_utility import *\nfrom copy import deepcopy\n\nclass Estimator:\n    \"\"\" build value network\n    \"\"\"\n    def __init__(self,\n                 sess,\n                 action_dim,\n                 state_dim,\n                 env,\n                 scope=\"estimator\",\n                 summaries_dir=None):\n        self.sess = sess\n        self.n_valid_grid = env.n_valid_grids\n        self.action_dim = action_dim\n        self.state_dim = state_dim\n        self.M = env.M\n        self.N = env.N\n        self.scope = scope\n        self.T = 144\n        self.env = env\n\n        # Writes Tensorboard summaries to disk\n        self.summary_writer = None\n        with tf.variable_scope(scope):\n\n            # Build the value function graph\n            # with tf.variable_scope(\"value\"):\n            value_loss = self._build_value_model()\n\n            with tf.variable_scope(\"policy\"):\n                actor_loss, entropy = self._build_mlp_policy()\n\n            self.loss = actor_loss + .5 * value_loss - 10 * entropy\n\n\n            # self.loss_gradients = tf.gradients(self.value_loss, tf.trainable_variables(scope=scope))\n                                           # tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope))\n\n        # Summaries for Tensorboard\n        self.summaries = tf.summary.merge([\n            tf.summary.scalar(\"value_loss\", self.value_loss),\n            tf.summary.scalar(\"value_output\", tf.reduce_mean(self.value_output)),\n            # tf.summary.scalar(\"gradient_norm_policy\", tf.reduce_sum([tf.norm(item) for item in self.loss_gradients]))\n        ])\n\n        self.policy_summaries = tf.summary.merge([\n            tf.summary.scalar(\"policy_loss\", self.policy_loss),\n            tf.summary.scalar(\"adv\", tf.reduce_mean(self.tfadv)),\n            tf.summary.scalar(\"entropy\", self.entropy),\n            # tf.summary.scalar(\"gradient_norm_policy\", tf.reduce_sum([tf.norm(item) for item in self.loss_gradients]))\n        ])\n\n        if summaries_dir:\n            summary_dir = os.path.join(summaries_dir, \"summaries_{}\".format(scope))\n            if not os.path.exists(summary_dir):\n                os.makedirs(summary_dir)\n            self.summary_writer = tf.summary.FileWriter(summary_dir)\n\n        self.neighbors_list = []\n        for idx, node_id in enumerate(env.target_grids):\n            neighbor_indices = env.nodes[node_id].layers_neighbors_id[0]  # index in env.nodes\n            neighbor_ids = [env.target_grids.index(env.nodes[item].get_node_index()) for item in neighbor_indices]\n            neighbor_ids.append(idx)\n            # index in env.target_grids == index in state\n            self.neighbors_list.append(neighbor_ids)\n\n        # compute valid action mask.\n        self.valid_action_mask = np.ones((self.n_valid_grid, self.action_dim))\n        self.valid_neighbor_node_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.nodes\n        self.valid_neighbor_grid_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.target_grids\n        for grid_idx, grid_id in enumerate(env.target_grids):\n            for neighbor_idx, neighbor in enumerate(self.env.nodes[grid_id].neighbors):\n                if neighbor is None:\n                    self.valid_action_mask[grid_idx, neighbor_idx] = 0\n                else:\n                    node_index = neighbor.get_node_index()  # node_index in env.nodes\n                    self.valid_neighbor_node_id[grid_idx, neighbor_idx] = node_index\n                    self.valid_neighbor_grid_id[grid_idx, neighbor_idx] = env.target_grids.index(node_index)\n\n            self.valid_neighbor_node_id[grid_idx, -1] = grid_id\n            self.valid_neighbor_grid_id[grid_idx, -1] = grid_idx\n\n    def _build_value_model(self):\n\n        self.state = X = tf.placeholder(shape=[None, self.state_dim], dtype=tf.float32, name=\"X\")\n\n        # The TD target value\n        self.y_pl = tf.placeholder(shape=[None, 1], dtype=tf.float32, name=\"y\")\n\n        self.loss_lr = tf.placeholder(tf.float32, None, \"learning_rate\")\n\n        # 3 layers feed forward network.\n        l1 = fc(X, \"l1\", 128, act=tf.nn.relu)\n        l2 = fc(l1, \"l2\", 64, act=tf.nn.relu)\n        l3 = fc(l2, \"l3\", 32, act=tf.nn.relu)\n        # l1 = tf.layers.dense(X, 1024, tf.nn.sigmoid, trainable=trainable)\n        # l2 = tf.layers.dense(l1, 512, tf.nn.sigmoid, trainable=trainable)\n        # l3 = tf.layers.dense(l2, 32, tf.nn.sigmoid, trainable=trainable)\n        self.value_output = fc(l3, \"value_output\", 1, act=tf.nn.relu)\n\n        # self.losses = tf.square(self.y_pl - self.value_output)\n        self.value_loss = tf.reduce_mean(tf.squared_difference(self.y_pl, self.value_output))\n\n        self.value_train_op = tf.train.AdamOptimizer(self.loss_lr).minimize(self.value_loss)\n\n        return self.value_loss\n\n    def _build_mlp_policy(self):\n\n        self.policy_state = tf.placeholder(shape=[None, self.state_dim], dtype=tf.float32, name=\"P\")\n        self.ACTION = tf.placeholder(shape=[None, self.action_dim], dtype=tf.float32, name=\"action\")\n        self.tfadv = tf.placeholder(shape=[None, 1], dtype=tf.float32, name='advantage')\n        self.neighbor_mask = tf.placeholder(shape=[None, self.action_dim], dtype=tf.float32, name=\"neighbormask\")\n        # this mask filter invalid actions and those action smaller than current grid value.\n\n        l1 = fc(self.policy_state, \"l1\", 128, act=tf.nn.relu)\n        l2 = fc(l1, \"l2\", 64, act=tf.nn.relu)\n        l3 = fc(l2, \"l3\", 32, act=tf.nn.relu)\n\n        self.logits = logits = fc(l3, \"logits\", self.action_dim, act=tf.nn.relu) + 1  # avoid valid_logits are all zeros\n        self.valid_logits = logits * self.neighbor_mask\n\n        self.softmaxprob = tf.nn.softmax(tf.log(self.valid_logits + 1e-8))\n        self.logsoftmaxprob = tf.nn.log_softmax(self.softmaxprob)\n\n        self.neglogprob = - self.logsoftmaxprob * self.ACTION\n        self.actor_loss = tf.reduce_mean(tf.reduce_sum(self.neglogprob * self.tfadv, axis=1))\n        self.entropy = - tf.reduce_mean(self.softmaxprob * self.logsoftmaxprob)\n\n        self.policy_loss = self.actor_loss - 0.01 * self.entropy\n\n        self.policy_train_op = tf.train.AdamOptimizer(self.loss_lr).minimize(self.policy_loss)\n        return self.actor_loss, self.entropy\n\n    def predict(self, s):\n        value_output = self.sess.run(self.value_output, {self.state: s})\n\n        return value_output\n\n    def action(self, s, context, epsilon):\n        \"\"\" Compute current action for all grids give states\n\n        :param s: 504 x stat_dim,\n        :return:\n        \"\"\"\n\n        value_output = self.sess.run(self.value_output, {self.state: s}).flatten()\n        action_tuple = []\n        valid_prob = []\n\n        # for training policy gradient.\n        action_choosen_mat = []\n        policy_state = []\n        curr_state_value = []\n        next_state_ids = []\n\n        grid_ids = np.argmax(s[:, -self.n_valid_grid:], axis=1)\n\n        # compute neighbor mask according to centralized value\n        curr_neighbor_mask = deepcopy(self.valid_action_mask)\n        for idx, grid_valid_idx in enumerate(grid_ids):\n            valid_qvalues = value_output[self.neighbors_list[grid_valid_idx]]  # value of current and its nearby grids\n            temp_qvalue = np.zeros(self.action_dim)\n            temp_qvalue[curr_neighbor_mask[grid_valid_idx] > 0] = valid_qvalues\n            temp_qvalue[temp_qvalue < temp_qvalue[-1]] = 0\n            curr_neighbor_mask[grid_valid_idx][np.where(temp_qvalue < temp_qvalue[-1])] = 0\n            if np.sum(curr_neighbor_mask[grid_valid_idx]) == 0:\n                curr_neighbor_mask[grid_valid_idx] = self.valid_action_mask[grid_valid_idx]\n\n        # compute policy probability.\n        action_probs = self.sess.run(self.softmaxprob, {self.policy_state: s,\n                                                        self.neighbor_mask: curr_neighbor_mask})\n\n        curr_neighbor_mask_policy = []\n        # sample action.\n        for idx, grid_valid_idx in enumerate(grid_ids):\n            action_prob = action_probs[idx]\n\n            # cast invalid action to zero, avlid numerical issue.\n            action_prob[self.valid_action_mask[grid_valid_idx] == 0] = 0\n\n            valid_prob.append(action_prob)   # action probability for state value function\n            if int(context[idx]) == 0:\n                continue\n\n            curr_action_indices_temp = np.random.choice(self.action_dim, int(context[idx]),\n                                                        p=action_prob/np.sum(action_prob))\n            # num of drivers dispatched to nearby locations [2,3,2,3,1,3,3]\n            # for numerically stable, avoid sum of action_prob > 1 with small value\n\n            curr_action_indices = [0] * self.action_dim\n            for kk in curr_action_indices_temp:\n                curr_action_indices[kk] += 1\n\n            start_node_id = self.env.target_grids[grid_valid_idx]\n            for curr_action_idx, num_driver in enumerate(curr_action_indices):\n                if num_driver > 0:\n                    end_node_id = int(self.valid_neighbor_node_id[grid_valid_idx, curr_action_idx])\n                    if end_node_id != start_node_id:\n                        action_tuple.append((start_node_id, end_node_id, num_driver))\n\n                    # book keeping for training\n                    temp_a = np.zeros(self.action_dim)\n                    temp_a[curr_action_idx] = 1\n                    action_choosen_mat.append(temp_a)\n                    policy_state.append(s[idx])\n                    curr_state_value.append(value_output[idx])\n                    next_state_ids.append(self.valid_neighbor_grid_id[grid_valid_idx, curr_action_idx])\n                    curr_neighbor_mask_policy.append(curr_neighbor_mask[idx])\n\n        return action_tuple, np.stack(valid_prob), \\\n               np.stack(policy_state), np.stack(action_choosen_mat), curr_state_value, \\\n               np.stack(curr_neighbor_mask_policy), next_state_ids\n\n    def compute_advantage(self, curr_state_value, next_state_ids, next_state, node_reward, gamma):\n        \"\"\"for policy network\"\"\"\n        advantage = []\n        node_reward = node_reward.flatten()\n        qvalue_next = self.sess.run(self.value_output, {self.state: next_state}).flatten()\n\n        for idx, next_state_id in enumerate(next_state_ids):\n            next_state_id = int(next_state_id)\n            temp_adv = node_reward[next_state_id] + gamma * qvalue_next[next_state_id] - curr_state_value[idx]\n            advantage.append(temp_adv)\n        return advantage\n\n    def compute_targets(self, valid_prob, next_state, node_reward, gamma):\n        targets = []\n        node_reward = node_reward.flatten()\n        qvalue_next = self.sess.run(self.value_output, {self.state: next_state}).flatten()\n\n        for idx in np.arange(self.n_valid_grid):\n            grid_prob = valid_prob[idx][self.valid_action_mask[idx]>0]\n            neighbor_grid_ids = self.neighbors_list[idx]\n            curr_grid_target = np.sum(grid_prob * (node_reward[neighbor_grid_ids] + gamma * qvalue_next[neighbor_grid_ids]))\n            # assert np.sum(grid_prob) == 1 numerical issue.\n            targets.append(curr_grid_target)\n\n        return np.array(targets).reshape([-1, 1])\n\n    def initialization(self, s, y, learning_rate):\n        sess = self.sess\n        feed_dict = {self.state: s, self.y_pl: y, self.loss_lr: learning_rate}\n        _, value_loss = sess.run([self.value_train_op, self.value_loss], feed_dict)\n        return value_loss\n\n    def update_policy(self, policy_state, advantage, action_choosen_mat, curr_neighbor_mask, learning_rate, global_step):\n        sess = self.sess\n        feed_dict = {self.policy_state: policy_state,\n                     self.tfadv: advantage,\n                     self.ACTION: action_choosen_mat,\n                     self.neighbor_mask: curr_neighbor_mask,\n                     self.loss_lr: learning_rate}\n        summaries, _, loss = sess.run([self.policy_summaries, self.policy_train_op, self.policy_loss], feed_dict)\n\n        if self.summary_writer:\n            self.summary_writer.add_summary(summaries, global_step)\n            self.summary_writer.flush()\n        return loss\n\n    def update_value(self, s, y, learning_rate, global_step):\n        \"\"\"\n        Updates the estimator towards the given targets.\n\n        Args:\n          s: State input of shape [batch_size, state_dim]\n          a: Chosen actions of shape [batch_size, action_dim], 0, 1 mask\n          y: Targets of shape [batch_size]\n\n        Returns:\n          The calculated loss on the batch.\n        \"\"\"\n        sess = self.sess\n        feed_dict = {self.state: s, self.y_pl: y, self.loss_lr: learning_rate}\n        summaries, _, loss = sess.run([self.summaries, self.value_train_op, self.value_loss], feed_dict)\n\n        if self.summary_writer:\n            self.summary_writer.add_summary(summaries, global_step)\n            self.summary_writer.flush()\n        return loss\n\n\n\n\nclass stateProcessor:\n    \"\"\"\n        Process a raw global state into the states of grids.\n    \"\"\"\n\n    def __init__(self,\n                 target_id_states,\n                 target_grids,\n                 n_valid_grids):\n        self.target_id_states = target_id_states  # valid grid index for driver and order distribution.\n        self.target_grids = target_grids   # valid grid id [22, 24, ...]  504 grids\n        self.n_valid_grids = n_valid_grids\n        self.T = 144\n        self.action_dim = 7\n        self.extend_state = True\n\n    def utility_conver_states(self, curr_state):\n        curr_s = np.array(curr_state).flatten()\n        curr_s_new = [curr_s[idx] for idx in self.target_id_states]\n        return np.array(curr_s_new)\n\n    def utility_normalize_states(self, curr_s):\n        max_driver_num = np.max(curr_s[:self.n_valid_grids])\n        max_order_num = np.max(curr_s[self.n_valid_grids:])\n        if max_order_num == 0:\n            max_order_num = 1\n        if max_driver_num == 0:\n            max_driver_num = 1\n        curr_s_new = np.zeros_like(curr_s)\n        curr_s_new[:self.n_valid_grids] = curr_s[:self.n_valid_grids] / max_driver_num\n        curr_s_new[self.n_valid_grids:] = curr_s[self.n_valid_grids:] / max_order_num\n        return curr_s_new\n\n    def utility_conver_reward(self, reward_node):\n        reward_node_new = [reward_node[idx] for idx in self.target_grids]\n        return np.array(reward_node_new)\n\n    def reward_wrapper(self, info, curr_s):\n        \"\"\" reformat reward from env to the input of model.\n        :param info: [node_reward(including neighbors), neighbor_reward]\n        :param curr_s:  processed by utility_conver_states, same time step as info.\n        :return:\n        \"\"\"\n\n        info_reward = info[0]\n        valid_nodes_reward = self.utility_conver_reward(info_reward[0])\n        devide = curr_s[:self.n_valid_grids]\n        devide[devide == 0] = 1\n        valid_nodes_reward = valid_nodes_reward/devide  # averaged rewards for drivers arriving this grid\n        return valid_nodes_reward\n\n    def compute_context(self, info):\n        # compute context\n        context = info.flatten()\n        context = [context[idx] for idx in self.target_grids]\n        return context\n\n    def to_grid_states(self, curr_s, curr_city_time):\n        \"\"\" extend global state to all agents' state.\n\n        :param curr_s:\n        :param curr_city_time: curr_s time step\n        :return:\n        \"\"\"\n        T = self.T\n\n        # curr_s = self.utility_conver_states(curr_state)\n        time_one_hot = np.zeros((T))\n        time_one_hot[curr_city_time % T] = 1\n        onehot_grid_id = np.eye(self.n_valid_grids)\n\n        s_grid = np.zeros((self.n_valid_grids, self.n_valid_grids * 3 + T))\n        s_grid[:, :self.n_valid_grids * 2] = np.stack([curr_s] * self.n_valid_grids)\n        s_grid[:, self.n_valid_grids * 2:self.n_valid_grids * 2 + T] = np.stack([time_one_hot] * self.n_valid_grids)\n        s_grid[:, -self.n_valid_grids:] = onehot_grid_id\n\n        return np.array(s_grid)\n\n    def to_grid_rewards(self, node_reward):\n        \"\"\"\n        :param node_reward: curr_city_time + 1 's reward\n        :return:\n        \"\"\"\n        return np.array(node_reward).reshape([-1, 1])\n\n    def to_action_mat(self, action_neighbor_idx):\n        action_mat = np.zeros((len(action_neighbor_idx), self.action_dim))\n        action_mat[np.arange(action_mat.shape[0]), action_neighbor_idx] = 1\n        return action_mat\n\n\nclass policyReplayMemory:\n    def __init__(self, memory_size, batch_size):\n        self.states = []\n        # self.next_states = []\n        self.neighbor_mask = []\n        self.actions = []\n        self.rewards = []  # advantages\n\n        self.batch_size = batch_size\n        self.memory_size = memory_size\n        self.current = 0\n        self.curr_lens = 0\n\n    def add(self, s, a, r, mask):\n        if self.curr_lens == 0:\n            self.states = s\n            self.actions = a\n            self.rewards = r\n            self.neighbor_mask = mask\n            self.curr_lens = self.states.shape[0]\n\n        elif self.curr_lens <= self.memory_size:\n            self.states = np.concatenate((self.states, s),axis=0)\n            self.neighbor_mask = np.concatenate((self.neighbor_mask, mask), axis=0)\n            self.actions = np.concatenate((self.actions, a), axis=0)\n            self.rewards = np.concatenate((self.rewards, r), axis=0)\n            self.curr_lens = self.states.shape[0]\n        else:\n            new_sample_lens = s.shape[0]\n            # random.seed(0)\n            index = random.randint(0, self.curr_lens - new_sample_lens)\n\n            self.states[index:(index + new_sample_lens)] = s\n            self.actions[index:(index + new_sample_lens)] = a\n            self.rewards[index:(index + new_sample_lens)] = r\n            self.neighbor_mask[index:(index + new_sample_lens)] = mask\n\n    def sample(self):\n\n        if self.curr_lens <= self.batch_size:\n            return [self.states, self.actions, np.array(self.rewards), self.neighbor_mask]\n        # random.seed(0)\n        indices = random.sample(range(0, self.curr_lens), self.batch_size)\n        batch_s = self.states[indices]\n        batch_a = self.actions[indices]\n        batch_r = self.rewards[indices]\n        batch_mask = self.neighbor_mask[indices]\n        return [batch_s, batch_a, batch_r, batch_mask]\n\n    def reset(self):\n        self.states = []\n        self.actions = []\n        self.rewards = []\n        self.neighbor_mask = []\n        self.curr_lens = 0\n\n\nclass ReplayMemory:\n    \"\"\" collect the experience and sample a batch for training networks.\n        without time ordering\n    \"\"\"\n    def __init__(self, memory_size, batch_size):\n        self.states = []\n        self.next_states = []\n        self.actions = []\n        self.rewards = []\n\n        self.batch_size = batch_size\n        self.memory_size = memory_size\n        self.current = 0\n        self.curr_lens = 0  # current memory lens\n\n    def add(self, s, a, r, next_s):\n        if self.curr_lens == 0:\n            self.states = s\n            self.actions = a\n            self.rewards = r\n            self.next_states = next_s\n            self.curr_lens = self.states.shape[0]\n\n        elif self.curr_lens <= self.memory_size:\n            self.states = np.concatenate((self.states, s),axis=0)\n            self.next_states = np.concatenate((self.next_states, next_s), axis=0)\n            self.actions = np.concatenate((self.actions, a), axis=0)\n            self.rewards = np.concatenate((self.rewards, r), axis=0)\n            self.curr_lens = self.states.shape[0]\n        else:\n            new_sample_lens = s.shape[0]\n            # random.seed(0)\n            index = random.randint(0, self.curr_lens - new_sample_lens)\n\n            self.states[index:(index + new_sample_lens)] = s\n            self.actions[index:(index + new_sample_lens)] = a\n            self.rewards[index:(index + new_sample_lens)] = r\n            self.next_states[index:(index + new_sample_lens)] = next_s\n\n    def sample(self):\n\n        if self.curr_lens <= self.batch_size:\n            return [self.states, self.actions, self.rewards, self.next_states]\n        # random.seed(0)\n        indices = random.sample(range(0, self.curr_lens), self.batch_size)\n        batch_s = self.states[indices]\n        batch_a = self.actions[indices]\n        batch_r = self.rewards[indices]\n        batch_mask = self.next_states[indices]\n        return [batch_s, batch_a, batch_r, batch_mask]\n\n    def reset(self):\n        self.states = []\n        self.actions = []\n        self.rewards = []\n        self.next_states = []\n        self.curr_lens = 0\n\n\n\nclass ModelParametersCopier():\n    \"\"\"\n    Copy model parameters of one estimator to another.\n    \"\"\"\n\n    def __init__(self, estimator1, estimator2):\n        \"\"\"\n        Defines copy-work operation graph.\n        Args:\n          estimator1: Estimator to copy the paramters from\n          estimator2: Estimator to copy the parameters to\n        \"\"\"\n        e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)]\n        e1_params = sorted(e1_params, key=lambda v: v.name)\n        e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)]\n        e2_params = sorted(e2_params, key=lambda v: v.name)\n\n        self.update_ops = []\n        for e1_v, e2_v in zip(e1_params, e2_params):\n            op = e2_v.assign(e1_v)\n            self.update_ops.append(op)\n\n    def make(self, sess):\n        \"\"\"\n        Makes copy.\n        Args:\n            sess: Tensorflow session instance\n        \"\"\"\n        sess.run(self.update_ops)\n\n\n\n\n"
  },
  {
    "path": "algorithm/cDQN.py",
    "content": "\n\nimport numpy as np\nimport tensorflow as tf\nimport random, os\nfrom alg_utility import *\n\n# this is essentially deep expected SARSA.\nclass Estimator:\n    \"\"\" build value network\n    \"\"\"\n    def __init__(self,\n                 sess,\n                 action_dim,\n                 state_dim,\n                 env,\n                 scope=\"estimator\",\n                 summaries_dir=None):\n        self.sess = sess\n        self.n_valid_grid = env.n_valid_grids\n        self.action_dim = action_dim\n        self.state_dim = state_dim\n        self.M = env.M\n        self.N = env.N\n        self.scope = scope\n        self.T = 144\n        self.env = env\n\n        # Writes Tensorboard summaries to disk\n        self.summary_writer = None\n        with tf.variable_scope(scope):\n            # Build the graph\n            self._build_model()\n\n            self.loss_gradients = tf.gradients(self.loss, tf.trainable_variables(scope=scope))\n                                           # tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=self.scope))\n        # Summaries for Tensorboard\n        self.summaries = tf.summary.merge([\n            tf.summary.scalar(\"loss\", self.loss),\n            tf.summary.scalar(\"value_output\", tf.reduce_mean(self.value_output)),\n            tf.summary.scalar(\"gradient_norm_policy\", tf.reduce_sum([tf.norm(item) for item in self.loss_gradients]))\n        ])\n\n        if summaries_dir:\n            summary_dir = os.path.join(summaries_dir, \"summaries_{}\".format(scope))\n            if not os.path.exists(summary_dir):\n                os.makedirs(summary_dir)\n            self.summary_writer = tf.summary.FileWriter(summary_dir)\n\n        self.neighbors_list = []\n        for idx, node_id in enumerate(env.target_grids):\n            neighbor_indices = env.nodes[node_id].layers_neighbors_id[0]  # index in env.nodes\n            neighbor_ids = [env.target_grids.index(env.nodes[item].get_node_index()) for item in neighbor_indices]\n            neighbor_ids.append(idx)\n            # index in env.target_grids == index in state\n            self.neighbors_list.append(neighbor_ids)\n\n        # compute valid action mask.\n        self.valid_action_mask = np.ones((self.n_valid_grid, self.action_dim))\n        self.valid_neighbor_node_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.nodes\n        self.valid_neighbor_grid_id = np.zeros((self.n_valid_grid, self.action_dim))  # id in env.target_grids\n        for grid_idx, grid_id in enumerate(env.target_grids):\n            for neighbor_idx, neighbor in enumerate(self.env.nodes[grid_id].neighbors):\n                if neighbor is None:\n                    self.valid_action_mask[grid_idx, neighbor_idx] = 0\n                else:\n                    node_index = neighbor.get_node_index()  # node_index in env.nodes\n                    self.valid_neighbor_node_id[grid_idx, neighbor_idx] = node_index\n                    self.valid_neighbor_grid_id[grid_idx, neighbor_idx] = env.target_grids.index(node_index)\n\n            self.valid_neighbor_node_id[grid_idx, -1] = grid_id\n            self.valid_neighbor_grid_id[grid_idx, -1] = grid_idx\n\n    def _build_model(self):\n        trainable = True\n        self.state = X = tf.placeholder(shape=[None, self.state_dim], dtype=tf.float32, name=\"X\")\n\n        # The TD target value\n        self.y_pl = tf.placeholder(shape=[None, 1], dtype=tf.float32, name=\"y\")\n\n        self.loss_lr = tf.placeholder(tf.float32, None, \"learning_rate\")\n\n        # 3 layers feed forward network.\n        l1 = fc(X, \"l1\", 128, act=tf.nn.relu)\n        l2 = fc(l1, \"l2\", 64, act=tf.nn.relu)\n        l3 = fc(l2, \"l3\", 32, act=tf.nn.relu)\n        # l1 = tf.layers.dense(X, 1024, tf.nn.sigmoid, trainable=trainable)\n        # l2 = tf.layers.dense(l1, 512, tf.nn.sigmoid, trainable=trainable)\n        # l3 = tf.layers.dense(l2, 32, tf.nn.sigmoid, trainable=trainable)\n        self.value_output = fc(l3, \"value_output\", 1, act=tf.nn.relu)\n\n        # self.losses = tf.square(self.y_pl - self.value_output)\n        self.loss = tf.reduce_mean(tf.squared_difference(self.y_pl, self.value_output))\n\n        self.train_op = tf.train.AdamOptimizer(self.loss_lr).minimize(self.loss)\n\n\n    def predict(self, s):\n        value_output = self.sess.run(self.value_output, {self.state: s})\n\n        return value_output\n\n    def action(self, s, context, epsilon):\n        \"\"\" Compute current action for all grids give states\n\n        :param s: 504 x stat_dim,\n        :return:\n        \"\"\"\n\n        # value of each grid at next time step, dispatched according to this value.\n        value_output = self.sess.run(self.value_output, {self.state: s}).flatten()\n        action_tuple = []\n        valid_prob = []\n\n        grid_ids = np.argmax(s[:, -self.n_valid_grid:], axis=1)\n\n        for idx, grid_valid_idx in enumerate(grid_ids):\n            valid_qvalues = value_output[self.neighbors_list[grid_valid_idx]]\n            temp_qvalue = np.zeros(self.action_dim)\n\n            if np.sum(valid_qvalues) == 0:\n                # all value equals to 0. this could explores conflicts action.\n                temp_qvalue[self.valid_action_mask[grid_valid_idx] > 0] = 1. / np.sum(\n                    self.valid_action_mask[grid_valid_idx])\n                action_prob = temp_qvalue\n                valid_prob.append(action_prob)\n            else:\n\n                temp_qvalue[self.valid_action_mask[grid_valid_idx] > 0] = valid_qvalues\n                temp_qvalue[temp_qvalue < temp_qvalue[-1]] = 0\n\n                best_action = np.argmax(temp_qvalue)\n                num_valid_action = np.count_nonzero(temp_qvalue)\n                action_prob = np.zeros_like(temp_qvalue)\n                action_prob[temp_qvalue > 0] = epsilon / float(num_valid_action)\n                action_prob[best_action] += 1 - epsilon\n                valid_prob.append(action_prob)\n\n            if int(context[idx]) == 0:\n                continue\n            curr_action_indices = np.random.multinomial(int(context[idx]),\n                                                        action_prob)\n\n            start_node_id = self.env.target_grids[grid_valid_idx]\n            for curr_action_idx, num_driver in enumerate(curr_action_indices):\n                if num_driver > 0:\n                    end_node_id = int(self.valid_neighbor_node_id[grid_valid_idx, curr_action_idx])\n                    if end_node_id != start_node_id:\n                        action_tuple.append((start_node_id, end_node_id, num_driver))\n\n        return action_tuple, np.stack(valid_prob)\n\n    def compute_targets(self, valid_prob, next_state, node_reward, gamma):\n        targets = []\n        node_reward = node_reward.flatten()\n        qvalue_next = self.sess.run(self.value_output, {self.state: next_state}).flatten()  # qvalue of next state\n\n        for idx in np.arange(self.n_valid_grid):\n            grid_prob = valid_prob[idx][self.valid_action_mask[idx]>0]\n            neighbor_grid_ids = self.neighbors_list[idx]\n            best_grid = np.argmax(grid_prob)\n            curr_grid_target = node_reward[neighbor_grid_ids][best_grid] + gamma * qvalue_next[neighbor_grid_ids][best_grid]\n            targets.append(curr_grid_target)\n\n        return np.array(targets).reshape([-1, 1])\n\n    def initialization(self, s, y, learning_rate):\n        sess = self.sess\n        feed_dict = {self.state: s, self.y_pl: y, self.loss_lr: learning_rate}\n        _, loss = sess.run([self.train_op, self.loss], feed_dict)\n        return loss\n\n    def update(self, s, y, learning_rate, global_step):\n        \"\"\"\n        Updates the estimator towards the given targets.\n\n        Args:\n          s: State input of shape [batch_size, state_dim]\n          a: Chosen actions of shape [batch_size, action_dim], 0, 1 mask\n          y: Targets of shape [batch_size]\n\n        Returns:\n          The calculated loss on the batch.\n        \"\"\"\n        sess = self.sess\n        feed_dict = {self.state: s, self.y_pl: y, self.loss_lr: learning_rate}\n        summaries, _, loss = sess.run([self.summaries, self.train_op, self.loss], feed_dict)\n\n        if self.summary_writer:\n            self.summary_writer.add_summary(summaries, global_step)\n            self.summary_writer.flush()\n        return loss\n\n    def _build_cnn_model(self):\n\n        # states of grid id and time\n        self.state_spacetime = Xst = tf.placeholder(shape=[None, self.n_valid_grid + self.T], dtype=tf.uint8, name=\"Xst\")\n\n        # states of distribution\n        self.state = X = tf.placeholder(shape=[None, self.M, self.N,  4], dtype=tf.uint8, name=\"X\")\n\n        # The TD target value\n        self.y_pl = tf.placeholder(shape=[None], dtype=tf.float32, name=\"y\")\n\n        batch_size = tf.shape(self.state)[0]\n\n        conv1 = tf.contrib.layers.conv2d(\n            X, 32, 8, 4, activation_fn=tf.nn.relu)\n        conv2 = tf.contrib.layers.conv2d(\n            conv1, 64, 4, 2, activation_fn=tf.nn.relu)\n        conv3 = tf.contrib.layers.conv2d(\n            conv2, 64, 3, 1, activation_fn=tf.nn.relu)\n\n        # Fully connected layers\n        flattened = tf.contrib.layers.flatten(conv3)\n        fc1 = tf.contrib.layers.fully_connected(flattened, 512)\n        self.predictions = tf.contrib.layers.fully_connected(fc1, self.action_dim)\n\n\nclass stateProcessor:\n    \"\"\"\n        Process a raw global state into the states of grids.\n    \"\"\"\n\n    def __init__(self,\n                 target_id_states,\n                 target_grids,\n                 n_valid_grids):\n        self.target_id_states = target_id_states  # valid grid index for driver and order distribution.\n        self.target_grids = target_grids   # valid grid id [22, 24, ...]\n        self.n_valid_grids = n_valid_grids\n        self.T = 144\n        self.action_dim = 7\n        self.extend_state = True\n\n    def utility_conver_states(self, curr_state):\n        curr_s = np.array(curr_state).flatten()\n        curr_s_new = [curr_s[idx] for idx in self.target_id_states]\n        return np.array(curr_s_new)\n\n    def utility_normalize_states(self, curr_s):\n        max_driver_num = np.max(curr_s[:self.n_valid_grids])\n        max_order_num = np.max(curr_s[self.n_valid_grids:])\n\n        curr_s_new = np.zeros_like(curr_s)\n        curr_s_new[:self.n_valid_grids] = curr_s[:self.n_valid_grids] / max_driver_num\n        curr_s_new[self.n_valid_grids:] = curr_s[self.n_valid_grids:] / max_order_num\n        return curr_s_new\n\n    def utility_conver_reward(self, reward_node):\n        reward_node_new = [reward_node[idx] for idx in self.target_grids]\n        return np.array(reward_node_new)\n\n    def reward_wrapper(self, info, curr_s):\n        info_reward = info[0]\n        valid_nodes_reward = self.utility_conver_reward(info_reward[0])\n        devide = curr_s[:self.n_valid_grids]\n        devide[devide == 0] = 1\n        valid_nodes_reward = valid_nodes_reward/devide\n        return valid_nodes_reward\n\n    def compute_context(self, info):\n        # 计算context\n        context = info.flatten()\n        context = [context[idx] for idx in self.target_grids]\n        return context\n\n    def to_grid_states(self, curr_s, curr_city_time):\n\n        T = self.T\n\n        # curr_s = self.utility_conver_states(curr_state)\n        time_one_hot = np.zeros((T))\n        time_one_hot[curr_city_time % T] = 1\n        onehot_grid_id = np.eye(self.n_valid_grids)\n\n        s_grid = np.zeros((self.n_valid_grids, self.n_valid_grids * 3 + T))\n        s_grid[:, :self.n_valid_grids * 2] = np.stack([curr_s] * self.n_valid_grids)\n        s_grid[:, self.n_valid_grids * 2:self.n_valid_grids * 2 + T] = np.stack([time_one_hot] * self.n_valid_grids)\n        s_grid[:, -self.n_valid_grids:] = onehot_grid_id\n\n        return np.array(s_grid)\n\n    def to_grid_rewards(self, node_reward):\n        return np.array(node_reward).reshape([-1, 1])\n\n    def to_action_mat(self, action_neighbor_idx):\n        action_mat = np.zeros((len(action_neighbor_idx), self.action_dim))\n        action_mat[np.arange(action_mat.shape[0]), action_neighbor_idx] = 1\n        return action_mat\n\n\nclass ReplayMemory:\n    \"\"\" collect the experience and sample a batch for training networks.\n        without time ordering\n    \"\"\"\n    def __init__(self, memory_size, batch_size):\n        self.states = []\n        self.next_states = []\n        self.actions = []\n        self.rewards = []\n\n        self.batch_size = batch_size\n        self.memory_size = memory_size\n        self.current = 0\n        self.curr_lens = 0\n\n    def add(self, s, a, r, next_s):\n        if self.curr_lens == 0:\n            self.states = s\n            self.actions = a\n            self.rewards = r\n            self.next_states = next_s\n            self.curr_lens = self.states.shape[0]\n\n        elif self.curr_lens <= self.memory_size:\n            self.states = np.concatenate((self.states, s),axis=0)\n            self.next_states = np.concatenate((self.next_states, next_s), axis=0)\n            self.actions = np.concatenate((self.actions, a), axis=0)\n            self.rewards = np.concatenate((self.rewards, r), axis=0)\n            self.curr_lens = self.states.shape[0]\n        else:\n            new_sample_lens = s.shape[0]\n            index = random.randint(0, self.curr_lens - new_sample_lens)\n\n            self.states[index:(index + new_sample_lens)] = s\n            self.actions[index:(index + new_sample_lens)] = a\n            self.rewards[index:(index + new_sample_lens)] = r\n            self.next_states[index:(index + new_sample_lens)] = next_s\n\n    def sample(self):\n\n        if self.curr_lens <= self.batch_size:\n            return [self.states, self.actions, self.rewards, self.next_states]\n        indices = random.sample(range(0, self.curr_lens), self.batch_size)\n        batch_s = self.states[indices]\n        batch_a = self.actions[indices]\n        batch_r = self.rewards[indices]\n        batch_next_s = self.next_states[indices]\n        return [batch_s, batch_a, batch_r, batch_next_s]\n\n    def reset(self):\n        self.states = []\n        self.actions = []\n        self.rewards = []\n        self.next_states = []\n        self.curr_lens = 0\n\n\n\nclass ModelParametersCopier():\n    \"\"\"\n    Copy model parameters of one estimator to another.\n    \"\"\"\n\n    def __init__(self, estimator1, estimator2):\n        \"\"\"\n        Defines copy-work operation graph.\n        Args:\n          estimator1: Estimator to copy the paramters from\n          estimator2: Estimator to copy the parameters to\n        \"\"\"\n        e1_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator1.scope)]\n        e1_params = sorted(e1_params, key=lambda v: v.name)\n        e2_params = [t for t in tf.trainable_variables() if t.name.startswith(estimator2.scope)]\n        e2_params = sorted(e2_params, key=lambda v: v.name)\n\n        self.update_ops = []\n        for e1_v, e2_v in zip(e1_params, e2_params):\n            op = e2_v.assign(e1_v)\n            self.update_ops.append(op)\n\n    def make(self, sess):\n        \"\"\"\n        Makes copy.\n        Args:\n            sess: Tensorflow session instance\n        \"\"\"\n        sess.run(self.update_ops)\n\n\n\n\n"
  },
  {
    "path": "run/run_IDQN.py",
    "content": "import pickle, sys\nsys.path.append(\"../\")\n\n# from simulator.utilities import *\nfrom algorithm.alg_utility import *\nfrom simulator.envs import *\n\n\n################## Load data ###################################\ndir_prefix = \"/mnt/research/linkaixi/AllData/dispatch/\"\ncurrent_time = time.strftime(\"%Y%m%d_%H-%M\")\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\nmkdir_p(log_dir)\nprint \"log dir is {}\".format(log_dir)\n\ndata_dir = dir_prefix + \"dispatch_realdata/data_for_simulator/\"\norder_time_dist = []\norder_price_dist = []\nmapped_matrix_int = pickle.load(open(data_dir+\"mapped_matrix_int.pkl\", 'rb'))\norder_num_dist = pickle.load(open(data_dir+\"order_num_dist\", 'rb'))\nidle_driver_dist_time = pickle.load(open(data_dir+\"idle_driver_dist_time\", 'rb'))\nidle_driver_location_mat = pickle.load(open(data_dir+\"idle_driver_location_mat\", 'rb'))\ntarget_ids = pickle.load(open(data_dir+\"target_grid_id.pkl\", 'rb'))\nonoff_driver_location_mat = pickle.load(open(data_dir + \"onoff_driver_location_mat\", 'rb'))\norder_filename = dir_prefix + \"dispatch_realdata/orders/all_orders_target\"\norder_real = pickle.load(open(order_filename, 'rb'))\nM, N = mapped_matrix_int.shape\nprint \"finish load data\"\n\n\n################## Initialize env ###################################\nn_side = 6\nGAMMA = 0.9\nl_max = 9\n\nenv = CityReal(mapped_matrix_int, order_num_dist,\n               idle_driver_dist_time, idle_driver_location_mat,\n               order_time_dist, order_price_dist,\n               l_max, M, N, n_side, 1/28.0, order_real, onoff_driver_location_mat)\n\n\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\n\n\ntemp = np.array(env.target_grids) + env.M * env.N\ntarget_id_states = env.target_grids + temp.tolist()\n\n# curr_s = np.array(env.reset_clean()).flatten()  # [0] driver dist; [1] order dist\n# curr_s = utility_conver_states(curr_s, target_id_states)\nprint \"******************* Finish generating one day order **********************\"\n\n\n\nprint \"******************* Starting training Deep SARSA **********************\"\nfrom algorithm.IDQN import *\n\nMAX_ITER = 50  # 10 iteration the Q-learning loss will converge.\nis_plot_figure = False\ncity_time_start = 0\nEP_LEN = 144\nglobal_step = 0\ncity_time_end = city_time_start + EP_LEN\nEPSILON = 0.9\ngamma = 0.9\nlearning_rate = 1e-2\n\nprev_epsiode_reward = 0\nall_rewards = []\norder_response_rates = []\nvalue_table_sum = []\nepisode_rewards = []\nepisode_conflicts_drivers = []\norder_response_rate_episode = []\nepisode_dispatched_drivers = []\nT = 144\naction_dim = 7\nstate_dim = env.n_valid_grids * 3 + T\n\n# tf.reset_default_graph()\nsess = tf.Session()\ntf.set_random_seed(1)\nq_estimator = Estimator(sess, action_dim,\n                        state_dim,\n                        env,\n                        scope=\"q_estimator\",\n                        summaries_dir=log_dir)\n\ntarget_estimator = Estimator(sess, action_dim, state_dim, env, scope=\"target_q\")\nsess.run(tf.global_variables_initializer())\nestimator_copy = ModelParametersCopier(q_estimator, target_estimator)\nreplay = ReplayMemory(memory_size=1e+6, batch_size=3000)\nstateprocessor = stateProcessor(target_id_states, env.target_grids, env.n_valid_grids)\n\nsaver = tf.train.Saver()\nsave_random_seed = []\nN_ITER_RUNS = 25\ntemp_value = 10\nRATIO = 1\nEPSILON_start = 0.5\nEPSILON_end = 0.1\nepsilon_decay_steps=15\nepsilons = np.linspace(EPSILON_start, EPSILON_end, epsilon_decay_steps)\nfor n_iter in np.arange(25):\n    RANDOM_SEED = n_iter + MAX_ITER - temp_value\n    env.reset_randomseed(RANDOM_SEED)\n    save_random_seed.append(RANDOM_SEED)\n    batch_s, batch_a, batch_r = [], [], []\n    batch_reward_gmv = []\n    epsiode_reward = 0\n    num_dispatched_drivers = 0\n\n    # reset env\n    is_regenerate_order = 1\n    curr_state = env.reset_clean(generate_order=is_regenerate_order, ratio=RATIO, city_time=city_time_start)\n    info = env.step_pre_order_assigin(curr_state)\n    context = stateprocessor.compute_context(info)\n    curr_s = stateprocessor.utility_conver_states(curr_state)\n    normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n    s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n    # record rewards to update the value table\n    episodes_immediate_rewards = []\n    num_conflicts_drivers = []\n    curr_num_actions = []\n    epsilon = epsilons[n_iter] if n_iter < 15 else EPSILON_end\n    for ii in np.arange(EP_LEN + 1):\n\n        # INPUT: state,  OUTPUT: action\n        qvalues, action_idx, action_idx_valid, action_neighbor_idx, \\\n        action_tuple, action_starting_gridids = q_estimator.action(s_grid, context, epsilon)\n        # a0\n\n        # ONE STEP: r0\n        next_state, r, info = env.step(action_tuple, 2)\n\n        # r0\n        immediate_reward = stateprocessor.reward_wrapper(info, curr_s)\n\n        # a0\n        action_mat = stateprocessor.to_action_mat(action_neighbor_idx)\n\n        # s0\n        s_grid_train = stateprocessor.to_grid_state_for_training(s_grid, action_starting_gridids)\n\n        # s1\n        s_grid_next = stateprocessor.to_grid_next_states(s_grid_train, next_state, action_idx_valid, env.city_time)\n\n        # Save transition to replay memory\n        if ii != 0:\n            # r1, c0\n            r_grid = stateprocessor.to_grid_rewards(action_idx_valid_prev, immediate_reward)\n            targets_batch = r_grid + gamma * target_estimator.predict(s_grid_next_prev)\n\n            # s0, a0, r1\n            replay.add(state_mat_prev, action_mat_prev, targets_batch, s_grid_next_prev)\n\n        state_mat_prev = s_grid_train\n        action_mat_prev = action_mat\n        context_prev = context\n        s_grid_next_prev = s_grid_next\n        action_idx_valid_prev = action_idx_valid\n\n        # c1\n        context = stateprocessor.compute_context(info[1])\n        # s1\n        curr_s = stateprocessor.utility_conver_states(next_state)\n        normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n        s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n        # Sample a minibatch from the replay memory and update q network training method1\n        if replay.curr_lens != 0:\n            for _ in np.arange(20):\n                fetched_batch = replay.sample()\n                mini_s, mini_a, mini_target, mini_next_s = fetched_batch\n                q_estimator.update(mini_s, mini_a, mini_target, learning_rate, global_step)\n                global_step += 1\n\n        # Perform gradient descent update\n        # book keeping\n        global_step += 1\n        all_rewards.append(r)\n        batch_reward_gmv.append(r)\n        order_response_rates.append(env.order_response_rate)\n        num_conflicts_drivers.append(collision_action(action_tuple))\n        curr_num_action = np.sum([aa[2] for aa in action_tuple]) if len(action_tuple) != 0 else 0\n        curr_num_actions.append(curr_num_action)\n\n    episode_reward = np.sum(batch_reward_gmv[1:])\n    episode_rewards.append(episode_reward)\n    n_iter_order_response_rate = np.mean(order_response_rates[1:])\n    order_response_rate_episode.append(n_iter_order_response_rate)\n    episode_conflicts_drivers.append(np.sum(num_conflicts_drivers[:-1]))\n    episode_dispatched_drivers.append(np.sum(curr_num_actions[:-1]))\n\n    print \"iteration {} ********* reward {} order{} conflicts {} drivers {}\".format(n_iter, episode_reward,\n                                                                                             order_response_rate_episode[-1],\n                                                                                             episode_conflicts_drivers[-1],\n                                                                                             episode_dispatched_drivers[-1])\n\n    pickle.dump([episode_rewards, order_response_rate_episode, save_random_seed, episode_conflicts_drivers,\n                 episode_dispatched_drivers], open(log_dir + \"results.pkl\", \"w\"))\n\n    if n_iter == 24:\n        break\n\n    # # training method 2.\n    # for _ in np.arange(4000):\n    #     fetched_batch = replay.sample()\n    #     mini_s, mini_a, mini_target, mini_next_s = fetched_batch\n    #     q_estimator.update(mini_s, mini_a, mini_target, learning_rate, global_step)\n    #     global_step += 1\n\n    # update target Q network\n    estimator_copy.make(sess)\n\n\n    saver.save(sess, log_dir+\"model.ckpt\")\n\n\n"
  },
  {
    "path": "run/run_baseline_nopolicy.py",
    "content": "\nimport pickle, sys\nsys.path.append(\"../\")\n\nfrom simulator.envs import *\n\n\n################## Load data ###################################\ndir_prefix = \"/mnt/research/linkaixi/AllData/dispatch/\"\ncurrent_time = time.strftime(\"%Y%m%d_%H-%M\")\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\nmkdir_p(log_dir)\nprint \"log dir is {}\".format(log_dir)\n\ndata_dir = dir_prefix + \"dispatch_realdata/data_for_simulator2017-07-24_2017-08-20/\"\norder_time_dist = []\norder_price_dist = []\nmapped_matrix_int = pickle.load(open(data_dir+\"mapped_matrix_int.pkl\", 'rb'))\norder_num_dist = pickle.load(open(data_dir+\"order_num_dist\", 'rb'))\nidle_driver_dist_time = pickle.load(open(data_dir+\"idle_driver_dist_time\", 'rb'))\nidle_driver_location_mat = pickle.load(open(data_dir+\"idle_driver_location_mat\", 'rb'))\ntarget_ids = pickle.load(open(data_dir+\"target_grid_id.pkl\", 'rb'))\nonoff_driver_location_mat = pickle.load(open(data_dir + \"onoff_driver_location_mat\", 'rb'))\norder_filename = dir_prefix + \"dispatch_realdata/order_new_2017-07-24_2017-08-20/all_orders_target\"\norder_real = pickle.load(open(order_filename, 'rb'))\nM, N = mapped_matrix_int.shape\nprint \"finish load data\"\n\n\n################## Initialize env ###################################\nn_side = 6\nGAMMA = 0.9\nl_max = 9\n\nenv = CityReal(mapped_matrix_int, order_num_dist,\n               idle_driver_dist_time, idle_driver_location_mat,\n               order_time_dist, order_price_dist,\n               l_max, M, N, n_side, 1/28.0, order_real, onoff_driver_location_mat)\n\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\nmkdir_p(log_dir)\n\ntemp = np.array(env.target_grids) + env.M * env.N\ntarget_id_states = env.target_grids + temp.tolist()\n\nprint \"******************* Finish generating one day order **********************\"\n\n\n\nprint \"******************* Starting runing no policy baseline **********************\"\n\n\nMAX_ITER = 50  # 10 iteration the Q-learning loss will converge.\nis_plot_figure = False\ncity_time_start = 0\nEP_LEN = 144\nglobal_step = 0\ncity_time_end = city_time_start + EP_LEN\nepsilon = 0.5\ngamma = 0.9\nlearning_rate = 1e-3\n\nprev_epsiode_reward = 0\ncurr_num_actions = []\nall_rewards = []\norder_response_rate_episode = []\nvalue_table_sum = []\nepisode_rewards = []\nnum_conflicts_drivers = []\ndriver_numbers_episode = []\norder_numbers_episode = []\n\nT = 144\naction_dim = 7\nstate_dim = env.n_valid_grids * 3 + T\n\nrecord_all_order_response_rate = []\n\n\ndef compute_context(target_grids, info):\n\n    context = info.flatten()\n    context = [context[idx] for idx in target_grids]\n    return context\n\nRATIO = 1\n\nprint \"Start Running \"\nsave_random_seed = []\nepisode_avaliables_vehicles = []\nfor n_iter in np.arange(10):\n    RANDOM_SEED = n_iter + MAX_ITER + 5\n    env.reset_randomseed(RANDOM_SEED)\n    save_random_seed.append(RANDOM_SEED)\n    batch_s, batch_a, batch_r = [], [], []\n    batch_reward_gmv = []\n    epsiode_reward = 0\n    num_dispatched_drivers = 0\n\n    driver_numbers = []\n    order_numbers = []\n    is_regenerate_order = 1\n    curr_state = env.reset_clean(generate_order=is_regenerate_order, ratio=RATIO, city_time=city_time_start)\n    driver_numbers.append(np.sum(curr_state[0]))\n    order_numbers.append(np.sum(curr_state[1]))\n    info = env.step_pre_order_assigin(curr_state)\n    context = compute_context(env.target_grids, np.array(info))\n\n    # record rewards to update the value table\n    episodes_immediate_rewards = []\n    order_response_rates = []\n    available_drivers = []\n    for ii in np.arange(EP_LEN + 1):\n        available_drivers.append(np.sum(context))\n        # ONE STEP: r0\n        next_state, r, info = env.step([], 2)\n        driver_numbers.append(np.sum(next_state[0]))\n        order_numbers.append(np.sum(next_state[1]))\n\n        context = compute_context(env.target_grids, np.array(info[1]))\n        # Perform gradient descent update\n        # book keeping\n        global_step += 1\n        all_rewards.append(r)\n        batch_reward_gmv.append(r)\n        order_response_rates.append(env.order_response_rate)\n\n    episode_reward = np.sum(batch_reward_gmv[1:])\n    episode_rewards.append(episode_reward)\n    driver_numbers_episode.append(np.sum(driver_numbers[:-1]))\n    order_numbers_episode.append(np.sum(order_numbers[:-1]))\n    episode_avaliables_vehicles.append(np.sum(available_drivers[:-1]))\n    n_iter_order_response_rate = np.mean(order_response_rates[1:])\n    order_response_rate_episode.append(n_iter_order_response_rate)\n    record_all_order_response_rate.append(order_response_rates)\n\n    print \"******** iteration {} ********* reward {}, order response rate {} available vehicle {}\".format(n_iter,\n                                                                                                          episode_reward,\n                                                                                        n_iter_order_response_rate,\n                                                                                        episode_avaliables_vehicles[-1])\n\n    pickle.dump([episode_rewards, order_response_rate_episode, save_random_seed,\n                 driver_numbers_episode, order_numbers_episode, episode_avaliables_vehicles], open(log_dir + \"results.pkl\", \"w\"))\n\n\nprint \"averaged available vehicles per time step: {}\".format(np.mean(episode_avaliables_vehicles)/144.0)"
  },
  {
    "path": "run/run_cA2C.py",
    "content": "# -*- coding: utf-8 -*-\nimport pickle, sys\nsys.path.append(\"../\")\n\n# from simulator.utilities import *\nfrom algorithm.alg_utility import *\nfrom simulator.envs import *\nfrom shutil import copyfile\n\n################## Load data ###################################\ndir_prefix = \"/mnt/research/linkaixi/AllData/dispatch/\"\ncurrent_time = time.strftime(\"%Y%m%d_%H-%M\")\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\nmkdir_p(log_dir)\nprint \"log dir is {}\".format(log_dir)\n\ndata_dir = dir_prefix + \"dispatch_realdata/data_for_simulator/\"\norder_time_dist = []\norder_price_dist = []\nmapped_matrix_int = pickle.load(open(data_dir+\"mapped_matrix_int.pkl\", 'rb'))\norder_num_dist = pickle.load(open(data_dir+\"order_num_dist\", 'rb'))\nidle_driver_dist_time = pickle.load(open(data_dir+\"idle_driver_dist_time\", 'rb'))\nidle_driver_location_mat = pickle.load(open(data_dir+\"idle_driver_location_mat\", 'rb'))\ntarget_ids = pickle.load(open(data_dir+\"target_grid_id.pkl\", 'rb'))\nonoff_driver_location_mat = pickle.load(open(data_dir + \"onoff_driver_location_mat\", 'rb'))\norder_filename = dir_prefix + \"dispatch_realdata/orders/all_orders_target\"\norder_real = pickle.load(open(order_filename, 'rb'))\nM, N = mapped_matrix_int.shape\nprint \"finish load data\"\n\n\n################## Initialize env ###################################\nn_side = 6\nGAMMA = 0.9\nl_max = 9\n\nenv = CityReal(mapped_matrix_int, order_num_dist,\n               idle_driver_dist_time, idle_driver_location_mat,\n               order_time_dist, order_price_dist,\n               l_max, M, N, n_side, 1/28.0, order_real, onoff_driver_location_mat)\n\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\n\n\ntemp = np.array(env.target_grids) + env.M * env.N\ntarget_id_states = env.target_grids + temp.tolist()\n\n\ncurr_s = np.array(env.reset_clean()).flatten()  # [0] driver dist; [1] order dist\ncurr_s = utility_conver_states(curr_s, target_id_states)\nprint \"******************* Finish generating one day order **********************\"\n\n\nprint \"******************* Starting training Deep actor critic **********************\"\nfrom algorithm.cA2C import *\n\n\n\nMAX_ITER = 50\nis_plot_figure = False\ncity_time_start = 0\nEP_LEN = 144\n\ncity_time_end = city_time_start + EP_LEN\nepsilon = 0.5\ngamma = 0.9\nlearning_rate = 1e-3\n\nprev_epsiode_reward = 0\n\nall_rewards = []\norder_response_rate_episode = []\nvalue_table_sum = []\nepisode_rewards = []\nepisode_conflicts_drivers = []\nrecord_all_order_response_rate = []\n\nT = 144\naction_dim = 7\nstate_dim = env.n_valid_grids * 3 + T\n\n\n# tf.reset_default_graph()\nsess = tf.Session()\ntf.set_random_seed(1)\nq_estimator = Estimator(sess, action_dim,\n                        state_dim,\n                        env,\n                        scope=\"q_estimator\",\n                        summaries_dir=log_dir)\n\n\nsess.run(tf.global_variables_initializer())\n\nreplay = ReplayMemory(memory_size=1e+6, batch_size=int(3e+3))\npolicy_replay = policyReplayMemory(memory_size=1e+6, batch_size=int(3e+3))\nstateprocessor = stateProcessor(target_id_states, env.target_grids, env.n_valid_grids)\n\n\nrestore = True\nsaver = tf.train.Saver()\n\n\n# record_curr_state = []\n# record_actions = []\nsave_random_seed = []\nepisode_dispatched_drivers = []\nglobal_step1 = 0\nglobal_step2 = 0\nRATIO = 1\nfor n_iter in np.arange(25):\n    RANDOM_SEED = n_iter + MAX_ITER - 10\n    env.reset_randomseed(RANDOM_SEED)\n    save_random_seed.append(RANDOM_SEED)\n    batch_s, batch_a, batch_r = [], [], []\n    batch_reward_gmv = []\n    epsiode_reward = 0\n    num_dispatched_drivers = 0\n\n    # reset env\n    is_regenerate_order = 1\n    curr_state = env.reset_clean(generate_order=is_regenerate_order, ratio=RATIO, city_time=city_time_start)\n    info = env.step_pre_order_assigin(curr_state)\n    context = stateprocessor.compute_context(info)\n    curr_s = stateprocessor.utility_conver_states(curr_state)\n    normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n    s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n    # record rewards to update the value table\n    episodes_immediate_rewards = []\n    num_conflicts_drivers = []\n    curr_num_actions = []\n    order_response_rates = []\n    for ii in np.arange(EP_LEN + 1):\n        # record_curr_state.append(curr_state)\n        # INPUT: state,  OUTPUT: action\n        action_tuple, valid_action_prob_mat, policy_state, action_choosen_mat, \\\n        curr_state_value, curr_neighbor_mask, next_state_ids = q_estimator.action(s_grid, context, epsilon)\n        # a0\n\n        # ONE STEP: r0\n        next_state, r, info = env.step(action_tuple, 2)\n\n        # r0\n        immediate_reward = stateprocessor.reward_wrapper(info, curr_s)\n\n        # Save transition to replay memory\n        if ii != 0:\n            # r1, c0\n            r_grid = stateprocessor.to_grid_rewards(immediate_reward)\n            # s0, a0, r1  for value newtwork\n            targets_batch = q_estimator.compute_targets(action_mat_prev, s_grid, r_grid, gamma)\n\n            # advantage for policy network.\n            advantage = q_estimator.compute_advantage(curr_state_value_prev, next_state_ids_prev,\n                                                      s_grid, r_grid, gamma)\n\n            replay.add(state_mat_prev, action_mat_prev, targets_batch, s_grid)\n            policy_replay.add(policy_state_prev, action_choosen_mat_prev, advantage, curr_neighbor_mask_prev)\n\n        # for updating value network\n        state_mat_prev = s_grid\n        action_mat_prev = valid_action_prob_mat\n\n        # for updating policy net\n        action_choosen_mat_prev = action_choosen_mat\n        curr_neighbor_mask_prev = curr_neighbor_mask\n        policy_state_prev = policy_state\n        # for computing advantage\n        curr_state_value_prev = curr_state_value\n        next_state_ids_prev = next_state_ids\n\n        # s1\n        curr_state = next_state\n        curr_s = stateprocessor.utility_conver_states(next_state)\n        normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n        s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n        # c1\n        context = stateprocessor.compute_context(info[1])\n\n        # training method 1.\n        # #    # Sample a minibatch from the replay memory and update q network\n        # if replay.curr_lens != 0:\n        #     # update policy network\n        #     for _ in np.arange(30):\n        #         batch_s, batch_a, batch_r, batch_mask = policy_replay.sample()\n        #         q_estimator.update_policy(batch_s, batch_r.reshape([-1, 1]), batch_a, batch_mask, learning_rate,\n        #                                   global_step2)\n        #         global_step2 += 1\n\n        # Perform gradient descent update\n        # book keeping\n        global_step1 += 1\n        global_step2 += 1\n        all_rewards.append(r)\n        batch_reward_gmv.append(r)\n        order_response_rates.append(env.order_response_rate)\n        curr_num_action = np.sum([aa[2] for aa in action_tuple]) if len(action_tuple) != 0 else 0\n        curr_num_actions.append(curr_num_action)\n        num_conflicts_drivers.append(collision_action(action_tuple))\n\n    episode_reward = np.sum(batch_reward_gmv[1:])\n    episode_rewards.append(episode_reward)\n    n_iter_order_response_rate = np.mean(order_response_rates[1:])\n    order_response_rate_episode.append(n_iter_order_response_rate)\n    record_all_order_response_rate.append(order_response_rates)\n    episode_conflicts_drivers.append(np.sum(num_conflicts_drivers[:-1]))\n    episode_dispatched_drivers.append(np.sum(curr_num_actions[:-1]))\n\n    print \"******** iteration {} ********* reward {}, order_response_rate {} number drivers {}, conflicts {}\".format(n_iter, episode_reward,\n                                                                                                       n_iter_order_response_rate,\n                                                                                                     episode_dispatched_drivers[-1],\n                                                                                                    episode_conflicts_drivers[-1])\n\n    pickle.dump([episode_rewards, order_response_rate_episode, save_random_seed, episode_conflicts_drivers,\n                 episode_dispatched_drivers], open(log_dir + \"results.pkl\", \"w\"))\n    if n_iter == 24:\n        break\n\n    # update value network\n    for _ in np.arange(4000):\n        batch_s, _, batch_r, _ = replay.sample()\n        iloss = q_estimator.update_value(batch_s, batch_r, 1e-3, global_step1)\n        global_step1 += 1\n\n    # training method 2\n    # update policy network\n    for _ in np.arange(4000):\n        batch_s, batch_a, batch_r, batch_mask = policy_replay.sample()\n        q_estimator.update_policy(batch_s, batch_r.reshape([-1, 1]), batch_a, batch_mask, learning_rate,\n                                  global_step2)\n        global_step2 += 1\n\n\n\n    saver.save(sess, log_dir+\"model.ckpt\")\n    if RANDOM_SEED == 54:\n        saver.save(sess, log_dir + \"model_before_testing.ckpt\")\n\n"
  },
  {
    "path": "run/run_cDQN.py",
    "content": "\nimport pickle, sys\nsys.path.append(\"../\")\n\n# from simulator.utilities import *\nfrom algorithm.alg_utility import *\nfrom simulator.envs import *\n\n################## Load data ###################################\ndir_prefix = \"/mnt/research/linkaixi/AllData/dispatch/\"\ncurrent_time = time.strftime(\"%Y%m%d_%H-%M\")\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\nmkdir_p(log_dir)\nprint \"log dir is {}\".format(log_dir)\n\n\ndata_dir = dir_prefix + \"dispatch_realdata/data_for_simulator/\"\norder_time_dist = []\norder_price_dist = []\nmapped_matrix_int = pickle.load(open(data_dir+\"mapped_matrix_int.pkl\", 'rb'))\norder_num_dist = pickle.load(open(data_dir+\"order_num_dist\", 'rb'))\nidle_driver_dist_time = pickle.load(open(data_dir+\"idle_driver_dist_time\", 'rb'))\nidle_driver_location_mat = pickle.load(open(data_dir+\"idle_driver_location_mat\", 'rb'))\ntarget_ids = pickle.load(open(data_dir+\"target_grid_id.pkl\", 'rb'))\nonoff_driver_location_mat = pickle.load(open(data_dir + \"onoff_driver_location_mat\", 'rb'))\norder_filename = dir_prefix + \"dispatch_realdata/orders/all_orders_target\"\norder_real = pickle.load(open(order_filename, 'rb'))\nM, N = mapped_matrix_int.shape\nprint \"finish load data\"\n\n\n################## Initialize env ###################################\nn_side = 6\nGAMMA = 0.9\nl_max = 9\n\nenv = CityReal(mapped_matrix_int, order_num_dist,\n               idle_driver_dist_time, idle_driver_location_mat,\n               order_time_dist, order_price_dist,\n               l_max, M, N, n_side, 1/28.0, order_real, onoff_driver_location_mat)\n\n\nlog_dir = dir_prefix + \"dispatch_simulator/experiments/{}/\".format(current_time)\n\n\ntemp = np.array(env.target_grids) + env.M * env.N\ntarget_id_states = env.target_grids + temp.tolist()\n\n\ncurr_s = np.array(env.reset_clean()).flatten()  # [0] driver dist; [1] order dist\ncurr_s = utility_conver_states(curr_s, target_id_states)\nprint \"******************* Finish generating one day order **********************\"\n\n\n\nprint \"******************* Starting training Deep SARSA **********************\"\nfrom algorithm.cDQN import *\n\nMAX_ITER = 50\nis_plot_figure = False\ncity_time_start = 0\nEP_LEN = 144\nglobal_step = 0\ncity_time_end = city_time_start + EP_LEN\nEPSILON = 0.8\ngamma = 0.9\nlearning_rate = 1e-3\n\nprev_epsiode_reward = 0\ncurr_num_actions = []\nall_rewards = []\norder_response_rate_episode = []\nvalue_table_sum = []\nepisode_rewards = []\nepisode_conflicts_drivers = []\nrecord_all_order_response_rate = []\n\nT = 144\naction_dim = 7\nstate_dim = env.n_valid_grids * 3 + T\n\n\n# tf.reset_default_graph()\nsess = tf.Session()\ntf.set_random_seed(1)\n\nq_estimator = Estimator(sess, action_dim,\n                        state_dim,\n                        env,\n                        scope=\"q_estimator\",\n                        summaries_dir=log_dir)\n\ntarget_estimator = Estimator(sess, action_dim, state_dim, env, scope=\"target_q\")\nsess.run(tf.global_variables_initializer())\nestimator_copy = ModelParametersCopier(q_estimator, target_estimator)\nreplay = ReplayMemory(memory_size=1e+6, batch_size=int(3e+3))\nstateprocessor = stateProcessor(target_id_states, env.target_grids, env.n_valid_grids)\n\nRATIO = 1\nsaver = tf.train.Saver()\n\n\nprint \"Start training contextual deep Q learning. \"\nsave_random_seed = []\nN_ITER_RUNS = 25\ntemp_value = 10\nEPSILON_start = 0.5\nEPSILON_end = 0.1\nepsilon_decay_steps=15\nepsilons = np.linspace(EPSILON_start, EPSILON_end, epsilon_decay_steps)\nepisode_dispatched_drivers = []\nfor n_iter in np.arange(N_ITER_RUNS):\n    RANDOM_SEED = n_iter + MAX_ITER - temp_value\n    env.reset_randomseed(RANDOM_SEED)\n    save_random_seed.append(RANDOM_SEED)\n    batch_s, batch_a, batch_r = [], [], []\n    batch_reward_gmv = []\n    epsiode_reward = 0\n    num_dispatched_drivers = 0\n\n    # reset env\n    # if n_iter % 1 == 0:\n    #     is_regenerate_order = 1\n    # else:\n    #     is_regenerate_order = 0\n    is_regenerate_order = 1\n    curr_state = env.reset_clean(generate_order=is_regenerate_order, ratio=RATIO, city_time=city_time_start)\n    info = env.step_pre_order_assigin(curr_state)\n    context = stateprocessor.compute_context(info)\n    curr_s = stateprocessor.utility_conver_states(curr_state)\n    normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n    s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n    # record rewards to update the value table\n    episodes_immediate_rewards = []\n    order_response_rates = []\n    # epsilon = EPSILON * (1 - np.max([n_iter, temp_value+5]) / N_ITER_RUNS)  #testing staget 不改变epsilon\n    epsilon = epsilons[n_iter] if n_iter < 15 else EPSILON_end\n    num_conflicts_drivers = []\n    curr_num_actions = []\n    for ii in np.arange(EP_LEN + 1):\n        # INPUT: state,  OUTPUT: action\n        action_tuple, valid_action_prob_mat = q_estimator.action(s_grid, context, epsilon)\n\n        # a0\n\n        # ONE STEP: r0\n        next_state, r, info = env.step(action_tuple, 2)\n\n        # r0\n        immediate_reward = stateprocessor.reward_wrapper(info, curr_s)\n\n        # Save transition to replay memory\n        if ii != 0:\n            # r1, c0\n            r_grid = stateprocessor.to_grid_rewards(immediate_reward)\n            # s0, a0, r1\n            targets_batch = target_estimator.compute_targets(action_mat_prev, s_grid, r_grid, gamma)\n            replay.add(state_mat_prev, action_mat_prev, targets_batch, s_grid)\n\n        state_mat_prev = s_grid\n        action_mat_prev = valid_action_prob_mat\n\n        # s1\n        curr_s = stateprocessor.utility_conver_states(next_state)\n        normalized_curr_s = stateprocessor.utility_normalize_states(curr_s)\n        s_grid = stateprocessor.to_grid_states(normalized_curr_s, env.city_time)  # t0, s0\n\n        # c1\n        context = stateprocessor.compute_context(info[1])\n\n        # training method 2\n        # Sample a minibatch from the replay memory and update q network\n        # if replay.curr_lens != 0:\n        #     for _ in np.arange(20):\n        #         batch_s, _, batch_r, _ = replay.sample()\n        #         iloss = q_estimator.update(batch_s, batch_r, 1e-3, global_step)\n        #         global_step += 1\n        # print \"******** city time {} *********\".format(env.city_time)\n\n        # Perform gradient descent update\n        # book keeping\n        global_step += 1\n        all_rewards.append(r)\n        batch_reward_gmv.append(r)\n        order_response_rates.append(env.order_response_rate)\n        curr_num_action = np.sum([aa[2] for aa in action_tuple]) if len(action_tuple) != 0 else 0\n        curr_num_actions.append(curr_num_action)\n        num_conflicts_drivers.append(collision_action(action_tuple))\n\n    # training method 1\n    for _ in np.arange(4000):\n        batch_s, _, batch_r, _ = replay.sample()\n        iloss = q_estimator.update(batch_s, batch_r, 1e-3, global_step)\n        global_step += 1\n\n        # update target Q network\n    #     if (global_step + 1) % 70 == 0:\n    estimator_copy.make(sess)\n\n    episode_reward = np.sum(batch_reward_gmv[1:])\n    episode_rewards.append(episode_reward)\n    n_iter_order_response_rate = np.mean(order_response_rates[1:])\n    order_response_rate_episode.append(n_iter_order_response_rate)\n    record_all_order_response_rate.append(order_response_rates)\n    episode_conflicts_drivers.append(np.sum(num_conflicts_drivers[:-1]))\n    episode_dispatched_drivers.append(np.sum(curr_num_actions[:-1]))\n\n\n    print \"******** iteration {} ********* reward {}, order_response_rate {} number drivers {}, conflicts {}, epsilon {}\".format(n_iter, episode_reward,\n                                                                                                        n_iter_order_response_rate,\n                                                                                                         episode_dispatched_drivers[-1],\n                                                                                                        episode_conflicts_drivers[-1],\n                                                                                                             epsilon)\n\n\n    pickle.dump([episode_rewards, order_response_rate_episode, save_random_seed, episode_conflicts_drivers, episode_dispatched_drivers], open(log_dir + \"results.pkl\", \"w\"))\n\n    saver.save(sess, log_dir+\"model.ckpt\")\n\n\n"
  },
  {
    "path": "simulator/__init__.py",
    "content": "\n\n\n"
  },
  {
    "path": "simulator/envs.py",
    "content": "import os, sys, random, time\nimport logging\nsys.path.append(\"../\")\n\nfrom objects import *\nfrom utilities import *\n# from algorithm import *\n\n# current_time = time.strftime(\"%Y%m%d_%H-%M\")\n# log_dir = \"/nfs/private/linkaixiang_i/data/dispatch_simulator/experiments/\"+current_time + \"/\"\n# mkdir_p(log_dir)\n# logging.basicConfig(filename=log_dir +'logger_env.log', level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\nlogger_ch = logging.StreamHandler()\nlogger_ch.setLevel(logging.DEBUG)\nlogger_ch.setFormatter(logging.Formatter(\n    '%(asctime)s[%(levelname)s][%(lineno)s:%(funcName)s]||%(message)s',\n    datefmt='%Y-%m-%d %H:%M:%S'))\nlogger.addHandler(logger_ch)\nRANDOM_SEED = 0  # unit test use this random seed.\n\nclass CityReal:\n    '''A real city is consists of M*N grids '''\n\n    def __init__(self, mapped_matrix_int, order_num_dist, idle_driver_dist_time, idle_driver_location_mat, order_time_dist, order_price_dist,\n                 l_max, M, N, n_side, probability=1.0/28, real_orders=\"\", onoff_driver_location_mat=\"\",\n                 global_flag=\"global\", time_interval=10):\n        \"\"\"\n        :param mapped_matrix_int: 2D matrix: each position is either -100 or grid id from order in real data.\n        :param order_num_dist: 144 [{node_id1: [mu, std]}, {node_id2: [mu, std]}, ..., {node_idn: [mu, std]}]\n                            node_id1 is node the index in self.nodes\n        :param idle_driver_dist_time: [[mu1, std1], [mu2, std2], ..., [mu144, std144]] mean and variance of idle drivers in\n        the city at each time\n        :param idle_driver_location_mat: 144 x num_valid_grids matrix.\n        :param order_time_dist: [ 0.27380797,..., 0.00205766] The probs of order duration = 1 to 9\n        :param order_price_dist: [[10.17, 3.34],   # mean and std of order's price, order durations = 10 minutes.\n                                   [15.02, 6.90],  # mean and std of order's price, order durations = 20 minutes.\n                                   ...,]\n        :param onoff_driver_location_mat: 144 x 504 x 2: 144 total time steps, num_valid_grids = 504.\n        mean and std of online driver number - offline driver number\n        onoff_driver_location_mat[t] = [[-0.625       2.92350389]  <-- Corresponds to the grid in target_node_ids\n                                        [ 0.09090909  1.46398452]\n                                        [ 0.09090909  2.36596622]\n                                        [-1.2         2.05588586]...]\n        :param M:\n        :param N:\n        :param n_side:\n        :param time_interval:\n        :param l_max: The max-duration of an order\n        :return:\n        \"\"\"\n        # City.__init__(self, M, N, n_side, time_interval)\n        self.M = M  # row numbers\n        self.N = N  # column numbers\n        self.nodes = [Node(i) for i in xrange(M * N)]  # a list of nodes: node id start from 0\n        self.drivers = {}  # driver[driver_id] = driver_instance  , driver_id start from 0\n        self.n_drivers = 0  # total idle number of drivers. online and not on service.\n        self.n_offline_drivers = 0  # total number of offline drivers.\n        self.construct_map_simulation(M, N, n_side)\n        self.city_time = 0\n        # self.idle_driver_distribution = np.zeros((M, N))\n        self.n_intervals = 1440 / time_interval\n        self.n_nodes = self.M * self.N\n        self.n_side = n_side\n        self.order_response_rate = 0\n\n        self.RANDOM_SEED = RANDOM_SEED\n\n        self.l_max = l_max  # Start from 1. The max number of layers an order can across.\n        assert l_max <= M-1 and l_max <= N-1\n        assert 1 <= l_max <= 9   # Ignore orders less than 10 minutes and larger than 1.5 hours\n\n        self.target_grids = []\n        self.n_valid_grids = 0  # num of valid grid\n        self.nodes = [None for _ in np.arange(self.M * self.N)]\n        self.construct_node_real(mapped_matrix_int)\n        self.mapped_matrix_int = mapped_matrix_int\n\n        self.construct_map_real(n_side)\n        self.order_num_dist = order_num_dist\n        self.distribution_name = \"Poisson\"\n        self.idle_driver_dist_time = idle_driver_dist_time\n        self.idle_driver_location_mat = idle_driver_location_mat\n\n        self.order_time_dist = order_time_dist[:l_max]/np.sum(order_time_dist[:l_max])\n        self.order_price_dist = order_price_dist\n\n        target_node_ids = []\n        target_grids_sorted = np.sort(mapped_matrix_int[np.where(mapped_matrix_int > 0)])\n        for item in target_grids_sorted:\n            x, y = np.where(mapped_matrix_int == item)\n            target_node_ids.append(ids_2dto1d(x, y, M, N)[0])\n        self.target_node_ids = target_node_ids\n        # store valid note id. Sort by number of orders emerged. descending.\n\n        self.node_mapping = {}\n        self.construct_mapping()\n\n        self.real_orders = real_orders  # 4 weeks' data\n        # [[92, 300, 143, 2, 13.2],...] origin grid, destination grid, start time, end time, price.\n\n\n        self.p = probability   # sample probability\n        self.time_keys = [int(dt.strftime('%H%M')) for dt in\n                          datetime_range(datetime(2017, 9, 1, 0), datetime(2017, 9, 2, 0),\n                                        timedelta(minutes=time_interval))]\n        self.day_orders = []  # one day's order.\n\n        self.onoff_driver_location_mat = onoff_driver_location_mat\n\n        # Stats\n        self.all_grids_on_number = 0  # current online # drivers.\n        self.all_grids_off_number = 0\n\n\n        self.out_grid_in_orders = np.zeros((self.n_intervals, len(self.target_grids)))\n        self.global_flag = global_flag\n        self.weights_layers_neighbors = [1.0, np.exp(-1), np.exp(-2)]\n\n\n    def construct_map_simulation(self, M, N, n):\n        \"\"\"Connect node to its neighbors based on a simulated M by N map\n            :param M: M row index matrix\n            :param N: N column index matrix\n            :param n: n - sided polygon\n        \"\"\"\n        for idx, current_node in enumerate(self.nodes):\n            if current_node is not None:\n                i, j = ids_1dto2d(idx, M, N)\n                current_node.set_neighbors(get_neighbor_list(i, j, M, N, n, self.nodes))\n\n    def construct_mapping(self):\n        \"\"\"\n        :return:\n        \"\"\"\n        target_grid_id = self.mapped_matrix_int[np.where(self.mapped_matrix_int>0)]\n        for g_id, n_id in zip(target_grid_id, self.target_grids):\n            self.node_mapping[g_id] = n_id\n\n    def construct_node_real(self, mapped_matrix_int):\n        \"\"\" Initialize node, only valid node in mapped_matrix_in will be initialized.\n        \"\"\"\n        row_inds, col_inds = np.where(mapped_matrix_int >= 0)\n\n        target_ids = []  # start from 0. \n        for x, y in zip(row_inds, col_inds):\n            node_id = ids_2dto1d(x, y, self.M, self.N)\n            self.nodes[node_id] = Node(node_id)  # node id start from 0.\n            target_ids.append(node_id)\n\n        for x, y in zip(row_inds, col_inds):\n            node_id = ids_2dto1d(x, y, self.M, self.N)\n            self.nodes[node_id].get_layers_neighbors(self.l_max, self.M, self.N, self)\n\n        self.target_grids = target_ids\n        self.n_valid_grids = len(target_ids)\n        \n    def construct_map_real(self, n_side):\n        \"\"\"Build node connection. \n        \"\"\"\n        for idx, current_node in enumerate(self.nodes):\n            i, j = ids_1dto2d(idx, self.M, self.N)\n            if current_node is not None:\n                current_node.set_neighbors(get_neighbor_list(i, j, self.M, self.N, n_side, self.nodes))\n\n    def initial_order_random(self, distribution_all, dis_paras_all):\n        \"\"\" Initialize order distribution\n        :param distribution: 'Poisson', 'Gaussian'\n        :param dis_paras:     lambda,    mu, sigma\n        \"\"\"\n        for idx, node in enumerate(self.nodes):\n            if node is not None:\n                node.order_distribution(distribution_all[idx], dis_paras_all[idx])\n\n    def get_observation(self):\n        next_state = np.zeros((2, self.M, self.N))\n        for _node in self.nodes:\n            if _node is not None:\n                row_id, column_id = ids_1dto2d(_node.get_node_index(), self.M, self.N)\n                next_state[0, row_id, column_id] = _node.idle_driver_num\n                next_state[1, row_id, column_id] = _node.order_num\n\n        return next_state\n\n    def get_num_idle_drivers(self):\n        \"\"\" Compute idle drivers\n        :return:\n        \"\"\"\n        temp_n_idle_drivers= 0\n        for _node in self.nodes:\n            if _node is not None:\n                temp_n_idle_drivers += _node.idle_driver_num\n        return temp_n_idle_drivers\n\n    def get_observation_driver_state(self):\n        \"\"\" Get idle driver distribution, computing #drivers from node.\n        :return:\n        \"\"\"\n        next_state = np.zeros((self.M, self.N))\n        for _node in self.nodes:\n            if _node is not None:\n                row_id, column_id = ids_1dto2d(_node.get_node_index(), self.M, self.N)\n                next_state[row_id, column_id] = _node.get_idle_driver_numbers_loop()\n\n        return next_state\n    def reset_randomseed(self, random_seed):\n        self.RANDOM_SEED = random_seed\n\n    def reset(self):\n        \"\"\" Return initial observation: get order distribution and idle driver distribution\n\n        \"\"\"\n\n        _M = self.M\n        _N = self.N\n        assert self.city_time == 0\n        # initialization drivers according to the distribution at time 0\n        num_idle_driver = self.utility_get_n_idle_drivers_real()\n        self.step_driver_online_offline_control(num_idle_driver)\n\n        # generate orders at first time step\n        distribution_name = [self.distribution_name]*(_M*_N)\n        distribution_param_dictionary = self.order_num_dist[self.city_time]\n        distribution_param = [0]*(_M*_N)\n        for key, value in distribution_param_dictionary.iteritems():\n            if self.distribution_name == 'Gaussian':\n                mu, sigma = value\n                distribution_param[key] = mu, sigma\n            elif self.distribution_name == 'Poisson':\n                mu = value[0]\n                distribution_param[key] = mu\n            else:\n                print \"Wrong distribution\"\n\n        self.initial_order_random(distribution_name, distribution_param)\n        self.step_generate_order_real()\n\n        return self.get_observation()\n\n    def reset_clean(self, generate_order=1, ratio=1, city_time=\"\"):\n        \"\"\" 1. bootstrap oneday's order data.\n            2. clean current drivers and orders, regenerate new orders and drivers.\n            can reset anytime\n        :return:\n        \"\"\"\n        if city_time != \"\":\n            self.city_time = city_time\n\n        # clean orders and drivers\n        self.drivers = {}  # driver[driver_id] = driver_instance  , driver_id start from 0\n        self.n_drivers = 0  # total idle number of drivers. online and not on service.\n        self.n_offline_drivers = 0  # total number of offline drivers.\n        for node in self.nodes:\n            if node is not None:\n                node.clean_node()\n\n        # Generate one day's order.\n        if generate_order == 1:\n            self.utility_bootstrap_oneday_order()\n\n        # Init orders of current time step\n        moment = self.city_time % self.n_intervals\n        self.step_bootstrap_order_real(self.day_orders[moment])\n\n        # Init current driver distribution\n        if self.global_flag == \"global\":\n            num_idle_driver = self.utility_get_n_idle_drivers_real()\n            num_idle_driver = int(num_idle_driver * ratio)\n        else:\n            num_idle_driver = self.utility_get_n_idle_drivers_nodewise()\n        self.step_driver_online_offline_control_new(num_idle_driver)\n        return self.get_observation()\n\n    def utility_collect_offline_drivers_id(self):\n        \"\"\"count how many drivers are offline\n        :return: offline_drivers: a list of offline driver id\n        \"\"\"\n        count = 0 # offline driver num\n        offline_drivers = []   # record offline driver id\n        for key, _driver in self.drivers.iteritems():\n            if _driver.online is False:\n                count += 1\n                offline_drivers.append(_driver.get_driver_id())\n        return offline_drivers\n\n    def utility_get_n_idle_drivers_nodewise(self):\n        \"\"\" compute idle drivers.\n        :return:\n        \"\"\"\n        time = self.city_time % self.n_intervals\n        idle_driver_num = np.sum(self.idle_driver_location_mat[time])\n        return int(idle_driver_num)\n\n\n    def utility_add_driver_real_new(self, num_added_driver):\n        curr_idle_driver_distribution = self.get_observation()[0]\n        curr_idle_driver_distribution_resort = np.array(\n            [int(curr_idle_driver_distribution.flatten()[index]) for index in\n             self.target_node_ids])\n\n        idle_driver_distribution = self.idle_driver_location_mat[self.city_time % self.n_intervals, :]\n\n        idle_diff = idle_driver_distribution.astype(int) - curr_idle_driver_distribution_resort\n        idle_diff[np.where(idle_diff <= 0)] = 0\n\n        node_ids = np.random.choice(self.target_node_ids, size=[num_added_driver],\n                                    p=idle_diff/float(np.sum(idle_diff)))\n\n        n_total_drivers = len(self.drivers.keys())\n        for ii, node_id in enumerate(node_ids):\n            added_driver_id = n_total_drivers + ii\n            self.drivers[added_driver_id] = Driver(added_driver_id)\n            self.drivers[added_driver_id].set_position(self.nodes[node_id])\n            self.nodes[node_id].add_driver(added_driver_id, self.drivers[added_driver_id])\n\n        self.n_drivers += num_added_driver\n\n    def utility_add_driver_real_new_offlinefirst(self, num_added_driver):\n\n        # curr_idle_driver_distribution = self.get_observation()[0][np.where(self.mapped_matrix_int > 0)]\n        curr_idle_driver_distribution = self.get_observation()[0]\n        curr_idle_driver_distribution_resort = np.array([int(curr_idle_driver_distribution.flatten()[index]) for index in\n                                                         self.target_node_ids])\n\n        idle_driver_distribution = self.idle_driver_location_mat[self.city_time % self.n_intervals, :]\n\n        idle_diff = idle_driver_distribution.astype(int) - curr_idle_driver_distribution_resort\n        idle_diff[np.where(idle_diff <= 0)] = 0\n\n        if float(np.sum(idle_diff)) == 0:\n            return\n        np.random.seed(self.RANDOM_SEED)\n        node_ids = np.random.choice(self.target_node_ids, size=[num_added_driver],\n                                    p=idle_diff/float(np.sum(idle_diff)))\n\n        for ii, node_id in enumerate(node_ids):\n\n            if self.nodes[node_id].offline_driver_num > 0:\n                self.nodes[node_id].set_offline_driver_online()\n                self.n_drivers += 1\n                self.n_offline_drivers -= 1\n            else:\n\n                n_total_drivers = len(self.drivers.keys())\n                added_driver_id = n_total_drivers\n                self.drivers[added_driver_id] = Driver(added_driver_id)\n                self.drivers[added_driver_id].set_position(self.nodes[node_id])\n                self.nodes[node_id].add_driver(added_driver_id, self.drivers[added_driver_id])\n                self.n_drivers += 1\n\n    def utility_add_driver_real_nodewise(self, node_id, num_added_driver):\n\n\n        while num_added_driver > 0:\n            if self.nodes[node_id].offline_driver_num > 0:\n                self.nodes[node_id].set_offline_driver_online()\n                self.n_drivers += 1\n                self.n_offline_drivers -= 1\n            else:\n\n                n_total_drivers = len(self.drivers.keys())\n                added_driver_id = n_total_drivers\n                self.drivers[added_driver_id] = Driver(added_driver_id)\n                self.drivers[added_driver_id].set_position(self.nodes[node_id])\n                self.nodes[node_id].add_driver(added_driver_id, self.drivers[added_driver_id])\n                self.n_drivers += 1\n            num_added_driver -= 1\n\n    def utility_set_drivers_offline_real_nodewise(self, node_id, n_drivers_to_off):\n\n        while n_drivers_to_off > 0:\n            if self.nodes[node_id].idle_driver_num > 0:\n                self.nodes[node_id].set_idle_driver_offline_random()\n                self.n_drivers -= 1\n                self.n_offline_drivers += 1\n                n_drivers_to_off -= 1\n                self.all_grids_off_number += 1\n            else:\n                break\n\n    def utility_set_drivers_offline_real_new(self, n_drivers_to_off):\n\n\n        curr_idle_driver_distribution = self.get_observation()[0]\n        curr_idle_driver_distribution_resort = np.array([int(curr_idle_driver_distribution.flatten()[index])\n                                                         for index in self.target_node_ids])\n\n        # historical idle driver distribution\n        idle_driver_distribution = self.idle_driver_location_mat[self.city_time % self.n_intervals, :]\n\n        # diff of curr idle driver distribution and history\n        idle_diff = curr_idle_driver_distribution_resort - idle_driver_distribution.astype(int)\n        idle_diff[np.where(idle_diff <= 0)] = 0\n\n        n_drivers_can_be_off = int(np.sum(curr_idle_driver_distribution_resort[np.where(idle_diff >= 0)]))\n        if n_drivers_to_off > n_drivers_can_be_off:\n            n_drivers_to_off = n_drivers_can_be_off\n\n        sum_idle_diff = np.sum(idle_diff)\n        if sum_idle_diff == 0:\n\n            return\n        np.random.seed(self.RANDOM_SEED)\n        node_ids = np.random.choice(self.target_node_ids, size=[n_drivers_to_off],\n                                    p=idle_diff / float(sum_idle_diff))\n\n        for ii, node_id in enumerate(node_ids):\n            if self.nodes[node_id].idle_driver_num > 0:\n                self.nodes[node_id].set_idle_driver_offline_random()\n                self.n_drivers -= 1\n                self.n_offline_drivers += 1\n                n_drivers_to_off -= 1\n\n\n    def utility_bootstrap_oneday_order(self):\n\n        num_all_orders = len(self.real_orders)\n        index_sampled_orders = np.where(np.random.binomial(1, self.p, num_all_orders) == 1)\n        one_day_orders = self.real_orders[index_sampled_orders]\n\n        self.out_grid_in_orders = np.zeros((self.n_intervals, len(self.target_grids)))\n\n        day_orders = [[] for _ in np.arange(self.n_intervals)]\n        for iorder in one_day_orders:\n            #  iorder: [92, 300, 143, 2, 13.2]\n            start_time = int(iorder[2])\n            if iorder[0] not in self.node_mapping.keys() and iorder[1] not in self.node_mapping.keys():\n                continue\n            start_node = self.node_mapping.get(iorder[0], -100)\n            end_node = self.node_mapping.get(iorder[1], -100)\n            duration = int(iorder[3])\n            price = iorder[4]\n\n\n            if start_node == -100:\n                column_index = self.target_grids.index(end_node)\n                self.out_grid_in_orders[(start_time + duration) % self.n_intervals, column_index] += 1\n                continue\n\n            day_orders[start_time].append([start_node, end_node, start_time, duration, price])\n        self.day_orders = day_orders\n\n    def step_driver_status_control(self):\n        # Deal with orders finished at time T=1, check driver status. finish order, set back to off service\n        for key, _driver in self.drivers.iteritems():\n            _driver.status_control_eachtime(self)\n        moment = self.city_time % self.n_intervals\n        orders_to_on_drivers = self.out_grid_in_orders[moment, :]\n        for idx, item in enumerate(orders_to_on_drivers):\n            if item != 0:\n                node_id = self.target_grids[idx]\n                self.utility_add_driver_real_nodewise(node_id, int(item))\n\n    def step_driver_online_offline_nodewise(self):\n        \"\"\" node wise control driver online offline\n        :return:\n        \"\"\"\n        moment = self.city_time % self.n_intervals\n        curr_onoff_distribution = self.onoff_driver_location_mat[moment]\n\n        self.all_grids_on_number = 0\n        self.all_grids_off_number = 0\n        for idx, target_node_id in enumerate(self.target_node_ids):\n            curr_mu    = curr_onoff_distribution[idx, 0]\n            curr_sigma = curr_onoff_distribution[idx, 1]\n            on_off_number = np.round(np.random.normal(curr_mu, curr_sigma, 1)[0]).astype(int)\n\n            if on_off_number > 0:\n                self.utility_add_driver_real_nodewise(target_node_id, on_off_number)\n                self.all_grids_on_number += on_off_number\n            elif on_off_number < 0:\n                self.utility_set_drivers_offline_real_nodewise(target_node_id, abs(on_off_number))\n            else:\n                pass\n\n    def step_driver_online_offline_control_new(self, n_idle_drivers):\n        \"\"\" control the online offline status of drivers\n\n        :param n_idle_drivers: the number of idle drivers expected at current moment\n        :return:\n        \"\"\"\n\n        offline_drivers = self.utility_collect_offline_drivers_id()\n        self.n_offline_drivers = len(offline_drivers)\n\n        if n_idle_drivers > self.n_drivers:\n\n            self.utility_add_driver_real_new_offlinefirst(n_idle_drivers - self.n_drivers)\n\n        elif n_idle_drivers < self.n_drivers:\n            self.utility_set_drivers_offline_real_new(self.n_drivers - n_idle_drivers)\n        else:\n            pass\n\n    def step_driver_online_offline_control(self, n_idle_drivers):\n        \"\"\" control the online offline status of drivers\n\n        :param n_idle_drivers: the number of idle drivers expected at current moment\n        :return:\n        \"\"\"\n\n        offline_drivers = self.utility_collect_offline_drivers_id()\n        self.n_offline_drivers = len(offline_drivers)\n        if n_idle_drivers > self.n_drivers:\n            # bring drivers online.\n            while self.n_drivers < n_idle_drivers:\n                if self.n_offline_drivers > 0:\n                    for ii in np.arange(self.n_offline_drivers):\n                        self.drivers[offline_drivers[ii]].set_online()\n                        self.n_drivers += 1\n                        self.n_offline_drivers -= 1\n                        if self.n_drivers == n_idle_drivers:\n                            break\n\n                self.utility_add_driver_real_new(n_idle_drivers - self.n_drivers)\n\n        elif n_idle_drivers < self.n_drivers:\n            self.utility_set_drivers_offline_real_new(self.n_drivers - n_idle_drivers)\n        else:\n            pass\n\n    def utility_get_n_idle_drivers_real(self):\n        \"\"\" control the number of idle drivers in simulator;\n        :return:\n        \"\"\"\n        time = self.city_time % self.n_intervals\n        mean, std = self.idle_driver_dist_time[time]\n        np.random.seed(self.city_time)\n        return np.round(np.random.normal(mean, std, 1)[0]).astype(int)\n\n    def utility_set_neighbor_weight(self, weights):\n        self.weights_layers_neighbors = weights\n\n    def step_generate_order_real(self):\n        # generate order at t + 1\n        for node in self.nodes:\n            if node is not None:\n                node_id = node.get_node_index()\n                # generate orders start from each node\n                random_seed = node.get_node_index() + self.city_time\n                node.generate_order_real(self.l_max, self.order_time_dist, self.order_price_dist,\n                                         self.city_time, self.nodes, random_seed)\n\n    def step_bootstrap_order_real(self, day_orders_t):\n        for iorder in day_orders_t:\n            start_node_id = iorder[0]\n            end_node_id = iorder[1]\n            start_node = self.nodes[start_node_id]\n\n            if end_node_id in self.target_grids:\n                end_node = self.nodes[end_node_id]\n            else:\n                end_node = None\n            start_node.add_order_real(self.city_time, end_node, iorder[3], iorder[4])\n\n    def step_assign_order(self):\n\n        reward = 0  # R_{t+1}\n        all_order_num = 0\n        finished_order_num = 0\n        for node in self.nodes:\n            if node is not None:\n                node.remove_unfinished_order(self.city_time)\n                reward_node, all_order_num_node, finished_order_num_node = node.simple_order_assign_real(self.city_time, self)\n                reward += reward_node\n                all_order_num += all_order_num_node\n                finished_order_num += finished_order_num_node\n        if all_order_num != 0:\n            self.order_response_rate = finished_order_num/float(all_order_num)\n        else:\n            self.order_response_rate = -1\n        return reward\n\n    def step_assign_order_broadcast_neighbor_reward_update(self):\n        \"\"\" Consider the orders whose destination or origin is not in the target region\n        :param num_layers:\n        :param weights_layers_neighbors: [1, 0.5, 0.25, 0.125]\n        :return:\n        \"\"\"\n\n        node_reward = np.zeros((len(self.nodes)))\n        neighbor_reward = np.zeros((len(self.nodes)))\n        # First round broadcast\n        reward = 0  # R_{t+1}\n        all_order_num = 0\n        finished_order_num = 0\n        for node in self.nodes:\n            if node is not None:\n\n                reward_node, all_order_num_node, finished_order_num_node = node.simple_order_assign_real(self.city_time, self)\n                reward += reward_node\n                all_order_num += all_order_num_node\n                finished_order_num += finished_order_num_node\n                node_reward[node.get_node_index()] += reward_node\n        # Second round broadcast\n        for node in self.nodes:\n            if node is not None:\n                if node.order_num != 0:\n                    reward_node_broadcast, finished_order_num_node_broadcast \\\n                        = node.simple_order_assign_broadcast_update(self, neighbor_reward)\n                    reward += reward_node_broadcast\n                    finished_order_num += finished_order_num_node_broadcast\n\n        node_reward = node_reward + neighbor_reward\n        if all_order_num != 0:\n            self.order_response_rate = finished_order_num/float(all_order_num)\n        else:\n            self.order_response_rate = -1\n\n        return reward, [node_reward, neighbor_reward]\n\n    def step_remove_unfinished_orders(self):\n        for node in self.nodes:\n            if node is not None:\n                node.remove_unfinished_order(self.city_time)\n\n    def step_pre_order_assigin(self, next_state):\n\n        remain_drivers = next_state[0] - next_state[1]\n        remain_drivers[remain_drivers < 0] = 0\n\n        remain_orders = next_state[1] - next_state[0]\n        remain_orders[remain_orders < 0] = 0\n\n        if np.sum(remain_orders) == 0 or np.sum(remain_drivers) == 0:\n            context = np.array([remain_drivers, remain_orders])\n            return context\n\n        remain_orders_1d = remain_orders.flatten()\n        remain_drivers_1d = remain_drivers.flatten()\n\n        for node in self.nodes:\n            if node is not None:\n                curr_node_id = node.get_node_index()\n                if remain_orders_1d[curr_node_id] != 0:\n                    for neighbor_node in node.neighbors:\n                        if neighbor_node is not None:\n                            neighbor_id = neighbor_node.get_node_index()\n                            a = remain_orders_1d[curr_node_id]\n                            b = remain_drivers_1d[neighbor_id]\n                            remain_orders_1d[curr_node_id] = max(a-b, 0)\n                            remain_drivers_1d[neighbor_id] = max(b-a, 0)\n                        if remain_orders_1d[curr_node_id] == 0:\n                            break\n\n        context = np.array([remain_drivers_1d.reshape(self.M, self.N),\n                   remain_orders_1d.reshape(self.M, self.N)])\n        return context\n\n    def step_dispatch_invalid(self, dispatch_actions):\n        \"\"\" If a\n        :param dispatch_actions:\n        :return:\n        \"\"\"\n        save_remove_id = []\n        for action in dispatch_actions:\n\n            start_node_id, end_node_id, num_of_drivers = action\n            if self.nodes[start_node_id] is None or num_of_drivers == 0:\n                continue  # not a feasible action\n\n            if self.nodes[start_node_id].get_driver_numbers() < num_of_drivers:\n                num_of_drivers = self.nodes[start_node_id].get_driver_numbers()\n\n            if end_node_id < 0:\n                for _ in np.arange(num_of_drivers):\n                    self.nodes[start_node_id].set_idle_driver_offline_random()\n                    self.n_drivers -= 1\n                    self.n_offline_drivers += 1\n                    self.all_grids_off_number += 1\n                continue\n\n            if self.nodes[end_node_id] is None:\n                for _ in np.arange(num_of_drivers):\n                    self.nodes[start_node_id].set_idle_driver_offline_random()\n                    self.n_drivers -= 1\n                    self.n_offline_drivers += 1\n                    self.all_grids_off_number += 1\n                continue\n\n            if self.nodes[end_node_id] not in self.nodes[start_node_id].neighbors:\n                raise ValueError('City:step(): not a feasible dispatch')\n\n\n            for _ in np.arange(num_of_drivers):\n                # t = 1 dispatch start, idle driver decrease\n                remove_driver_id = self.nodes[start_node_id].remove_idle_driver_random()\n                save_remove_id.append((end_node_id, remove_driver_id))\n                self.drivers[remove_driver_id].set_position(None)\n                self.drivers[remove_driver_id].set_offline_for_start_dispatch()\n                self.n_drivers -= 1\n\n        return save_remove_id\n\n    def step_add_dispatched_drivers(self, save_remove_id):\n        # drivers dispatched at t, arrived at t + 1\n        for destination_node_id, arrive_driver_id in save_remove_id:\n            self.drivers[arrive_driver_id].set_position(self.nodes[destination_node_id])\n            self.drivers[arrive_driver_id].set_online_for_finish_dispatch()\n            self.nodes[destination_node_id].add_driver(arrive_driver_id, self.drivers[arrive_driver_id])\n            self.n_drivers += 1\n\n    def step_increase_city_time(self):\n        self.city_time += 1\n        # set city time of drivers\n        for driver_id, driver in self.drivers.iteritems():\n            driver.set_city_time(self.city_time)\n\n    def step(self, dispatch_actions, generate_order=1):\n        info = []\n        '''**************************** T = 1 ****************************'''\n        # Loop over all dispatch action, change the driver distribution\n        save_remove_id = self.step_dispatch_invalid(dispatch_actions)\n        # When the drivers go to invalid grid, set them offline.\n\n        reward, reward_node = self.step_assign_order_broadcast_neighbor_reward_update()\n\n        '''**************************** T = 2 ****************************'''\n        # increase city time t + 1\n        self.step_increase_city_time()\n        self.step_driver_status_control()  # drivers finish order become available again.\n\n        # drivers dispatched at t, arrived at t + 1, become available at t+1\n        self.step_add_dispatched_drivers(save_remove_id)\n\n        # generate order at t + 1\n        if generate_order == 1:\n            self.step_generate_order_real()\n        else:\n            moment = self.city_time % self.n_intervals\n            self.step_bootstrap_order_real(self.day_orders[moment])\n        \n        # offline online control;\n        self.step_driver_online_offline_nodewise()\n\n        self.step_remove_unfinished_orders()\n        # get states S_{t+1}  [driver_dist, order_dist]\n        next_state = self.get_observation()\n\n        context = self.step_pre_order_assigin(next_state)\n        info = [reward_node, context]\n        return next_state, reward, info\n"
  },
  {
    "path": "simulator/objects.py",
    "content": "import numpy as np\nfrom abc import ABCMeta, abstractmethod\nfrom utilities import *\n\nclass Distribution():\n    ''' Define the distribution from which sample the orders'''\n    __metaclass__ = ABCMeta  # python 2.7\n    @abstractmethod\n    def sample(self):\n        pass\n\nclass PoissonDistribution(Distribution):\n\n    def __init__(self, lam):\n        self._lambda = lam\n\n    def sample(self, seed=0):\n        np.random.seed(seed)\n        return np.random.poisson(self._lambda, 1)[0]\n\n\nclass GaussianDistribution(Distribution):\n\n    def __init__(self, args):\n        mu, sigma = args\n        self.mu = mu        # mean\n        self.sigma = sigma  # standard deviation\n\n    def sample(self, seed=0):\n        np.random.seed(seed)\n        return np.random.normal(self.mu, self.sigma, 1)[0]\n\n\nclass Node(object):\n    __slots__ = ('neighbors', '_index', 'orders', 'drivers',\n                 'order_num', 'idle_driver_num', 'offline_driver_num'\n                 'order_generator', 'offline_driver_num', 'order_generator',\n                 'n_side', 'layers_neighbors', 'layers_neighbors_id')\n\n    def __init__(self, index):\n        # private\n        self._index = index   # unique node index.\n\n        # public\n        self.neighbors = []  # a list of nodes that neighboring the Nodes\n        self.orders = []     # a list of orders\n        self.drivers = {}    # a dictionary of driver objects contained in this node\n        self.order_num = 0\n        self.idle_driver_num = 0  # number of idle drivers in this node\n        self.offline_driver_num = 0\n        self.order_generator = None\n\n        self.n_side = 0      # the topology is a n-sided map\n        self.layers_neighbors = []  # layer 1 indices: layers_neighbors[0] = [[1,1], [0, 1], ...],\n        # layer 2 indices layers_neighbors[1]\n        self.layers_neighbors_id = [] # layer 1: layers_neighbors_id[0] = [2, 1,.]\n\n    def clean_node(self):\n        self.orders = []\n        self.order_num = 0\n        self.drivers = {}\n        self.idle_driver_num = 0\n        self.offline_driver_num = 0\n\n    def get_layers_neighbors(self, l_max, M, N, env):\n\n        x, y = ids_1dto2d(self.get_node_index(), M, N)\n        self.layers_neighbors = get_layers_neighbors(x, y, l_max, M, N)\n        for layer_neighbors in self.layers_neighbors:\n            temp = []\n            for item in layer_neighbors:\n                x, y = item\n                node_id = ids_2dto1d(x, y, M, N)\n                if env.nodes[node_id] is not None:\n                    temp.append(node_id)\n            self.layers_neighbors_id.append(temp)\n\n    def get_node_index(self):\n        return self._index\n\n    def get_driver_numbers(self):\n        return self.idle_driver_num\n\n    def get_idle_driver_numbers_loop(self):\n        temp_idle_driver = 0\n        for key, driver in self.drivers.iteritems():\n            if driver.onservice is False and driver.online is True:\n                temp_idle_driver += 1\n        return temp_idle_driver\n\n    def get_off_driver_numbers_loop(self):\n        temp_idle_driver = 0\n        for key, driver in self.drivers.iteritems():\n            if driver.onservice is False and driver.online is False:\n                temp_idle_driver += 1\n        return temp_idle_driver\n\n    def order_distribution(self, distribution, dis_paras):\n\n        if distribution == 'Poisson':\n            self.order_generator = PoissonDistribution(dis_paras)\n        elif distribution == 'Gaussian':\n            self.order_generator = GaussianDistribution(dis_paras)\n        else:\n            pass\n\n    def generate_order_random(self, city_time, nodes, seed):\n        \"\"\"Generate new orders at each time step\n        \"\"\"\n        num_order_t = self.order_generator.sample(seed)\n        self.order_num += num_order_t\n\n        for ii in np.arange(num_order_t):\n            price = np.random.normal(50, 5, 1)[0]\n            price = 10 if price < 0 else price\n\n            current_node_id = self.get_node_index()\n            destination_node = [kk for kk in np.arange(len(nodes)) if kk != current_node_id]\n            self.orders.append(Order(nodes[current_node_id],\n                                     nodes[np.random.choice(destination_node, 1)[0]],\n                                     city_time,\n                                     # city_time + np.random.choice(5, 1)[0]+1,\n                                     np.random.choice(2, 1)[0]+1,  # duration\n                                     price, 1))\n        return\n\n    def generate_order_real(self, l_max, order_time_dist, order_price_dist, city_time, nodes, seed):\n        \"\"\"Generate new orders at each time step\n        \"\"\"\n        num_order_t = self.order_generator.sample(seed)\n        self.order_num += num_order_t\n        for ii in np.arange(num_order_t):\n\n            if l_max == 1:\n                duration = 1\n            else:\n\n                duration = np.random.choice(np.arange(1, l_max+1), p=order_time_dist)\n            price_mean, price_std = order_price_dist[duration-1]\n            price = np.random.normal(price_mean, price_std, 1)[0]\n            price = price if price > 0 else price_mean\n\n            current_node_id = self.get_node_index()\n            destination_node = []\n            for jj in np.arange(duration):\n                for kk in self.layers_neighbors_id[jj]:\n                    if nodes[kk] is not None:\n                        destination_node.append(kk)\n            self.orders.append(Order(nodes[current_node_id],\n                                     nodes[np.random.choice(destination_node, 1)[0]],\n                                     city_time,\n                                     duration,\n                                     price, 1))\n        return\n\n    def add_order_real(self, city_time, destination_node, duration, price):\n        current_node_id = self.get_node_index()\n        self.orders.append(Order(self,\n                                 destination_node,\n                                 city_time,\n                                 duration,\n                                 price, 0))\n        self.order_num += 1\n\n    def set_neighbors(self, nodes_list):\n        self.neighbors = nodes_list\n        self.n_side = len(nodes_list)\n\n    def remove_idle_driver_random(self):\n        \"\"\"Randomly remove one idle driver from current grid\"\"\"\n        removed_driver_id = \"NA\"\n        for key, item in self.drivers.iteritems():\n            if item.onservice is False and item.online is True:\n                self.remove_driver(key)\n                removed_driver_id = key\n            if removed_driver_id != \"NA\":\n                break\n        assert removed_driver_id != \"NA\"\n        return removed_driver_id\n\n    def set_idle_driver_offline_random(self):\n        \"\"\"Randomly set one idle driver offline\"\"\"\n        removed_driver_id = \"NA\"\n        for key, item in self.drivers.iteritems():\n            if item.onservice is False and item.online is True:\n                item.set_offline()\n                removed_driver_id = key\n            if removed_driver_id != \"NA\":\n                break\n        assert removed_driver_id != \"NA\"\n        return removed_driver_id\n\n    def set_offline_driver_online(self):\n\n        online_driver_id = \"NA\"\n        for key, item in self.drivers.iteritems():\n            if item.onservice is False and item.online is False:\n                item.set_online()\n                online_driver_id = key\n            if online_driver_id != \"NA\":\n                break\n        assert online_driver_id != \"NA\"\n        return online_driver_id\n\n    def get_driver_random(self):\n        \"\"\"Randomly get one driver\"\"\"\n        assert self.idle_driver_num > 0\n        get_driver_id = 0\n        for key in self.drivers.iterkeys():\n            get_driver_id = key\n            break\n        return self.drivers[get_driver_id]\n\n    def remove_driver(self, driver_id):\n\n        removed_driver = self.drivers.pop(driver_id, None)\n        self.idle_driver_num -= 1\n        if removed_driver is None:\n            raise ValueError('Nodes.remove_driver: Remove a driver that is not in this node')\n\n        return removed_driver\n\n    def add_driver(self, driver_id, driver):\n        self.drivers[driver_id] = driver\n        self.idle_driver_num += 1\n\n    def remove_unfinished_order(self, city_time):\n        un_finished_order_index = []\n        for idx, o in enumerate(self.orders):\n            # order un served\n            if o.get_wait_time()+o.get_begin_time() < city_time:\n                un_finished_order_index.append(idx)\n\n            # order completed\n            if o.get_assigned_time() + o.get_duration() == city_time and o.get_assigned_time() != -1:\n                un_finished_order_index.append(idx)\n\n        if len(un_finished_order_index) != 0:\n            # remove unfinished orders\n            self.orders = [i for j, i in enumerate(self.orders) if j not in un_finished_order_index]\n            self.order_num = len(self.orders)\n\n    def simple_order_assign(self, city_time, city):\n        reward = 0\n        num_assigned_order = min(self.order_num, self.idle_driver_num)\n        served_order_index = []\n        for idx in np.arange(num_assigned_order):\n            order_to_serve = self.orders[idx]\n            order_to_serve.set_assigned_time(city_time)\n            self.order_num -= 1\n            reward += order_to_serve.get_price()\n            served_order_index.append(idx)\n            for key, assigned_driver in self.drivers.iteritems():\n                if assigned_driver.onservice is False and assigned_driver.online is True:\n                    assigned_driver.take_order(order_to_serve)\n                    removed_driver = self.drivers.pop(assigned_driver.get_driver_id(), None)\n                    assert removed_driver is not None\n                    city.n_drivers -= 1\n                    break\n\n        all_order_num = len(self.orders)\n        finished_order_num = len(served_order_index)\n\n        # remove served orders\n        self.orders = [i for j, i in enumerate(self.orders) if j not in served_order_index]\n        assert self.order_num == len(self.orders)\n\n        return reward, all_order_num, finished_order_num\n\n    def simple_order_assign_real(self, city_time, city):\n\n        reward = 0\n        num_assigned_order = min(self.order_num, self.idle_driver_num)\n        served_order_index = []\n        for idx in np.arange(num_assigned_order):\n            order_to_serve = self.orders[idx]\n            order_to_serve.set_assigned_time(city_time)\n            self.order_num -= 1\n            reward += order_to_serve.get_price()\n            served_order_index.append(idx)\n            for key, assigned_driver in self.drivers.iteritems():\n                if assigned_driver.onservice is False and assigned_driver.online is True:\n                    if order_to_serve.get_end_position() is not None:\n                        assigned_driver.take_order(order_to_serve)\n                        removed_driver = self.drivers.pop(assigned_driver.get_driver_id(), None)\n                        assert removed_driver is not None\n                    else:\n                        assigned_driver.set_offline()  # order destination is not in target region\n                    city.n_drivers -= 1\n                    break\n\n        all_order_num = len(self.orders)\n        finished_order_num = len(served_order_index)\n\n        # remove served orders\n        self.orders = [i for j, i in enumerate(self.orders) if j not in served_order_index]\n        assert self.order_num == len(self.orders)\n\n        return reward, all_order_num, finished_order_num\n\n\n    def simple_order_assign_broadcast_update(self, city, neighbor_node_reward):\n\n        assert self.idle_driver_num == 0\n        reward = 0\n        num_finished_orders = 0\n        for neighbor_node in self.neighbors:\n            if neighbor_node is not None and neighbor_node.idle_driver_num > 0:\n                num_assigned_order = min(self.order_num, neighbor_node.idle_driver_num)\n                rr = self.utility_assign_orders_neighbor(city, neighbor_node, num_assigned_order)\n                reward += rr\n                neighbor_node_reward[neighbor_node.get_node_index()] += rr\n                num_finished_orders += num_assigned_order\n            if self.order_num == 0:\n                break\n\n        assert self.order_num == len(self.orders)\n        return reward, num_finished_orders\n\n    def utility_assign_orders_neighbor(self, city, neighbor_node, num_assigned_order):\n\n        served_order_index = []\n        reward = 0\n        curr_city_time = city.city_time\n        for idx in np.arange(num_assigned_order):\n            order_to_serve = self.orders[idx]\n            order_to_serve.set_assigned_time(curr_city_time)\n            self.order_num -= 1\n            reward += order_to_serve.get_price()\n            served_order_index.append(idx)\n            for key, assigned_driver in neighbor_node.drivers.iteritems():\n                if assigned_driver.onservice is False and assigned_driver.online is True:\n                    if order_to_serve.get_end_position() is not None:\n                        assigned_driver.take_order(order_to_serve)\n                        removed_driver = neighbor_node.drivers.pop(assigned_driver.get_driver_id(), None)\n                        assert removed_driver is not None\n                    else:\n                        assigned_driver.set_offline()\n                    city.n_drivers -= 1\n                    break\n\n        # remove served orders\n        self.orders = [i for j, i in enumerate(self.orders) if j not in served_order_index]\n        assert self.order_num == len(self.orders)\n\n        return reward\n\n\nclass Driver(object):\n    __slots__ = (\"online\", \"onservice\", 'order', 'node', 'city_time', '_driver_id')\n\n    def __init__(self, driver_id):\n        self.online = True\n        self.onservice = False\n        self.order = None     # the order this driver is serving\n        self.node = None      # the node that contain this driver.\n        self.city_time = 0  # track the current system time\n\n        # private\n        self._driver_id = driver_id  # unique driver id.\n\n    def set_position(self, node):\n        self.node = node\n\n    def set_order_start(self, order):\n        self.order = order\n\n    def set_order_finish(self):\n        self.order = None\n        self.onservice = False\n\n    def get_driver_id(self):\n        return self._driver_id\n\n    def update_city_time(self):\n        self.city_time += 1\n\n    def set_city_time(self, city_time):\n        self.city_time = city_time\n\n    def set_offline(self):\n        assert self.onservice is False and self.online is True\n        self.online = False\n        self.node.idle_driver_num -= 1\n        self.node.offline_driver_num += 1\n\n    def set_offline_for_start_dispatch(self):\n\n        assert self.onservice is False\n        self.online = False\n\n    def set_online(self):\n        assert self.onservice is False\n        self.online = True\n        self.node.idle_driver_num += 1\n        self.node.offline_driver_num -= 1\n\n    def set_online_for_finish_dispatch(self):\n\n        self.online = True\n        assert self.onservice is False\n\n    def take_order(self, order):\n        \"\"\" take order, driver show up at destination when order is finished\n        \"\"\"\n        assert self.online == True\n        self.set_order_start(order)\n        self.onservice = True\n        self.node.idle_driver_num -= 1\n\n    def status_control_eachtime(self, city):\n\n        assert self.city_time == city.city_time\n        if self.onservice is True:\n            assert self.online is True\n            order_end_time = self.order.get_assigned_time() + self.order.get_duration()\n            if self.city_time == order_end_time:\n                self.set_position(self.order.get_end_position())\n                self.set_order_finish()\n                self.node.add_driver(self._driver_id, self)\n                city.n_drivers += 1\n            elif self.city_time < order_end_time:\n                pass\n            else:\n                raise ValueError('Driver: status_control_eachtime(): order end time less than city time')\n\n\nclass Order(object):\n    __slots__ = ('_begin_p', '_end_p', '_begin_t',\n                 '_t', '_p', '_waiting_time', '_assigned_time')\n\n    def __init__(self, begin_position, end_position, begin_time, duration, price, wait_time):\n        self._begin_p = begin_position  # node\n        self._end_p = end_position      # node\n        self._begin_t = begin_time\n        # self._end_t = end_time\n        self._t = duration              # the duration of order.\n        self._p = price\n        self._waiting_time = wait_time  # a order can last for \"wait_time\" to be taken\n        self._assigned_time = -1\n\n    def get_begin_position(self):\n        return self._begin_p\n\n    def get_begin_position_id(self):\n        return self._begin_p.get_node_index()\n\n    def get_end_position(self):\n        return self._end_p\n\n    def get_begin_time(self):\n        return self._begin_t\n\n    def set_assigned_time(self, city_time):\n        self._assigned_time = city_time\n\n    def get_assigned_time(self):\n        return self._assigned_time\n\n    # def get_end_time(self):\n    #     return self._end_t\n\n    def get_duration(self):\n        return self._t\n\n    def get_price(self):\n        return self._p\n\n    def get_wait_time(self):\n        return self._waiting_time\n"
  },
  {
    "path": "simulator/utilities.py",
    "content": "import numpy as np\nimport os\nimport errno\n\n\n\nfrom datetime import datetime, timedelta\n\ndef datetime_range(start, end, delta):\n    current = start\n    while current < end:\n        yield current\n        current += delta\n\n\ndef mkdir_p(path):\n    try:\n        os.makedirs(path)\n    except OSError as exc:  # Python >2.5\n        if exc.errno == errno.EEXIST and os.path.isdir(path):\n            pass\n        else:\n            raise\n\n\ndef ids_2dto1d(i, j, M, N):\n    '''\n    convert (i,j) in a M by N matrix to index in M*N list. (row wise)\n    matrix: [[1,2,3], [4, 5, 6]]\n    list: [0, 1, 2, 3, 4, 5, 6]\n    index start from 0\n    '''\n    assert 0 <= i < M and 0 <= j < N\n    index = i * N + j\n    return index\n\n\ndef ids_1dto2d(ids, M, N):\n    ''' inverse of ids_2dto1d(i, j, M, N)\n        index start from 0\n    '''\n    i = ids / N\n    j = ids - N * i\n    return (i, j)\n\n\ndef get_neighbor_list(i, j, M, N, n, nodes):\n    ''' n: n-sided polygon, construct for a 2d map\n                 1\n             6       2\n               center\n             5       3\n                 4\n    return index of neighbor 1, 2, 3, 4, 5,6 in the matrix\n    '''\n\n    neighbor_list = [None] * n\n    if n == 6:\n        # hexagonal\n        if j % 2 == 0:\n            if i - 1 >= 0:\n                neighbor_list[0] = nodes[ids_2dto1d(i-1, j,   M, N)]\n            if j + 1 < N:\n                neighbor_list[1] = nodes[ids_2dto1d(i,   j+1, M, N)]\n            if i + 1 < M and j + 1 < N:\n                neighbor_list[2] = nodes[ids_2dto1d(i+1, j+1, M, N)]\n            if i + 1 < M:\n                neighbor_list[3] = nodes[ids_2dto1d(i+1, j,   M, N)]\n            if i + 1 < M and j - 1 >= 0:\n                neighbor_list[4] = nodes[ids_2dto1d(i+1, j-1, M, N)]\n            if j - 1 >= 0:\n                neighbor_list[5] = nodes[ids_2dto1d(i,   j-1, M, N)]\n        elif j % 2 == 1:\n            if i - 1 >= 0:\n                neighbor_list[0] = nodes[ids_2dto1d(i-1, j,   M, N)]\n            if i - 1 >= 0 and j + 1 < N:\n                neighbor_list[1] = nodes[ids_2dto1d(i-1, j+1, M, N)]\n            if j + 1 < N:\n                neighbor_list[2] = nodes[ids_2dto1d(i,   j+1, M, N)]\n            if i + 1 < M:\n                neighbor_list[3] = nodes[ids_2dto1d(i+1, j,   M, N)]\n            if j - 1 >= 0:\n                neighbor_list[4] = nodes[ids_2dto1d(i,   j-1, M, N)]\n            if i - 1 >= 0 and j - 1 >= 0:\n                neighbor_list[5] = nodes[ids_2dto1d(i-1, j-1, M, N)]\n    elif n == 4:\n        # square\n        if i - 1 >= 0:\n            neighbor_list[0] = nodes[ids_2dto1d(i-1, j,   M, N)]\n        if j + 1 < N:\n            neighbor_list[1] = nodes[ids_2dto1d(i,   j+1, M, N)]\n        if i + 1 < M:\n            neighbor_list[2] = nodes[ids_2dto1d(i+1, j,   M, N)]\n        if j - 1 >= 0:\n            neighbor_list[3] = nodes[ids_2dto1d(i,   j-1, M, N)]\n\n    return neighbor_list\n\n\ndef get_neighbor_index(i, j):\n    \"\"\"\n                 1\n             6       2\n                center\n             5       3\n                 4\n    return index of neighbor 1, 2, 3, 4, 5,6 in the matrix\n    \"\"\"\n    neighbor_matrix_ids = []\n    if j % 2 == 0:\n        neighbor_matrix_ids = [[i - 1, j    ],\n                               [i,     j + 1],\n                               [i + 1, j + 1],\n                               [i + 1, j    ],\n                               [i + 1, j - 1],\n                               [i    , j - 1]]\n    elif j % 2 == 1:\n        neighbor_matrix_ids = [[i - 1, j    ],\n                               [i - 1, j + 1],\n                               [i    , j + 1],\n                               [i + 1, j    ],\n                               [i    , j - 1],\n                               [i - 1, j - 1]]\n\n    return neighbor_matrix_ids\n\n\ndef get_layers_neighbors(i, j, l_max, M, N):\n    \"\"\"get neighbors of node layer by layer, todo BFS.\n       i, j: center node location\n       L_max: max number of layers\n       layers_neighbors: layers_neighbors[0] first layer neighbor: 6 nodes: can arrived in 1 time step.\n       layers_neighbors[1]: 2nd layer nodes id\n       M, N: matrix rows and columns.\n    \"\"\"\n    assert l_max >= 1\n    layers_neighbors = []\n    layer1_neighbor = get_neighbor_index(i, j)  #[[1,1], [0, 1], ...]\n    temp = []\n    for item in layer1_neighbor:\n        x, y = item\n        if 0 <= x <= M-1 and 0 <= y <= N-1:\n            temp.append(item)\n    layers_neighbors.append(temp)\n\n    node_id_neighbors = []\n    for item in layer1_neighbor:\n        x, y = item\n        if 0 <= x <= M-1 and 0 <= y <= N-1:\n            node_id_neighbors.append(ids_2dto1d(x, y, M, N))\n\n    layers_neighbors_set = set(node_id_neighbors)\n    curr_ndoe_id = ids_2dto1d(i, j, M, N)\n    layers_neighbors_set.add(curr_ndoe_id)\n\n    t = 1\n    while t < l_max:\n        t += 1\n        layer_neighbor_temp = []\n        for item in layers_neighbors[-1]:\n            x, y = item\n            if 0 <= x <= M-1 and 0 <= y <= N-1:\n                layer_neighbor_temp += get_neighbor_index(x, y)\n\n        layer_neighbor = []  # remove previous layer neighbors\n        for item in layer_neighbor_temp:\n            x, y = item\n            if 0 <= x <= M-1 and 0 <= y <= N-1:\n                node_id = ids_2dto1d(x, y, M, N)\n                if node_id not in layers_neighbors_set:\n                    layer_neighbor.append(item)\n                    layers_neighbors_set.add(node_id)\n        layers_neighbors.append(layer_neighbor)\n\n    return layers_neighbors\n\n\ndef get_driver_status(env):\n    idle_driver_dist = np.zeros((env.M, env.N))\n    for driver_id, cur_drivers in env.drivers.iteritems():\n        if cur_drivers.node is not None:\n            node_id = cur_drivers.node.get_node_index()\n            row, col = ids_1dto2d(node_id, env.M, env.N)\n            if cur_drivers.onservice is False and cur_drivers.online is True:\n                idle_driver_dist[row, col] += 1\n\n    return idle_driver_dist\n\ndef debug_print_drivers(node):\n    print(\"Status of all drivers in the node {}\".format(node.get_node_index()))\n    print(\"|{:12}|{:12}|{:12}|{:12}|\".format(\"driver id\", \"driver location\", \"online\", \"onservice\"))\n\n    for driver_id, cur_drivers in node.drivers.iteritems():\n        if cur_drivers.node is not None:\n            node_id = cur_drivers.node.get_node_index()\n        else:\n            node_id = \"none\"\n        print(\"|{:12}|{:12}|{:12}|{:12}|\".format(driver_id, node_id, cur_drivers.online, cur_drivers.onservice))\n\n\n\n"
  },
  {
    "path": "tests/run_example.py",
    "content": "\nfrom collections import defaultdict\nimport sys\nimport traceback\nimport os, sys\nsys.path.append(\"../\")\nfrom simulator.envs import *\n\n\ndef running_example():\n    mapped_matrix_int = np.array([[1, -100, 3], [5, 4, 2], [6, 7, 8]])\n    M, N = mapped_matrix_int.shape\n    order_num_dist = []\n    num_valid_grid = 8\n    idle_driver_location_mat = np.zeros((144, 8))\n\n    for ii in np.arange(144):\n        time_dict = {}\n        for jj in np.arange(M*N):  # num of grids\n            time_dict[jj] = [2]\n        order_num_dist.append(time_dict)\n        idle_driver_location_mat[ii, :] = [2] * num_valid_grid\n\n    idle_driver_dist_time = [[10, 1] for _ in np.arange(144)]\n\n    n_side = 6\n    l_max = 2\n    order_time = [0.2, 0.2, 0.15,\n                  0.15,  0.1,  0.1,\n                  0.05, 0.04,  0.01]\n    order_price = [[10.17, 3.34],  # mean and std of order price when duration is 10 min\n                   [15.02, 6.90],  # mean and std of order price when duration is 20 min\n                   [23.22, 11.63],\n                   [32.14, 16.20],\n                   [40.99, 20.69],\n                   [49.94, 25.61],\n                   [58.98, 31.69],\n                   [68.80, 37.25],\n                   [79.40, 44.39]]\n\n    order_real = []\n    onoff_driver_location_mat = []\n    for tt in np.arange(144):\n        order_real += [[1, 5, tt, 1, 13.2], [2, 6, tt, 1, 13.2], [3, 1, tt, 1, 13.2],\n                       [5, 3, tt, 1, 13.2], [6, 2, tt, 1, 13.2], [7, 9, tt, 1, 13.2],\n                       [9, 10, tt, 1, 13.2], [10, 6, tt, 1, 13.2], [9, 7, tt, 1, 13.2]]\n        onoff_driver_location_mat.append([[-0.625,       2.92350389],\n                                         [0.09090909,  1.46398452],\n                                         [0.09090909,  2.36596622],\n                                         [0.09090909, 2.36596622],\n                                         [0.09090909, 1.46398452],\n                                         [0.09090909, 1.46398452],\n                                         [0.09090909, 1.46398452],\n                                         [0.09090909, 1.46398452],\n                                         [0.09090909, 1.46398452]])\n    env = CityReal(mapped_matrix_int, order_num_dist, idle_driver_dist_time, idle_driver_location_mat,\n                   order_time, order_price, l_max, M, N, n_side, 1, np.array(order_real), np.array(onoff_driver_location_mat))\n\n    state = env.reset_clean()\n    order_response_rates = []\n    T = 0\n    max_iter = 144\n    while T < max_iter:\n        # if T % 5 == 0:\n        #     state = env.reset_clean(generate_order=2)\n        dispatch_action = []\n        state, reward, _ = env.step(dispatch_action, generate_order=2)\n\n        print \"City time {}: Order response rate: {}\".format(env.city_time-1, env.order_response_rate)\n        order_response_rates.append(env.order_response_rate)\n\n        print(\"idle driver: {} == {} total num of drivers: {}\".format(np.sum(state[0]),\n                                                                      np.sum(env.get_observation_driver_state()),\n                                                                      len(env.drivers.keys())))\n\n        assert np.sum(state[0]) == env.n_drivers\n\n        T += 1\n    print np.mean(order_response_rates)\n\n\nif __name__ == \"__main__\":\n    running_example()\n\n"
  }
]