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