View Javadoc
1   package org.opentrafficsim.demo;
2   
3   import java.awt.Dimension;
4   import java.awt.event.ActionEvent;
5   import java.rmi.RemoteException;
6   import java.util.ArrayList;
7   import java.util.List;
8   
9   import javax.naming.NamingException;
10  import javax.swing.Box;
11  import javax.swing.ButtonGroup;
12  import javax.swing.JLabel;
13  import javax.swing.JOptionPane;
14  import javax.swing.JPanel;
15  import javax.swing.JRadioButton;
16  
17  import org.djunits.unit.util.UNITS;
18  import org.djunits.value.vdouble.scalar.Duration;
19  import org.djunits.value.vdouble.scalar.Time;
20  import org.opentrafficsim.core.dsol.OtsAnimator;
21  import org.opentrafficsim.core.dsol.OtsSimulatorInterface;
22  import org.opentrafficsim.core.network.NetworkException;
23  import org.opentrafficsim.draw.core.OtsDrawingException;
24  import org.opentrafficsim.draw.graphs.GraphPath;
25  import org.opentrafficsim.draw.graphs.TrajectoryPlot;
26  import org.opentrafficsim.draw.graphs.road.GraphLaneUtil;
27  import org.opentrafficsim.road.network.RoadNetwork;
28  import org.opentrafficsim.road.network.lane.Lane;
29  import org.opentrafficsim.road.network.sampling.LaneDataRoad;
30  import org.opentrafficsim.road.network.sampling.RoadSampler;
31  import org.opentrafficsim.swing.graphs.SwingPlot;
32  import org.opentrafficsim.swing.gui.OtsAnimationPanel;
33  import org.opentrafficsim.swing.gui.OtsSimulationApplication;
34  
35  import nl.tudelft.simulation.dsol.SimRuntimeException;
36  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameter;
37  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterMap;
38  import nl.tudelft.simulation.dsol.model.inputparameters.InputParameterSelectionMap;
39  import nl.tudelft.simulation.dsol.swing.gui.TablePanel;
40  import nl.tudelft.simulation.dsol.swing.gui.inputparameters.AbstractInputField;
41  import nl.tudelft.simulation.dsol.swing.gui.inputparameters.InputField;
42  import nl.tudelft.simulation.dsol.swing.gui.inputparameters.TabbedParameterDialog;
43  import nl.tudelft.simulation.language.DSOLException;
44  
45  /**
46   * Simplest contour plots demonstration.
47   * <p>
48   * Copyright (c) 2013-2023 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
49   * BSD-style license. See <a href="https://opentrafficsim.org/docs/license.html">OpenTrafficSim License</a>.
50   * </p>
51   * @author <a href="https://tudelft.nl/staff/p.knoppers-1">Peter Knoppers</a>
52   */
53  public class NetworksSwing extends OtsSimulationApplication<NetworksModel> implements UNITS
54  {
55      /** */
56      private static final long serialVersionUID = 1L;
57  
58      /**
59       * Create a Networks Swing application.
60       * @param title String; the title of the Frame
61       * @param panel OtsAnimationPanel; the tabbed panel to display
62       * @param model NetworksModel; the model
63       * @throws OtsDrawingException on animation error
64       */
65      public NetworksSwing(final String title, final OtsAnimationPanel panel, final NetworksModel model)
66              throws OtsDrawingException
67      {
68          super(model, panel);
69          RoadNetwork network = model.getNetwork();
70          System.out.println(network.getLinkMap());
71      }
72  
73      /** {@inheritDoc} */
74      @Override
75      protected void addTabs()
76      {
77          addStatisticsTabs(getModel().getSimulator());
78      }
79  
80      /**
81       * Main program.
82       * @param args String[]; the command line arguments (not used)
83       */
84      public static void main(final String[] args)
85      {
86          demo(true);
87      }
88  
89      /**
90       * Start the demo.
91       * @param exitOnClose boolean; when running stand-alone: true; when running as part of a demo: false
92       */
93      public static void demo(final boolean exitOnClose)
94      {
95          try
96          {
97              OtsAnimator simulator = new OtsAnimator("NetworksSwing");
98              final NetworksModel otsModel = new NetworksModel(simulator);
99              if (NetworksParameterDialog.process(otsModel.getInputParameterMap()))
100             {
101                 simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(3600.0), otsModel);
102                 OtsAnimationPanel animationPanel = new OtsAnimationPanel(otsModel.getNetwork().getExtent(),
103                         new Dimension(800, 600), simulator, otsModel, DEFAULT_COLORER, otsModel.getNetwork());
104                 NetworksSwing app = new NetworksSwing("Networks", animationPanel, otsModel);
105                 app.setExitOnClose(exitOnClose);
106                 animationPanel.enableSimulationControlButtons();
107             }
108             else
109             {
110                 if (exitOnClose)
111                 {
112                     System.exit(0);
113                 }
114             }
115         }
116         catch (SimRuntimeException | NamingException | RemoteException | OtsDrawingException | DSOLException exception)
117         {
118             exception.printStackTrace();
119         }
120     }
121 
122     /**
123      * Add the statistics tabs.
124      * @param simulator OtsSimulatorInterface; the simulator on which sampling can be scheduled
125      */
126     protected final void addStatisticsTabs(final OtsSimulatorInterface simulator)
127     {
128         int graphCount = getModel().pathCount();
129         int columns = 1;
130         int rows = 0 == columns ? 0 : (int) Math.ceil(graphCount * 1.0 / columns);
131         TablePanel charts = new TablePanel(columns, rows);
132         RoadSampler sampler = new RoadSampler(getModel().getNetwork());
133         Duration updateInterval = Duration.instantiateSI(10.0);
134         for (int graphIndex = 0; graphIndex < graphCount; graphIndex++)
135         {
136             List<Lane> start = new ArrayList<>();
137             start.add(getModel().getPath(graphIndex).get(0));
138             GraphPath<LaneDataRoad> path;
139             try
140             {
141                 path = GraphLaneUtil.createPath("name", start.get(0));
142             }
143             catch (NetworkException exception)
144             {
145                 throw new RuntimeException(exception);
146             }
147             GraphPath.initRecording(sampler, path);
148             SwingPlot plot = new SwingPlot(new TrajectoryPlot("Trajectories on lane " + (graphIndex + 1), updateInterval,
149                     simulator, sampler.getSamplerData(), path));
150             charts.setCell(plot.getContentPane(), graphIndex % columns, graphIndex / columns);
151         }
152 
153         getAnimationPanel().getTabbedPane().addTab(getAnimationPanel().getTabbedPane().getTabCount(), "statistics ", charts);
154     }
155 
156     /** A parameter dialog with a radio button for the network choice tab. */
157     private static class NetworksParameterDialog extends TabbedParameterDialog
158     {
159         /** */
160         private static final long serialVersionUID = 1L;
161 
162         /**
163          * @param inputParameterMap InputParameterMap; the parameter map to display
164          */
165         NetworksParameterDialog(final InputParameterMap inputParameterMap)
166         {
167             super(inputParameterMap);
168         }
169 
170         /** {@inheritDoc} */
171         @SuppressWarnings({"rawtypes", "unchecked"})
172         @Override
173         public void addParameterField(final JPanel panel, final InputParameter<?, ?> parameter)
174         {
175             if (parameter instanceof InputParameterSelectionMap<?, ?>)
176             {
177                 this.fields.add(new InputFieldSelectionMapRadio(panel, (InputParameterSelectionMap<?, ?>) parameter));
178             }
179             else
180             {
181                 super.addParameterField(panel, parameter);
182             }
183         }
184 
185         /** {@inheritDoc} */
186         @Override
187         public void actionPerformed(final ActionEvent e)
188         {
189             boolean ok = true;
190             try
191             {
192                 for (InputField field : this.fields)
193                 {
194                     if (field instanceof InputFieldSelectionMapRadio<?, ?>)
195                     {
196                         InputFieldSelectionMapRadio<?, ?> f = (InputFieldSelectionMapRadio<?, ?>) field;
197                         f.getParameter().setObjectValue(f.getValue());
198                     }
199                 }
200             }
201             catch (Exception exception)
202             {
203                 JOptionPane.showMessageDialog(null, exception.getMessage(), "Data Entry Error", JOptionPane.ERROR_MESSAGE);
204                 ok = false;
205             }
206             if (ok)
207             {
208                 super.actionPerformed(e);
209             }
210         }
211 
212         /**
213          * Construct a tabbed parameter dialog that is not a part of a higher dialog.
214          * @param inputParameterMap InputParameterMap; the parameter map to use
215          * @return whether the data was entered correctly or not
216          */
217         public static boolean process(final InputParameterMap inputParameterMap)
218         {
219             NetworksParameterDialog dialog = new NetworksParameterDialog(inputParameterMap);
220             return !dialog.stopped;
221         }
222     }
223 
224     /**
225      * Radio button selection map.
226      * @param <K> key of the selection map
227      * @param <T> return type of the selection map
228      */
229     public static class InputFieldSelectionMapRadio<K, T> extends AbstractInputField
230     {
231         /** combo box for the user interface. */
232         private List<JRadioButton> buttons = new ArrayList<>();
233 
234         /** combo box for the user interface. */
235         private List<T> values = new ArrayList<>();
236 
237         /**
238          * Create a string field on the screen.
239          * @param panel JPanel; panel to add the field to
240          * @param parameter InputParameterSelectionMap&lt;K,T&gt;; the parameter
241          */
242         public InputFieldSelectionMapRadio(final JPanel panel, final InputParameterSelectionMap<K, T> parameter)
243         {
244             super(parameter);
245             Box box = Box.createVerticalBox();
246             box.add(new JLabel("  "));
247             box.add(new JLabel(parameter.getShortName()));
248             ButtonGroup group = new ButtonGroup();
249             for (K option : parameter.getOptions().keySet())
250             {
251                 String item = option.toString();
252                 T value = parameter.getOptions().get(option);
253                 JRadioButton button = new JRadioButton(item);
254                 button.setActionCommand(item);
255                 if (value.equals(parameter.getDefaultValue()))
256                 {
257                     button.setSelected(true);
258                 }
259                 group.add(button);
260                 box.add(button);
261                 this.buttons.add(button);
262                 this.values.add(value);
263             }
264             panel.add(box);
265         }
266 
267         /** {@inheritDoc} */
268         @SuppressWarnings("unchecked")
269         @Override
270         public InputParameterSelectionMap<K, T> getParameter()
271         {
272             return (InputParameterSelectionMap<K, T>) super.getParameter();
273         }
274 
275         /** @return the mapped value of the field in the gui, selected by the key's toString() value. */
276         public T getValue()
277         {
278             for (JRadioButton button : this.buttons)
279             {
280                 if (button.isSelected())
281                 {
282                     System.out.println("SELECTED: " + this.values.get(this.buttons.indexOf(button)));
283                     return this.values.get(this.buttons.indexOf(button));
284                 }
285             }
286             return this.values.get(0);
287         }
288     }
289 }