├── .dockerignore ├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── doc └── aido-client-protocol.md ├── pom.xml └── src ├── main ├── java │ └── amodeus │ │ ├── amod │ │ ├── ScenarioCreator.java │ │ ├── ScenarioExecutionSequence.java │ │ ├── ScenarioPreparer.java │ │ ├── ScenarioServer.java │ │ ├── ScenarioViewer.java │ │ ├── analysis │ │ │ ├── CustomAnalysis.java │ │ │ ├── RoboTaxiRequestHistoGramExport.java │ │ │ ├── RoboTaxiRequestRecorder.java │ │ │ └── RoboTaxiRequestRecorderHtml.java │ │ ├── dispatcher │ │ │ ├── DemoDispatcher.java │ │ │ └── DemoDispatcherShared.java │ │ ├── ext │ │ │ ├── Static.java │ │ │ ├── UserLocationSpecs.java │ │ │ └── UserReferenceFrames.java │ │ ├── generator │ │ │ └── DemoGenerator.java │ │ └── router │ │ │ ├── CustomRouter.java │ │ │ └── CustomRouterDemo.java │ │ └── socket │ │ ├── SocketExport.java │ │ ├── SocketHost.java │ │ ├── SocketHtmlReport.java │ │ ├── SocketModule.java │ │ ├── SocketPopulationPreparer.java │ │ ├── SocketPreparer.java │ │ ├── SocketScenarioResource.java │ │ ├── SocketServer.java │ │ ├── StaticHelper.java │ │ ├── core │ │ ├── CleanSocketScenarios.java │ │ ├── CommandConsistency.java │ │ ├── EfficiencyScore.java │ │ ├── FleetSizeScore.java │ │ ├── LinComScore.java │ │ ├── ScoreParameters.java │ │ ├── ServiceQualityScore.java │ │ ├── SocketDispatcherHost.java │ │ ├── SocketDistanceRecorder.java │ │ ├── SocketRequestCompiler.java │ │ ├── SocketRoboTaxiCompiler.java │ │ ├── SocketScenarioDownload.java │ │ ├── SocketScoreCompiler.java │ │ ├── SocketScoreElement.java │ │ ├── SocketVehicleStatistic.java │ │ └── StaticHelper.java │ │ └── demo │ │ ├── DispatchingLogic.java │ │ ├── SocketGuest.java │ │ └── SocketStarterHelper.java ├── python │ ├── .gitignore │ ├── AidoGuest.py │ ├── DispatchingLogic.py │ └── utils │ │ ├── RoboTaxiStatus.py │ │ ├── StringSocket.py │ │ ├── Translator.py │ │ └── __init__.py └── resources │ ├── .gitignore │ ├── dtd │ └── av_v1.dtd │ ├── scenario │ └── SanFrancisco │ │ ├── network_pt2matsim.zip │ │ └── scenario.zip │ └── socket │ ├── ScoreParameters.properties │ └── scenarios.properties └── test └── java └── amodeus ├── amod ├── DemoTest.java └── ext │ └── UserLocationSpecsTest.java └── socket ├── SocketScenarioResourceTest.java ├── core ├── EfficiencyScoreTest.java ├── FleetSizeScoreTest.java ├── HttpDownloaderTest.java ├── ScoreParametersTest.java ├── ServiceQualityScoreTest.java └── SocketScenarioDownloadTest.java └── demo └── SocketGuestTest.java /.dockerignore: -------------------------------------------------------------------------------- 1 | ** 2 | !src 3 | !pom.xml 4 | !doc 5 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # maven 2 | target/ 3 | pom.xml.tag 4 | pom.xml.releaseBackup 5 | pom.xml.versionsBackup 6 | pom.xml.next 7 | release.properties 8 | dependency-reduced-pom.xml 9 | buildNumber.properties 10 | .mvn/timing.properties 11 | 12 | # matsim output (in case deletion fails) 13 | output/ 14 | 15 | # eclipse 16 | .settings/ 17 | .project 18 | .classpath 19 | 20 | # datahaki 21 | testall.sh 22 | gendocs.sh 23 | 24 | # intelliJ 25 | .idea/ 26 | amod.iml 27 | 28 | # https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore 29 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm 30 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 31 | 32 | # User-specific stuff: 33 | .idea/**/workspace.xml 34 | .idea/**/tasks.xml 35 | .idea/dictionaries 36 | 37 | # Sensitive or high-churn files: 38 | .idea/**/dataSources/ 39 | .idea/**/dataSources.ids 40 | .idea/**/dataSources.xml 41 | .idea/**/dataSources.local.xml 42 | .idea/**/sqlDataSources.xml 43 | .idea/**/dynamic.xml 44 | .idea/**/uiDesigner.xml 45 | 46 | # Gradle: 47 | .idea/**/gradle.xml 48 | .idea/**/libraries 49 | 50 | # CMake 51 | cmake-build-debug/ 52 | 53 | # Mongo Explorer plugin: 54 | .idea/**/mongoSettings.xml 55 | 56 | ## File-based project format: 57 | *.iws 58 | 59 | ## Plugin-specific files: 60 | 61 | # IntelliJ 62 | out/ 63 | 64 | # mpeltonen/sbt-idea plugin 65 | .idea_modules/ 66 | 67 | # JIRA plugin 68 | atlassian-ide-plugin.xml 69 | 70 | # Cursive Clojure plugin 71 | .idea/replstate.xml 72 | 73 | # Crashlytics plugin (for Android Studio and IntelliJ) 74 | com_crashlytics_export_strings.xml 75 | crashlytics.properties 76 | crashlytics-build.properties 77 | fabric.properties 78 | 79 | # macos files 80 | .DS_Store 81 | 82 | # temporary 83 | virtualNetwork/* 84 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | before_install: 2 | - sudo apt-get -qq update 3 | - sudo apt-get install swig 4 | 5 | language: java 6 | jdk: 7 | - openjdk11 8 | 9 | notifications: 10 | email: false 11 | 12 | script: 13 | - mkdir dependencies 14 | 15 | # Install tensor master 16 | - cd dependencies 17 | - git clone https://github.com/amodeus-science/tensor.git 18 | - cd tensor 19 | - mvn install -DskipTests=True 20 | - cd .. && cd .. 21 | 22 | # Install AMoDeus master 23 | - cd dependencies 24 | - git clone https://github.com/amodeus-science/amodeus.git 25 | - cd amodeus 26 | - mvn install -DskipTests=True 27 | - cd .. && cd .. 28 | - export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:dependencies/amodeus/resources/3rdparty/glpk/lib/jni 29 | 30 | # Test amod 31 | - mvn install -DskipTests=true -B -V -Dmaven.test.redirectTestOutputToFile -Dmatsim.preferLocalDtds=true 32 | - mvn test -B -Dmaven.test.redirectTestOutputToFile -Dmatsim.preferLocalDtds=true 33 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # amodeus.amod Build Status 2 | 3 | This repository allows to run an autonomous mobility-on-demand scenario using the [amodeus library](https://github.com/amodeus-science/amodeus). 4 | 5 | Try it, orchestrate your own fleet of amod-taxis! Watch a [visualization](https://www.youtube.com/watch?v=QkFtIQQSHto) of a traffic simulation in San Francisco generated using this repository. 6 | 7 | 8 |
9 | 10 | ![p1t1](https://user-images.githubusercontent.com/4012178/38852194-23c0b602-4219-11e8-90af-ce5c589ddf47.png) 11 | 12 | 13 | 14 | ![p1t4](https://user-images.githubusercontent.com/4012178/38852209-30616834-4219-11e8-81db-41fe71f7599e.png) 15 | 16 | 17 | 18 | ![p1t3](https://user-images.githubusercontent.com/4012178/38852252-4f4d178e-4219-11e8-9634-434200922ed0.png) 19 | 20 | 21 | 22 | ![p1t2](https://user-images.githubusercontent.com/4012178/38852212-3200c8d8-4219-11e8-9dad-eb0aa33e1357.png) 23 | 24 |
25 | 26 | ## Admins 27 | 28 | AMoDeus is jointly maintained and further developed by the Admins and Code Owners Christian Fluri (ETH Zürich), Joel Gächter (ETH Zürich), Sebastian Hörl (ETH Zürich), Claudio Ruch, Jan Hakenberg, ChengQi Lu (TU Berlin), and Marc Albert (nuTonomy). 29 | 30 | Please let us know if you'd like to contribute! 31 | 32 | ## First steps in the amod repository 33 | 34 | ### Prerequisites 35 | 36 | - You may work on a Linux, Mac or Windows OS with a set of different possible IDEs. The combination Ubuntu, Java 8, Eclipse has worked well. 37 | - Install Java SE Development Kit (version 8, or above) 38 | - Install Apache Maven 39 | - Install IDE (ideally Eclipse Oxygen or Photon) 40 | - Install GLPK and GLPK for Java (Ensure you install compatible versions, e.g. [here](http://glpk-java.sourceforge.net/gettingStarted.html)) 41 | - Prerequisites are: GCC, Libtool, Swig and Subversion 42 | - Install Git and connect to GitHub with [SSH](https://help.github.com/articles/connecting-to-github-with-ssh/) 43 | 44 | The code format of the `amod` repository is specified in the `amodeus` profile that you can import from [amodeus-code-style.xml](https://raw.githubusercontent.com/amodeus-science/amodeus/master/amodeus-code-style.xml). 45 | 46 | ### Getting Started 47 | 48 | Follow these step-by-step instructions or the [video](https://www.youtube.com/watch?v=hay5VGhQ7S8) to set up, prepare, and run your first simulation. You can get a sample simulation scenario at https://www.amodeus.science/ 49 | 1. Clone amod 50 | 2. Import to eclipse as existing maven project (Package Explorer->Import) using the pom.xml in the top folder of this repository. 51 | 3. Set up Run Configurations for: (ScenarioPreparer; ScenarioServer; ScenarioViewer), chose the Working Directory to be the top Simulation Folder directory. 52 | 4. Adjust the simulation settings in the 3 config files: av.xml for av fleet values (e.g. number vehicles), AmodeusOptions.properties for AMoDeus settings (e.g. max number of people) and config.xml for Matsim settings (e.g. output directory). 53 | 5. Add JAVA VM arguments if necessary, e.g., `-Xmx10000m` to run with 10 GB of RAM and `-Dmatsim.preferLocalDtds=true` to prefer the local Dtds. 54 | 6. Run the `ScenarioPreparer` as a Java application: wait until termination 55 | 7. Run the `ScenarioServer` as a Java application: the simulation should run 56 | 8. Run the `ScenarioViewer` as a Java application: the visualization of the scenario should open in a separate window 57 | 58 | ## Gallery 59 | 60 | 61 |
62 | 63 | ![usecase_amodeus](https://user-images.githubusercontent.com/4012178/35968174-668b6e54-0cc3-11e8-9c1b-a3e011fa0600.png) 64 | 65 | Zurich 66 | 67 | 68 | 69 | ![p1t5](https://user-images.githubusercontent.com/4012178/38852351-ce176dc6-4219-11e8-93a5-7ad58247e82b.png) 70 | 71 | San Francisco 72 | 73 | 74 | 75 | ![San Francisco](https://user-images.githubusercontent.com/4012178/37365948-4ab45794-26ff-11e8-8e2d-ceb1b526e962.png) 76 | 77 | San Francisco 78 | 79 |
80 | 81 | ## String Interface 82 | 83 | TODO improve and adapt documentation, de-dockerize 84 | Run `docker-compose up` to run the San Fransisco simulation. This will run two services, `aido-host` and `aido-guest`, which will communicate over port `9382`. 85 | 86 | The protocol is specified [here](https://github.com/amodeus-science/amod/blob/master/doc/aido-client-protocol.md). 87 | 88 | --- 89 | 90 | ![ethz300](https://user-images.githubusercontent.com/4012178/45925071-bf9d3b00-bf0e-11e8-9d92-e30650fd6bf6.png) 91 | -------------------------------------------------------------------------------- /doc/aido-client-protocol.md: -------------------------------------------------------------------------------- 1 | # AIDO client protocol 2 | 3 | This file outlines the communication protocol previously for the Artificial Intelligence Driving Olympics (=AIDO) autonomous mobility-on-demand competition, for assistance please contact [mailto] (clruch@idsc.mavt.ethz.ch). 4 | 5 | The communication is text based. 6 | 7 | Each message is a string that terminates with a line break `\n`. Apart from the last character, the string does **not** contain another line break. 8 | 9 | *Remark:* The notation adheres to the *Mathematica* standard for nested lists, [see here](https://reference.wolfram.com/language/tutorial/NestedLists.html). 10 | 11 | The communication takes place between the main processes in [AidoHost](https://github.com/idsc-frazzoli/amod/blob/master/src/main/java/ch/ethz/idsc/aido/AidoHost.java) and [AidoGuest](https://github.com/idsc-frazzoli/amod/blob/master/src/main/java/ch/ethz/idsc/aido/demo/AidoGuest.java). AidoHost contains the simulation environment, while a modified version of AidoGuest can be used by the participant of AIDO to place their own fleet operational policy. **AidoHost** is implemented as a **Server** and **AidoGuest** as a **Client**. 12 | 13 | ## Port of server 14 | 15 | The server listens for incoming `TCP/IP` connections at port `9382`. 16 | 17 | ## Initialization 18 | 19 | ### Client -> Server 20 | 21 | The server requires information about which scenario to run. The range of options is visible in [this file](https://github.com/idsc-frazzoli/amod/blob/master/src/main/resources/aido/scenarios.properties). The client sends the first line for instance as 22 | 23 | {SanFrancisco.20080518} 24 | 25 | The line encodes the name of the scenario `SanFrancisco.20080518`, valid scenarios names include also `TelAviv`, `Santiago`, `Berlin`. 26 | 27 | 28 | ### Server -> Client 29 | 30 | The server replies with the total number of requests in the scenario, bounding box of the scenario coordinates and the nominal fleet size. 31 | 32 | {190788,{{-71.38020297181387, -33.869660953686626}, {-70.44406349551404, -33.0303523690584}},700} 33 | 34 | The interpretation is 35 | 36 | {number of requests,{{longitude min, latitude min}, {longitude max, latitude max}}, nominal fleet size} 37 | 38 | The coordinates of the bouding box are denoted in the WGS:84 coordinate system. 39 | 40 | ### Client -> Server 41 | 42 | The client then responds by chosing the desired number of requests and the desired fleet size, for instance 43 | 44 | {10000,277} 45 | 46 | 47 | The interpretation is 48 | 49 | {desired number of requests, desired fleet size} 50 | 51 | The desired number of requests must be a positive integer. If it is larger than the total requests in the chosen scenario, the total requests in the chosen scenario are used in the simulation. The desired fleet size can be any positive integer. 52 | 53 | ## Main loop 54 | 55 | ### Server -> Client 56 | 57 | The server gives the signal that the simulation has completed, or notifies the client about the state of the simulation. 58 | 59 | When simulation is finished, the server sends an empty list 60 | 61 | {} 62 | 63 | in which case the client should exit the main loop and proceed to receive the evaluation. 64 | 65 | When the simulation is ongoing, the server sends a list of the following structure: 66 | 67 | {simulation time, VEHICLES, REQUESTS, REWARDS} 68 | 69 | #### VEHICLES 70 | 71 | The variable `VEHICLES` encodes the status of all vehicles. `VEHICLES` is a list of the form 72 | 73 | {VEHICLE_STATUS[1], ..., VEHICLE_STATUS[n]} 74 | 75 | The variable `VEHICLE_STATUS` is a list of the form 76 | 77 | {vehicle index, {longitude position, latitude position}, STATUS, IS_DIVERTABLE} 78 | 79 | The vehicle index is a non-negative integer. 80 | 81 | The field `STATUS` is one of the following strings `DRIVEWITHCUSTOMER`, `DRIVETOCUSTOMER`, `REBALANCEDRIVE`, or `STAY` (without quotation marks). 82 | 83 | The field `IS_DIVERTABLE` is either the value `0` or `1`. The value `0` encodes that the vehicle is not divertable. The value `1` encodes that the vehicle is divertable. 84 | 85 | #### REQUESTS 86 | 87 | The variable `REQUESTS` encodes the status of all open, i.e. unserved requests. `REQUESTS` is a list of the form 88 | 89 | {REQUEST_STATUS[1], ..., REQUEST_STATUS[m]} 90 | 91 | The variable `REQUEST_STATUS` is a list of the form 92 | 93 | {request index, submission time, {longitude origin, latitude origin}, {longitude destination, latitude destination}} 94 | 95 | Each request has a unique, non-negative integer as index. 96 | 97 | The `submission time` is a numeric value less than `simulation time`. 98 | 99 | #### REWARDS 100 | 101 | The variable `REWARDS` is a list that contains the gains accumulated in different categories since the previous simulation step. 102 | 103 | {service reward, efficiency reward, fleet size reward} 104 | 105 | The value of `THIRD_REWARD` is initially `0` but switches to `-Infinity` if the maximum wait-time among the unserviced requests exceeds 10 minutes. 106 | 107 | The final score vector is the (undiscounted) sum of all reward vectors. 108 | 109 | ### Client -> Server 110 | 111 | The client has to instruct the simulation server on how to divert the vehicles. 112 | Each vehicle can either be sent on a pickup drive to fetch a waiting customer, or a rebalancing drive. 113 | The message is a list of the form: 114 | 115 | {PICKUPS, REBALANCING} 116 | 117 | The variable `PICKUPS` is a list of the form 118 | 119 | {PICKUP_PAIR[1], ..., PICKUP_PAIR[p]} 120 | 121 | The variable `PICKUP_PAIR` is a list with two entries that associates a divertable vehicle with an open request. The list is of the form 122 | 123 | {vehicle index, request index} 124 | 125 | The variable `REBALANCING` is a list of the form 126 | 127 | {REBALANCE[1], ..., REBALANCE[r]} 128 | 129 | The variable `REBALANCE` is of the form 130 | 131 | {vehicle index, {longitude destination, latitude destination}} 132 | 133 | Important: 134 | Each vehicle index may only appear in either the pickup or rebalancing instructions. Additionally, within the list, each vehicle index may only appear once. Each request index may only appear once in the list of pickup instructions. However, in the next time step, another vehicle may be assigned to the same request. In that case, the former vehicle will stop driving. 135 | 136 | Examples: 137 | * The client may choose to send `{{}, {}}` which corresponds to an empty list of pickup instructions, and an empty list of rebalancing instructions. 138 | * The client is not required to use rebalancing instructions. A message of the form `{PICKUPS, {}}` is valid. 139 | * The client may choose to only send rebalancing instructions. In that case, the message is the form `{{}, REBALANCING}` is valid. 140 | 141 | 142 | ## Evaluation 143 | 144 | ### Server -> Client 145 | 146 | The server sends the (undiscounted) sum of all reward vectors. In the last component, a reward of `-n` incurs, which represents the cost for the number of vehicles used. 147 | 148 | {service score, efficiency score, fleet size score} 149 | 150 | In particular, the `fleet size score` takes the value `-n` or `-Infinity`. 151 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 4 | 4.0.0 5 | amodeus 6 | amod 7 | 2.1.0 8 | jar 9 | 10 | 11 | 11 12 | 11 13 | false 14 | 15 | 16 | 17 | 18 | amodeus 19 | amodeus 20 | 2.1.0 21 | 22 | 23 | amodeus 24 | amodtaxi 25 | 2.0.0 26 | 27 | 28 | junit 29 | junit 30 | 4.13.1 31 | test 32 | 33 | 34 | 35 | 36 | 37 | tensor-mvn-repo 38 | https://raw.github.com/amodeus-science/tensor/mvn-repo/ 39 | 40 | true 41 | always 42 | 43 | 44 | 45 | amodeus-mvn-repo 46 | https://raw.github.com/amodeus-science/amodeus/mvn-repo/ 47 | 48 | true 49 | always 50 | 51 | 52 | 53 | amodtaxi-mvn-repo 54 | https://raw.github.com/amodeus-science/amodtaxi/mvn-repo/ 55 | 56 | true 57 | always 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | org.apache.maven.plugins 66 | maven-compiler-plugin 67 | 3.1 68 | 69 | 11 70 | 11 71 | 72 | 73 | 74 | org.apache.maven.plugins 75 | maven-source-plugin 76 | 3.0.1 77 | 78 | 79 | attach-sources 80 | verify 81 | 82 | jar-no-fork 83 | 84 | 85 | 86 | 87 | 88 | org.apache.maven.plugins 89 | maven-javadoc-plugin 90 | 2.10.4 91 | 92 | 93 | 94 | 95 | org.apache.maven.plugins 96 | maven-shade-plugin 97 | 3.1.1 98 | 99 | 100 | 102 | amod.demo.ScenarioStandalone 103 | 104 | amod.demo.ScenarioStandalone 105 | Java Advanced Imaging Image I/O Tools 106 | 1.1 107 | Sun Microsystems, Inc. 108 | com.sun.media.imageio 109 | 1.1 110 | Sun Microsystems, Inc. 111 | com.sun.media.imageio 112 | 113 | 114 | 115 | 116 | 118 | 119 | amod.demo.ScenarioStandalone 120 | 121 | 122 | 123 | 125 | 126 | 128 | 129 | 130 | *:* 131 | 132 | META-INF/*.SF 133 | META-INF/*.DSA 134 | META-INF/*.RSA 135 | 136 | 137 | 138 | 139 | 140 | 141 | package 142 | 143 | shade 144 | 145 | 146 | 147 | 148 | 149 | 150 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ScenarioCreator.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod; 3 | 4 | import java.io.File; 5 | import java.util.HashMap; 6 | import java.util.Map; 7 | 8 | import amodeus.amodeus.util.io.MultiFileTools; 9 | import amodeus.amodeus.util.math.GlobalAssert; 10 | import amodeus.amodtaxi.scenario.ScenarioCreation; 11 | import amodeus.amodtaxi.scenario.chicago.ChicagoScenarioCreation; 12 | import amodeus.amodtaxi.scenario.sanfrancisco.SanFranciscoScenarioCreation; 13 | 14 | /** provides a quick access to the implementations of {@link ScenarioCreation}: 15 | * {@link ChicagoScenarioCreation} 16 | * {@link SanFranciscoScenarioCreation} */ 17 | public enum ScenarioCreator { 18 | CHICAGO { 19 | @Override 20 | public ScenarioCreation in(File workingDirectory) throws Exception { 21 | return ChicagoScenarioCreation.in(workingDirectory); 22 | } 23 | }, 24 | SAN_FRANCISCO { 25 | @Override 26 | public ScenarioCreation in(File workingDirectory) throws Exception { 27 | return SanFranciscoScenarioCreation.of(workingDirectory, (File) null).get(0); 28 | } 29 | }; 30 | 31 | /** creates a scenario with some basic settings in 32 | * @param workingDirectory 33 | * @return {@link ScenarioCreation} 34 | * @throws Exception if scenario could not be properly created */ 35 | public abstract ScenarioCreation in(File workingDirectory) throws Exception; 36 | 37 | // --- 38 | 39 | public static void main(String[] args) throws Exception { 40 | if (args.length < 1) 41 | throw new RuntimeException("No scenario specified! Provide scenario name as argument."); 42 | 43 | Map scenarios = new HashMap<>(); 44 | scenarios.put("chicago", ScenarioCreator.CHICAGO); 45 | scenarios.put("sanfrancisco", ScenarioCreator.SAN_FRANCISCO); 46 | scenarios.put("san_francisco", ScenarioCreator.SAN_FRANCISCO); 47 | scenarios.put("san-francisco", ScenarioCreator.SAN_FRANCISCO); 48 | 49 | ScenarioCreation scenario = scenarios.get(args[0].toLowerCase()).in(MultiFileTools.getDefaultWorkingDirectory()); 50 | GlobalAssert.that(scenario.directory().exists()); 51 | System.out.println("Created a ready to use AMoDeus scenario in " + scenario.directory()); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ScenarioExecutionSequence.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod; 3 | 4 | import java.net.MalformedURLException; 5 | 6 | /** Helper class to run a default preparer and server, the typical 7 | * sequence of execution. */ 8 | /* package */ enum ScenarioExecutionSequence { 9 | ; 10 | 11 | public static void main(String[] args) throws MalformedURLException, Exception { 12 | // preliminary steps, e.g., seting up data structures required by operational policies 13 | ScenarioPreparer.main(args); 14 | // running the simulation 15 | ScenarioServer.main(args); 16 | // viewing results, the viewer can also connect to a running simulation. 17 | ScenarioViewer.main(args); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ScenarioPreparer.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod; 3 | 4 | import java.io.File; 5 | import java.net.MalformedURLException; 6 | 7 | import amodeus.amodeus.options.ScenarioOptions; 8 | import amodeus.amodeus.options.ScenarioOptionsBase; 9 | import amodeus.amodeus.prep.ConfigCreator; 10 | import amodeus.amodeus.prep.NetworkPreparer; 11 | import amodeus.amodeus.prep.PopulationPreparer; 12 | import amodeus.amodeus.prep.TheApocalypse; 13 | import amodeus.amodeus.prep.VirtualNetworkPreparer; 14 | import amodeus.amodeus.util.io.MultiFileTools; 15 | import org.matsim.amodeus.config.AmodeusConfigGroup; 16 | import org.matsim.amodeus.config.modal.GeneratorConfig; 17 | import org.matsim.api.core.v01.Scenario; 18 | import org.matsim.api.core.v01.network.Network; 19 | import org.matsim.api.core.v01.population.Population; 20 | import org.matsim.core.config.Config; 21 | import org.matsim.core.config.ConfigUtils; 22 | import org.matsim.core.scenario.ScenarioUtils; 23 | 24 | import amodeus.amod.ext.Static; 25 | 26 | /** Class to prepare a given scenario for MATSim, includes preparation of 27 | * network, population, creation of virtualNetwork and travelData objects. As an 28 | * example a user may want to restrict the population size to few 100s of agents 29 | * to run simulations quickly during testing, or the network should be reduced 30 | * to a certain area. */ 31 | /* package */ enum ScenarioPreparer { 32 | ; 33 | 34 | public static void main(String[] args) throws MalformedURLException, Exception { 35 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 36 | run(workingDirectory); 37 | } 38 | 39 | /** loads scenario preparer in the {@link File} workingDirectory @param 40 | * workingDirectory 41 | * 42 | * @throws MalformedURLException 43 | * @throws Exception */ 44 | public static void run(File workingDirectory) throws MalformedURLException, Exception { 45 | Static.setup(); 46 | System.out.println("\n\n\n" + Static.glpInfo() + "\n\n\n"); 47 | 48 | /** The {@link ScenarioOptions} contain amodeus specific options. Currently there 49 | * are 3 options files: - MATSim configurations (config.xml) - AV package 50 | * configurations (av.xml) - AMoDeus configurations (AmodeusOptions.properties). 51 | * 52 | * The number of configs is planned to be reduced in subsequent refactoring 53 | * steps. */ 54 | ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 55 | Static.setLPtoNone(workingDirectory); 56 | 57 | /** MATSim config */ 58 | AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup(); 59 | // avConfigGroup.addMode(new AmodeusModeConfig("av")); 60 | Config config = ConfigUtils.loadConfig(scenarioOptions.getPreparerConfigName(), avConfigGroup); 61 | Scenario scenario = ScenarioUtils.loadScenario(config); 62 | GeneratorConfig genConfig = avConfigGroup.getModes().values().iterator().next().getGeneratorConfig(); 63 | int numRt = genConfig.getNumberOfVehicles(); 64 | System.out.println("NumberOfVehicles=" + numRt); 65 | 66 | /** adaption of MATSim network, e.g., radius cutting */ 67 | Network network = scenario.getNetwork(); 68 | network = NetworkPreparer.run(network, scenarioOptions); 69 | 70 | /** adaption of MATSim population, e.g., radius cutting */ 71 | Population population = scenario.getPopulation(); 72 | 73 | /** this reduced the population size to allow for faster simulation initially, 74 | * remove to have bigger simualation */ 75 | TheApocalypse.reducesThe(population).toNoMoreThan(2000); 76 | 77 | long apoSeed = 1234; 78 | PopulationPreparer.run(network, population, scenarioOptions, config, apoSeed); 79 | 80 | /** creating a virtual network, e.g., for operational policies requiring a graph 81 | * structure on the city */ 82 | int endTime = (int) config.qsim().getEndTime().seconds(); 83 | VirtualNetworkPreparer.INSTANCE.create(network, population, scenarioOptions, numRt, endTime); // 84 | 85 | /** create a simulation MATSim config file linking the created input data */ 86 | ConfigCreator.createSimulationConfigFile(config, scenarioOptions); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ScenarioServer.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod; 3 | 4 | import java.io.File; 5 | import java.net.MalformedURLException; 6 | import java.util.Objects; 7 | 8 | import amodeus.amodeus.analysis.Analysis; 9 | import amodeus.amodeus.data.LocationSpec; 10 | import amodeus.amodeus.data.ReferenceFrame; 11 | import amodeus.amodeus.linkspeed.TaxiTravelTimeRouter; 12 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 13 | import amodeus.amodeus.net.SimulationServer; 14 | import amodeus.amodeus.options.ScenarioOptions; 15 | import amodeus.amodeus.options.ScenarioOptionsBase; 16 | import amodeus.amodeus.util.io.MultiFileTools; 17 | import amodeus.amodeus.util.math.GlobalAssert; 18 | import amodeus.amodeus.util.matsim.AddCoordinatesToActivities; 19 | import org.matsim.amodeus.AmodeusConfigurator; 20 | import org.matsim.amodeus.config.AmodeusConfigGroup; 21 | import org.matsim.amodeus.framework.AmodeusUtils; 22 | import org.matsim.api.core.v01.Scenario; 23 | import org.matsim.api.core.v01.network.Network; 24 | import org.matsim.api.core.v01.population.Population; 25 | import org.matsim.contrib.dvrp.run.DvrpConfigGroup; 26 | import org.matsim.core.config.Config; 27 | import org.matsim.core.config.ConfigUtils; 28 | import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; 29 | import org.matsim.core.config.groups.QSimConfigGroup; 30 | import org.matsim.core.controler.AbstractModule; 31 | import org.matsim.core.controler.Controler; 32 | import org.matsim.core.scenario.ScenarioUtils; 33 | 34 | import amodeus.amod.analysis.CustomAnalysis; 35 | import amodeus.amod.dispatcher.DemoDispatcher; 36 | import amodeus.amod.ext.Static; 37 | import amodeus.amod.generator.DemoGenerator; 38 | 39 | /** This class runs an AMoDeus simulation based on MATSim. The results can be 40 | * viewed if the {@link ScenarioViewer} is executed in the same working 41 | * directory and the button "Connect" is pressed. */ 42 | /* package */ enum ScenarioServer { 43 | ; 44 | 45 | public static void main(String[] args) throws MalformedURLException, Exception { 46 | simulate(MultiFileTools.getDefaultWorkingDirectory()); 47 | } 48 | 49 | /** runs a simulation run using input data from Amodeus.properties, av.xml and 50 | * MATSim config.xml 51 | * 52 | * @throws MalformedURLException 53 | * @throws Exception */ 54 | public static void simulate(File workingDirectory) throws MalformedURLException, Exception { 55 | Static.setup(); 56 | System.out.println("\n\n\n" + Static.glpInfo() + "\n\n\n"); 57 | 58 | /** working directory and options */ 59 | ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 60 | 61 | /** set to true in order to make server wait for at least 1 client, for 62 | * instance viewer client, for fals the ScenarioServer starts the simulation 63 | * immediately */ 64 | boolean waitForClients = scenarioOptions.getBoolean("waitForClients"); 65 | File configFile = new File(scenarioOptions.getSimulationConfigName()); 66 | 67 | /** geographic information */ 68 | LocationSpec locationSpec = scenarioOptions.getLocationSpec(); 69 | ReferenceFrame referenceFrame = locationSpec.referenceFrame(); 70 | 71 | /** open server port for clients to connect to */ 72 | SimulationServer.INSTANCE.startAcceptingNonBlocking(); 73 | SimulationServer.INSTANCE.setWaitForClients(waitForClients); 74 | 75 | /** load MATSim configs - including av.xml configurations, load routing packages */ 76 | GlobalAssert.that(configFile.exists()); 77 | DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup(); 78 | dvrpConfigGroup.setTravelTimeEstimationAlpha(0.05); 79 | Config config = ConfigUtils.loadConfig(configFile.toString(), new AmodeusConfigGroup(), dvrpConfigGroup); 80 | config.planCalcScore().addActivityParams(new ActivityParams("activity")); 81 | 82 | config.qsim().setStartTime(0.0); 83 | config.qsim().setSimStarttimeInterpretation(QSimConfigGroup.StarttimeInterpretation.onlyUseStarttime); 84 | 85 | /** MATSim does not allow the typical duration not to be set, therefore for scenarios 86 | * generated from taxi data such as the "SanFrancisco" scenario, it is set to 1 hour. */ 87 | // TODO @Sebastian fix this to meaningful values, remove, or add comment 88 | // this was added because there are sometimes problems, is there a more elegant option? 89 | for (ActivityParams activityParams : config.planCalcScore().getActivityParams()) 90 | activityParams.setTypicalDuration(3600.0); 91 | 92 | /** output directory for saving results */ 93 | String outputdirectory = config.controler().getOutputDirectory(); 94 | 95 | /** load MATSim scenario for simulation */ 96 | Scenario scenario = ScenarioUtils.loadScenario(config); 97 | AddCoordinatesToActivities.run(scenario); 98 | Network network = scenario.getNetwork(); 99 | Population population = scenario.getPopulation(); 100 | GlobalAssert.that(Objects.nonNull(network)); 101 | GlobalAssert.that(Objects.nonNull(population)); 102 | 103 | MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame); 104 | Controler controller = new Controler(scenario); 105 | AmodeusConfigurator.configureController(controller, scenarioOptions); 106 | 107 | /** With the subsequent lines an additional user-defined dispatcher is added, functionality 108 | * in class 109 | * DemoDispatcher, as long as the dispatcher was not selected in the file av.xml, it is not 110 | * used in the simulation. */ 111 | controller.addOverridingModule(new AbstractModule() { 112 | @Override 113 | public void install() { 114 | AmodeusUtils.registerDispatcherFactory(binder(), // 115 | DemoDispatcher.class.getSimpleName(), DemoDispatcher.Factory.class); 116 | } 117 | }); 118 | 119 | /** With the subsequent lines, additional user-defined initial placement logic called 120 | * generator is added, 121 | * functionality in class DemoGenerator. As long as the generator is not selected in the 122 | * file av.xml, 123 | * it is not used in the simulation. */ 124 | controller.addOverridingModule(new AbstractModule() { 125 | @Override 126 | public void install() { 127 | AmodeusUtils.registerGeneratorFactory(binder(), "DemoGenerator", DemoGenerator.Factory.class); 128 | } 129 | }); 130 | 131 | /** With the subsequent lines, another custom router is added apart from the 132 | * {@link DefaultAStarLMRouter}, 133 | * it has to be selected in the av.xml file with the lines as follows: 134 | * 135 | * 136 | * 137 | * ... 138 | * 139 | * otherwise the normal {@link DefaultAStarLMRouter} will be used. */ 140 | /** Custom router that ensures same network speeds as taxis in original data set. */ 141 | controller.addOverridingModule(new AbstractModule() { 142 | @Override 143 | public void install() { 144 | bind(TaxiTravelTimeRouter.Factory.class); 145 | AmodeusUtils.bindRouterFactory(binder(), TaxiTravelTimeRouter.class.getSimpleName()).to(TaxiTravelTimeRouter.Factory.class); 146 | } 147 | }); 148 | 149 | /** run simulation */ 150 | controller.run(); 151 | 152 | /** close port for visualizaiton */ 153 | SimulationServer.INSTANCE.stopAccepting(); 154 | 155 | /** perform analysis of simulation, a demo of how to add custom analysis methods 156 | * is provided in the package amod.demo.analysis */ 157 | Analysis analysis = Analysis.setup(scenarioOptions, new File(outputdirectory), network, db); 158 | CustomAnalysis.addTo(analysis); 159 | analysis.run(); 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ScenarioViewer.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod; 3 | 4 | import java.io.File; 5 | import java.io.FileNotFoundException; 6 | import java.io.IOException; 7 | 8 | import amodeus.amodeus.data.LocationSpec; 9 | import amodeus.amodeus.data.ReferenceFrame; 10 | import amodeus.amodeus.gfx.AmodeusComponent; 11 | import amodeus.amodeus.gfx.AmodeusViewerFrame; 12 | import amodeus.amodeus.gfx.ViewerConfig; 13 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 14 | import amodeus.amodeus.options.ScenarioOptions; 15 | import amodeus.amodeus.options.ScenarioOptionsBase; 16 | import amodeus.amodeus.util.io.MultiFileTools; 17 | import amodeus.amodeus.util.matsim.NetworkLoader; 18 | import amodeus.amodeus.virtualnetwork.core.VirtualNetworkGet; 19 | import org.matsim.api.core.v01.network.Network; 20 | import org.matsim.core.config.Config; 21 | import org.matsim.core.config.ConfigUtils; 22 | 23 | import amodeus.amod.ext.Static; 24 | 25 | /** the viewer allows to connect to the scenario server or to view saved simulation results. */ 26 | /* package */ enum ScenarioViewer { 27 | ; 28 | 29 | public static void main(String[] args) throws FileNotFoundException, IOException { 30 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 31 | run(workingDirectory); 32 | } 33 | 34 | /** Execute in simulation folder to view past results or connect to simulation server 35 | * 36 | * @param workingDirectory 37 | * @throws FileNotFoundException 38 | * @throws IOException */ 39 | public static void run(File workingDirectory) throws FileNotFoundException, IOException { 40 | Static.setup(); 41 | ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 42 | 43 | /** load options */ 44 | Config config = ConfigUtils.loadConfig(scenarioOptions.getSimulationConfigName()); 45 | System.out.println("MATSim config file: " + scenarioOptions.getSimulationConfigName()); 46 | final File outputSubDirectory = new File(config.controler().getOutputDirectory()).getAbsoluteFile(); 47 | if (!outputSubDirectory.isDirectory()) 48 | throw new RuntimeException("output directory: " + outputSubDirectory.getAbsolutePath() + " not found."); 49 | System.out.println("outputSubDirectory=" + outputSubDirectory.getAbsolutePath()); 50 | File outputDirectory = outputSubDirectory.getParentFile(); 51 | System.out.println("showing simulation results from outputDirectory=" + outputDirectory); 52 | 53 | /** geographic information, .e.g., coordinate system */ 54 | LocationSpec locationSpec = scenarioOptions.getLocationSpec(); 55 | ReferenceFrame referenceFrame = locationSpec.referenceFrame(); 56 | 57 | /** MATSim simulation network */ 58 | Network network = NetworkLoader.fromConfigFile(new File(workingDirectory, scenarioOptions.getString("simuConfig"))); 59 | System.out.println("INFO network loaded"); 60 | System.out.println("INFO total links " + network.getLinks().size()); 61 | System.out.println("INFO total nodes " + network.getNodes().size()); 62 | 63 | /** initializing the viewer */ 64 | MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame); 65 | AmodeusComponent amodeusComponent = AmodeusComponent.createDefault(db, workingDirectory); 66 | 67 | /** virtual network layer, should not cause problems if layer does not exist */ 68 | amodeusComponent.virtualNetworkLayer.setVirtualNetwork(VirtualNetworkGet.readDefault(network, scenarioOptions)); 69 | 70 | /** starting the viewer */ 71 | ViewerConfig viewerConfig = ViewerConfig.from(db, workingDirectory); 72 | System.out.println("Used viewer config: " + viewerConfig); 73 | AmodeusViewerFrame amodeusViewerFrame = new AmodeusViewerFrame(amodeusComponent, outputDirectory, network, scenarioOptions); 74 | amodeusViewerFrame.setDisplayPosition(viewerConfig.settings.coord, viewerConfig.settings.zoom); 75 | amodeusViewerFrame.jFrame.setSize(viewerConfig.settings.dimensions); 76 | amodeusViewerFrame.jFrame.setVisible(true); 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/analysis/CustomAnalysis.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.analysis; 3 | 4 | import java.io.File; 5 | 6 | import amodeus.amodeus.analysis.Analysis; 7 | import amodeus.amodeus.data.LocationSpec; 8 | import amodeus.amodeus.data.ReferenceFrame; 9 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 10 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 11 | import amodeus.amodeus.net.SimulationObject; 12 | import amodeus.amodeus.options.ScenarioOptions; 13 | import amodeus.amodeus.options.ScenarioOptionsBase; 14 | import amodeus.amodeus.util.io.MultiFileTools; 15 | import amodeus.amodeus.util.matsim.NetworkLoader; 16 | import org.matsim.api.core.v01.network.Network; 17 | import org.matsim.core.config.Config; 18 | import org.matsim.core.config.ConfigUtils; 19 | 20 | import amodeus.amod.ext.Static; 21 | 22 | /** This is a demonstration of the functionality of AMoDeus that customized analysis and reporting 23 | * elements can be easily added. In this example, we present the case in which for every 24 | * {@link RoboTaxi} the number of served requests is recorded and then a Histogram image is added 25 | * to the HTML report */ 26 | public enum CustomAnalysis { 27 | ; 28 | 29 | /** to be executed in simulation directory to perform analysis, i.e., the directory must 30 | * contain the "output" folder that is compiled during a simulation. In the output folder, there 31 | * is a list of {@link SimulationObject} which contain the data stored for the simulation. 32 | * 33 | * @throws Exception */ 34 | public static void main(String[] args) throws Exception { 35 | Static.setup(); 36 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 37 | ScenarioOptions scenOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 38 | File configFile = new File(workingDirectory, scenOptions.getString("simuConfig")); 39 | Config config = ConfigUtils.loadConfig(configFile.toString()); 40 | String outputdirectory = config.controler().getOutputDirectory(); 41 | Network network = NetworkLoader.fromConfigFile(configFile); 42 | LocationSpec locationSpec = scenOptions.getLocationSpec(); 43 | ReferenceFrame referenceFrame = locationSpec.referenceFrame(); 44 | MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame); 45 | 46 | /** the analysis is created */ 47 | Analysis analysis = Analysis.setup(scenOptions, new File(outputdirectory), network, db); 48 | 49 | /** create and add a custom element */ 50 | addTo(analysis); 51 | 52 | /** finally, the analysis is run with the introduced custom element */ 53 | analysis.run(); 54 | } 55 | 56 | public static void addTo(Analysis analysis) { 57 | /** first an element to gather the necessary data is defined, it is an implementation of the 58 | * interface AnalysisElement */ 59 | RoboTaxiRequestRecorder roboTaxiRequestRecorder = new RoboTaxiRequestRecorder(); 60 | 61 | /** next an element to export the processed data to an image or other element is defined, it 62 | * is an implementation of the interface AnalysisExport */ 63 | RoboTaxiRequestHistoGramExport roboTaxiRequestExport = new RoboTaxiRequestHistoGramExport(roboTaxiRequestRecorder); 64 | 65 | /** finally a section for the HTML report is defined, which is an implementation of the 66 | * interface 67 | * HtmlReportElement */ 68 | RoboTaxiRequestRecorderHtml roboTaxiRequestRecorderHtml = new RoboTaxiRequestRecorderHtml(roboTaxiRequestRecorder); 69 | 70 | /** all are added to the Analysis before running */ 71 | analysis.addAnalysisElement(roboTaxiRequestRecorder); 72 | analysis.addAnalysisExport(roboTaxiRequestExport); 73 | analysis.addHtmlElement(roboTaxiRequestRecorderHtml); 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/analysis/RoboTaxiRequestHistoGramExport.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.analysis; 3 | 4 | import java.io.File; 5 | 6 | import amodeus.amodeus.analysis.AnalysisSummary; 7 | import amodeus.amodeus.analysis.element.AnalysisExport; 8 | import amodeus.amodeus.analysis.plot.AmodeusChartUtils; 9 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 10 | import amodeus.amodeus.util.math.GlobalAssert; 11 | import amodeus.tensor.fig.Histogram; 12 | import amodeus.tensor.fig.VisualSet; 13 | import org.jfree.chart.JFreeChart; 14 | import org.jfree.chart.axis.CategoryAnchor; 15 | import org.jfree.chart.axis.CategoryLabelPositions; 16 | import org.jfree.chart.plot.CategoryPlot; 17 | import org.matsim.amodeus.dvrp.request.AmodeusRequest; 18 | 19 | import ch.ethz.idsc.tensor.RationalScalar; 20 | import ch.ethz.idsc.tensor.RealScalar; 21 | import ch.ethz.idsc.tensor.Scalar; 22 | import ch.ethz.idsc.tensor.Scalars; 23 | import ch.ethz.idsc.tensor.Tensor; 24 | import ch.ethz.idsc.tensor.alg.Range; 25 | import ch.ethz.idsc.tensor.img.ColorDataIndexed; 26 | import ch.ethz.idsc.tensor.pdf.BinCounts; 27 | import ch.ethz.idsc.tensor.red.Total; 28 | 29 | /** This class generates a png Histogram image of the number of {@link AmodeusRequest} served by each 30 | * {@link RoboTaxi} */ 31 | /* package */ class RoboTaxiRequestHistoGramExport implements AnalysisExport { 32 | public final static String FILENAME = "requestsPerRoboTaxi.png"; 33 | private static final int WIDTH = 1000; 34 | private static final int HEIGHT = 750; 35 | private final RoboTaxiRequestRecorder roboTaxiRequestRecorder; 36 | 37 | public RoboTaxiRequestHistoGramExport(RoboTaxiRequestRecorder roboTaxiRequestRecorder) { 38 | this.roboTaxiRequestRecorder = roboTaxiRequestRecorder; 39 | } 40 | 41 | @Override 42 | public void summaryTarget(AnalysisSummary analysisSummary, File relativeDirectory, ColorDataIndexed colorScheme) { 43 | /** the data for the histogram is gathered from the RoboTaxiRequestRecorder, basic 44 | * information can also be retrieved from the analsysisSummary */ 45 | Tensor requestsPerRoboTaxi = roboTaxiRequestRecorder.getRequestsPerRoboTaxi(); 46 | Scalar numberOfRoboTaxis = RealScalar.of(requestsPerRoboTaxi.length()); 47 | Scalar totalRequestsServed = (Scalar) Total.of(requestsPerRoboTaxi); 48 | Scalar histoGrambinSize = Scalars.lessThan(RealScalar.ZERO, totalRequestsServed) ? // 49 | totalRequestsServed.divide(numberOfRoboTaxis.multiply(RealScalar.of(10))) : RealScalar.ONE; 50 | 51 | try { 52 | /** compute bins */ 53 | Scalar numValues = RationalScalar.of(requestsPerRoboTaxi.length(), 1); 54 | Tensor bins = BinCounts.of(requestsPerRoboTaxi, histoGrambinSize); 55 | bins = bins.divide(numValues).multiply(RealScalar.of(100)); // norm 56 | 57 | VisualSet visualSet = new VisualSet(colorScheme); 58 | visualSet.add(Range.of(0, bins.length()).multiply(histoGrambinSize), bins); 59 | // --- 60 | visualSet.setPlotLabel("Number of Requests Served per RoboTaxi"); 61 | visualSet.setAxesLabelY("% of RoboTaxis"); 62 | visualSet.setAxesLabelX("Requests"); 63 | 64 | JFreeChart jFreeChart = Histogram.of(visualSet, s -> "[" + s.number() + " , " + s.add(histoGrambinSize).number() + ")"); 65 | CategoryPlot categoryPlot = jFreeChart.getCategoryPlot(); 66 | categoryPlot.getDomainAxis().setLowerMargin(0.0); 67 | categoryPlot.getDomainAxis().setUpperMargin(0.0); 68 | categoryPlot.getDomainAxis().setCategoryMargin(0.0); 69 | categoryPlot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_90); 70 | categoryPlot.setDomainGridlinePosition(CategoryAnchor.START); 71 | 72 | File file = new File(relativeDirectory, FILENAME); 73 | AmodeusChartUtils.saveAsPNG(jFreeChart, file.toString(), WIDTH, HEIGHT); 74 | GlobalAssert.that(file.isFile()); 75 | } catch (Exception exception) { 76 | System.err.println("Plot of the Number of Requests per RoboTaxi Failed"); 77 | exception.printStackTrace(); 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/analysis/RoboTaxiRequestRecorder.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.analysis; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import amodeus.amodeus.analysis.Analysis; 8 | import amodeus.amodeus.analysis.element.AnalysisElement; 9 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 10 | import amodeus.amodeus.dispatcher.core.RoboTaxiStatus; 11 | import amodeus.amodeus.net.SimulationObject; 12 | import amodeus.amodeus.net.VehicleContainerUtils; 13 | import ch.ethz.idsc.tensor.RealScalar; 14 | import ch.ethz.idsc.tensor.Tensor; 15 | 16 | /** this class records the number of requests served by each {@link RoboTaxi} bases on the 17 | * {@link SimulationObject} which are loaded during the {@link Analysis} of an AMoDeus 18 | * simulation run. */ 19 | /* package */ class RoboTaxiRequestRecorder implements AnalysisElement { 20 | private Map vehicleRequestCount = new HashMap<>(); 21 | private Map prevStatus = new HashMap<>(); 22 | 23 | @Override 24 | public void register(SimulationObject simulationObject) { 25 | /** initialize map when first simulationObject arrives */ 26 | if (vehicleRequestCount.size() == 0) { 27 | simulationObject.vehicles.forEach(vc -> vehicleRequestCount.put(vc.vehicleIndex, 0)); 28 | simulationObject.vehicles.forEach(vc -> prevStatus.put(vc.vehicleIndex, RoboTaxiStatus.STAY)); 29 | } 30 | 31 | /** whenever status changes to DriveWithCustomer, the taxi has served a request */ 32 | simulationObject.vehicles.forEach(vc -> // 33 | { 34 | int vehicle = vc.vehicleIndex; 35 | if (VehicleContainerUtils.finalStatus(vc).equals(RoboTaxiStatus.DRIVEWITHCUSTOMER) // 36 | && !prevStatus.get(vehicle).equals(RoboTaxiStatus.DRIVEWITHCUSTOMER)) 37 | vehicleRequestCount.put(vehicle, vehicleRequestCount.get(vehicle) + 1); 38 | }); 39 | 40 | /** add previous status */ 41 | simulationObject.vehicles.forEach(vc -> prevStatus.put(vc.vehicleIndex, VehicleContainerUtils.finalStatus(vc))); 42 | } 43 | 44 | /** @return {@link Tensor} containing the requests served for each {@link RoboTaxi} */ 45 | public Tensor getRequestsPerRoboTaxi() { 46 | return Tensor.of(vehicleRequestCount.values().stream().map(RealScalar::of)); 47 | // Tensor requests = Tensors.empty(); 48 | // vehicleRequestCount.values().stream().forEach(count -> requests.append(RealScalar.of(count))); 49 | // return requests; 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/analysis/RoboTaxiRequestRecorderHtml.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.analysis; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import amodeus.amodeus.analysis.AnalysisSummary; 8 | import amodeus.amodeus.analysis.report.HtmlBodyElement; 9 | import amodeus.amodeus.analysis.report.HtmlReportElement; 10 | 11 | /** This class adds a histogram image to the AMoDeus HTML report which was previously 12 | * compiled in the class {@link RoboTaxiRequestHistoGramExport} */ 13 | /* package */ class RoboTaxiRequestRecorderHtml implements HtmlReportElement { 14 | private static final String IMAGE_FOLDER = "../data"; // relative to report folder 15 | 16 | RoboTaxiRequestRecorder roboTaxiRequestRecorder; 17 | 18 | public RoboTaxiRequestRecorderHtml(RoboTaxiRequestRecorder roboTaxiRequestRecorder) { 19 | this.roboTaxiRequestRecorder = roboTaxiRequestRecorder; 20 | } 21 | 22 | @Override 23 | public Map process(AnalysisSummary analysisSummary) { 24 | Map bodyElements = new HashMap<>(); 25 | HtmlBodyElement aRElement = new HtmlBodyElement(); 26 | 27 | /** histogram of number of requests per robotaxi */ 28 | aRElement.getHTMLGenerator().insertTextLeft("This histogram shows the number of reuquest served by each RoboTaxi:"); 29 | aRElement.getHTMLGenerator().insertImg(IMAGE_FOLDER + "/" + RoboTaxiRequestHistoGramExport.FILENAME, 800, 600); 30 | 31 | /** add together with title of section */ 32 | bodyElements.put("Requests per RoboTaxi Analysis", aRElement); 33 | return bodyElements; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/dispatcher/DemoDispatcher.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.dispatcher; 3 | 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | import java.util.Map; 7 | import java.util.Random; 8 | 9 | import amodeus.amodeus.dispatcher.core.DispatcherUtils; 10 | import amodeus.amodeus.dispatcher.core.RebalancingDispatcher; 11 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 12 | import amodeus.amodeus.dispatcher.core.RoboTaxiUsageType; 13 | import amodeus.amodeus.dispatcher.util.DrivebyRequestStopper; 14 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 15 | import amodeus.amodeus.util.matsim.SafeConfig; 16 | import org.matsim.amodeus.components.AmodeusDispatcher; 17 | import org.matsim.amodeus.components.AmodeusRouter; 18 | import org.matsim.amodeus.config.AmodeusModeConfig; 19 | import org.matsim.api.core.v01.network.Link; 20 | import org.matsim.api.core.v01.network.Network; 21 | import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingStrategy; 22 | import org.matsim.contrib.dvrp.passenger.PassengerRequest; 23 | import org.matsim.contrib.dvrp.run.ModalProviders.InstanceGetter; 24 | import org.matsim.core.api.experimental.events.EventsManager; 25 | import org.matsim.core.config.Config; 26 | import org.matsim.core.router.util.TravelTime; 27 | 28 | /** Dispatcher sends vehicles to all links in the network and lets them pickup 29 | * any customers which are waiting along the road. */ 30 | public class DemoDispatcher extends RebalancingDispatcher { 31 | private final List links; 32 | private final double rebPos = 0.99; 33 | private final Random randGen = new Random(1234); 34 | private final int rebalancingPeriod; 35 | private int total_abortTrip = 0; 36 | 37 | private DemoDispatcher(Config config, AmodeusModeConfig operatorConfig, TravelTime travelTime, // 38 | AmodeusRouter router, EventsManager eventsManager, Network network, MatsimAmodeusDatabase db, RebalancingStrategy drtRebalancing) { 39 | super(config, operatorConfig, travelTime, router, eventsManager, db, drtRebalancing, RoboTaxiUsageType.SINGLEUSED); 40 | links = new ArrayList<>(network.getLinks().values()); 41 | SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig()); 42 | rebalancingPeriod = safeConfig.getInteger("rebalancingPeriod", 120); 43 | } 44 | 45 | @Override 46 | public void redispatch(double now) { 47 | /** stop all vehicles which are driving by an open request */ 48 | Map stopDrivingBy = DrivebyRequestStopper // 49 | .stopDrivingBy(DispatcherUtils.getPassengerRequestsAtLinks(getPassengerRequests()), // 50 | getDivertableRoboTaxis(), this::setRoboTaxiPickup); 51 | total_abortTrip += stopDrivingBy.size(); 52 | 53 | /** send vehicles to travel around the city to random links (random loitering) */ 54 | final long round_now = Math.round(now); 55 | if (round_now % rebalancingPeriod == 0 && 0 < getPassengerRequests().size()) 56 | for (RoboTaxi roboTaxi : getDivertableRoboTaxis()) 57 | if (rebPos > randGen.nextDouble()) 58 | setRoboTaxiRebalance(roboTaxi, pollNextDestination()); 59 | } 60 | 61 | private Link pollNextDestination() { 62 | return links.get(randGen.nextInt(links.size())); 63 | } 64 | 65 | @Override 66 | protected String getInfoLine() { 67 | return String.format("%s AT=%5d", super.getInfoLine(), total_abortTrip); 68 | } 69 | 70 | public static class Factory implements AVDispatcherFactory { 71 | @Override 72 | public AmodeusDispatcher createDispatcher(InstanceGetter inject) { 73 | Config config = inject.get(Config.class); 74 | MatsimAmodeusDatabase db = inject.get(MatsimAmodeusDatabase.class); 75 | EventsManager eventsManager = inject.get(EventsManager.class); 76 | 77 | AmodeusModeConfig operatorConfig = inject.getModal(AmodeusModeConfig.class); 78 | Network network = inject.getModal(Network.class); 79 | AmodeusRouter router = inject.getModal(AmodeusRouter.class); 80 | TravelTime travelTime = inject.getModal(TravelTime.class); 81 | RebalancingStrategy drtRebalancing = inject.getModal(RebalancingStrategy.class); 82 | 83 | return new DemoDispatcher(config, operatorConfig, travelTime, router, eventsManager, network, db, drtRebalancing); 84 | } 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/dispatcher/DemoDispatcherShared.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.dispatcher; 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collections; 6 | import java.util.Comparator; 7 | import java.util.List; 8 | import java.util.Random; 9 | 10 | import org.matsim.amodeus.components.AmodeusDispatcher; 11 | import org.matsim.amodeus.components.AmodeusRouter; 12 | import org.matsim.amodeus.config.AmodeusModeConfig; 13 | import org.matsim.api.core.v01.network.Link; 14 | import org.matsim.api.core.v01.network.Network; 15 | import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingStrategy; 16 | import org.matsim.contrib.dvrp.passenger.PassengerRequest; 17 | import org.matsim.contrib.dvrp.run.ModalProviders.InstanceGetter; 18 | import org.matsim.core.api.experimental.events.EventsManager; 19 | import org.matsim.core.config.Config; 20 | import org.matsim.core.router.util.TravelTime; 21 | 22 | import amodeus.amodeus.dispatcher.core.RebalancingDispatcher; 23 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 24 | import amodeus.amodeus.dispatcher.core.RoboTaxiUsageType; 25 | import amodeus.amodeus.dispatcher.core.schedule.directives.Directive; 26 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 27 | import amodeus.amodeus.util.matsim.SafeConfig; 28 | 29 | /** this is a demo of functionality for the shared dispatchers (> 1 person in {@link RoboTaxi} 30 | * 31 | * whenever 4 {@link PassengerRequest}s are open, a {@link RoboTaxi} is assigned to pickup all of them, 32 | * it first picks up passengers 1,2,3,4 and then starts to bring passengers 1,2,3 to their destinations. 33 | * Passenger 4 is less lucky as the {@link RoboTaxi} first visits the city's North pole (northern most link) 34 | * before passenger 4 is finally dropped of and the procedure starts from beginning. */ 35 | /* package */ class DemoDispatcherShared extends RebalancingDispatcher { 36 | private final int dispatchPeriod; 37 | private final int rebalancePeriod; 38 | private final Random randGen = new Random(1234); 39 | private final Link cityNorthPole; 40 | private final List equatorLinks; 41 | 42 | protected DemoDispatcherShared(Network network, // 43 | Config config, AmodeusModeConfig operatorConfig, // 44 | TravelTime travelTime, AmodeusRouter router, EventsManager eventsManager, // 45 | MatsimAmodeusDatabase db, RebalancingStrategy drtRebalancing) { 46 | super(config, operatorConfig, travelTime, router, eventsManager, db, drtRebalancing, RoboTaxiUsageType.SHARED); 47 | this.cityNorthPole = getNorthPole(network); 48 | this.equatorLinks = getEquator(network); 49 | SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig()); 50 | dispatchPeriod = safeConfig.getInteger("dispatchPeriod", 30); 51 | rebalancePeriod = safeConfig.getInteger("rebalancingPeriod", 1800); 52 | Collections.shuffle(new ArrayList<>(network.getLinks().values()), randGen); 53 | } 54 | 55 | @Override 56 | protected void redispatch(double now) { 57 | final long round_now = Math.round(now); 58 | 59 | if (round_now % dispatchPeriod == 0) { 60 | /** assignment of {@link RoboTaxi}s */ 61 | for (RoboTaxi sharedRoboTaxi : getDivertableUnassignedRoboTaxis()) { 62 | if (getUnassignedRequests().size() >= 4) { 63 | List unassignedRequests = new ArrayList<>(getUnassignedRequests()); 64 | 65 | /** select 4 requests */ 66 | PassengerRequest firstRequest = unassignedRequests.get(0); 67 | PassengerRequest secondRequest = unassignedRequests.get(1); 68 | PassengerRequest thirdRequest = unassignedRequests.get(2); 69 | PassengerRequest fourthRequest = unassignedRequests.get(3); 70 | 71 | /** add pickup for request 1 */ 72 | addSharedRoboTaxiPickup(sharedRoboTaxi, firstRequest); 73 | 74 | /** add pickup for request 2 and move to first location */ 75 | addSharedRoboTaxiPickup(sharedRoboTaxi, secondRequest); 76 | Directive sharedAVCourse = Directive.pickup(secondRequest); 77 | sharedRoboTaxi.moveToPrevious(sharedAVCourse); 78 | 79 | /** add pickup for request 3 and move to first location */ 80 | addSharedRoboTaxiPickup(sharedRoboTaxi, thirdRequest); 81 | Directive sharedAVCourse3 = Directive.pickup(thirdRequest); 82 | sharedRoboTaxi.moveToPrevious(sharedAVCourse3); 83 | sharedRoboTaxi.moveToPrevious(sharedAVCourse3); 84 | 85 | /** add pickup for request 4 and reorder the menu based on a list of Shared Courses */ 86 | List courses = new ArrayList<>(sharedRoboTaxi.getUnmodifiableViewOfCourses()); 87 | courses.add(3, Directive.pickup(fourthRequest)); 88 | courses.add(Directive.dropoff(fourthRequest)); 89 | addSharedRoboTaxiPickup(sharedRoboTaxi, fourthRequest); 90 | sharedRoboTaxi.updateMenu(courses); 91 | 92 | /** add a redirect task (to the north pole) and move to prev */ 93 | Link redirectLink = cityNorthPole; 94 | Directive redirectCourse = Directive.drive(redirectLink); 95 | addSharedRoboTaxiRedirect(sharedRoboTaxi, redirectCourse); 96 | sharedRoboTaxi.moveToPrevious(redirectCourse); 97 | } else { 98 | break; 99 | } 100 | } 101 | } 102 | 103 | /** dispatching of available {@link RoboTaxi}s to the equator */ 104 | if (round_now % rebalancePeriod == 0) 105 | /** relocation of empty {@link RoboTaxi}s to a random link on the equator */ 106 | for (RoboTaxi roboTaxi : getDivertableUnassignedRoboTaxis()) { 107 | Link rebalanceLink = equatorLinks.get(randGen.nextInt(equatorLinks.size())); 108 | setRoboTaxiRebalance(roboTaxi, rebalanceLink); 109 | } 110 | } 111 | 112 | /** @param network 113 | * @return northern most {@link Link} in the {@link Network} */ 114 | private static Link getNorthPole(Network network) { 115 | return network.getLinks().values().stream().max(Comparator.comparingDouble(l -> l.getCoord().getY())).get(); 116 | } 117 | 118 | /** @param network 119 | * @return all {@link Link}s crossing the equator of the city {@link Network} , starting 120 | * with links on the equator, if no links found, the search radius is increased by 1 m */ 121 | private static List getEquator(Network network) { 122 | double northX = network.getLinks().values().stream().mapToDouble(l -> l.getCoord().getY()).max().getAsDouble(); 123 | double southX = network.getLinks().values().stream().mapToDouble(l -> l.getCoord().getY()).min().getAsDouble(); 124 | double equator = southX + (northX - southX) / 2; 125 | 126 | List equatorLinks = new ArrayList<>(); 127 | double margin = 0.0; 128 | while (equatorLinks.size() < 1) { 129 | for (Link l : network.getLinks().values()) { 130 | boolean crossEq1 = l.getFromNode().getCoord().getY() - margin <= // 131 | equator && l.getToNode().getCoord().getY() + margin >= equator; 132 | boolean crossEq2 = l.getFromNode().getCoord().getY() + margin >= // 133 | equator && l.getToNode().getCoord().getY() - margin <= equator; 134 | if (crossEq1 || crossEq2) 135 | equatorLinks.add(l); 136 | } 137 | margin += 1.0; 138 | } 139 | return equatorLinks; 140 | } 141 | 142 | public static class Factory implements AVDispatcherFactory { 143 | @Override 144 | public AmodeusDispatcher createDispatcher(InstanceGetter inject) { 145 | Config config = inject.get(Config.class); 146 | MatsimAmodeusDatabase db = inject.get(MatsimAmodeusDatabase.class); 147 | EventsManager eventsManager = inject.get(EventsManager.class); 148 | 149 | AmodeusModeConfig operatorConfig = inject.getModal(AmodeusModeConfig.class); 150 | Network network = inject.getModal(Network.class); 151 | AmodeusRouter router = inject.getModal(AmodeusRouter.class); 152 | TravelTime travelTime = inject.getModal(TravelTime.class); 153 | RebalancingStrategy drtRebalancing = inject.getModal(RebalancingStrategy.class); 154 | 155 | return new DemoDispatcherShared(network, config, operatorConfig, travelTime, router, eventsManager, db, drtRebalancing); 156 | } 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ext/Static.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.ext; 3 | 4 | import java.io.File; 5 | import java.io.FileInputStream; 6 | import java.io.FileNotFoundException; 7 | import java.io.FileOutputStream; 8 | import java.io.IOException; 9 | import java.io.InputStream; 10 | import java.io.OutputStream; 11 | import java.util.Properties; 12 | 13 | import amodeus.amodeus.data.LocationSpec; 14 | import amodeus.amodeus.data.LocationSpecDatabase; 15 | import amodeus.amodeus.options.LPOptionsBase; 16 | import org.gnu.glpk.GLPK; 17 | 18 | public enum Static { 19 | ; 20 | 21 | public static void setup() { 22 | for (LocationSpec locationSpec : UserLocationSpecs.values()) 23 | LocationSpecDatabase.INSTANCE.put(locationSpec); 24 | } 25 | 26 | public static void checkGLPKLib() { 27 | try { 28 | System.out.println("Working with GLPK version " + GLPK.glp_version()); 29 | } catch (Exception exception) { 30 | System.err.println(glpInfo()); 31 | } 32 | } 33 | 34 | public static String glpInfo() { 35 | return "GLPK for java is necessary for some configurations of the preparer or server. \n " + "In order to install it, follow the instructions provided at\n: " 36 | + "http://glpk-java.sourceforge.net/gettingStarted.html \n" + "In order to work properly, either the location of the GLPK library must be specified in \n" 37 | + "the environment variable, using for instance the command" + "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib/jni \n" 38 | + "where /usr/local/lib/jni is the path where the file libglpk_java.so is located \n" 39 | + "in your installation. Alternatively, the path can also be supplied as a JAVA runtime \n" + "argument, e.g., -Djava.library.path=/usr/local/lib/jni"; 40 | } 41 | 42 | /** For many dispatchers, a linear program is solved previous to the simulation start 43 | * to initialize data structures for rebalancing. This requires the GLPK library to work. 44 | * This call ensures that no linear program must be solved by changing the file LPOptions.properties 45 | * in the @param workingDirectory to ensure that initial users do not get stopped by this obstacle. */ 46 | public static void setLPtoNone(File workingDirectory) throws FileNotFoundException, IOException { 47 | Properties props = new Properties(); 48 | File file = new File(workingDirectory, LPOptionsBase.OPTIONSFILENAME); 49 | try (InputStream inputStream = new FileInputStream(file)) { 50 | props.load(inputStream); 51 | } 52 | try (OutputStream outputStream = new FileOutputStream(file)) { 53 | props.setProperty("LPSolver", "NONE"); 54 | props.store(outputStream, null); 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ext/UserLocationSpecs.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.ext; 3 | 4 | import amodeus.amodeus.data.LocationSpec; 5 | import amodeus.amodeus.data.ReferenceFrame; 6 | import org.matsim.api.core.v01.Coord; 7 | 8 | /* package */ enum UserLocationSpecs implements LocationSpec { 9 | SANFRANCISCO( // 10 | UserReferenceFrames.SANFRANCISCO, // 11 | new Coord(-122.4363005, 37.7511686)), // 12 | BERLIN( // 13 | UserReferenceFrames.BERLIN, // 14 | new Coord(4595438.15, 5821747.77)), // 15 | SANTIAGO_DE_CHILE( // 16 | UserReferenceFrames.SANTIAGO_DE_CHILE, // 17 | new Coord(-3956418.76, -7864204.17)), // 18 | AUCKLAND( // 19 | UserReferenceFrames.AUCKLAND, // 20 | new Coord(-36.8426, 174.7662)), // 21 | TEL_AVIV( // 22 | UserReferenceFrames.TEL_AVIV, // 23 | new Coord(179549.58, 665848.14)), // 24 | CHICAGO( // 25 | UserReferenceFrames.CHICAGO, // 26 | new Coord(-74.005, 40.712)) 27 | ; 28 | 29 | private final ReferenceFrame referenceFrame; 30 | // increasing the first value goes right 31 | // increasing the second value goes north 32 | private final Coord center; 33 | 34 | UserLocationSpecs(ReferenceFrame referenceFrame, Coord center) { 35 | this.referenceFrame = referenceFrame; 36 | this.center = center; 37 | } 38 | 39 | @Override 40 | public ReferenceFrame referenceFrame() { 41 | return referenceFrame; 42 | } 43 | 44 | @Override 45 | public Coord center() { 46 | return center; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/ext/UserReferenceFrames.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.ext; 3 | 4 | import amodeus.amodeus.data.ReferenceFrame; 5 | import amodeus.amodeus.util.math.SI; 6 | import org.matsim.core.utils.geometry.CoordinateTransformation; 7 | import org.matsim.core.utils.geometry.transformations.GeotoolsTransformation; 8 | import org.matsim.core.utils.geometry.transformations.IdentityTransformation; 9 | 10 | import ch.ethz.idsc.tensor.qty.Unit; 11 | 12 | /* package */ enum UserReferenceFrames implements ReferenceFrame { 13 | IDENTITY( // 14 | new IdentityTransformation(), // 15 | new IdentityTransformation()), // 16 | SANFRANCISCO( // 17 | new GeotoolsTransformation("EPSG:26743", "WGS84"), // 18 | new GeotoolsTransformation("WGS84", "EPSG:26743"), // 19 | Unit.of("ft")), // 20 | BERLIN( // 21 | new GeotoolsTransformation("EPSG:31468", "WGS84"), // 22 | new GeotoolsTransformation("WGS84", "EPSG:31468")), // 23 | SANTIAGO_DE_CHILE( // 24 | new GeotoolsTransformation("EPSG:32719", "WGS84"), // 25 | new GeotoolsTransformation("WGS84", "EPSG:32719")), // 26 | AUCKLAND( // 27 | new GeotoolsTransformation("EPSG:2193", "WGS84"), // 28 | new GeotoolsTransformation("WGS84", "EPSG:2193")), // 29 | TEL_AVIV( // 30 | new GeotoolsTransformation("EPSG:2039", "WGS84"), // 31 | new GeotoolsTransformation("WGS84", "EPSG:2039")), // 32 | CHICAGO( // 33 | new GeotoolsTransformation("EPSG:3435", "WGS84"), // 34 | new GeotoolsTransformation("WGS84", "EPSG:3435")) 35 | ; 36 | // --- 37 | private final CoordinateTransformation coords_toWGS84; 38 | private final CoordinateTransformation coords_fromWGS84; 39 | private final Unit unit; 40 | 41 | UserReferenceFrames(CoordinateTransformation c1, CoordinateTransformation c2) { 42 | this(c1, c2, SI.METER); 43 | } 44 | 45 | UserReferenceFrames(CoordinateTransformation c1, CoordinateTransformation c2, Unit unit) { 46 | coords_toWGS84 = c1; 47 | coords_fromWGS84 = c2; 48 | this.unit = unit; 49 | } 50 | 51 | @Override 52 | public CoordinateTransformation coords_fromWGS84() { 53 | return coords_fromWGS84; 54 | } 55 | 56 | @Override 57 | public CoordinateTransformation coords_toWGS84() { 58 | return coords_toWGS84; 59 | } 60 | 61 | @Override 62 | public Unit unit() { 63 | return unit; 64 | } 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/generator/DemoGenerator.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.generator; 3 | 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.LinkedList; 7 | import java.util.List; 8 | 9 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 10 | import amodeus.amodeus.generator.RandomDensityGenerator; 11 | import org.apache.log4j.Logger; 12 | import org.matsim.amodeus.components.AmodeusGenerator; 13 | import org.matsim.amodeus.components.generator.AmodeusIdentifiers; 14 | import org.matsim.amodeus.config.AmodeusModeConfig; 15 | import org.matsim.api.core.v01.Id; 16 | import org.matsim.api.core.v01.network.Link; 17 | import org.matsim.api.core.v01.network.Network; 18 | import org.matsim.contrib.dvrp.fleet.DvrpVehicle; 19 | import org.matsim.contrib.dvrp.fleet.DvrpVehicleSpecification; 20 | import org.matsim.contrib.dvrp.fleet.ImmutableDvrpVehicleSpecification; 21 | import org.matsim.contrib.dvrp.run.ModalProviders.InstanceGetter; 22 | import org.matsim.core.gbl.MatsimRandom; 23 | 24 | 25 | /** the initial placement of {@link RoboTaxi} in the {@link Network} is determined 26 | * with an {@link AmodeusGenerator}. In most cases it is sufficient to use the 27 | * {@link RandomDensityGenerator} provided in AMoDeus, however, users may wish 28 | * to have an initial placement of {@link RoboTaxi} determined by themselves. 29 | * This class demonstrates such a placement in which 10 random links are chosen 30 | * and all vehicles are placed on these random links. */ 31 | public class DemoGenerator implements AmodeusGenerator { 32 | private static final Logger LOGGER = Logger.getLogger(DemoGenerator.class); 33 | // --- 34 | private final int capacity; 35 | private final AmodeusModeConfig operatorConfig; 36 | private final Collection randomLinks = new ArrayList<>(); 37 | 38 | public DemoGenerator(AmodeusModeConfig operatorConfig, Network network, int capacity) { 39 | this.operatorConfig = operatorConfig; 40 | this.capacity = capacity; 41 | 42 | /** determine 10 random links in the network */ 43 | int bound = network.getLinks().size(); 44 | for (int i = 0; i < 10; ++i) { 45 | int elemRand = MatsimRandom.getRandom().nextInt(bound); 46 | Link link = network.getLinks().values().stream().skip(elemRand).findFirst().get(); 47 | randomLinks.add(link); 48 | } 49 | } 50 | 51 | @Override 52 | public List generateVehicles() { 53 | long generatedVehicles = 0; 54 | List vehicles = new LinkedList<>(); 55 | while (generatedVehicles < operatorConfig.getGeneratorConfig().getNumberOfVehicles()) { 56 | ++generatedVehicles; 57 | 58 | /** select one of the 10 random links for placement */ 59 | int elemRand = MatsimRandom.getRandom().nextInt(randomLinks.size()); 60 | Link linkSel = randomLinks.stream().skip(elemRand).findFirst().get(); 61 | 62 | LOGGER.info("car placed at link " + linkSel); 63 | 64 | Id id = AmodeusIdentifiers.createVehicleId(operatorConfig.getMode(), generatedVehicles); 65 | 66 | vehicles.add(ImmutableDvrpVehicleSpecification.newBuilder() // 67 | .id(id) // 68 | .serviceBeginTime(0.0) // 69 | .serviceEndTime(Double.POSITIVE_INFINITY) // 70 | .capacity(capacity) // 71 | .startLinkId(linkSel.getId()) // 72 | .build()); 73 | } 74 | return vehicles; 75 | } 76 | 77 | public static class Factory implements AmodeusGenerator.AVGeneratorFactory { 78 | @Override 79 | public AmodeusGenerator createGenerator(InstanceGetter inject) { 80 | AmodeusModeConfig operatorConfig = inject.getModal(AmodeusModeConfig.class); 81 | Network network = inject.getModal(Network.class); 82 | int capacity = operatorConfig.getGeneratorConfig().getCapacity(); 83 | 84 | return new DemoGenerator(operatorConfig, network, capacity); 85 | } 86 | } 87 | } -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/router/CustomRouter.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.router; 3 | 4 | import java.io.IOException; 5 | import java.util.concurrent.Future; 6 | 7 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 8 | import org.matsim.amodeus.components.AmodeusRouter; 9 | import org.matsim.api.core.v01.network.Network; 10 | import org.matsim.api.core.v01.network.Node; 11 | import org.matsim.api.core.v01.population.Person; 12 | import org.matsim.contrib.dvrp.run.ModalProviders.InstanceGetter; 13 | import org.matsim.core.router.util.LeastCostPathCalculator.Path; 14 | import org.matsim.vehicles.Vehicle; 15 | 16 | /** This is a nonfunctional sample demonstrating of how to include a custom router 17 | * to AMoDeus which is not the standard choice of the Paralllel Djikstra router used 18 | * normally to calculate the path for {@link RoboTaxi} */ 19 | /* package */ class CustomRouter implements AmodeusRouter { 20 | 21 | @Override 22 | public Future calcLeastCostPath(Node fromNode, Node toNode, double starttime, Person person, Vehicle vehicle) { 23 | /** here a path neets to be computed and returned accordign to your custom logic */ 24 | throw new RuntimeException("This CustomRouter is not functional."); 25 | } 26 | 27 | @Override 28 | public void close() throws IOException { 29 | /** here all Threads that were opened during execution should be closed, this function 30 | * is called within AMoDeus after the simulation has ended. */ 31 | throw new RuntimeException("This CustomRouter is not functional."); 32 | } 33 | 34 | /** here it is possible to inject objects such as the {@link Network}, see as 35 | * example the DefaultAVRouter */ 36 | public static class Factory implements AmodeusRouter.Factory { 37 | @Override 38 | public AmodeusRouter createRouter(InstanceGetter inject) { 39 | return new CustomRouter(); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/amodeus/amod/router/CustomRouterDemo.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.router; 3 | 4 | /** Nonfunctional code explaining how a custom router would be incluced to an AMoDeus simulation. */ 5 | /* package */ class CustomRouterDemo { 6 | 7 | public static void main(String[] args) { 8 | /** In order to include a custom router, you should add this line in ScenarioServer 9 | * before starting the simualtion: 10 | * 11 | * controler.addOverridingModule(new AbstractModule() { 12 | * 13 | * @Override 14 | * public void install() { 15 | * bind(CustomRouter.Factory.class); 16 | * AVUtils.bindRouterFactory(binder(), CustomRouter.class.getSimpleName()).to(CustomRouter.Factory.class); 17 | * } 18 | * }); 19 | * 20 | * 21 | * Then, in av.xml, specify your custom router as follows: 22 | * 23 | * 24 | * 25 | * 26 | * 27 | * 28 | * 29 | * 30 | * 31 | * 32 | * 33 | * 34 | * 35 | * 36 | * 37 | * 38 | * 39 | * 40 | * 41 | * 42 | * 43 | * 44 | * 45 | * 46 | * 47 | * 48 | * 49 | * 50 | * 51 | * 52 | * 53 | * 54 | * If no router is specified, then the standard router is chosen. Invalid specifications 55 | * lead to exceptions. */ 56 | throw new RuntimeException(); 57 | } 58 | } -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketExport.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | 6 | import amodeus.amodeus.analysis.AnalysisSummary; 7 | import amodeus.amodeus.analysis.UnitSaveUtils; 8 | import amodeus.amodeus.analysis.element.AnalysisExport; 9 | import amodeus.amodeus.analysis.element.AnalysisMeanFilter; 10 | import amodeus.amodeus.analysis.plot.AmodeusChartUtils; 11 | import amodeus.amodeus.util.math.GlobalAssert; 12 | import amodeus.tensor.fig.TimedChart; 13 | import amodeus.tensor.fig.VisualRow; 14 | import amodeus.tensor.fig.VisualSet; 15 | import org.jfree.chart.JFreeChart; 16 | 17 | import amodeus.socket.core.SocketScoreElement; 18 | import ch.ethz.idsc.tensor.Tensor; 19 | import ch.ethz.idsc.tensor.Unprotect; 20 | import ch.ethz.idsc.tensor.img.ColorDataIndexed; 21 | 22 | /* package */ class SocketExport implements AnalysisExport { 23 | 24 | /** settings for plot */ 25 | /* package */ static final String FILENAME_SCORE_INCR = "socketScores1and2Diff.png"; 26 | /* package */ static final String FILENAME_SCORE_INTG = "socketScores1and2Intg.png"; 27 | /* package */ static final String FILENAME_SCORE3_INTG = "socketScore3Intg.png"; 28 | private static final int WIDTH = 1000; 29 | private static final int HEIGHT = 750; 30 | 31 | /** socket score element */ 32 | private final SocketScoreElement socketScoreElement; 33 | 34 | public SocketExport(SocketScoreElement socketScoreElement) { 35 | this.socketScoreElement = socketScoreElement; 36 | } 37 | 38 | @Override 39 | public void summaryTarget(AnalysisSummary analysisSummary, File relativeDirectory, ColorDataIndexed colorScheme) { 40 | 41 | Tensor scoreDiffHistory = socketScoreElement.getScoreDiffHistory(); 42 | Tensor scoreIntgHistory = socketScoreElement.getScoreIntgHistory(); 43 | 44 | /** produce charts that show 2 scores during simulation (integrated and 45 | * increment) */ 46 | Tensor time = scoreDiffHistory.get(Tensor.ALL, 0); 47 | Tensor linCombScoresDiff = Tensor.of(scoreDiffHistory.stream().map(row -> row.extract(1, 3))); 48 | Tensor linCombScoresIntg = Tensor.of(scoreIntgHistory.stream().map(row -> row.extract(1, 3))); 49 | 50 | /** figures for service quality score and efficiency score */ 51 | try { 52 | JFreeChart chart = timeChart("Service Quality and Efficiency Score Increments", // 53 | new String[] { "service quality performance [1]", "efficiency performance [1]" }, // 54 | "time of day", "scores increments", time, linCombScoresDiff, colorScheme); 55 | File fileChart = new File(relativeDirectory, FILENAME_SCORE_INCR); 56 | AmodeusChartUtils.saveAsPNG(chart, fileChart.toString(), WIDTH, HEIGHT); 57 | GlobalAssert.that(fileChart.isFile()); 58 | } catch (Exception e1) { 59 | System.err.println("Plotting the scores was unsuccessful."); 60 | e1.printStackTrace(); 61 | } 62 | 63 | try { 64 | JFreeChart chart = timeChart("Service Quality and Efficiency Score Integrated", // 65 | new String[] { "service quality performance [1]", "efficiency performance [1]" }, // 66 | "time of day", "scores integrated", time, linCombScoresIntg, colorScheme); 67 | File fileChart = new File(relativeDirectory, FILENAME_SCORE_INTG); 68 | AmodeusChartUtils.saveAsPNG(chart, fileChart.toString(), WIDTH, HEIGHT); 69 | GlobalAssert.that(fileChart.isFile()); 70 | } catch (Exception e1) { 71 | System.err.println("Plotting the scores was unsuccessful."); 72 | e1.printStackTrace(); 73 | } 74 | 75 | /** figures for fleet size score */ 76 | Tensor fleetSizeScoreIntg = Tensor.of(scoreIntgHistory.stream().map(row -> row.extract(3, 4))); 77 | 78 | try { 79 | JFreeChart chart = timeChart("Fleet Size Score Integrated", // 80 | new String[] { "fleet size score integrated" }, // 81 | "time of day", "scores integrated", time, fleetSizeScoreIntg, colorScheme); 82 | File fileChart = new File(relativeDirectory, FILENAME_SCORE_INTG); 83 | chart.getXYPlot().getRangeAxis().setRange(fleetSizeScoreIntg.get(0).Get(0).number().intValue() * 2.0, 0.0); 84 | AmodeusChartUtils.saveAsPNG(chart, fileChart.toString(), WIDTH, HEIGHT); 85 | GlobalAssert.that(fileChart.isFile()); 86 | } catch (Exception e1) { 87 | System.err.println("Plotting the scores was unsuccessful."); 88 | e1.printStackTrace(); 89 | } 90 | 91 | /** export incremental and integrated scores data */ 92 | try { 93 | UnitSaveUtils.saveFile(socketScoreElement.getScoreDiffHistory(), "socketScoresIncr", relativeDirectory); 94 | UnitSaveUtils.saveFile(socketScoreElement.getScoreIntgHistory(), "socketScoresIntg", relativeDirectory); 95 | } catch (Exception exception) { 96 | System.err.println("Saving score history was unsuccessful."); 97 | exception.printStackTrace(); 98 | } 99 | } 100 | 101 | private JFreeChart timeChart(String title, String[] labels, String xAxisLabel, String yAxisLabel, Tensor time, Tensor values, ColorDataIndexed colorDataIndexed) { 102 | GlobalAssert.that(Unprotect.dimension1(values) == labels.length); 103 | 104 | VisualSet visualSet = new VisualSet(colorDataIndexed); 105 | for (int i = 0; i < labels.length; ++i) { 106 | Tensor vector = values.get(Tensor.ALL, i); 107 | vector = AnalysisMeanFilter.of(vector); 108 | VisualRow visualRow = visualSet.add(time, vector); 109 | visualRow.setLabel(labels[i]); 110 | } 111 | 112 | visualSet.setPlotLabel(title); 113 | visualSet.setAxesLabelX(xAxisLabel); 114 | visualSet.setAxesLabelY(yAxisLabel); 115 | 116 | return TimedChart.of(visualSet); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketHost.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | import java.util.Objects; 6 | 7 | import amodeus.amodeus.analysis.Analysis; 8 | import amodeus.amodeus.options.ScenarioOptions; 9 | import amodeus.amodeus.options.ScenarioOptionsBase; 10 | import amodeus.amodeus.prep.LegCount; 11 | import amodeus.amodeus.util.io.MultiFileTools; 12 | import amodeus.amodeus.util.matsim.xml.ConfigDispatcherChanger; 13 | import amodeus.amodeus.util.matsim.xml.ConfigVehiclesChanger; 14 | import amodeus.amodeus.util.net.StringServerSocket; 15 | import amodeus.amodeus.util.net.StringSocket; 16 | import amodeus.amodeus.video.VideoGenerator; 17 | import org.matsim.amodeus.config.AmodeusModeConfig; 18 | 19 | import amodeus.socket.core.ScoreParameters; 20 | import amodeus.socket.core.SocketDispatcherHost; 21 | import amodeus.socket.core.SocketScoreElement; 22 | import ch.ethz.idsc.tensor.RealScalar; 23 | import ch.ethz.idsc.tensor.Scalar; 24 | import ch.ethz.idsc.tensor.Tensor; 25 | import ch.ethz.idsc.tensor.Tensors; 26 | import ch.ethz.idsc.tensor.red.Total; 27 | import ch.ethz.idsc.tensor.sca.Round; 28 | 29 | //TODO refactor and shorten @clruch 30 | /** host that runs in container. 31 | * a client can connect to a running host via TCP/IP 32 | * 33 | * Usage: 34 | * java -cp target/amod-VERSION.jar amod.socket.SocketHost [city] */ 35 | public enum SocketHost { 36 | ; 37 | public static final int PORT = 9382; 38 | private static final String ENV_SCENARIO = "SCENARIO"; 39 | private static final String ENV_FLEET_SIZE = "FLEET_SIZE"; 40 | private static final String ENV_REQUESTS_SIZE = "REQUESTS_SIZE"; 41 | private static final String ENV_VIDEO_EXPORT = "VIDEO_EXPORT"; 42 | 43 | public static void main(String[] args) throws Exception { 44 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 45 | run(workingDirectory); 46 | } 47 | 48 | public static void run(File workingDirectory) throws Exception { 49 | System.out.println("Using scenario directory: " + workingDirectory); 50 | StringSocket stringSocket = null; 51 | 52 | /** open String server and wait for initial command */ 53 | try (StringServerSocket serverSocket = new StringServerSocket(PORT)) { 54 | stringSocket = serverSocket.getSocketWait(); 55 | serverSocket.close(); // only allow one connection 56 | // --- 57 | String readLine = stringSocket.readLine(); 58 | Tensor config = Tensors.fromString(readLine); 59 | System.out.println("SocketHost config: " + config); 60 | Thread.sleep(1000); 61 | String scenarioTag = config.Get(0).toString(); 62 | { 63 | String env = System.getenv(ENV_SCENARIO); 64 | if (Objects.nonNull(env)) 65 | env = scenarioTag; 66 | } 67 | 68 | /** download the chosen scenario */ 69 | SocketScenarioResource.extract(scenarioTag, workingDirectory); 70 | 71 | /** setup environment variables */ 72 | StaticHelper.setup(); 73 | 74 | /** run first part of scenario preparer */ 75 | SocketPreparer preparer = new SocketPreparer(workingDirectory); 76 | 77 | /** get number of requests in population */ 78 | long numReq = LegCount.of(preparer.getPopulation(), AmodeusModeConfig.DEFAULT_MODE); 79 | 80 | Scalar nominalFleetSize = Round.of(RealScalar.of(numReq).multiply(ScoreParameters.GLOBAL.gamma)); 81 | Tensor initialInfo = Tensors.of(RealScalar.of(numReq), preparer.getBoundingBox(), nominalFleetSize); 82 | 83 | /** send initial data: {numberRequests,boundingBox} */ 84 | stringSocket.writeln(initialInfo); 85 | 86 | /** get additional information */ 87 | String readLine2 = stringSocket.readLine(); 88 | Tensor config2 = Tensors.fromString(readLine2); 89 | int numReqDes = config2.Get(0).number().intValue(); 90 | int fleetSize = config2.Get(1).number().intValue(); 91 | 92 | { 93 | String env = System.getenv(ENV_REQUESTS_SIZE); 94 | if (Objects.nonNull(env)) 95 | try { 96 | numReqDes = Integer.parseInt(env); 97 | } catch (Exception exception) { 98 | exception.printStackTrace(); 99 | } 100 | } 101 | { 102 | String env = System.getenv(ENV_FLEET_SIZE); 103 | if (Objects.nonNull(env)) 104 | try { 105 | fleetSize = Integer.parseInt(env); 106 | } catch (Exception exception) { 107 | exception.printStackTrace(); 108 | } 109 | } 110 | 111 | /** run second part of preparer */ 112 | preparer.run2(numReqDes); 113 | 114 | /** run with socket dispatcher */ 115 | ScenarioOptions scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 116 | String simConfigPath = scenarioOptions.getSimulationConfigName(); 117 | ConfigDispatcherChanger.change(simConfigPath, SocketDispatcherHost.class.getSimpleName()); 118 | ConfigVehiclesChanger.change(simConfigPath, fleetSize); 119 | SocketServer socketServer = new SocketServer(); 120 | socketServer.simulate(stringSocket, numReqDes, workingDirectory); 121 | 122 | /** send empty tensor "{}" to stop */ 123 | stringSocket.writeln(Tensors.empty()); 124 | 125 | /** analyze and send final score */ 126 | Analysis analysis = Analysis.setup(socketServer.getScenarioOptions(), socketServer.getOutputDirectory(), // 127 | socketServer.getNetwork(), preparer.getDatabase()); 128 | SocketScoreElement socketScoreElement = new SocketScoreElement(fleetSize, numReqDes, preparer.getDatabase()); 129 | analysis.addAnalysisElement(socketScoreElement); 130 | 131 | SocketExport socketExport = new SocketExport(socketScoreElement); 132 | analysis.addAnalysisExport(socketExport); 133 | 134 | SocketHtmlReport socketHtmlReport = new SocketHtmlReport(socketScoreElement); 135 | analysis.addHtmlElement(socketHtmlReport); 136 | analysis.run(); 137 | 138 | { /** create a video if environment variable is set */ 139 | String env = System.getenv(ENV_VIDEO_EXPORT); 140 | if (Objects.nonNull(env) && env.equalsIgnoreCase("true")) 141 | new VideoGenerator(workingDirectory).start(); 142 | } 143 | 144 | /** send final score, 145 | * {total waiting time, total distance with customer, total empty distance} */ 146 | stringSocket.writeln(Total.of(socketScoreElement.getScoreDiffHistory())); 147 | 148 | } catch (Exception exception) { 149 | // exception.printStackTrace(); 150 | shutdown(stringSocket); 151 | throw exception; 152 | } 153 | } 154 | 155 | private static void shutdown(StringSocket stringSocket) throws Exception { 156 | if (Objects.nonNull(stringSocket)) { 157 | /** send empty tensor "{}" to stop */ 158 | stringSocket.writeln(Tensors.empty()); 159 | /** send fictitious costs */ 160 | stringSocket.writeln(StaticHelper.FAILURE_SCORE); 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketHtmlReport.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import amodeus.amodeus.analysis.AnalysisSummary; 8 | import amodeus.amodeus.analysis.element.DistanceElement; 9 | import amodeus.amodeus.analysis.report.HtmlBodyElement; 10 | import amodeus.amodeus.analysis.report.HtmlGenerator; 11 | import amodeus.amodeus.analysis.report.HtmlReportElement; 12 | import amodeus.socket.core.SocketScoreElement; 13 | import ch.ethz.idsc.tensor.RealScalar; 14 | import ch.ethz.idsc.tensor.Scalar; 15 | import ch.ethz.idsc.tensor.Tensor; 16 | import ch.ethz.idsc.tensor.Tensors; 17 | import ch.ethz.idsc.tensor.alg.Transpose; 18 | import ch.ethz.idsc.tensor.red.Total; 19 | 20 | /* package */ class SocketHtmlReport implements HtmlReportElement { 21 | 22 | /** relative to report folder */ 23 | private static final String IMAGE_FOLDER = "../data"; 24 | // --- 25 | private final SocketScoreElement socketScoreElement; 26 | private Scalar totalMeanWaitingTime; 27 | private Scalar totalEfficiencyRatio; /* empty distance divided by total distance */ 28 | private Scalar numberOfVehicles; 29 | 30 | public SocketHtmlReport(SocketScoreElement socketScoreElement) { 31 | this.socketScoreElement = socketScoreElement; 32 | } 33 | 34 | @Override 35 | public Map process(AnalysisSummary analysisSummary) { 36 | 37 | totalMeanWaitingTime = analysisSummary.getTravelTimeAnalysis().getWaitAggrgte().Get(1); 38 | 39 | { 40 | DistanceElement distanceElement = analysisSummary.getDistanceElement(); 41 | Scalar sum = distanceElement.totalDistancePicku.add(distanceElement.totalDistanceRebal); 42 | // if totalDistance == 0.0, the ratio is NaN 43 | totalEfficiencyRatio = sum.divide(distanceElement.totalDistance); 44 | } 45 | 46 | numberOfVehicles = RealScalar.of(analysisSummary.getSimulationInformationElement().vehicleSize()); 47 | 48 | Map bodyElements = new HashMap<>(); 49 | { 50 | HtmlBodyElement aRElement = new HtmlBodyElement(); 51 | 52 | aRElement.getHTMLGenerator().insertTextLeft(HtmlGenerator.bold("Scores during Simulation")); 53 | aRElement.getHTMLGenerator().newLine(); 54 | aRElement.getHTMLGenerator().insertImg(IMAGE_FOLDER + "/" + SocketExport.FILENAME_SCORE_INCR, 800, 600); 55 | aRElement.getHTMLGenerator().insertImg(IMAGE_FOLDER + "/" + SocketExport.FILENAME_SCORE_INTG, 800, 600); 56 | aRElement.getHTMLGenerator().insertImg(IMAGE_FOLDER + "/" + SocketExport.FILENAME_SCORE3_INTG, 800, 600); 57 | 58 | aRElement.getHTMLGenerator() 59 | .insertTextLeft(HtmlGenerator.bold("Final Scores") + // 60 | "\n\t" + "final service quality score:" + // 61 | "\n\t" + "final efficiency score:" + // 62 | "\n\t" + "final fleet size score:" // 63 | ); 64 | aRElement.getHTMLGenerator() 65 | .insertTextLeft(" " + // 66 | "\n" + Total.of(Transpose.of(socketScoreElement.getScoreDiffHistory()).get(1)) + // 67 | "\n" + Total.of(Transpose.of(socketScoreElement.getScoreDiffHistory()).get(2)) + // 68 | "\n" + Total.of(Transpose.of(socketScoreElement.getScoreDiffHistory()).get(3)) // 69 | ); 70 | aRElement.getHTMLGenerator().newLine(); 71 | 72 | bodyElements.put("Socket Scores", aRElement); 73 | } 74 | return bodyElements; 75 | 76 | } 77 | 78 | /** @return */ 79 | public Tensor getFinalScore() { 80 | return Tensors.of(totalMeanWaitingTime, totalEfficiencyRatio, numberOfVehicles); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketModule.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.util.Objects; 5 | 6 | import amodeus.amodeus.util.net.StringSocket; 7 | import org.matsim.api.core.v01.network.Network; 8 | import org.matsim.core.controler.AbstractModule; 9 | 10 | import com.google.inject.Provides; 11 | import com.google.inject.Singleton; 12 | 13 | public class SocketModule extends AbstractModule { 14 | private final StringSocket stringSocket; 15 | private final int numReqTot; 16 | 17 | public SocketModule(StringSocket stringSocket, int numReqTot) { 18 | this.stringSocket = Objects.requireNonNull(stringSocket); 19 | this.numReqTot = numReqTot; 20 | } 21 | 22 | @Override 23 | public void install() { 24 | // --- 25 | } 26 | 27 | @Provides 28 | @Singleton 29 | public StringSocket provideStringSocket(Network network) { 30 | return stringSocket; 31 | } 32 | 33 | @Provides 34 | @Singleton 35 | public int provideNumReqTot() { 36 | return numReqTot; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketPopulationPreparer.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | 6 | import amodeus.amodeus.options.ScenarioOptions; 7 | import amodeus.amodeus.prep.LegCount; 8 | import amodeus.amodeus.prep.PopulationCutter; 9 | import amodeus.amodeus.prep.TheRequestApocalypse; 10 | import amodeus.amodeus.util.io.GZHandler; 11 | import amodeus.amodeus.util.math.GlobalAssert; 12 | import org.matsim.amodeus.config.AmodeusModeConfig; 13 | import org.matsim.api.core.v01.network.Network; 14 | import org.matsim.api.core.v01.population.Population; 15 | import org.matsim.core.config.Config; 16 | import org.matsim.core.population.io.PopulationWriter; 17 | 18 | /* package */ enum SocketPopulationPreparer { 19 | ; 20 | 21 | public static void run(Network network, Population population, ScenarioOptions scenOptions, // 22 | Config config, long seed, int numReqDes) throws Exception { 23 | /** ensure population contained in network */ 24 | PopulationCutter populationCutter = scenOptions.getPopulationCutter(); 25 | populationCutter.cut(population, network, config); 26 | 27 | /** apocalypse reduces the number of requests */ 28 | TheRequestApocalypse.reducesThe(population).toNoMoreThan(numReqDes, seed); 29 | GlobalAssert.that(0 < population.getPersons().size()); 30 | GlobalAssert.that(LegCount.of(population, AmodeusModeConfig.DEFAULT_MODE) == numReqDes); 31 | 32 | final File fileExportGz = new File(scenOptions.getPreparedPopulationName() + ".xml.gz"); 33 | final File fileExport = new File(scenOptions.getPreparedPopulationName() + ".xml"); 34 | 35 | /** write the modified population to file */ 36 | PopulationWriter populationWriter = new PopulationWriter(population); 37 | populationWriter.write(fileExportGz.toString()); 38 | 39 | /** extract the created .gz file */ 40 | GZHandler.extract(fileExportGz, fileExport); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketPreparer.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | import java.net.MalformedURLException; 6 | 7 | import amodeus.amodeus.data.LocationSpec; 8 | import amodeus.amodeus.data.ReferenceFrame; 9 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 10 | import amodeus.amodeus.net.TensorCoords; 11 | import amodeus.amodeus.options.ScenarioOptions; 12 | import amodeus.amodeus.options.ScenarioOptionsBase; 13 | import amodeus.amodeus.prep.ConfigCreator; 14 | import amodeus.amodeus.prep.NetworkPreparer; 15 | import org.matsim.amodeus.config.AmodeusConfigGroup; 16 | import org.matsim.amodeus.config.modal.GeneratorConfig; 17 | import org.matsim.api.core.v01.Coord; 18 | import org.matsim.api.core.v01.Scenario; 19 | import org.matsim.api.core.v01.network.Network; 20 | import org.matsim.api.core.v01.population.Population; 21 | import org.matsim.core.config.Config; 22 | import org.matsim.core.config.ConfigUtils; 23 | import org.matsim.core.network.NetworkUtils; 24 | import org.matsim.core.scenario.ScenarioUtils; 25 | 26 | import amodeus.amod.ext.Static; 27 | import ch.ethz.idsc.tensor.Tensor; 28 | import ch.ethz.idsc.tensor.Tensors; 29 | 30 | public class SocketPreparer { 31 | private final Population population; 32 | private final ScenarioOptions scenOpt; 33 | private final Config config; 34 | private final Network network; 35 | private final MatsimAmodeusDatabase db; 36 | private final int numRt; 37 | 38 | /** loads scenario preparer in the {@link File} workingDirectory 39 | * 40 | * @param workingDirectory 41 | * @throws MalformedURLException 42 | * @throws Exception */ 43 | public SocketPreparer(File workingDirectory) throws MalformedURLException, Exception { 44 | Static.setup(); 45 | 46 | /** amodeus options */ 47 | scenOpt = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 48 | 49 | /** MATSim config */ 50 | // configMatsim = ConfigUtils.loadConfig(scenOpt.getPreparerConfigName()); 51 | AmodeusConfigGroup avConfigGroup = new AmodeusConfigGroup(); 52 | config = ConfigUtils.loadConfig(scenOpt.getPreparerConfigName(), avConfigGroup); 53 | 54 | Scenario scenario = ScenarioUtils.loadScenario(config); 55 | GeneratorConfig genConfig = avConfigGroup.getModes().values().iterator().next().getGeneratorConfig(); 56 | numRt = genConfig.getNumberOfVehicles(); 57 | System.out.println("socketPrep NumberOfVehicles=" + numRt); 58 | 59 | /** adaption of MATSim network, e.g., radius cutting */ 60 | Network network = scenario.getNetwork(); 61 | this.network = NetworkPreparer.run(network, scenOpt); 62 | 63 | /** adaption of MATSim population, e.g., radius cutting */ 64 | population = scenario.getPopulation(); 65 | 66 | LocationSpec locationSpec = scenOpt.getLocationSpec(); 67 | ReferenceFrame referenceFrame = locationSpec.referenceFrame(); 68 | this.db = MatsimAmodeusDatabase.initialize(network, referenceFrame); 69 | } 70 | 71 | /** second part of preparer 72 | * 73 | * @param numReqDes 74 | * @throws Exception */ 75 | public void run2(int numReqDes) throws Exception { 76 | long apoSeed = 1234; 77 | SocketPopulationPreparer.run(network, population, scenOpt, config, apoSeed, numReqDes); 78 | 79 | /** creating a virtual network, e.g., for dispatchers using a graph structure on the city */ 80 | // int endTime = (int) config.qsim().getEndTime(); 81 | // VirtualNetworkPreparer.INSTANCE.create(network, population, scenOpt, numRt,endTime); 82 | 83 | /** create a simulation MATSim config file linking the created input data */ 84 | ConfigCreator.createSimulationConfigFile(config, scenOpt); 85 | } 86 | 87 | public Tensor getBoundingBox() { 88 | /** send initial data (bounding box), {{minX, minY}, {maxX, maxY}} */ 89 | double[] bbox = NetworkUtils.getBoundingBox(network.getNodes().values()); 90 | 91 | return Tensors.of(TensorCoords.toTensor( // 92 | scenOpt.getLocationSpec().referenceFrame().coords_toWGS84().transform(new Coord(bbox[0], bbox[1]))), // 93 | TensorCoords.toTensor( // 94 | scenOpt.getLocationSpec().referenceFrame().coords_toWGS84().transform(new Coord(bbox[2], bbox[3])))); 95 | } 96 | 97 | public Population getPopulation() { 98 | return population; 99 | } 100 | 101 | public MatsimAmodeusDatabase getDatabase() { 102 | return db; 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketScenarioResource.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | import java.io.FileOutputStream; 6 | import java.io.IOException; 7 | import java.io.InputStream; 8 | import java.io.OutputStream; 9 | import java.util.List; 10 | 11 | import amodeus.amodeus.util.io.Unzip; 12 | import amodeus.socket.core.SocketScenarioDownload; 13 | 14 | public enum SocketScenarioResource { 15 | ; 16 | 17 | private static final String SCENARIO_ZIP = "scenario.zip"; 18 | 19 | /** @param key for instance "SanFrancisco.20080518" 20 | * @throws IOException */ 21 | public static List extract(final String key, File workingDirectory) throws IOException { 22 | /** file name is arbitrary, file will be deleted after un-zipping */ 23 | final File file = new File(workingDirectory, SCENARIO_ZIP); 24 | String resource = "/scenario/" + key.replace('.', '/') + "/" + SCENARIO_ZIP; 25 | try (InputStream inputStream = SocketScenarioResource.class.getResourceAsStream(resource)) { 26 | System.out.println("obtain as resource: [" + resource + "]"); 27 | try (OutputStream outputStream = new FileOutputStream(file)) { 28 | byte[] buffer = new byte[1024]; 29 | int length; 30 | while (0 < (length = inputStream.read(buffer))) 31 | outputStream.write(buffer, 0, length); 32 | } 33 | 34 | } catch (Exception exception) { 35 | System.out.println("scenario not fount as resource: [" + resource + "]"); 36 | SocketScenarioDownload.of(key, file); 37 | } 38 | List list = Unzip.of(file, workingDirectory, true); 39 | file.delete(); 40 | return list; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/SocketServer.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | import java.net.MalformedURLException; 6 | import java.util.Objects; 7 | 8 | import amodeus.amodeus.data.LocationSpec; 9 | import amodeus.amodeus.data.ReferenceFrame; 10 | import amodeus.amodeus.generator.RandomDensityGenerator; 11 | import amodeus.amodeus.linkspeed.LinkSpeedDataContainer; 12 | import amodeus.amodeus.linkspeed.LinkSpeedUtils; 13 | import amodeus.amodeus.linkspeed.TaxiTravelTimeRouter; 14 | import amodeus.amodeus.linkspeed.TrafficDataModule; 15 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 16 | import amodeus.amodeus.net.SimulationServer; 17 | import amodeus.amodeus.options.ScenarioOptions; 18 | import amodeus.amodeus.options.ScenarioOptionsBase; 19 | import amodeus.amodeus.util.math.GlobalAssert; 20 | import amodeus.amodeus.util.matsim.AddCoordinatesToActivities; 21 | import amodeus.amodeus.util.net.StringSocket; 22 | import org.matsim.amodeus.AmodeusConfigurator; 23 | import org.matsim.amodeus.config.AmodeusConfigGroup; 24 | import org.matsim.amodeus.framework.AmodeusUtils; 25 | import org.matsim.api.core.v01.Scenario; 26 | import org.matsim.api.core.v01.network.Network; 27 | import org.matsim.api.core.v01.population.Population; 28 | import org.matsim.contrib.dvrp.run.DvrpConfigGroup; 29 | import org.matsim.core.config.Config; 30 | import org.matsim.core.config.ConfigUtils; 31 | import org.matsim.core.config.groups.PlanCalcScoreConfigGroup.ActivityParams; 32 | import org.matsim.core.controler.AbstractModule; 33 | import org.matsim.core.controler.Controler; 34 | import org.matsim.core.scenario.ScenarioUtils; 35 | 36 | import amodeus.amod.ext.Static; 37 | import amodeus.socket.core.SocketDispatcherHost; 38 | 39 | /** only one ScenarioServer can run at one time, since a fixed network port is 40 | * reserved to serve the simulation status */ 41 | /* package */ class SocketServer { 42 | 43 | private File configFile; 44 | private File outputDirectory; 45 | private Network network; 46 | private ReferenceFrame referenceFrame; 47 | private ScenarioOptions scenarioOptions; 48 | 49 | /** runs a simulation run using input data from Amodeus.properties, av.xml and MATSim config.xml 50 | * 51 | * @throws MalformedURLException 52 | * @throws Exception */ 53 | 54 | public void simulate(StringSocket stringSocket, int numReqTot, // 55 | File workingDirectory) throws MalformedURLException, Exception { 56 | Static.setup(); 57 | /** working directory and options */ 58 | scenarioOptions = new ScenarioOptions(workingDirectory, ScenarioOptionsBase.getDefault()); 59 | 60 | /** set to true in order to make server wait for at least 1 client, for 61 | * instance viewer client, for fals the ScenarioServer starts the simulation 62 | * immediately */ 63 | boolean waitForClients = scenarioOptions.getBoolean("waitForClients"); 64 | configFile = new File(scenarioOptions.getSimulationConfigName()); 65 | /** geographic information */ 66 | LocationSpec locationSpec = scenarioOptions.getLocationSpec(); 67 | referenceFrame = locationSpec.referenceFrame(); 68 | 69 | /** open server port for clients to connect to */ 70 | SimulationServer.INSTANCE.startAcceptingNonBlocking(); 71 | SimulationServer.INSTANCE.setWaitForClients(waitForClients); 72 | 73 | /** load MATSim configs - including av.xml configurations, load routing packages */ 74 | GlobalAssert.that(configFile.exists()); 75 | DvrpConfigGroup dvrpConfigGroup = new DvrpConfigGroup(); 76 | dvrpConfigGroup.setTravelTimeEstimationAlpha(0.05); 77 | Config config = ConfigUtils.loadConfig(configFile.toString(), new AmodeusConfigGroup(), dvrpConfigGroup); 78 | config.planCalcScore().addActivityParams(new ActivityParams("activity")); 79 | // TODO @Sebastian fix this to meaningful values, remove, or add comment 80 | // this was added because there are sometimes problems, is there a more elegant option? 81 | for (ActivityParams activityParams : config.planCalcScore().getActivityParams()) { 82 | activityParams.setTypicalDuration(3600.0); 83 | } 84 | 85 | /** load MATSim scenario for simulation */ 86 | Scenario scenario = ScenarioUtils.loadScenario(config); 87 | AddCoordinatesToActivities.run(scenario); 88 | network = scenario.getNetwork(); 89 | Population population = scenario.getPopulation(); 90 | GlobalAssert.that(Objects.nonNull(network)); 91 | GlobalAssert.that(Objects.nonNull(population)); 92 | 93 | Objects.requireNonNull(network); 94 | MatsimAmodeusDatabase db = MatsimAmodeusDatabase.initialize(network, referenceFrame); 95 | Controler controller = new Controler(scenario); 96 | AmodeusConfigurator.configureController(controller, scenarioOptions); 97 | 98 | /** try to load link speed data and use for speed adaption in network */ 99 | try { 100 | File linkSpeedDataFile = new File(scenarioOptions.getLinkSpeedDataName()); 101 | System.out.println(linkSpeedDataFile.toString()); 102 | LinkSpeedDataContainer lsData = LinkSpeedUtils.loadLinkSpeedData(linkSpeedDataFile); 103 | controller.addOverridingQSimModule(new TrafficDataModule(lsData)); 104 | } catch (Exception exception) { 105 | System.err.println("Unable to load linkspeed data, freeflow speeds will be used in the simulation."); 106 | exception.printStackTrace(); 107 | } 108 | 109 | controller.addOverridingModule(new SocketModule(stringSocket, numReqTot)); 110 | 111 | /** Custom router that ensures same network speeds as taxis in original data set. */ 112 | controller.addOverridingModule(new AbstractModule() { 113 | @Override 114 | public void install() { 115 | bind(TaxiTravelTimeRouter.Factory.class); 116 | AmodeusUtils.bindRouterFactory(binder(), TaxiTravelTimeRouter.class.getSimpleName()).to(TaxiTravelTimeRouter.Factory.class); 117 | } 118 | }); 119 | 120 | /** adding the dispatcher to receive and process string fleet commands */ 121 | controller.addOverridingModule(new AbstractModule() { 122 | @Override 123 | public void install() { 124 | AmodeusUtils.registerDispatcherFactory(binder(), "SocketDispatcherHost", SocketDispatcherHost.Factory.class); 125 | } 126 | }); 127 | 128 | /** adding an initial vehicle placer */ 129 | controller.addOverridingModule(new AbstractModule() { 130 | @Override 131 | public void install() { 132 | AmodeusUtils.bindGeneratorFactory(binder(), RandomDensityGenerator.class.getSimpleName()).// 133 | to(RandomDensityGenerator.Factory.class); 134 | } 135 | }); 136 | 137 | /** run simulation */ 138 | controller.run(); 139 | 140 | /** close port for visualizaiton */ 141 | SimulationServer.INSTANCE.stopAccepting(); 142 | 143 | /** perform analysis of simulation */ 144 | /** output directory for saving results */ 145 | outputDirectory = new File(config.controler().getOutputDirectory()); 146 | 147 | } 148 | 149 | /* package */ File getOutputDirectory() { 150 | return outputDirectory; 151 | } 152 | 153 | /* package */ File getConfigFile() { 154 | return configFile; 155 | } 156 | 157 | /* package */ Network getNetwork() { 158 | return network; 159 | } 160 | 161 | /* package */ ReferenceFrame getReferenceFrame() { 162 | return referenceFrame; 163 | } 164 | 165 | /* package */ ScenarioOptions getScenarioOptions() { 166 | return scenarioOptions; 167 | } 168 | } 169 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/StaticHelper.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import ch.ethz.idsc.tensor.DoubleScalar; 5 | import ch.ethz.idsc.tensor.alg.Array; 6 | 7 | /* package */ enum StaticHelper { 8 | ; 9 | static final String FAILURE_SCORE = Array.of(l -> DoubleScalar.NEGATIVE_INFINITY, 3).toString(); 10 | 11 | static void setup() { 12 | System.setProperty("matsim.preferLocalDtds", "true"); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/CleanSocketScenarios.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.io.File; 5 | import java.util.Arrays; 6 | 7 | /* package */ enum CleanSocketScenarios { 8 | ; 9 | 10 | /** clean up downloaded files for socket scenaros */ 11 | public static void now() { 12 | String[] files = new String[] { "AmodeusOptions.properties", "LPOptions.properties", // 13 | "av.xml", "matsimConfig.xml", "personAtrributes-with-subpopulation.xml", // 14 | "preparedNetwork.xml.gz", "preparedNetwork.xml", "config_full.xml", // 15 | "linkSpeedData", "config.xml", "preparedConfig.xml", "preparedPopulation.xml", // 16 | "preparedPopulation.xml.gz", "population.xml", "population.xml.gz", // 17 | "rawPopulation.xml.gz", "network.xml.gz", "rawNetwork.xml.gz", "rawFacilities.xml.gz" }; 18 | Arrays.stream(files).map(File::new).filter(File::exists).forEach(file -> { 19 | if (!file.delete()) 20 | System.out.println("file: " + file.getName() + " not deleted."); 21 | }); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/CommandConsistency.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | import amodeus.amodeus.util.math.GlobalAssert; 8 | import ch.ethz.idsc.tensor.Scalar; 9 | import ch.ethz.idsc.tensor.Tensor; 10 | 11 | public enum CommandConsistency { 12 | ; 13 | 14 | /** Performs the following consistency checks on the commands received and fails if >=1 15 | * check is failing: 16 | * 17 | * 1) ensure every RoboTaxi should be in {0,1} of the commands 18 | * 2) ensure every request should only be assigned {0,1} times 19 | * 20 | * @param commands */ 21 | public static void check(Tensor commands) { 22 | // GlobalAssert.that(ExactScalarQ.all(commands)); 23 | 24 | /** 1) ensure every RoboTaxi should be in {0,1} of the commands 25 | ** 2) ensure every request should only be assigned {0,1} times */ 26 | Set usdRobTaxis = new HashSet<>(); 27 | Set usedPickups = new HashSet<>(); 28 | 29 | Tensor pickups = commands.get(0); 30 | for (Tensor pickup : pickups) { 31 | GlobalAssert.that(usdRobTaxis.add(pickup.Get(0))); 32 | GlobalAssert.that(usedPickups.add(pickup.Get(1))); 33 | } 34 | 35 | Tensor rebalances = commands.get(1); 36 | for (Tensor rebalance : rebalances) 37 | GlobalAssert.that(usdRobTaxis.add(rebalance.Get(0))); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/EfficiencyScore.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | /* package */ class EfficiencyScore extends LinComScore { 5 | /* package */ EfficiencyScore(ScoreParameters scoreParameters) { 6 | super(scoreParameters.alpha34); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/FleetSizeScore.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.GlobalAssert; 5 | import amodeus.amodeus.util.math.SI; 6 | import ch.ethz.idsc.tensor.RationalScalar; 7 | import ch.ethz.idsc.tensor.RealScalar; 8 | import ch.ethz.idsc.tensor.Scalar; 9 | import ch.ethz.idsc.tensor.Scalars; 10 | import ch.ethz.idsc.tensor.qty.Quantity; 11 | 12 | /** the fleetsize score is defined as following, in the case that the maximum waiting time 13 | * wMax is not violated, its toal is -fleetSize, i.e., the differences are 14 | * {0,-fleetSize,0,...,0} 15 | * 16 | * if the summmed waiting time exceeds wMax, then the final score is -Infinity, the 17 | * differences then are 18 | * {0,-fleetSize,0,...,0,-Infinity,0,...,0} */ 19 | /* package */ class FleetSizeScore { 20 | private final Scalar wMax; 21 | private final Scalar fleetSize; 22 | private Scalar scoreFinal = RealScalar.ZERO; 23 | private Scalar scoreFinalPrev = RealScalar.ZERO; 24 | private Scalar timeViolate = Quantity.of(-1, SI.SECOND); 25 | private Scalar totalWait = Quantity.of(0, SI.SECOND); 26 | private boolean firstTime = true; 27 | 28 | public FleetSizeScore(ScoreParameters scoreParameters, int totReq, int fleetSize) { 29 | Scalar wmean = scoreParameters.wmean; 30 | wMax = wmean.multiply(RealScalar.of(totReq)); 31 | this.fleetSize = RationalScalar.of(fleetSize, 1); 32 | this.scoreFinal = RealScalar.ZERO; 33 | } 34 | 35 | public void update(Scalar incrWait, Scalar time) { 36 | GlobalAssert.that(Scalars.lessEquals(Quantity.of(0, SI.SECOND), incrWait)); 37 | GlobalAssert.that(Scalars.lessEquals(Quantity.of(0, SI.SECOND), time)); 38 | totalWait = totalWait.add(incrWait); 39 | if (firstTime) { /** score starts at 0, then goes to -N */ 40 | scoreFinal = fleetSize.negate(); 41 | firstTime = false; 42 | } else { 43 | /** update previous score */ 44 | scoreFinalPrev = scoreFinal; 45 | /** first time violation takes place, augment to -Infty */ 46 | if (Scalars.lessThan(wMax, totalWait) // 47 | && !scoreFinal.equals(Quantity.of(Double.NEGATIVE_INFINITY, SI.ONE))) { 48 | scoreFinal = Quantity.of(Double.NEGATIVE_INFINITY, SI.ONE); 49 | timeViolate = time; 50 | } 51 | } 52 | } 53 | 54 | public Scalar getTimeToViolate() { 55 | return timeViolate; 56 | } 57 | 58 | public Scalar getScoreDiff() { 59 | Scalar scoreDiff = scoreFinal.subtract(scoreFinalPrev); 60 | if (Double.isNaN(scoreDiff.number().doubleValue())) 61 | return RealScalar.ZERO; 62 | return scoreDiff; 63 | } 64 | 65 | public Scalar getScoreIntg() { 66 | return scoreFinal; 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/LinComScore.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.GlobalAssert; 5 | import ch.ethz.idsc.tensor.RealScalar; 6 | import ch.ethz.idsc.tensor.Scalar; 7 | import ch.ethz.idsc.tensor.Scalars; 8 | import ch.ethz.idsc.tensor.Tensor; 9 | 10 | /** used to compute scores which are a linear combination 11 | * of variables and weights */ 12 | /* package */ abstract class LinComScore { 13 | protected final Tensor alpha; 14 | /** the weight */ 15 | private Scalar score = RealScalar.ZERO; 16 | private Scalar scorePrev = RealScalar.ZERO; 17 | 18 | protected LinComScore(Tensor alpha) { 19 | this.alpha = alpha; 20 | } 21 | 22 | public void update(Tensor measurement) { 23 | scorePrev = score; 24 | score = ((Scalar) measurement.dot(alpha)).add(scorePrev); 25 | } 26 | 27 | public Scalar getScoreIntg() { 28 | return score; 29 | } 30 | 31 | public Scalar getScoreDiff() { 32 | Scalar scoreDiff = score.subtract(scorePrev); 33 | // the check below is specific to the reward function used in reenforcement learning 34 | // the check below is not strictly required in general 35 | GlobalAssert.that(Scalars.lessEquals(scoreDiff, RealScalar.ZERO)); 36 | return scoreDiff; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/ScoreParameters.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import ch.ethz.idsc.tensor.RealScalar; 5 | import ch.ethz.idsc.tensor.Scalar; 6 | import ch.ethz.idsc.tensor.Tensor; 7 | import ch.ethz.idsc.tensor.Tensors; 8 | import ch.ethz.idsc.tensor.io.ResourceData; 9 | import ch.ethz.idsc.tensor.io.TensorProperties; 10 | import ch.ethz.idsc.tensor.qty.Quantity; 11 | 12 | /** values in class are required by SocketHost 13 | * therefore class was made public */ 14 | public class ScoreParameters { 15 | /** overrides default values defined in class 16 | * with the values parsed from the properties file */ 17 | public static final ScoreParameters GLOBAL = TensorProperties.wrap(new ScoreParameters()) // 18 | .set(ResourceData.properties("/socket/ScoreParameters.properties")); 19 | 20 | /** service quality */ 21 | public Tensor alpha12 = Tensors.fromString("{-0.5[s^-1], -0.7[m^-1]}"); 22 | 23 | /** efficiency score */ 24 | public Tensor alpha34 = Tensors.fromString("{-0.5[s^-1], -0.5[m^-1]}"); 25 | 26 | /** standard fleet size as a fraction of the total number of requests */ 27 | public Scalar gamma = RealScalar.of(0.025); 28 | 29 | /** mean wait time for the fleet reduction */ 30 | public Scalar wmean = Quantity.of(300.0, "s"); 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/ServiceQualityScore.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | /* package */ class ServiceQualityScore extends LinComScore { 5 | /* package */ ServiceQualityScore(ScoreParameters scoreParameters) { 6 | super(scoreParameters.alpha12); 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketDispatcherHost.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | import java.util.Objects; 7 | 8 | import org.matsim.amodeus.components.AmodeusDispatcher; 9 | import org.matsim.amodeus.components.AmodeusRouter; 10 | import org.matsim.amodeus.config.AmodeusModeConfig; 11 | import org.matsim.amodeus.plpc.ParallelLeastCostPathCalculator; 12 | import org.matsim.api.core.v01.network.Link; 13 | import org.matsim.api.core.v01.network.Network; 14 | import org.matsim.contrib.drt.optimizer.rebalancing.RebalancingStrategy; 15 | import org.matsim.contrib.dvrp.passenger.PassengerRequest; 16 | import org.matsim.contrib.dvrp.run.ModalProviders.InstanceGetter; 17 | import org.matsim.core.api.experimental.events.EventsManager; 18 | import org.matsim.core.config.Config; 19 | import org.matsim.core.router.util.TravelTime; 20 | 21 | import amodeus.amodeus.dispatcher.core.RebalancingDispatcher; 22 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 23 | import amodeus.amodeus.dispatcher.core.RoboTaxiUsageType; 24 | import amodeus.amodeus.net.FastLinkLookup; 25 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 26 | import amodeus.amodeus.util.matsim.SafeConfig; 27 | import amodeus.amodeus.util.net.StringSocket; 28 | import ch.ethz.idsc.tensor.RealScalar; 29 | import ch.ethz.idsc.tensor.Tensor; 30 | import ch.ethz.idsc.tensor.Tensors; 31 | 32 | // TODO refactor and shorten @clruch 33 | public class SocketDispatcherHost extends RebalancingDispatcher { 34 | private final MatsimAmodeusDatabase db; 35 | 36 | private final Map idRoboTaxiMap = new HashMap<>(); 37 | private final Map idRequestMap = new HashMap<>(); 38 | private final FastLinkLookup fastLinkLookup; 39 | private final StringSocket clientSocket; 40 | private final int numReqTot; 41 | private final int dispatchPeriod; 42 | private final SocketRequestCompiler socketReqComp; 43 | private final SocketRoboTaxiCompiler socketRobTaxComp; 44 | // --- 45 | private SocketScoreCompiler socketScoreCompiler; 46 | 47 | protected SocketDispatcherHost(Network network, Config config, AmodeusModeConfig operatorConfig, TravelTime travelTime, 48 | ParallelLeastCostPathCalculator parallelLeastCostPathCalculator, EventsManager eventsManager, // 49 | StringSocket clientSocket, int numReqTot, // 50 | MatsimAmodeusDatabase db, RebalancingStrategy drtRebalancing) { 51 | super(config, operatorConfig, travelTime, parallelLeastCostPathCalculator, eventsManager, db, drtRebalancing, RoboTaxiUsageType.SINGLEUSED); 52 | this.db = db; 53 | this.clientSocket = Objects.requireNonNull(clientSocket); 54 | this.numReqTot = numReqTot; 55 | this.fastLinkLookup = new FastLinkLookup(network, db); 56 | SafeConfig safeConfig = SafeConfig.wrap(operatorConfig.getDispatcherConfig()); 57 | this.dispatchPeriod = safeConfig.getInteger("dispatchPeriod", 30); 58 | socketReqComp = new SocketRequestCompiler(db); 59 | socketRobTaxComp = new SocketRoboTaxiCompiler(db); 60 | } 61 | 62 | @Override 63 | protected void redispatch(double now) { 64 | final long round_now = Math.round(now); 65 | 66 | if (getRoboTaxis().size() > 0 && idRoboTaxiMap.isEmpty()) { 67 | getRoboTaxis().forEach( // 68 | roboTaxi -> idRoboTaxiMap.put(roboTaxi.getId().index(), roboTaxi)); 69 | socketScoreCompiler = new SocketScoreCompiler(getRoboTaxis(), numReqTot, db); 70 | } 71 | 72 | if (round_now % dispatchPeriod == 0) { 73 | 74 | if (Objects.nonNull(socketScoreCompiler)) 75 | try { 76 | getPassengerRequests().forEach( // 77 | avRequest -> idRequestMap.put(avRequest.getId().index(), avRequest)); 78 | 79 | Tensor status = Tensors.of(RealScalar.of((long) now), // 80 | socketRobTaxComp.compile(getRoboTaxis()), // 81 | socketReqComp.compile(getPassengerRequests()), // 82 | socketScoreCompiler.compile(round_now, getRoboTaxis(), getPassengerRequests())); 83 | clientSocket.writeln(status); 84 | 85 | String fromClient = clientSocket.readLine(); 86 | 87 | Tensor commands = Tensors.fromString(fromClient); 88 | CommandConsistency.check(commands); 89 | 90 | Tensor pickups = commands.get(0); 91 | for (Tensor pickup : pickups) { 92 | RoboTaxi roboTaxi = idRoboTaxiMap.get(pickup.Get(0).number().intValue()); 93 | PassengerRequest avRequest = idRequestMap.get(pickup.Get(1).number().intValue()); 94 | setRoboTaxiPickup(roboTaxi, avRequest); 95 | } 96 | 97 | Tensor rebalances = commands.get(1); 98 | for (Tensor rebalance : rebalances) { 99 | RoboTaxi roboTaxi = idRoboTaxiMap.get(rebalance.Get(0).number().intValue()); 100 | Link link = fastLinkLookup.linkFromWGS84(rebalance.get(1)); 101 | setRoboTaxiRebalance(roboTaxi, link); 102 | } 103 | } catch (Exception exception) { 104 | exception.printStackTrace(); 105 | } 106 | } 107 | } 108 | 109 | public static class Factory implements AVDispatcherFactory { 110 | @Override 111 | public AmodeusDispatcher createDispatcher(InstanceGetter inject) { 112 | Config config = inject.get(Config.class); 113 | MatsimAmodeusDatabase db = inject.get(MatsimAmodeusDatabase.class); 114 | EventsManager eventsManager = inject.get(EventsManager.class); 115 | 116 | AmodeusModeConfig operatorConfig = inject.getModal(AmodeusModeConfig.class); 117 | Network network = inject.getModal(Network.class); 118 | AmodeusRouter router = inject.getModal(AmodeusRouter.class); 119 | TravelTime travelTime = inject.getModal(TravelTime.class); 120 | RebalancingStrategy drtRebalancing = inject.getModal(RebalancingStrategy.class); 121 | 122 | // TODO: Probably worth configuring this in some other way (not binding String and int) 123 | int numReqTot = inject.get(int.class); 124 | StringSocket stringSocket = inject.get(StringSocket.class); 125 | 126 | return new SocketDispatcherHost(network, config, operatorConfig, travelTime, router, eventsManager, // 127 | stringSocket, numReqTot, db, drtRebalancing); 128 | } 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketDistanceRecorder.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 8 | import amodeus.amodeus.net.SimulationObject; 9 | import ch.ethz.idsc.tensor.Tensor; 10 | 11 | /* package */ class SocketDistanceRecorder { 12 | private final MatsimAmodeusDatabase db; 13 | private final Map map = new HashMap<>(); 14 | 15 | public SocketDistanceRecorder(MatsimAmodeusDatabase db) { 16 | this.db = db; 17 | } 18 | 19 | Tensor distance(SimulationObject simulationObject) { 20 | return simulationObject.vehicles.stream() // 21 | .map(vehicleContainer -> map.computeIfAbsent(vehicleContainer.vehicleIndex, // 22 | i -> new SocketVehicleStatistic(db)).distance(vehicleContainer)) // 23 | .reduce(Tensor::add) // 24 | .orElse(StaticHelper.ZEROS.copy()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketRequestCompiler.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.Collection; 5 | 6 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 7 | import amodeus.amodeus.net.TensorCoords; 8 | import org.matsim.contrib.dvrp.passenger.PassengerRequest; 9 | 10 | import ch.ethz.idsc.tensor.RealScalar; 11 | import ch.ethz.idsc.tensor.Tensor; 12 | import ch.ethz.idsc.tensor.Tensors; 13 | 14 | public class SocketRequestCompiler { 15 | private final MatsimAmodeusDatabase db; 16 | 17 | public SocketRequestCompiler(MatsimAmodeusDatabase db) { 18 | this.db = db; 19 | } 20 | 21 | public Tensor compile(Collection requests) { 22 | return Tensor.of(requests.stream().map(this::of)); 23 | } 24 | 25 | private Tensor of(PassengerRequest request) { 26 | // id 27 | Tensor info = Tensors.vector(request.getId().index()); 28 | // submission time 29 | info.append(RealScalar.of(request.getSubmissionTime())); 30 | // from location 31 | info.append(TensorCoords.toTensor(db.referenceFrame.coords_toWGS84().transform( // 32 | request.getFromLink().getCoord()))); 33 | // to location 34 | info.append(TensorCoords.toTensor(db.referenceFrame.coords_toWGS84().transform( // 35 | request.getToLink().getCoord()))); 36 | return info; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketRoboTaxiCompiler.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.List; 5 | 6 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 7 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 8 | import amodeus.amodeus.net.TensorCoords; 9 | import ch.ethz.idsc.tensor.Tensor; 10 | import ch.ethz.idsc.tensor.Tensors; 11 | import ch.ethz.idsc.tensor.io.StringScalar; 12 | import ch.ethz.idsc.tensor.qty.Boole; 13 | 14 | public class SocketRoboTaxiCompiler { 15 | private final MatsimAmodeusDatabase db; 16 | 17 | public SocketRoboTaxiCompiler(MatsimAmodeusDatabase db) { 18 | this.db = db; 19 | } 20 | 21 | public Tensor compile(List roboTaxis) { 22 | return Tensor.of(roboTaxis.stream().map(this::ofTaxi)); 23 | } 24 | 25 | private Tensor ofTaxi(RoboTaxi roboTaxi) { 26 | // id 27 | Tensor info = Tensors.vector(roboTaxi.getId().index()); 28 | // divertable location 29 | info.append(TensorCoords.toTensor(db.referenceFrame.coords_toWGS84().transform( // 30 | roboTaxi.getDivertableLocation().getCoord()))); 31 | // status 32 | info.append(StringScalar.of(roboTaxi.getStatus().name())); 33 | // divertable? 34 | info.append(Boole.of(roboTaxi.isDivertable())); 35 | return info; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketScenarioDownload.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.util.Properties; 7 | 8 | import amodeus.amodeus.util.io.ContentType; 9 | import amodeus.amodeus.util.io.Unzip; 10 | import ch.ethz.idsc.tensor.io.ResourceData; 11 | import ch.ethz.idsc.tensor.io.URLFetch; 12 | 13 | public enum SocketScenarioDownload { 14 | ; 15 | 16 | /** @param key for instance "SanFrancisco.20080519" 17 | * @throws IOException */ 18 | public static void extract(File workingDirecotry, String key) throws IOException { 19 | File file = new File(workingDirecotry, "scenario.zip"); 20 | of(key, file); 21 | Unzip.of(file, workingDirecotry, true); 22 | file.delete(); 23 | } 24 | 25 | /** @param key for instance "SanFrancisco.20080519" 26 | * @param file local target 27 | * @throws IOException */ 28 | public static void of(String key, File file) throws IOException { 29 | Properties properties = ResourceData.properties("/socket/scenarios.properties"); 30 | if (properties.containsKey(key)) { 31 | /** chosing scenario */ 32 | String value = properties.getProperty(key); 33 | System.out.println("scenario: " + value); 34 | /** file name is arbitrary, file will be deleted after un-zipping */ 35 | try (URLFetch urlFetch = new URLFetch(value)) { 36 | ContentType.APPLICATION_ZIP.require(urlFetch.contentType()); 37 | urlFetch.download(file); 38 | } 39 | return; 40 | } 41 | throw new RuntimeException(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketScoreCompiler.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.Collection; 5 | import java.util.List; 6 | 7 | import amodeus.amodeus.dispatcher.core.RequestStatus; 8 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 9 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 10 | import amodeus.amodeus.net.SimulationObjectCompiler; 11 | import org.matsim.contrib.dvrp.passenger.PassengerRequest; 12 | 13 | import ch.ethz.idsc.tensor.Tensor; 14 | 15 | public class SocketScoreCompiler { 16 | private static final String INFO_LINE = ""; 17 | private static final int TOTAL_MATCHED_REQUESTS = -1; 18 | // --- 19 | private final SocketScoreElement socketScoreElement; 20 | private final MatsimAmodeusDatabase db; 21 | 22 | public SocketScoreCompiler(List roboTaxis, int totReq, MatsimAmodeusDatabase db) { 23 | this.db = db; 24 | socketScoreElement = new SocketScoreElement(roboTaxis.size(), totReq, ScoreParameters.GLOBAL, db); 25 | } 26 | 27 | public Tensor compile(long timeMatsim, List roboTaxis, Collection requests) { 28 | /** create a {@link SimulationObject} */ 29 | SimulationObjectCompiler simulationObjectCompiler = // 30 | SimulationObjectCompiler.create(timeMatsim, INFO_LINE, TOTAL_MATCHED_REQUESTS, db); 31 | simulationObjectCompiler.insertVehicles(roboTaxis); 32 | simulationObjectCompiler.insertRequests(requests, RequestStatus.EMPTY); // request status not used 33 | 34 | /** insert and evaluate */ 35 | socketScoreElement.register(simulationObjectCompiler.compile()); 36 | return socketScoreElement.getScoreDiff(); 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketScoreElement.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.analysis.element.AnalysisElement; 5 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 6 | import amodeus.amodeus.net.SimulationObject; 7 | import amodeus.amodeus.util.math.SI; 8 | import ch.ethz.idsc.tensor.RationalScalar; 9 | import ch.ethz.idsc.tensor.Scalar; 10 | import ch.ethz.idsc.tensor.Tensor; 11 | import ch.ethz.idsc.tensor.Tensors; 12 | import ch.ethz.idsc.tensor.io.TableBuilder; 13 | import ch.ethz.idsc.tensor.qty.Quantity; 14 | 15 | public class SocketScoreElement implements AnalysisElement { 16 | 17 | private final SocketDistanceRecorder socketDistanceRecorder; 18 | private final TableBuilder scoreDiffTable = new TableBuilder(); 19 | private final TableBuilder scoreIntgTable = new TableBuilder(); 20 | private final ServiceQualityScore squScore; 21 | private final EfficiencyScore effScore; 22 | private final FleetSizeScore fltScore; 23 | // --- 24 | private Scalar timeBefore = Quantity.of(0, SI.SECOND); 25 | 26 | public SocketScoreElement(int numberRoboTaxis, int totReq, MatsimAmodeusDatabase db) { 27 | this(numberRoboTaxis, totReq, ScoreParameters.GLOBAL, db); 28 | } 29 | 30 | public SocketScoreElement( // 31 | int numberRoboTaxis, int totReq, ScoreParameters scoreParameters, MatsimAmodeusDatabase db) { 32 | socketDistanceRecorder = new SocketDistanceRecorder(db); 33 | squScore = new ServiceQualityScore(scoreParameters); 34 | effScore = new EfficiencyScore(scoreParameters); 35 | fltScore = new FleetSizeScore(scoreParameters, totReq, numberRoboTaxis); 36 | } 37 | 38 | @Override 39 | public void register(SimulationObject simulationObject) { 40 | /** time */ 41 | Scalar time = Quantity.of(simulationObject.now, SI.SECOND); 42 | Scalar dt = time.subtract(timeBefore); 43 | 44 | /** the first scalar entry of the score is time spent waiting in the current time step, i.e., 45 | * total of current waiting times: 4 customers waiting for 1 time step --> 46 | * 4 time steps of waiting time accumulated */ 47 | Scalar currWaitTime = RationalScalar.of(simulationObject.requests.size(), 1).multiply(dt); 48 | 49 | /** the second scalar entry of the score is the distance driven with full vehicles (with customer) 50 | * the third scalar entry of the score is the distance driven with empty vehicles (without customer) 51 | * 52 | * This distance is always accounted when a vehicle leaves a link, so for an individual vehicle 53 | * it produced a sequence {...,0,0,d1,0,0,d2,0,...} */ 54 | 55 | Tensor currDistance = socketDistanceRecorder.distance(simulationObject); 56 | Scalar distEmpty = currDistance.Get(1); 57 | 58 | /** update scores with information */ 59 | squScore.update(Tensors.of(currWaitTime, distEmpty)); 60 | effScore.update(Tensors.of(currWaitTime, distEmpty)); 61 | fltScore.update(currWaitTime, time); 62 | 63 | /** add score differences to history */ 64 | scoreDiffTable.appendRow(time, squScore.getScoreDiff(), effScore.getScoreDiff(), fltScore.getScoreDiff()); 65 | scoreIntgTable.appendRow(time, squScore.getScoreIntg(), effScore.getScoreIntg(), fltScore.getScoreIntg()); 66 | 67 | timeBefore = time; 68 | } 69 | 70 | /** @return incremental score */ 71 | public Tensor getScoreDiff() { 72 | return Tensors.of(squScore.getScoreDiff(), effScore.getScoreDiff(), fltScore.getScoreDiff()); 73 | } 74 | 75 | public Tensor getScoreDiffHistory() { 76 | return scoreDiffTable.getTable(); 77 | } 78 | 79 | public Tensor getScoreIntgHistory() { 80 | return scoreIntgTable.getTable(); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/SocketVehicleStatistic.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.LinkedList; 5 | import java.util.List; 6 | 7 | import amodeus.amodeus.dispatcher.core.RoboTaxi; 8 | import amodeus.amodeus.net.MatsimAmodeusDatabase; 9 | import amodeus.amodeus.net.VehicleContainer; 10 | import amodeus.amodeus.net.VehicleContainerUtils; 11 | import amodeus.amodeus.util.math.SI; 12 | import org.matsim.api.core.v01.network.Link; 13 | 14 | import ch.ethz.idsc.tensor.RationalScalar; 15 | import ch.ethz.idsc.tensor.Scalar; 16 | import ch.ethz.idsc.tensor.Tensor; 17 | import ch.ethz.idsc.tensor.Tensors; 18 | import ch.ethz.idsc.tensor.qty.Quantity; 19 | 20 | // TODO @joel small rounding errors compared to VehicleStatistic 21 | // ... find out where the differences come from and adapt 22 | /* package */ class SocketVehicleStatistic { 23 | private final MatsimAmodeusDatabase db; 24 | 25 | public SocketVehicleStatistic(MatsimAmodeusDatabase db) { 26 | this.db = db; 27 | } 28 | 29 | /** list is used as a buffer and is periodically emptied */ 30 | private final List list = new LinkedList<>(); 31 | private int lastLinkIndex = -1; 32 | 33 | /** @param vc 34 | * @return vector of length 2, entries have unit "m" */ 35 | Tensor distance(VehicleContainer vc) { 36 | Tensor distance = StaticHelper.ZEROS.copy(); 37 | if (vc.linkTrace[vc.linkTrace.length - 1] != lastLinkIndex) { 38 | distance = consolidate(); 39 | list.clear(); 40 | lastLinkIndex = vc.linkTrace[vc.linkTrace.length - 1]; 41 | } 42 | list.add(vc); 43 | return distance; 44 | } 45 | 46 | /** this function is called when the {@link RoboTaxi} has changed the link, then we can 47 | * register the distance covered by the vehicle on the previous link and associate it to 48 | * timesteps. The logic is that the distance is added evenly to the time steps. 49 | * 50 | * @return vector of length 2, entries have unit "m" */ 51 | public Tensor consolidate() { 52 | Scalar distDrive = Quantity.of(0, SI.METER); 53 | Scalar distEmpty = Quantity.of(0, SI.METER); 54 | if (!list.isEmpty()) { 55 | final int linkId = list.get(0).linkTrace[list.get(0).linkTrace.length - 1]; 56 | Link distanceLink = db.getOsmLink(linkId).link; 57 | /** this total distance on the link was travelled on during all simulationObjects stored 58 | * in the list. */ 59 | Scalar distance = Quantity.of(distanceLink.getLength(), SI.METER); 60 | 61 | int part = Math.toIntExact(list.stream().filter(VehicleContainerUtils::isDriving).count()); 62 | Scalar stepDistcontrib = distance.divide(RationalScalar.of(part, 1)); 63 | 64 | for (VehicleContainer vehicleContainer : list) { 65 | switch (VehicleContainerUtils.finalStatus(vehicleContainer)) { 66 | case DRIVEWITHCUSTOMER: 67 | distDrive = distDrive.add(stepDistcontrib); 68 | break; 69 | case DRIVETOCUSTOMER: 70 | distEmpty = distEmpty.add(stepDistcontrib); 71 | break; 72 | case REBALANCEDRIVE: 73 | distEmpty = distEmpty.add(stepDistcontrib); 74 | break; 75 | default: 76 | break; 77 | } 78 | } 79 | } 80 | return Tensors.of(distDrive, distEmpty); 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/core/StaticHelper.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.GlobalAssert; 5 | import amodeus.amodeus.util.math.SI; 6 | import ch.ethz.idsc.tensor.Scalars; 7 | import ch.ethz.idsc.tensor.Tensor; 8 | import ch.ethz.idsc.tensor.Tensors; 9 | import ch.ethz.idsc.tensor.alg.VectorQ; 10 | import ch.ethz.idsc.tensor.qty.Quantity; 11 | 12 | /* package */ enum StaticHelper { 13 | ; 14 | /** distances zero */ 15 | public static final Tensor ZEROS = Tensors.of(Quantity.of(0, SI.METER), Quantity.of(0, SI.METER)).unmodifiable(); 16 | 17 | /** check that score monotonously increasing with respect to time */ 18 | public static void requirePositiveOrZero(Tensor scoreAdd) { 19 | VectorQ.requireLength(scoreAdd, 3); 20 | GlobalAssert.that(Scalars.lessEquals(Quantity.of(0, SI.SECOND), scoreAdd.Get(0))); 21 | GlobalAssert.that(Scalars.lessEquals(Quantity.of(0, SI.METER), scoreAdd.Get(1))); 22 | GlobalAssert.that(Scalars.lessEquals(Quantity.of(0, SI.METER), scoreAdd.Get(2))); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/demo/DispatchingLogic.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.demo; 3 | 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | import java.util.SortedMap; 7 | import java.util.TreeMap; 8 | 9 | import amodeus.amodeus.dispatcher.core.RoboTaxiStatus; 10 | import ch.ethz.idsc.tensor.RealScalar; 11 | import ch.ethz.idsc.tensor.Scalar; 12 | import ch.ethz.idsc.tensor.Tensor; 13 | import ch.ethz.idsc.tensor.Tensors; 14 | import ch.ethz.idsc.tensor.pdf.Distribution; 15 | import ch.ethz.idsc.tensor.pdf.RandomVariate; 16 | import ch.ethz.idsc.tensor.pdf.UniformDistribution; 17 | import ch.ethz.idsc.tensor.sca.Round; 18 | 19 | /** dispatching logic in the SocketGuest demo to compute dispatching instructions 20 | * that are forwarded to the SocketHost */ 21 | /* package */ class DispatchingLogic { 22 | private final Set matchedReq = new HashSet<>(); 23 | private final Set matchedTax = new HashSet<>(); 24 | private final Distribution dist_lng; 25 | private final Distribution dist_lat; 26 | 27 | /** @param bottomLeft {lngMin, latMin} 28 | * @param topRight {lngMax, latMax} */ 29 | public DispatchingLogic(Tensor bottomLeft, Tensor topRight) { 30 | Scalar lngMin = bottomLeft.Get(0); 31 | Scalar lngMax = topRight.Get(0); 32 | Scalar latMin = bottomLeft.Get(1); 33 | Scalar latMax = topRight.Get(1); 34 | 35 | System.out.println("minimum longitude in network: " + lngMin); 36 | System.out.println("maximum longitude in network: " + lngMax); 37 | System.out.println("minimum latitude in network: " + latMin); 38 | System.out.println("maximum latitude in network: " + latMax); 39 | 40 | /** Example: 41 | * minimum longitude in network: -71.38020297181387 42 | * maximum longitude in network: -70.44406349551404 43 | * minimum latitude in network: -33.869660953686626 44 | * maximum latitude in network: -33.0303523690584 */ 45 | 46 | dist_lng = UniformDistribution.of(lngMin, lngMax); 47 | dist_lat = UniformDistribution.of(latMin, latMax); 48 | } 49 | 50 | public Tensor of(Tensor status) { 51 | Tensor pickup = Tensors.empty(); 52 | Tensor rebalance = Tensors.empty(); 53 | 54 | Scalar time = status.Get(0); 55 | if (Round.toMultipleOf(RealScalar.of(60)).apply(time).equals(time)) { // every minute 56 | int index = 0; 57 | 58 | /** sort requests according to submission time */ 59 | SortedMap requests = new TreeMap<>(); 60 | for (Tensor request : status.get(2)) { 61 | requests.put(request.Get(1), request); 62 | } 63 | 64 | /** for each unassigned request, add a taxi in STAY mode */ 65 | for (Tensor request : requests.values()) { 66 | if (!matchedReq.contains(request.Get(0))) { 67 | while (index < status.get(1).length()) { 68 | Tensor roboTaxi = status.get(1, index); 69 | if (RoboTaxiStatus.valueOf(roboTaxi.Get(2).toString())// 70 | .equals(RoboTaxiStatus.STAY)) { 71 | pickup.append(Tensors.of(roboTaxi.Get(0), request.Get(0))); 72 | matchedReq.add(request.Get(0)); 73 | matchedTax.add(roboTaxi.Get(0)); 74 | ++index; 75 | break; 76 | } 77 | ++index; 78 | } 79 | } 80 | } 81 | 82 | /** rebalance 1 of the remaining and unmatched STAY taxis */ 83 | for (int i = 0; i < status.get(1).length(); ++i) { 84 | Tensor roboTaxi = status.get(1, i); 85 | if (RoboTaxiStatus.valueOf(roboTaxi.Get(2).toString())// 86 | .equals(RoboTaxiStatus.STAY)) { 87 | if (!matchedTax.contains(roboTaxi.Get(0))) { 88 | Tensor rebalanceLocation = getRandomRebalanceLocation(); 89 | rebalance.append(Tensors.of(roboTaxi.Get(0), rebalanceLocation)); 90 | break; 91 | } 92 | } 93 | } 94 | } 95 | return Tensors.of(pickup, rebalance); 96 | } 97 | 98 | private Tensor getRandomRebalanceLocation() { 99 | /** ATTENTION: AMoDeus internally uses the convention 100 | * (longitude, latitude) for a WGS:84 pair, 101 | * not the other way around as in some other cases. */ 102 | return Tensors.of( // 103 | RandomVariate.of(dist_lng), // 104 | RandomVariate.of(dist_lat)); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/demo/SocketGuest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.demo; 3 | 4 | import java.io.IOException; 5 | import java.net.Socket; 6 | import java.net.UnknownHostException; 7 | import java.util.Objects; 8 | 9 | import amodeus.amodeus.util.math.GlobalAssert; 10 | import amodeus.amodeus.util.net.StringSocket; 11 | import amodeus.socket.SocketHost; 12 | import ch.ethz.idsc.tensor.RealScalar; 13 | import ch.ethz.idsc.tensor.Scalar; 14 | import ch.ethz.idsc.tensor.Scalars; 15 | import ch.ethz.idsc.tensor.Tensor; 16 | import ch.ethz.idsc.tensor.Tensors; 17 | import ch.ethz.idsc.tensor.io.StringScalar; 18 | 19 | /** SocketGuest is a simple demo client that interacts with SocketHost. 20 | * 21 | * Usage: 22 | * java -cp target/amod-VERSION.jar amod.socket.demo.SocketGuest [IP of host] */ 23 | public class SocketGuest { 24 | 25 | /** default values for demo */ 26 | static final String SCENARIO = "SanFrancisco"; 27 | static final int REQUEST_NUMBER_DESIRED = 500; 28 | static final int NUMBER_OF_VEHICLES = 20; 29 | private static final int PRINT_SCORE_PERIOD = 200; 30 | 31 | /** @param args 1 entry which is IP address 32 | * @throws Exception */ 33 | public static void main(String[] args) throws Exception { 34 | SocketGuest socketGuest = new SocketGuest(args.length == 0 ? "localhost" : args[0]); 35 | socketGuest.run(SCENARIO, REQUEST_NUMBER_DESIRED, NUMBER_OF_VEHICLES); 36 | } 37 | 38 | // --- 39 | 40 | private final String ip; 41 | 42 | /** @param ip for instance "localhost" */ 43 | public SocketGuest(String ip) { 44 | this.ip = ip; 45 | } 46 | 47 | public void run(String scenario, int requestsDesired, int numberOfVehicles) throws UnknownHostException, IOException, Exception { 48 | /** connect to SocketGuest */ 49 | try (StringSocket stringSocket = new StringSocket(new Socket(ip, SocketHost.PORT))) { 50 | /** send initial command, e.g., {SanFrancisco.20080518} */ 51 | Tensor config = Tensors.of(StringScalar.of(scenario)); /** scenario name */ 52 | stringSocket.writeln(config); 53 | 54 | /** receive information on chosen scenario, i.e., bounding box and number of 55 | * requests, the city grid is inside the WGS:84 coordinates bounded by the 56 | * box bottomLeft, topRight, 57 | * {{longitude min, latitude min}, {longitude max, latitude max}} */ 58 | Tensor scenarioInfo = Tensors.fromString(stringSocket.readLine()); 59 | Scalar numReq = (Scalar) scenarioInfo.get(0); 60 | Tensor bbox = scenarioInfo.get(1); 61 | Tensor bottomLeft = bbox.get(0); 62 | Tensor topRight = bbox.get(1); 63 | Scalar nominalFleetSize = (Scalar) scenarioInfo.get(2); 64 | 65 | /** chose number of Requests and fleet size */ 66 | Scalar numReqDes = RealScalar.of(requestsDesired); 67 | GlobalAssert.that(Scalars.lessEquals(numReqDes, numReq)); 68 | Scalar numRoboTaxi = RealScalar.of(numberOfVehicles); 69 | 70 | System.out.println("Nominal fleet size: " + nominalFleetSize); 71 | System.out.println("Chosen fleet size: " + numRoboTaxi); 72 | 73 | Tensor configSize = Tensors.of(numReqDes, numRoboTaxi); 74 | stringSocket.writeln(configSize); 75 | 76 | final DispatchingLogic dispatchingLogic; 77 | 78 | /** receive dispatching status and send dispatching command */ 79 | dispatchingLogic = new DispatchingLogic(bottomLeft, topRight); 80 | 81 | int count = 0; 82 | while (true) { 83 | String string = stringSocket.readLine(); 84 | if (Objects.nonNull(string)) { // when the server closed prematurely 85 | Tensor status = Tensors.fromString(string); 86 | if (Tensors.isEmpty(status)) // server signal that simulation is finished 87 | break; 88 | 89 | Tensor score = status.get(3); 90 | if (++count % PRINT_SCORE_PERIOD == 0) 91 | System.out.println("score = " + score + " at " + status.Get(0)); 92 | 93 | Tensor command = dispatchingLogic.of(status); 94 | stringSocket.writeln(command); 95 | } else { 96 | System.err.println("server terminated prematurely?"); 97 | break; 98 | } 99 | } 100 | 101 | /** receive final performance score/stats */ 102 | Tensor finalScores = Tensors.fromString(stringSocket.readLine()); 103 | System.out.println("final service quality score: " + finalScores.Get(0)); 104 | System.out.println("final efficiency score: " + finalScores.Get(1)); 105 | System.out.println("final fleet size score: " + finalScores.Get(2)); 106 | } // <- closing string socket 107 | } 108 | } 109 | -------------------------------------------------------------------------------- /src/main/java/amodeus/socket/demo/SocketStarterHelper.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.demo; 3 | 4 | import amodeus.socket.SocketHost; 5 | 6 | /** function starts {@link SocketHost} process and {@link SocketGuest} process 7 | * in different threads for testing. */ 8 | /* package */ enum SocketStarterHelper { 9 | ; 10 | 11 | public static void main(String[] args) throws Exception { 12 | /** {@link SocketHost} runs a simulation of an autonomous mobility-on-demand 13 | * system in the AMoDeus framework */ 14 | new Thread(new Runnable() { 15 | @Override 16 | public void run() { 17 | try { 18 | SocketHost.main(args); 19 | } catch (Exception exception) { 20 | exception.printStackTrace(); 21 | } 22 | } 23 | }).start(); 24 | 25 | Thread.sleep(1000); 26 | 27 | /** {@link SocketGuest} executes the dispatching logic encoded 28 | * in another programming language */ 29 | SocketGuest.main(args); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/python/.gitignore: -------------------------------------------------------------------------------- 1 | # python specific ignores 2 | __pycache__/ 3 | *.pyc 4 | *.pyo -------------------------------------------------------------------------------- /src/main/python/AidoGuest.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from DispatchingLogic import DispatchingLogic 3 | from utils.StringSocket import StringSocket 4 | 5 | 6 | class AidoGuest: 7 | """ 8 | AidoGuest is a simple demo client that interacts with AidoHost. 9 | """ 10 | 11 | # default values for demo 12 | SCENARIO = 'SanFrancisco.20080518' 13 | REQUEST_NUMBER_DESIRED = 500 14 | NUMBER_OF_VEHICLES = 20 15 | PRINT_SCORE_PERIOD = 200 16 | 17 | def __init__(self, ip='localhost'): 18 | """ 19 | :param ip: for instance "localhost" 20 | """ 21 | self.ip = ip 22 | 23 | def run(self): 24 | """connect to AidoGuest""" 25 | stringSocket = StringSocket(self.ip) 26 | # send initial command, e.g., {SanFrancisco.20080518} 27 | stringSocket.writeln('{%s}' % self.SCENARIO) # scenario name 28 | 29 | # receive information on chosen scenario, i.e., bounding box and number of requests, the city grid is 30 | # inside the WGS: 84 coordinates bounded by the box bottomLeft, topRight, 31 | # {{longitude min, latitude min}, {longitude max, latitude max}} 32 | numReq, bbox, nominalFleetSize = stringSocket.readLine() 33 | bottomLeft, topRight = bbox 34 | 35 | # chose number of Requests and fleet size 36 | assert self.REQUEST_NUMBER_DESIRED <= numReq 37 | print("Nominal fleet size:", nominalFleetSize) 38 | print("Chosen fleet size: ", self.NUMBER_OF_VEHICLES) 39 | 40 | configSize = [self.REQUEST_NUMBER_DESIRED, self.NUMBER_OF_VEHICLES] 41 | stringSocket.writeln(configSize) 42 | 43 | dispatchingLogic = DispatchingLogic(bottomLeft, topRight) 44 | 45 | # receive dispatching status and send dispatching command 46 | count = 0 47 | while True: 48 | status = stringSocket.readLine() 49 | if status == '': # when the server closed prematurely 50 | raise IOError("server terminated prematurely?") 51 | elif not status: # server signal that simulation is finished 52 | break 53 | else: 54 | count += 1 55 | score = status[3] 56 | if count % self.PRINT_SCORE_PERIOD: 57 | print("score = %s at %s" % (score, status[0])) 58 | 59 | command = dispatchingLogic.of(status) 60 | stringSocket.writeln(command) 61 | 62 | # receive final performance score/stats 63 | finalScores = stringSocket.readLine() 64 | print("final service quality score: ", finalScores[1]) 65 | print("final efficiency score: ", finalScores[2]) 66 | print("final fleet size score: ", finalScores[3]) 67 | 68 | stringSocket.close() 69 | 70 | 71 | if __name__ == '__main__': 72 | try: 73 | aidoGuest = AidoGuest(sys.argv[1]) 74 | except IndexError: 75 | aidoGuest = AidoGuest() 76 | aidoGuest.run() 77 | -------------------------------------------------------------------------------- /src/main/python/DispatchingLogic.py: -------------------------------------------------------------------------------- 1 | import random 2 | from utils.RoboTaxiStatus import RoboTaxiStatus 3 | 4 | 5 | class DispatchingLogic: 6 | """ 7 | dispatching logic in the AidoGuest demo to compute dispatching instructions that are forwarded to the AidoHost 8 | """ 9 | def __init__(self, bottomLeft, topRight): 10 | """ 11 | :param bottomLeft: {lngMin, latMin} 12 | :param topRight: {lngMax, latMax} 13 | """ 14 | self.lngMin = bottomLeft[0] 15 | self.lngMax = topRight[0] 16 | self.latMin = bottomLeft[1] 17 | self.latMax = topRight[1] 18 | 19 | print("minimum longitude in network: ", self.lngMin) 20 | print("maximum longitude in network: ", self.lngMax) 21 | print("minimum latitude in network: ", self.latMin) 22 | print("maximum latitude in network: ", self.latMax) 23 | 24 | # Example: 25 | # minimum longitude in network: -71.38020297181387 26 | # maximum longitude in network: -70.44406349551404 27 | # minimum latitude in network: -33.869660953686626 28 | # maximum latitude in network: -33.0303523690584 29 | 30 | self.matchedReq = set() 31 | self.matchedTax = set() 32 | 33 | def of(self, status): 34 | assert isinstance(status, list) 35 | pickup = [] 36 | rebalance = [] 37 | 38 | time = status[0] 39 | if time % 60 == 0: # every minute 40 | index = 0 41 | 42 | # sort requests according to submission time 43 | requests = sorted(status[2].copy(), key=lambda request: request[1]) 44 | 45 | # for each unassigned request, add a taxi in STAY mode 46 | for request in requests: 47 | if request[0] not in self.matchedReq: 48 | while index < len(status[1]): 49 | roboTaxi = status[1][index] 50 | if roboTaxi[2] is RoboTaxiStatus.STAY: 51 | pickup.append([roboTaxi[0], request[0]]) 52 | self.matchedReq.add(request[0]) 53 | self.matchedTax.add(roboTaxi[0]) 54 | index += 1 55 | break 56 | index += 1 57 | 58 | # rebalance 1 of the remaining and unmatched STAY taxis 59 | for roboTaxi in status[1]: 60 | if roboTaxi[2] is RoboTaxiStatus.STAY and roboTaxi[0] not in self.matchedTax: 61 | rebalanceLocation = self.getRandomRebalanceLocation() 62 | rebalance.append([roboTaxi[0], rebalanceLocation]) 63 | break 64 | 65 | return [pickup, rebalance] 66 | 67 | def getRandomRebalanceLocation(self): 68 | """ 69 | ATTENTION: AMoDeus internally uses the convention (longitude, latitude) for a WGS:84 pair, not the other way 70 | around as in some other cases. 71 | """ 72 | return [random.uniform(self.lngMin, self.lngMax), 73 | random.uniform(self.latMin, self.latMax)] 74 | -------------------------------------------------------------------------------- /src/main/python/utils/RoboTaxiStatus.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | 3 | 4 | class RoboTaxiStatus(Enum): 5 | DRIVEWITHCUSTOMER = 'DRIVEWITHCUSTOMER' 6 | DRIVETOCUSTOMER = 'DRIVETOCUSTOMER' 7 | REBALANCEDRIVE = 'REBALANCEDRIVE' 8 | STAY = 'STAY' 9 | OFFSERVICE = 'OFFSERVICE' 10 | 11 | @staticmethod 12 | def values(): 13 | return [e.value for e in RoboTaxiStatus] 14 | -------------------------------------------------------------------------------- /src/main/python/utils/StringSocket.py: -------------------------------------------------------------------------------- 1 | import socket 2 | from utils import Translator 3 | 4 | 5 | class StringSocket(socket.socket): 6 | def __init__(self, ip, port=9382): 7 | try: 8 | super(StringSocket, self).__init__(socket.AF_INET, socket.SOCK_STREAM) 9 | self.connect((ip, port)) 10 | except socket.error: 11 | raise IOError("Unable to create StringSocket!") 12 | self.buffer = '' 13 | 14 | def writeln(self, message): 15 | assert isinstance(message, (str, list)), "Input %s <%s> has to be string or list!" % (message, type(message)) 16 | msg = Translator.listToTensorString(message) if isinstance(message, list) else message 17 | self.sendall(str.encode(msg + '\n')) 18 | 19 | def readLine(self, buffer=4096): 20 | while '\n' not in self.buffer: 21 | self.buffer += self.recv(buffer).decode() 22 | lines = self.buffer.split('\n') 23 | line = lines.pop(0) 24 | self.buffer = '\n'.join(lines) 25 | return Translator.tensorStringToList(line) 26 | -------------------------------------------------------------------------------- /src/main/python/utils/Translator.py: -------------------------------------------------------------------------------- 1 | import ast 2 | import re 3 | from utils.RoboTaxiStatus import RoboTaxiStatus 4 | 5 | 6 | def tensorStringToList(string): 7 | """turn java tensor string representation into python list""" 8 | assert isinstance(string, str) 9 | # make string readable for ast.literal_eval 10 | s = re.sub(r" ?\[[^)]+\]", "", string).replace('{', '[').replace('}', ']').replace('-Infinity', "'-Infinity'") 11 | for status in RoboTaxiStatus.values(): 12 | s = s.replace(status, "'%s'" % status) 13 | # evaluate string 14 | try: 15 | array = ast.literal_eval(s) 16 | except (ValueError, SyntaxError): 17 | raise ValueError("Unable to translate '%s'!" % string) 18 | else: 19 | return replaceStatus(array) # insert meaningful values 20 | 21 | 22 | def listToTensorString(array): 23 | """turn python list into java tensor string representation""" 24 | assert isinstance(array, list) 25 | a = [listToTensorString(element) if isinstance(element, list) else element for element in array] 26 | return '{%s}' % ', '.join(list(map(str, a))) 27 | 28 | 29 | def replaceStatus(element): 30 | if isinstance(element, list): 31 | return [replaceStatus(e) for e in element] 32 | else: 33 | try: 34 | return RoboTaxiStatus[element] 35 | except KeyError: 36 | return element 37 | -------------------------------------------------------------------------------- /src/main/python/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amodeus-science/amod/0c238f983c9f636f516d35fa17a7d63c513eb44a/src/main/python/utils/__init__.py -------------------------------------------------------------------------------- /src/main/resources/.gitignore: -------------------------------------------------------------------------------- 1 | !.gitignore 2 | -------------------------------------------------------------------------------- /src/main/resources/dtd/av_v1.dtd: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 15 | 16 | 19 | 20 | 23 | 24 | 27 | -------------------------------------------------------------------------------- /src/main/resources/scenario/SanFrancisco/network_pt2matsim.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amodeus-science/amod/0c238f983c9f636f516d35fa17a7d63c513eb44a/src/main/resources/scenario/SanFrancisco/network_pt2matsim.zip -------------------------------------------------------------------------------- /src/main/resources/scenario/SanFrancisco/scenario.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/amodeus-science/amod/0c238f983c9f636f516d35fa17a7d63c513eb44a/src/main/resources/scenario/SanFrancisco/scenario.zip -------------------------------------------------------------------------------- /src/main/resources/socket/ScoreParameters.properties: -------------------------------------------------------------------------------- 1 | # 2008-09-07 2 | # file contains the score parameters used for aido amod championships 3 | 4 | # the weights for championships 1 and 2 are encoded as vectors 5 | # alpha12 = {alpha1, alpha2} 6 | # alpha34 = {alpha3, alpha4} 7 | 8 | 9 | # weights for championships 1 10 | alpha12 ={-25.0/1000000[s^-1], -1.0/1000000[m^-1]} 11 | 12 | # weights for championships 2 13 | alpha34 ={-24.0/1000000[s^-1], -4.0/1000000[m^-1]} 14 | 15 | # gamma is the standard fleet size as a fraction of the total number of requests 16 | gamma =0.025 17 | 18 | # championship 3 19 | # wmean is the mean wait time for the fleet reduction 20 | wmean =300.0[s] -------------------------------------------------------------------------------- /src/main/resources/socket/scenarios.properties: -------------------------------------------------------------------------------- 1 | Berlin =https://polybox.ethz.ch/index.php/s/vKrCSb8UFkxt2R0/download 2 | #https://polybox.ethz.ch/index.php/s/avFSUpgU673HmxH/download 3 | Santiago =https://polybox.ethz.ch/index.php/s/VuWHPwUL6TxujdK/download 4 | #https://polybox.ethz.ch/index.php/s/oZd3Kxn8dWEB5rI/download 5 | # TelAviv =https://polybox.ethz.ch/index.php/s/LtwfJ0boLBR6aSd/download 6 | #https://polybox.ethz.ch/index.php/s/l8pCtx1t7Ueb9f8/download 7 | SanFrancisco =https://polybox.ethz.ch/index.php/s/wnxkosFnIvVPoGJ/download 8 | 9 | # obsolete 10 | # _SanFrancisco =https://polybox.ethz.ch/index.php/s/AP9zPPk8wT4KWit/download 11 | 12 | # wrong linkSpeedDataFileName 13 | # _Santiago =https://polybox.ethz.ch/index.php/s/80AIOODRRAxNnf2/download 14 | # _TelAviv =https://polybox.ethz.ch/index.php/s/tXDJV07dMltqE8U/download 15 | SanFrancisco20200502 =https://polybox.ethz.ch/index.php/s/o5lsGffyRsspkJP/download -------------------------------------------------------------------------------- /src/test/java/amodeus/amod/DemoTest.java: -------------------------------------------------------------------------------- 1 | package amodeus.amod; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | import amodeus.amodeus.util.io.Locate; 7 | import amodeus.amodeus.util.io.MultiFileTools; 8 | import amodeus.amodeus.util.io.Unzip; 9 | import amodeus.amodtaxi.scenario.ScenarioCreation; 10 | import amodeus.amodtaxi.scenario.sanfrancisco.TraceFileChoice; 11 | import org.junit.AfterClass; 12 | import org.junit.Test; 13 | 14 | import ch.ethz.idsc.tensor.io.DeleteDirectory; 15 | 16 | public class DemoTest { 17 | 18 | @Test 19 | public void test() throws Exception { 20 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 21 | 22 | try { 23 | File map = new File(Locate.repoFolder(ScenarioCreator.class, "amod"), "src/main/resources/scenario/SanFrancisco/network_pt2matsim.zip"); 24 | Unzip.of(map, workingDirectory, false); 25 | } catch (IOException e) { 26 | e.printStackTrace(); 27 | } 28 | 29 | // 1 download scenario 30 | ScenarioCreation creation = ScenarioCreator.SAN_FRANCISCO.in(workingDirectory); 31 | // 2 run preparer 32 | ScenarioPreparer.run(creation.directory()); 33 | // 3 run server 34 | ScenarioServer.simulate(creation.directory()); 35 | } 36 | 37 | @AfterClass 38 | public static void cleanUp() throws IOException { 39 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 40 | new File(workingDirectory, "AmodeusOptions.properties").delete(); 41 | new File(workingDirectory, "LPOptions.properties").delete(); 42 | new File(workingDirectory, "config_full.xml").delete(); 43 | new File(workingDirectory, "map.osm").delete(); 44 | new File(workingDirectory, "network.xml").delete(); 45 | new File(workingDirectory, "network.xml.gz").delete(); 46 | new File(workingDirectory, "network_pt2matsim.xml").delete(); 47 | new File(workingDirectory, "pt2matsim_settings.xml").delete(); 48 | 49 | if (TraceFileChoice.DEFAULT_DATA.exists()) 50 | DeleteDirectory.of(TraceFileChoice.DEFAULT_DATA, 1, 5); 51 | 52 | DeleteDirectory.of(new File(workingDirectory, "Scenario"), 2, 14); 53 | DeleteDirectory.of(new File(workingDirectory, "2008-06-04"), 2, 14); 54 | DeleteDirectory.of(new File(workingDirectory, "output"), 5, 11000); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/amodeus/amod/ext/UserLocationSpecsTest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.amod.ext; 3 | 4 | import junit.framework.TestCase; 5 | 6 | public class UserLocationSpecsTest extends TestCase { 7 | public void testSimple() { 8 | assertNotNull(UserLocationSpecs.SANFRANCISCO.center()); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/SocketScenarioResourceTest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket; 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | import java.util.List; 7 | 8 | import amodeus.amodeus.util.io.MultiFileTools; 9 | import junit.framework.TestCase; 10 | 11 | public class SocketScenarioResourceTest extends TestCase { 12 | public void testLocal() throws IOException { 13 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 14 | List list = SocketScenarioResource.extract("SanFrancisco", workingDirectory); 15 | try { 16 | assertEquals(list.size(), 7); 17 | } finally { 18 | list.forEach(File::delete); 19 | } 20 | } 21 | 22 | public void testDownload() throws IOException { 23 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 24 | List list = SocketScenarioResource.extract("SanFrancisco", workingDirectory); 25 | try { 26 | assertEquals(list.size(), 7); 27 | } finally { 28 | list.forEach(File::delete); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/EfficiencyScoreTest.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.SI; 5 | import ch.ethz.idsc.tensor.NumberQ; 6 | import ch.ethz.idsc.tensor.qty.Quantity; 7 | import junit.framework.TestCase; 8 | 9 | public class EfficiencyScoreTest extends TestCase { 10 | public void testSimple() { 11 | EfficiencyScore efficiencyScore = new EfficiencyScore(ScoreParameters.GLOBAL); 12 | NumberQ.require(efficiencyScore.alpha.Get(0).multiply(Quantity.of(3, SI.SECOND))); 13 | NumberQ.require(efficiencyScore.alpha.Get(1).multiply(Quantity.of(3, SI.METER))); 14 | try { 15 | NumberQ.require(efficiencyScore.alpha.Get(1).multiply(Quantity.of(3, SI.SECOND))); 16 | fail(); 17 | } catch (Exception exception) { 18 | // --- 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/FleetSizeScoreTest.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.SI; 5 | import ch.ethz.idsc.tensor.Scalar; 6 | import ch.ethz.idsc.tensor.Tensor; 7 | import ch.ethz.idsc.tensor.Tensors; 8 | import ch.ethz.idsc.tensor.qty.Quantity; 9 | import ch.ethz.idsc.tensor.red.Total; 10 | import junit.framework.TestCase; 11 | 12 | public class FleetSizeScoreTest extends TestCase { 13 | 14 | public void testFulfill() { 15 | FleetSizeScore fsc = new FleetSizeScore(ScoreParameters.GLOBAL, 10, 27); 16 | Tensor sumDiff = Tensors.empty(); 17 | for (int i = 0; i < 10; ++i) { 18 | fsc.update(Quantity.of(100, SI.SECOND), Quantity.of(i, SI.SECOND)); 19 | sumDiff.append(fsc.getScoreDiff()); 20 | } 21 | assertEquals(-27, ((Scalar) Total.of(sumDiff)).number().intValue()); 22 | } 23 | 24 | public void testFail() { 25 | FleetSizeScore fsc = new FleetSizeScore(ScoreParameters.GLOBAL, 10, 27); 26 | Tensor sumDiff = Tensors.empty(); 27 | for (int i = 0; i < 10; ++i) { 28 | fsc.update(Quantity.of(500, SI.SECOND), Quantity.of(i, SI.SECOND)); 29 | sumDiff.append(fsc.getScoreDiff()); 30 | } 31 | assertEquals(Double.NEGATIVE_INFINITY, ((Scalar) Total.of(sumDiff)).number().doubleValue()); 32 | } 33 | 34 | public void testFail2() { 35 | FleetSizeScore fsc = new FleetSizeScore(ScoreParameters.GLOBAL, 10, 27); 36 | try { 37 | fsc.update(Quantity.of(-2, SI.SECOND), Quantity.of(2, SI.SECOND)); 38 | fail(); 39 | } catch (Exception exception) { 40 | // --- 41 | } 42 | try { 43 | fsc.update(Quantity.of(2, SI.SECOND), Quantity.of(-2, SI.SECOND)); 44 | fail(); 45 | } catch (Exception exception) { 46 | // --- 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/HttpDownloaderTest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | 7 | import amodeus.amodeus.util.io.ContentType; 8 | import ch.ethz.idsc.tensor.io.HomeDirectory; 9 | import ch.ethz.idsc.tensor.io.URLFetch; 10 | import junit.framework.TestCase; 11 | 12 | public class HttpDownloaderTest extends TestCase { 13 | public void testSimple() throws IOException { 14 | File file = HomeDirectory.file("favicon.ico"); 15 | assertFalse(file.exists()); 16 | 17 | try (URLFetch urlFetch = new URLFetch("http://www.djtascha.de/favicon.ico")) { 18 | ContentType.IMAGE_XICON.require(urlFetch.contentType()); 19 | urlFetch.download(file); 20 | } 21 | 22 | try { 23 | assertTrue(file.isFile()); 24 | } finally { 25 | file.delete(); 26 | } 27 | } 28 | 29 | public void testHttps() throws IOException { 30 | File file = HomeDirectory.file("scenario.zip"); 31 | System.out.println(file.getAbsolutePath()); 32 | assertFalse(file.exists()); 33 | 34 | boolean inactive = false; 35 | try (URLFetch urlFetch = new URLFetch("https://polybox.ethz.ch/index.php/s/o5lsGffyRsspkJP/download")) { 36 | ContentType.APPLICATION_ZIP.require(urlFetch.contentType()); 37 | urlFetch.download(file); 38 | } catch (IOException e) { 39 | if (e.getMessage().equals("503")) { 40 | System.err.println("currently no active competition"); 41 | inactive = true; 42 | } else throw e; 43 | } 44 | 45 | try { 46 | assertTrue(inactive || file.isFile()); 47 | } finally { 48 | file.delete(); 49 | } 50 | } 51 | 52 | public void testFail() { 53 | File file = HomeDirectory.file("scenario-does-not-exist.zip"); 54 | assertFalse(file.exists()); 55 | try { 56 | try (URLFetch urlFetch = new URLFetch( // 57 | "https://polybox.ethz.ch/index.php/s/C3QUuk3cuWWS1Gmy/download123")) { // 58 | ContentType.APPLICATION_ZIP.require(urlFetch.contentType()); 59 | } 60 | fail(); 61 | } catch (Exception exception) { 62 | // --- 63 | } 64 | assertFalse(file.exists()); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/ScoreParametersTest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.util.Properties; 5 | 6 | import ch.ethz.idsc.tensor.io.ResourceData; 7 | import junit.framework.TestCase; 8 | 9 | public class ScoreParametersTest extends TestCase { 10 | public void testScoreParam() { 11 | assertNotNull(ScoreParameters.GLOBAL); 12 | } 13 | 14 | public void testScenarios() { 15 | Properties properties = ResourceData.properties("/socket/scenarios.properties"); 16 | assertNotNull(properties); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/ServiceQualityScoreTest.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import amodeus.amodeus.util.math.SI; 5 | import ch.ethz.idsc.tensor.NumberQ; 6 | import ch.ethz.idsc.tensor.qty.Quantity; 7 | import junit.framework.TestCase; 8 | 9 | public class ServiceQualityScoreTest extends TestCase { 10 | public void testSimple() { 11 | ServiceQualityScore efficiencyScore = new ServiceQualityScore(ScoreParameters.GLOBAL); 12 | NumberQ.require(efficiencyScore.alpha.Get(0).multiply(Quantity.of(3, SI.SECOND))); 13 | NumberQ.require(efficiencyScore.alpha.Get(1).multiply(Quantity.of(3, SI.METER))); 14 | try { 15 | NumberQ.require(efficiencyScore.alpha.Get(1).multiply(Quantity.of(3, SI.SECOND))); 16 | fail(); 17 | } catch (Exception exception) { 18 | // --- 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/core/SocketScenarioDownloadTest.java: -------------------------------------------------------------------------------- 1 | /* amodeus - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.core; 3 | 4 | import java.io.File; 5 | import java.io.IOException; 6 | 7 | import amodeus.amodeus.util.io.MultiFileTools; 8 | import junit.framework.TestCase; 9 | 10 | public class SocketScenarioDownloadTest extends TestCase { 11 | public void testSimple() throws IOException { 12 | File workingDirectory = MultiFileTools.getDefaultWorkingDirectory(); 13 | File file = new File(workingDirectory, "scenario.zip"); // <3MB 14 | assertFalse(file.exists()); 15 | 16 | boolean inactive = false; 17 | try { 18 | SocketScenarioDownload.of("SanFrancisco", file); 19 | } catch (IOException e) { 20 | if (e.getMessage().equals("503")) { 21 | System.err.println("currently no active competition"); 22 | inactive = true; 23 | } else throw e; 24 | } 25 | 26 | try { 27 | assertTrue(inactive || file.isFile()); 28 | } finally { 29 | file.delete(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/amodeus/socket/demo/SocketGuestTest.java: -------------------------------------------------------------------------------- 1 | /* amod - Copyright (c) 2018, ETH Zurich, Institute for Dynamic Systems and Control */ 2 | package amodeus.socket.demo; 3 | 4 | import ch.ethz.idsc.tensor.RealScalar; 5 | import ch.ethz.idsc.tensor.Tensor; 6 | import ch.ethz.idsc.tensor.Tensors; 7 | import ch.ethz.idsc.tensor.io.StringScalar; 8 | import junit.framework.TestCase; 9 | 10 | public class SocketGuestTest extends TestCase { 11 | public void testSimple() { 12 | Tensor config = Tensors.of( // 13 | StringScalar.of(SocketGuest.SCENARIO), // scenario name 14 | RealScalar.of(SocketGuest.REQUEST_NUMBER_DESIRED), // ratio of population 15 | RealScalar.of(SocketGuest.NUMBER_OF_VEHICLES)); // number of vehicles 16 | assertEquals(config.toString().indexOf('\"'), -1); 17 | } 18 | } 19 | --------------------------------------------------------------------------------