View Javadoc
1   package org.opentrafficsim.aimsun;
2   
3   import java.awt.Dimension;
4   import java.io.ByteArrayInputStream;
5   import java.io.File;
6   import java.io.IOException;
7   import java.io.Serializable;
8   import java.net.URISyntaxException;
9   import java.nio.charset.StandardCharsets;
10  import java.nio.file.Files;
11  import java.nio.file.Paths;
12  import java.util.LinkedHashMap;
13  import java.util.Map;
14  
15  import javax.naming.NamingException;
16  import javax.swing.JFileChooser;
17  import javax.swing.JOptionPane;
18  import javax.swing.filechooser.FileFilter;
19  import javax.xml.bind.JAXBException;
20  import javax.xml.parsers.ParserConfigurationException;
21  
22  import org.djunits.value.vdouble.scalar.Duration;
23  import org.djunits.value.vdouble.scalar.Length;
24  import org.djunits.value.vdouble.scalar.Time;
25  import org.opentrafficsim.core.dsol.AbstractOTSModel;
26  import org.opentrafficsim.core.dsol.OTSLoggingAnimator;
27  import org.opentrafficsim.core.dsol.OTSModelInterface;
28  import org.opentrafficsim.core.dsol.OTSSimulationException;
29  import org.opentrafficsim.core.dsol.OTSSimulatorInterface;
30  import org.opentrafficsim.core.geometry.OTSGeometryException;
31  import org.opentrafficsim.core.gtu.GTUException;
32  import org.opentrafficsim.core.gtu.GTUType;
33  import org.opentrafficsim.core.network.NetworkException;
34  import org.opentrafficsim.draw.core.OTSDrawingException;
35  import org.opentrafficsim.road.network.OTSRoadNetwork;
36  import org.opentrafficsim.road.network.factory.xml.XmlParserException;
37  import org.opentrafficsim.road.network.factory.xml.parser.XmlNetworkLaneParser;
38  import org.opentrafficsim.road.network.lane.CrossSectionLink;
39  import org.opentrafficsim.road.network.lane.conflict.ConflictBuilder;
40  import org.opentrafficsim.road.network.lane.conflict.LaneCombinationList;
41  import org.opentrafficsim.swing.gui.OTSAnimationPanel;
42  import org.opentrafficsim.swing.gui.OTSSimulationApplication;
43  import org.opentrafficsim.trafficcontrol.TrafficControlException;
44  import org.xml.sax.SAXException;
45  
46  import nl.tudelft.simulation.dsol.SimRuntimeException;
47  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterException;
48  import nl.tudelft.simulation.jstats.streams.MersenneTwister;
49  import nl.tudelft.simulation.jstats.streams.StreamInterface;
50  import nl.tudelft.simulation.language.DSOLException;
51  
52  /**
53   * Select a OTS-network XML file, load it and run it.
54   * <p>
55   * Copyright (c) 2013-2020 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
56   * BSD-style license. See <a href="http://opentrafficsim.org/node/13">OpenTrafficSim License</a>.
57   * <p>
58   * @version $Revision$, $LastChangedDate$, by $Author$, initial version Apr 21, 2017 <br>
59   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
60   * @author <a href="http://www.tudelft.nl/pknoppers">Peter Knoppers</a>
61   * @author <a href="http://www.transport.citg.tudelft.nl">Wouter Schakel</a>
62   */
63  public class LoadXML extends OTSSimulationApplication<OTSModelInterface>
64  {
65      /** */
66      private static final long serialVersionUID = 20170421L;
67  
68      /**
69       * @param model OTSModelInterface; the model
70       * @param animationPanel OTSAnimationPanel; the animation panel
71       * @throws OTSDrawingException on drawing error
72       */
73      public LoadXML(final OTSModelInterface model, final OTSAnimationPanel animationPanel) throws OTSDrawingException
74      {
75          super(model, animationPanel);
76      }
77  
78      /**
79       * Load a network from an XML file; program entry point.
80       * @param args String[]; the command line arguments; optional name of file to load
81       * @throws IOException when the file could not be read
82       * @throws InputParameterException should never happen
83       * @throws OTSSimulationException when an error occurs during simulation
84       * @throws NamingException when a name collision is detected
85       * @throws SimRuntimeException should never happen
86       */
87      public static void main(final String[] args)
88              throws IOException, SimRuntimeException, NamingException, OTSSimulationException, InputParameterException
89      {
90          // TODO: LaneOperationalPlanBuilder.INSTANT_LANE_CHANGES = false;
91          String fileName;
92          String xml;
93          if (0 == args.length)
94          {
95              JFileChooser fileChooser = new JFileChooser();
96              fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
97              fileChooser.addChoosableFileFilter(new FileFilter()
98              {
99  
100                 @Override
101                 public boolean accept(final File f)
102                 {
103                     if (f.isDirectory())
104                     {
105                         return true;
106                     }
107                     String name = f.getName();
108                     int length = name.length();
109                     if (length < 5)
110                     {
111                         return false;
112                     }
113                     String type = name.substring(length - 4);
114                     return type.equalsIgnoreCase(".xml");
115                 }
116 
117                 @Override
118                 public String getDescription()
119                 {
120                     return "XML files";
121                 }
122             });
123             fileChooser.removeChoosableFileFilter(fileChooser.getAcceptAllFileFilter());
124             if (JFileChooser.APPROVE_OPTION != fileChooser.showOpenDialog(null))
125             {
126                 System.out.println("No file chosen; exiting");
127                 System.exit(0);
128             }
129             fileName = fileChooser.getSelectedFile().getAbsolutePath();
130         }
131         else
132         {
133             fileName = args[0];
134         }
135         xml = new String(Files.readAllBytes(Paths.get(fileName)));
136         try
137         {
138             OTSLoggingAnimator simulator = new OTSLoggingAnimator("C:/Temp/loadXMLeventlog.txt", "LoadXML");
139             XMLModel xmlModel = new XMLModel(simulator, "XML model", "Model built from XML file " + fileName, xml);
140             Map<String, StreamInterface> map = new LinkedHashMap<>();
141             // TODO: This seed is Aimsun specific.
142             map.put("generation", new MersenneTwister(6L));
143             simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(3600.0), xmlModel, map);
144             OTSAnimationPanel animationPanel = new OTSAnimationPanel(xmlModel.getNetwork().getExtent(), new Dimension(800, 600),
145                     simulator, xmlModel, DEFAULT_COLORER, xmlModel.getNetwork());
146             new LoadXML(xmlModel, animationPanel);
147         }
148         catch (SimRuntimeException | OTSDrawingException | DSOLException sre)
149         {
150             JOptionPane.showMessageDialog(null, sre.getMessage(), "Exception occured", JOptionPane.ERROR_MESSAGE);
151             System.exit(1);
152         }
153     }
154 
155     /**
156      * The Model.
157      */
158     static class XMLModel extends AbstractOTSModel
159     {
160         /** */
161         private static final long serialVersionUID = 20170421L;
162 
163         /** The network. */
164         private OTSRoadNetwork network;
165 
166         /** The XML. */
167         private final String xml;
168 
169         /**
170          * @param simulator OTSSimulatorInterface; the simulator
171          * @param shortName String; name of the model
172          * @param description String; description of the model
173          * @param xml String; the XML string
174          */
175         XMLModel(final OTSSimulatorInterface simulator, final String shortName, final String description, final String xml)
176         {
177             super(simulator, shortName, description);
178             this.xml = xml;
179         }
180 
181         /** {@inheritDoc} */
182         @Override
183         public void constructModel() throws SimRuntimeException
184         {
185             this.network = new OTSRoadNetwork(getShortName(), true, getSimulator());
186             try
187             {
188                 XmlNetworkLaneParser.build(new ByteArrayInputStream(this.xml.getBytes(StandardCharsets.UTF_8)), this.network,
189                         false);
190                 // TODO: These links are Aimsun specific.
191                 LaneCombinationList ignoreList = new LaneCombinationList();
192                 ignoreList.addLinkCombination((CrossSectionLink) this.network.getLink("928_J5"),
193                         (CrossSectionLink) this.network.getLink("928_J6"));
194                 ignoreList.addLinkCombination((CrossSectionLink) this.network.getLink("925_J1"),
195                         (CrossSectionLink) this.network.getLink("925_J2"));
196                 LaneCombinationList permittedList = new LaneCombinationList();
197                 ConflictBuilder.buildConflictsParallel(this.network, this.network.getGtuType(GTUType.DEFAULTS.VEHICLE),
198                         getSimulator(), new ConflictBuilder.FixedWidthGenerator(Length.instantiateSI(2.0)), ignoreList,
199                         permittedList);
200                 // new GTUDumper(simulator, Time.ZERO, Duration.instantiateSI(60), network, "C:/Temp/loadxml");
201             }
202             catch (NetworkException | OTSGeometryException | JAXBException | URISyntaxException | XmlParserException
203                     | SAXException | ParserConfigurationException | GTUException | IOException
204                     | TrafficControlException exception)
205             {
206                 exception.printStackTrace();
207                 // Abusing the SimRuntimeException to propagate the message to the main method (the problem could actually be a
208                 // parsing problem)
209                 throw new SimRuntimeException(exception.getMessage());
210             }
211         }
212 
213         /** {@inheritDoc} */
214         @Override
215         public OTSRoadNetwork getNetwork()
216         {
217             return this.network;
218         }
219 
220         /** {@inheritDoc} */
221         @Override
222         public Serializable getSourceId()
223         {
224             return "XMLModel";
225         }
226 
227     }
228 
229 }