The following document contains the results of PMD's CPD 6.13.0.
File | Line |
---|---|
org\opentrafficsim\demo\web\OTSDemoServer.java | 429 |
org\opentrafficsim\demo\web\OTSFederatedDemoServer.java | 309 |
this.webServer.sessionWebModelMap.get(sessionId).handle(target, baseRequest, request, response); } else if (this.webServer.sessionModelMap.containsKey(sessionId)) { OTSModelInterface model = this.webServer.sessionModelMap.get(sessionId); String answer = "<message>ok</message>"; if (request.getParameter("message") != null) { String message = request.getParameter("message"); String[] parts = message.split("\\|"); String command = parts[0]; switch (command) { case "getTitle": { answer = "<title>" + model.getShortName() + "</title>"; break; } case "getParameterMap": { answer = makeParameterMap(model); break; } case "setParameters": { answer = setParameters(model, message); break; } default: { System.err.println("Got unknown message from client: " + command); answer = "<message>" + request.getParameter("message") + "</message>"; break; } } } response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.setContentLength(answer.length()); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write(answer); response.flushBuffer(); baseRequest.setHandled(true); } } } /** * Make the parameter set that can be interpreted by the parameters.html page. * @param model the model with parameters * @return an XML string with the parameters */ private String makeParameterMap(final OTSModelInterface model) { StringBuffer answer = new StringBuffer(); answer.append("<parameters>\n"); InputParameterMap inputParameterMap = model.getInputParameterMap(); for (InputParameter<?, ?> tab : inputParameterMap.getSortedSet()) { if (!(tab instanceof InputParameterMap)) { System.err.println("Input parameter " + tab.getShortName() + " cannot be displayed in a tab"); } else { answer.append("<tab>" + tab.getDescription() + "</tab>\n"); InputParameterMap tabbedMap = (InputParameterMap) tab; for (InputParameter<?, ?> parameter : tabbedMap.getSortedSet()) { addParameterField(answer, parameter); } } } answer.append("</parameters>\n"); return answer.toString(); } /** * Add the right type of field for this parameter to the string buffer. * @param answer StringBuffer; the buffer to add the XML-info for the parameter * @param parameter InputParameter<?,?>; the input parameter to display */ public void addParameterField(final StringBuffer answer, final InputParameter<?, ?> parameter) { if (parameter instanceof InputParameterDouble) { InputParameterDouble pd = (InputParameterDouble) parameter; answer.append("<double key='" + pd.getExtendedKey() + "' name='" + pd.getShortName() + "' description='" + pd.getDescription() + "'>" + pd.getValue() + "</double>\n"); } else if (parameter instanceof InputParameterFloat) { InputParameterFloat pf = (InputParameterFloat) parameter; answer.append("<float key='" + pf.getExtendedKey() + "' name='" + pf.getShortName() + "' description='" + pf.getDescription() + "'>" + pf.getValue() + "</float>\n"); } else if (parameter instanceof InputParameterBoolean) { InputParameterBoolean pb = (InputParameterBoolean) parameter; answer.append("<boolean key='" + pb.getExtendedKey() + "' name='" + pb.getShortName() + "' description='" + pb.getDescription() + "'>" + pb.getValue() + "</boolean>\n"); } else if (parameter instanceof InputParameterLong) { InputParameterLong pl = (InputParameterLong) parameter; answer.append("<long key='" + pl.getExtendedKey() + "' name='" + pl.getShortName() + "' description='" + pl.getDescription() + "'>" + pl.getValue() + "</long>\n"); } else if (parameter instanceof InputParameterInteger) { InputParameterInteger pi = (InputParameterInteger) parameter; answer.append("<integer key='" + pi.getExtendedKey() + "' name='" + pi.getShortName() + "' description='" + pi.getDescription() + "'>" + pi.getValue() + "</integer>\n"); } else if (parameter instanceof InputParameterString) { InputParameterString ps = (InputParameterString) parameter; answer.append("<string key='" + ps.getExtendedKey() + "' name='" + ps.getShortName() + "' description='" + ps.getDescription() + "'>" + ps.getValue() + "</string>\n"); } else if (parameter instanceof InputParameterDoubleScalar) { InputParameterDoubleScalar<?, ?> pds = (InputParameterDoubleScalar<?, ?>) parameter; String val = getValueInUnit(pds); List<String> units = getUnits(pds); answer.append("<doubleScalar key='" + pds.getExtendedKey() + "' name='" + pds.getShortName() + "' description='" + pds.getDescription() + "'><value>" + val + "</value>\n"); for (String unit : units) { Unit<?> unitValue = pds.getUnitParameter().getOptions().get(unit); if (unitValue.equals(pds.getUnitParameter().getValue())) answer.append("<unit chosen='true'>" + unit + "</unit>\n"); else answer.append("<unit chosen='false'>" + unit + "</unit>\n"); } answer.append("</doubleScalar>\n"); } else if (parameter instanceof InputParameterFloatScalar) { InputParameterFloatScalar<?, ?> pds = (InputParameterFloatScalar<?, ?>) parameter; String val = getValueInUnit(pds); List<String> units = getUnits(pds); answer.append("<floatScalar key='" + pds.getExtendedKey() + "' name='" + pds.getShortName() + "' description='" + pds.getDescription() + "'><value>" + val + "</value>\n"); for (String unit : units) { Unit<?> unitValue = pds.getUnitParameter().getOptions().get(unit); if (unitValue.equals(pds.getUnitParameter().getValue())) answer.append("<unit chosen='true'>" + unit + "</unit>\n"); else answer.append("<unit chosen='false'>" + unit + "</unit>\n"); } answer.append("</floatScalar>\n"); } else if (parameter instanceof InputParameterSelectionList<?>) { // TODO InputParameterSelectionList } else if (parameter instanceof InputParameterDistDiscreteSelection) { // TODO InputParameterSelectionList } else if (parameter instanceof InputParameterDistContinuousSelection) { // TODO InputParameterDistContinuousSelection } else if (parameter instanceof InputParameterSelectionMap<?, ?>) { // TODO InputParameterSelectionMap } } /** * @param <U> the unit * @param <T> the scalar type * @param parameter double scalar input parameter * @return default value in the unit */ private <U extends Unit<U>, T extends AbstractDoubleScalar<U, T>> String getValueInUnit(final InputParameterDoubleScalar<U, T> parameter) { return "" + parameter.getDefaultTypedValue().getInUnit(parameter.getDefaultTypedValue().getDisplayUnit()); } /** * @param <U> the unit * @param <T> the scalar type * @param parameter double scalar input parameter * @return abbreviations for the units */ private <U extends Unit<U>, T extends AbstractDoubleScalar<U, T>> List<String> getUnits(final InputParameterDoubleScalar<U, T> parameter) { List<String> unitList = new ArrayList<>(); for (String option : parameter.getUnitParameter().getOptions().keySet()) { unitList.add(option.toString()); } return unitList; } /** * @param <U> the unit * @param <T> the scalar type * @param parameter double scalar input parameter * @return default value in the unit */ private <U extends Unit<U>, T extends AbstractFloatScalar<U, T>> String getValueInUnit(final InputParameterFloatScalar<U, T> parameter) { return "" + parameter.getDefaultTypedValue().getInUnit(parameter.getDefaultTypedValue().getDisplayUnit()); } /** * @param <U> the unit * @param <T> the scalar type * @param parameter double scalar input parameter * @return abbreviations for the units */ private <U extends Unit<U>, T extends AbstractFloatScalar<U, T>> List<String> getUnits(final InputParameterFloatScalar<U, T> parameter) { List<String> unitList = new ArrayList<>(); for (String option : parameter.getUnitParameter().getOptions().keySet()) { unitList.add(option.toString()); } return unitList; } /** * Make the parameter set that can be interpreted by the parameters.html page. * @param model the model with parameters * @param message the key-value pairs of the set parameters * @return the errors if they are detected. If none, errors is set to "OK" */ private String setParameters(final OTSModelInterface model, final String message) { String errors = "OK"; InputParameterMap inputParameters = model.getInputParameterMap(); String[] parts = message.split("\\|"); Map<String, String> unitMap = new LinkedHashMap<>(); for (int i = 1; i < parts.length - 3; i += 3) { String id = parts[i].trim().replaceFirst("model.", ""); String type = parts[i + 1].trim(); String val = parts[i + 2].trim(); if (type.equals("UNIT")) { unitMap.put(id, val); } } for (int i = 1; i < parts.length - 3; i += 3) { String id = parts[i].trim().replaceFirst("model.", ""); String type = parts[i + 1].trim(); String val = parts[i + 2].trim(); try { if (type.equals("DOUBLE")) { InputParameterDouble param = (InputParameterDouble) inputParameters.get(id); param.setDoubleValue(Double.valueOf(val)); } else if (type.equals("FLOAT")) { InputParameterFloat param = (InputParameterFloat) inputParameters.get(id); param.setFloatValue(Float.valueOf(val)); } else if (type.equals("BOOLEAN")) { InputParameterBoolean param = (InputParameterBoolean) inputParameters.get(id); param.setBooleanValue(val.toUpperCase().startsWith("T")); } else if (type.equals("LONG")) { InputParameterLong param = (InputParameterLong) inputParameters.get(id); param.setLongValue(Long.valueOf(val)); } else if (type.equals("INTEGER")) { InputParameterInteger param = (InputParameterInteger) inputParameters.get(id); param.setIntValue(Integer.valueOf(val)); } else if (type.equals("STRING")) { InputParameterString param = (InputParameterString) inputParameters.get(id); param.setStringValue(val); } if (type.equals("DOUBLESCALAR")) { InputParameterDoubleScalar<?, ?> param = (InputParameterDoubleScalar<?, ?>) inputParameters.get(id); param.getDoubleParameter().setDoubleValue(Double.valueOf(val)); String unitString = unitMap.get(id); if (unitString == null) System.err.println("Could not find unit for DoubleScalar parameter with id=" + id); else { Unit<?> unit = param.getUnitParameter().getOptions().get(unitString); if (unit == null) System.err.println( "Could not find unit " + unitString + " for DoubleScalar parameter with id=" + id); else { param.getUnitParameter().setObjectValue(unit); param.setCalculatedValue(); // it will retrieve the set double value and unit } } } } catch (Exception exception) { if (errors.equals("OK")) errors = "ERRORS IN INPUT VALUES:\n"; errors += "Field " + id + ": " + exception.getMessage() + "\n"; } } return errors; } } } |
File | Line |
---|---|
org\opentrafficsim\ahfe\AHFEAnimation.java | 100 |
org\opentrafficsim\ahfe\AHFESimulation.java | 89 |
int replication = 1; String anticipationStrategy = "none"; Duration reactionTime = Duration.instantiateSI(0.0); Duration anticipationTime = Duration.ZERO; double truckFraction = 0.05; double distanceError = 0.0; // 0.05; double speedError = 0.0; // 0.01; double accelerationError = 0.0; // 0.10; Frequency leftDemand = new Frequency(3500.0, FrequencyUnit.PER_HOUR); Frequency rightDemand = new Frequency(3200.0, FrequencyUnit.PER_HOUR); double leftFraction = 0.55; String scenario = "test"; for (String arg : args) { int equalsPos = arg.indexOf("="); if (equalsPos >= 0) { // set something String key = arg.substring(0, equalsPos); String value = arg.substring(equalsPos + 1); if ("autorun".equalsIgnoreCase(key)) { if ("true".equalsIgnoreCase(value)) { autorun = true; } else if ("false".equalsIgnoreCase(value)) { autorun = false; } else { System.err.println("bad autorun value " + value + " (ignored)"); } } else if ("replication".equalsIgnoreCase(key)) { try { replication = Integer.parseInt(value); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable replication number \"" + value + "\""); } } else if ("anticipation".equalsIgnoreCase(key)) { if (value.equalsIgnoreCase("none") || value.equalsIgnoreCase("constant_speed") || value.equalsIgnoreCase("constant_acceleration")) { anticipationStrategy = value; } else { System.err.println("Ignoring unparsable anticipation \"" + value + "\""); } } else if ("reactiontime".equalsIgnoreCase(key)) { try { reactionTime = Duration.instantiateSI(java.lang.Double.parseDouble(value)); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable reaction time \"" + value + "\""); } } else if ("anticipationtime".equalsIgnoreCase(key)) { try { anticipationTime = Duration.instantiateSI(java.lang.Double.parseDouble(value)); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable anticipation time \"" + value + "\""); } } else if ("truckfraction".equalsIgnoreCase(key)) { try { truckFraction = java.lang.Double.parseDouble(value); Throw.when(truckFraction < 0.0 || truckFraction > 1.0, IllegalArgumentException.class, "Truck fraction must be between 0 and 1."); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable truck fraction \"" + value + "\""); } } else if ("distanceerror".equalsIgnoreCase(key)) { try { distanceError = java.lang.Double.parseDouble(value); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable distance error \"" + value + "\""); } } else if ("speederror".equalsIgnoreCase(key)) { try { speedError = java.lang.Double.parseDouble(value); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable speed error \"" + value + "\""); } } else if ("accelerationerror".equalsIgnoreCase(key)) { try { accelerationError = java.lang.Double.parseDouble(value); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable acceleration error \"" + value + "\""); } } else if ("leftdemand".equalsIgnoreCase(key)) { try { leftDemand = new Frequency(java.lang.Double.parseDouble(value), FrequencyUnit.PER_HOUR); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable left demand \"" + value + "\""); } } else if ("rightdemand".equalsIgnoreCase(key)) { try { rightDemand = new Frequency(java.lang.Double.parseDouble(value), FrequencyUnit.PER_HOUR); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable right demand \"" + value + "\""); } } else if ("leftfraction".equalsIgnoreCase(key)) { try { leftFraction = java.lang.Double.parseDouble(value); } catch (NumberFormatException nfe) { System.err.println("Ignoring unparsable left fraction \"" + value + "\""); } } else if ("scenario".equalsIgnoreCase(key)) { scenario = value; } else { System.out.println("Ignoring unknown setting " + arg); } } else { // not a flag System.err.println("Ignoring argument " + arg); } } final boolean finalAutoRun = autorun; final int finalReplication = replication; final String finalAnticipationStrategy = anticipationStrategy; final Duration finalReactionTime = reactionTime; final Duration finalAnticipationTime = anticipationTime; final double finalTruckFraction = truckFraction; final double finalDistanceError = distanceError; final double finalSpeedError = speedError; final double finalAccelerationError = accelerationError; final Frequency finalLeftDemand = leftDemand; final Frequency finalRightDemand = rightDemand; final double finalLeftFraction = leftFraction; final String finalScenario = scenario; SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { |
File | Line |
---|---|
org\opentrafficsim\ahfe\AHFEAnimation.java | 403 |
org\opentrafficsim\ahfe\AHFESimulation.java | 384 |
return new Rectangle2D.Double(-50, -100, 8050, 150); } /** * The AHFE simulation model. */ static class AHFEModel extends AbstractOTSModel { /** */ private static final long serialVersionUID = 20170228L; /** The network. */ private OTSRoadNetwork network; /** Replication. */ private final Integer replication; /** Anticipation strategy. */ private final String anticipationStrategy; /** Reaction time. */ private final Duration reactionTime; /** Future anticipation time. */ private final Duration anticipationTime; /** Truck fraction. */ private final double truckFraction; /** Distance error. */ private final double distanceError; /** Speed error. */ private final double speedError; /** Acceleration error. */ private final double accelerationError; /** Left demand. */ private final Frequency leftDemand; /** Right demand. */ private final Frequency rightDemand; /** Left fraction, per road. */ private final double leftFraction; /** Sampler. */ private Sampler<GtuData> sampler; /** * @param simulator OTSSimulatorInterface; the simulator * @param replication Integer; replication * @param anticipationStrategy String; anticipation strategy * @param reactionTime Duration; reaction time * @param anticipationTime Duration; anticipation time * @param truckFraction double; truck fraction * @param distanceError double; distance error * @param speedError double; speed error * @param accelerationError double; acceleration error * @param leftFraction double; left demand * @param rightDemand Frequency; right demand * @param leftDemand Frequency; left fraction, per road */ @SuppressWarnings("checkstyle:parameternumber") AHFEModel(final OTSSimulatorInterface simulator, final Integer replication, final String anticipationStrategy, final Duration reactionTime, final Duration anticipationTime, final double truckFraction, final double distanceError, final double speedError, final double accelerationError, final Frequency leftDemand, final Frequency rightDemand, final double leftFraction) { super(simulator); this.replication = replication; this.anticipationStrategy = anticipationStrategy; this.reactionTime = reactionTime; this.anticipationTime = anticipationTime; this.truckFraction = truckFraction; this.distanceError = distanceError; this.speedError = speedError; this.accelerationError = accelerationError; this.leftDemand = leftDemand; this.rightDemand = rightDemand; this.leftFraction = leftFraction; } /** {@inheritDoc} */ @SuppressWarnings("synthetic-access") @Override public void constructModel() throws SimRuntimeException { this.sampler = new RoadSampler(this.simulator); this.sampler.registerExtendedDataType(new TimeToCollision()); try { URL xmlURL = URLResource.getResource("/AHFE/Network.xml"); this.network = new OTSRoadNetwork("AHFE", true); XmlNetworkLaneParser.build(xmlURL, this.network, getSimulator()); // Space-time regions for sampler LinkData linkData = new LinkData((CrossSectionLink) this.network.getLink("LEFTIN")); registerLinkToSampler(linkData, ignoreStart, linkData.getLength()); linkData = new LinkData((CrossSectionLink) this.network.getLink("RIGHTIN")); registerLinkToSampler(linkData, ignoreStart, linkData.getLength()); linkData = new LinkData((CrossSectionLink) this.network.getLink("CONVERGE")); registerLinkToSampler(linkData, Length.ZERO, linkData.getLength()); linkData = new LinkData((CrossSectionLink) this.network.getLink("WEAVING")); registerLinkToSampler(linkData, Length.ZERO, linkData.getLength()); linkData = new LinkData((CrossSectionLink) this.network.getLink("END")); registerLinkToSampler(linkData, Length.ZERO, linkData.getLength().minus(ignoreEnd)); // Generator AHFEUtil.createDemand(this.network, new DefaultSwitchableGTUColorer(), this.simulator, getReplication(), |
File | Line |
---|---|
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java | 253 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java | 221 |
this.trafCOD = new TrafCOD(controllerName, program, getSimulator(), this.controllerDisplayPanel, backgroundImage, displayObjectLocations); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_STATE_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_VARIABLE_CREATED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED); // Subscribe the TrafCOD machine to trace command events that we emit addListener(this.trafCOD, TrafficController.TRAFFICCONTROL_SET_TRACING); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TGX", 8, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "XR1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TD1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TGX", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] {controllerName, "TL", 11, true}); // System.out.println("demo: emitting a SET TRACING event for all variables related to stream 11"); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new Object[] { controllerName, "", 11, true }); // this.trafCOD.traceVariablesOfStream(TrafficController.NO_STREAM, true); // this.trafCOD.traceVariablesOfStream(11, true); // this.trafCOD.traceVariable("MRV", 11, true); } catch (Exception exception) { exception.printStackTrace(); } } /** {@inheritDoc} */ @Override public final OTSRoadNetwork getNetwork() { return this.network; } /** * @return trafCOD */ public final TrafCOD getTrafCOD() { return this.trafCOD; } /** * @return controllerDisplayPanel */ public final JPanel getControllerDisplayPanel() { return this.controllerDisplayPanel; } /** {@inheritDoc} */ @Override public void notify(final EventInterface event) throws RemoteException { EventType type = event.getType(); Object[] payload = (Object[]) event.getContent(); if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type)) { // System.out.println("Evalution starts at " + getSimulator().getSimulatorTime()); return; } else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type)) { System.out.println("Conflict group changed from " + ((String) payload[1]) + " to " + ((String) payload[2])); } else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type)) { System.out.println(String.format("Variable changed %s <- %d %s", payload[1], payload[4], payload[5])); } else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type)) { System.out.println("Warning " + payload[1]); } else { System.out.print("TrafCODDemo received event of type " + event.getType() + ", payload ["); String separator = ""; for (Object o : payload) { System.out.print(separator + o); separator = ","; } System.out.println("]"); } } } } |
File | Line |
---|---|
org\opentrafficsim\ahfe\AHFEAnimation.java | 307 |
org\opentrafficsim\ahfe\AHFESimulation.java | 295 |
int reportTimeClick = 60; while (true) { int currentTime = (int) simulator.getSimulatorTime().si; if (currentTime >= lastReportedTime + reportTimeClick) { lastReportedTime = currentTime / reportTimeClick * reportTimeClick; System.out.println("time is " + simulator.getSimulatorTime()); } try { simulator.step(); } catch (SimRuntimeException sre) { if (sre.getCause() != null && sre.getCause().getCause() != null && sre.getCause().getCause().getMessage().equals( "Model has calcalated a negative infinite or negative max value acceleration.")) { System.err.println("Collision detected."); String file = finalScenario + ".csv.zip"; FileOutputStream fos = null; ZipOutputStream zos = null; OutputStreamWriter osw = null; BufferedWriter bw = null; try { fos = new FileOutputStream(file); zos = new ZipOutputStream(fos); zos.putNextEntry(new ZipEntry(finalScenario + ".csv")); osw = new OutputStreamWriter(zos); bw = new BufferedWriter(osw); bw.write("Collision"); bw.write(simulator.getSimulatorTime().toString()); } catch (IOException exception2) { throw new RuntimeException("Could not write to file.", exception2); } // close file on fail finally { try { if (bw != null) { bw.close(); } if (osw != null) { osw.close(); } if (zos != null) { zos.close(); } if (fos != null) { fos.close(); } } catch (IOException ex) { ex.printStackTrace(); } } } else { System.out.println("Simulation ends; time is " + simulator.getSimulatorTime()); if (ahfeModel.getSampler() != null) { ahfeModel.getSampler().writeToFile(finalScenario + ".csv"); } } long t2 = System.currentTimeMillis(); System.out.println("Run took " + (t2 - t1) / 1000 + "s."); System.exit(0); break; } } } } catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException exception) |
File | Line |
---|---|
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java | 249 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java | 173 |
this.simulator, this.controllerDisplayPanel, null, null); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_STATE_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_VARIABLE_CREATED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED); // Subscribe the TrafCOD machine to trace command events that we // emit addListener(this.trafCOD, TrafficController.TRAFFICCONTROL_SET_TRACING); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TGX", 8, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "XR1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TD1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TGX", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TL", 11, true}); // System.out.println("demo: emitting a SET TRACING event for // all variables related to stream 11"); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] { controllerName, "", 11, true }); // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(TrafficController.NO_STREAM, // true); // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(11, true); // TrafCODDemo2.this.trafCOD.traceVariable("MRV", 11, true); } catch (Exception exception) { exception.printStackTrace(); } } /** {@inheritDoc} */ @Override public final OTSRoadNetwork getNetwork() { return this.network; } /** * @return trafCOD */ public final TrafCOD getTrafCOD() { return this.trafCOD; } /** * @return controllerDisplayPanel */ public final JPanel getControllerDisplayPanel() { return this.controllerDisplayPanel; } /** {@inheritDoc} */ @Override public void notify(final EventInterface event) throws RemoteException { EventType type = event.getType(); Object[] payload = (Object[]) event.getContent(); if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type)) { // System.out.println("Evaluation starts at " + // getSimulator().getSimulatorTime()); return; } else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type)) { System.out.println("Conflict group changed from " + ((String) payload[1]) + " to " + ((String) payload[2])); } else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type)) { System.out.println(String.format("Variable changed %s <- %d %s", payload[1], payload[4], payload[5])); } else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type)) { System.out.println("Warning " + payload[1]); } else { System.out.print("TrafCODDemo received event of type " + event.getType() + ", payload ["); String separator = ""; for (Object o : payload) { System.out.print(separator + o); separator = ","; } System.out.println("]"); } } } } |
File | Line |
---|---|
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java | 249 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java | 254 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java | 222 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java | 174 |
this.simulator, this.controllerDisplayPanel, null, null); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_STATE_CHANGED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_VARIABLE_CREATED); this.trafCOD.addListener(this, TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED); // Subscribe the TrafCOD machine to trace command events that we // emit addListener(this.trafCOD, TrafficController.TRAFFICCONTROL_SET_TRACING); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TGX", 8, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "XR1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TD1", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TGX", 11, true}); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] {controllerName, "TL", 11, true}); // System.out.println("demo: emitting a SET TRACING event for // all variables related to stream 11"); // fireEvent(TrafficController.TRAFFICCONTROL_SET_TRACING, new // Object[] { controllerName, "", 11, true }); // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(TrafficController.NO_STREAM, // true); // TrafCODDemo2.this.trafCOD.traceVariablesOfStream(11, true); // TrafCODDemo2.this.trafCOD.traceVariable("MRV", 11, true); } catch (Exception exception) { exception.printStackTrace(); } } /** {@inheritDoc} */ @Override public final OTSRoadNetwork getNetwork() { return this.network; } /** * @return trafCOD */ public final TrafCOD getTrafCOD() { return this.trafCOD; } /** * @return controllerDisplayPanel */ public final JPanel getControllerDisplayPanel() { return this.controllerDisplayPanel; } /** {@inheritDoc} */ @Override public void notify(final EventInterface event) throws RemoteException { EventType type = event.getType(); Object[] payload = (Object[]) event.getContent(); if (TrafficController.TRAFFICCONTROL_CONTROLLER_EVALUATING.equals(type)) { // System.out.println("Evaluation starts at " + // getSimulator().getSimulatorTime()); return; } else if (TrafficController.TRAFFICCONTROL_CONFLICT_GROUP_CHANGED.equals(type)) { System.out.println("Conflict group changed from " + ((String) payload[1]) + " to " + ((String) payload[2])); } else if (TrafficController.TRAFFICCONTROL_TRACED_VARIABLE_UPDATED.equals(type)) { System.out.println(String.format("Variable changed %s <- %d %s", payload[1], payload[4], payload[5])); } else if (TrafficController.TRAFFICCONTROL_CONTROLLER_WARNING.equals(type)) { System.out.println("Warning " + payload[1]); } else { System.out.print("TrafCODDemo received event of type " + event.getType() + ", payload ["); String separator = ""; for (Object o : payload) { System.out.print(separator + o); separator = ","; } System.out.println("]"); } } } } |
File | Line |
---|---|
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java | 187 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java | 182 |
List<CONTROL> trafficControllerList = ots.getCONTROL(); Throw.when(trafficControllerList.size() != 1, NetworkException.class, "OTS contains wrong number of traffic controllers (should be 1, got %1)", trafficControllerList.size()); CONTROL controller = trafficControllerList.get(0); List<TRAFCOD> trafCodList = controller.getTRAFCOD(); Throw.when(trafCodList.size() != 1, NetworkException.class, "Controller should contain one TRAFCOD (got %1)", trafCodList.size()); TRAFCOD trafCod = trafCodList.get(0); String programString = trafCod.getPROGRAM().getValue(); List<String> program = null == programString ? TrafCOD.loadTextFromURL(new URL(trafCod.getPROGRAMFILE())) : Arrays.asList(programString.split("\n")); TRAFCOD.CONSOLE.MAP mapData = trafCod.getCONSOLE().getMAP(); BufferedImage backgroundImage = null; if (null != mapData) { String graphicsType = mapData.getTYPE(); String encoding = mapData.getENCODING(); String encodedData = mapData.getValue(); if (!"base64".contentEquals(encoding)) { throw new RuntimeException("Unexpected image encoding: " + encoding); } byte[] imageBytes = DatatypeConverter.parseBase64Binary(encodedData); switch (graphicsType) { case "PNG": backgroundImage = ImageIO.read(new ByteArrayInputStream(imageBytes)); // javax.imageio.ImageIO.write(backgroundImage, "png", new File("c:\\temp\\test.png")); break; default: throw new RuntimeException("Unexpected image type: " + graphicsType); } } String objectLocationsString = trafCod.getCONSOLE().getCOORDINATES().getValue(); List<String> displayObjectLocations = null == objectLocationsString ? TrafCOD.loadTextFromURL(new URL(trafCod.getCONSOLE().getCOORDINATESFILE())) : Arrays.asList(objectLocationsString.split("\n")); this.trafCOD = new TrafCOD(controllerName, program, getSimulator(), this.controllerDisplayPanel, backgroundImage, displayObjectLocations); |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneSwing.java | 99 |
org\opentrafficsim\demo\StraightSwing.java | 99 |
CircularLaneSwing app = new CircularLaneSwing("Circular Lane", animationPanel, otsModel); app.setExitOnClose(exitOnClose); } else { if (exitOnClose) { System.exit(0); } } } catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException exception) { exception.printStackTrace(); } } /** * Add the statistics tabs. * @param simulator OTSSimulatorInterface; the simulator on which sampling can be scheduled */ protected final void addStatisticsTabs(final OTSSimulatorInterface simulator) { GraphPath<KpiLaneDirection> path; try { path = GraphLaneUtil.createPath("Lane", new LaneDirection(getModel().getPath().get(0), GTUDirectionality.DIR_PLUS)); } catch (NetworkException exception) { throw new RuntimeException("Could not create a path as a lane has no set speed limit.", exception); } RoadSampler sampler = new RoadSampler(simulator); ContourDataSource<?> dataPool = new ContourDataSource<>(sampler, path); TablePanel charts = new TablePanel(3, 2); SwingPlot plot = null; plot = new SwingTrajectoryPlot(new TrajectoryPlot("TrajectoryPlot", Duration.instantiateSI(10.0), simulator, sampler, path)); charts.setCell(plot.getContentPane(), 0, 0); plot = new SwingContourPlot(new ContourPlotDensity("DensityPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 1, 0); plot = new SwingContourPlot(new ContourPlotSpeed("SpeedPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 2, 0); plot = new SwingContourPlot(new ContourPlotFlow("FlowPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 1, 1); plot = new SwingContourPlot(new ContourPlotAcceleration("AccelerationPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 2, 1); getAnimationPanel().getTabbedPane().addTab(getAnimationPanel().getTabbedPane().getTabCount(), "statistics ", charts); } } |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneSwing.java | 99 |
org\opentrafficsim\demo\SequentialLanes.java | 137 |
org\opentrafficsim\demo\StraightSwing.java | 99 |
CircularLaneSwing app = new CircularLaneSwing("Circular Lane", animationPanel, otsModel); app.setExitOnClose(exitOnClose); } else { if (exitOnClose) { System.exit(0); } } } catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException exception) { exception.printStackTrace(); } } /** * Add the statistics tabs. * @param simulator OTSSimulatorInterface; the simulator on which sampling can be scheduled */ protected final void addStatisticsTabs(final OTSSimulatorInterface simulator) { GraphPath<KpiLaneDirection> path; try { path = GraphLaneUtil.createPath("Lane", new LaneDirection(getModel().getPath().get(0), GTUDirectionality.DIR_PLUS)); } catch (NetworkException exception) { throw new RuntimeException("Could not create a path as a lane has no set speed limit.", exception); } RoadSampler sampler = new RoadSampler(simulator); ContourDataSource<?> dataPool = new ContourDataSource<>(sampler, path); TablePanel charts = new TablePanel(3, 2); SwingPlot plot = null; plot = new SwingTrajectoryPlot(new TrajectoryPlot("TrajectoryPlot", Duration.instantiateSI(10.0), simulator, sampler, path)); charts.setCell(plot.getContentPane(), 0, 0); plot = new SwingContourPlot(new ContourPlotDensity("DensityPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 1, 0); plot = new SwingContourPlot(new ContourPlotSpeed("SpeedPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 2, 0); plot = new SwingContourPlot(new ContourPlotFlow("FlowPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 1, 1); plot = new SwingContourPlot(new ContourPlotAcceleration("AccelerationPlot", simulator, dataPool)); charts.setCell(plot.getContentPane(), 2, 1); getAnimationPanel().getTabbedPane().addTab(getAnimationPanel().getTabbedPane().getTabCount(), "statistics ", charts); } |
File | Line |
---|---|
org\opentrafficsim\demo\FundamentalDiagrams.java | 297 |
org\opentrafficsim\demo\StraightModel.java | 178 |
| InputParameterException exception) { exception.printStackTrace(); } } /** * Set up the block. */ protected final void createBlock() { this.block.setTrafficLightColor(TrafficLightColor.RED); } /** * Remove the block. */ protected final void removeBlock() { this.block.setTrafficLightColor(TrafficLightColor.GREEN); } /** * Generate cars at a fixed rate (implemented by re-scheduling this method). */ protected final void generateCar() { try { boolean generateTruck = this.stream.nextDouble() > this.carProbability; Length vehicleLength = new Length(generateTruck ? 15 : 4, METER); LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.network.getGtuType(GTUType.DEFAULTS.CAR), vehicleLength, new Length(1.8, METER), new Speed(200, KM_PER_HOUR), vehicleLength.times(0.5), this.simulator, this.network); gtu.setParameters(generateTruck ? this.parametersTruck : this.parametersCar); gtu.setNoLaneChangeDistance(Length.ZERO); gtu.setMaximumAcceleration(Acceleration.instantiateSI(3.0)); gtu.setMaximumDeceleration(Acceleration.instantiateSI(-8.0)); // strategical planner LaneBasedStrategicalPlanner strategicalPlanner = generateTruck ? this.strategicalPlannerGeneratorTrucks.create(gtu, null, null, null) : this.strategicalPlannerGeneratorCars.create(gtu, null, null, null); Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1); Length initialPosition = new Length(20, METER); initialPositions.add(new DirectedLanePosition(this.lane, initialPosition, GTUDirectionality.DIR_PLUS)); Speed initialSpeed = new Speed(100.0, KM_PER_HOUR); gtu.init(strategicalPlanner, initialPositions, initialSpeed); this.simulator.scheduleEventRel(this.headway, this, this, "generateCar", null); } catch (SimRuntimeException | NetworkException | GTUException | OTSGeometryException exception) { exception.printStackTrace(); } } |
File | Line |
---|---|
org\opentrafficsim\ahfe\AHFEAnimation.java | 513 |
org\opentrafficsim\ahfe\AHFESimulation.java | 494 |
AHFEUtil.createDemand(this.network, new DefaultSwitchableGTUColorer(), this.simulator, getReplication(), getAnticipationStrategy(), getReactionTime(), getAnticipationTime(), getTruckFraction(), SIMEND, getLeftDemand(), getRightDemand(), getLeftFraction(), getDistanceError(), getSpeedError(), getAccelerationError()); } catch (Exception exception) { exception.printStackTrace(); } } /** * Register a link to the sampler, so data is sampled there. * @param linkData LinkData; link data * @param startDistance Length; start distance on link * @param endDistance Length; end distance on link */ private void registerLinkToSampler(final LinkData linkData, final Length startDistance, final Length endDistance) { for (LaneDataInterface laneData : linkData.getLaneDatas()) { Length start = laneData.getLength().times(startDistance.si / linkData.getLength().si); Length end = laneData.getLength().times(endDistance.si / linkData.getLength().si); this.sampler.registerSpaceTimeRegion(new SpaceTimeRegion( new KpiLaneDirection(laneData, KpiGtuDirectionality.DIR_PLUS), start, end, WARMUP, SIMEND)); } } /** {@inheritDoc} */ @Override public OTSRoadNetwork getNetwork() { return this.network; } /** * @return replication. */ public Integer getReplication() { return this.replication; } /** * @return anticipationStrategy. */ public String getAnticipationStrategy() { return this.anticipationStrategy; } /** * @return reactionTime. */ public Duration getReactionTime() { return this.reactionTime; } /** * @return anticipationTime. */ public Duration getAnticipationTime() { return this.anticipationTime; } /** * @return truckFraction. */ public double getTruckFraction() { return this.truckFraction; } /** * @return distanceError. */ public double getDistanceError() { return this.distanceError; } /** * @return speedError. */ public double getSpeedError() { return this.speedError; } /** * @return accelerationError. */ public double getAccelerationError() { return this.accelerationError; } /** * @return leftDemand. */ public Frequency getLeftDemand() { return this.leftDemand; } /** * @return rightDemand. */ public Frequency getRightDemand() { return this.rightDemand; } /** * @return leftFraction. */ public double getLeftFraction() { return this.leftFraction; } /** * @return sampler */ public final Sampler<GtuData> getSampler() { return this.sampler; } } } |
File | Line |
---|---|
org\opentrafficsim\demo\FundamentalDiagrams.java | 270 |
org\opentrafficsim\demo\StraightModel.java | 152 |
new SinkSensor(sinkLane, new Length(10.0, METER), Compatible.EVERYTHING, this.simulator); this.carProbability = (double) getInputParameter("generic.carProbability"); this.parametersCar = InputParameterHelper.getParametersCar(getInputParameterMap()); this.parametersTruck = InputParameterHelper.getParametersTruck(getInputParameterMap()); this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); // 1500 [veh / hour] == 2.4s headway this.headway = new Duration(3600.0 / 1500.0, SECOND); // Schedule creation of the first car (this will re-schedule itself one headway later, etc.). this.simulator.scheduleEventAbs(Time.ZERO, this, this, "generateCar", null); this.block = new SimpleTrafficLight(this.lane.getId() + "_TL", this.lane, new Length(new Length(4000.0, LengthUnit.METER)), this.simulator); this.block.setTrafficLightColor(TrafficLightColor.GREEN); // Create a block at t = 5 minutes this.simulator.scheduleEventAbs(new Time(300, TimeUnit.BASE_SECOND), this, this, "createBlock", null); // Remove the block at t = 7 minutes this.simulator.scheduleEventAbs(new Time(420, TimeUnit.BASE_SECOND), this, this, "removeBlock", null); } catch (SimRuntimeException | NetworkException | GTUException | OTSGeometryException | ParameterException |
File | Line |
---|---|
org\opentrafficsim\demo\FundamentalDiagrams.java | 317 |
org\opentrafficsim\demo\SequentialLanes.java | 371 |
org\opentrafficsim\demo\StraightModel.java | 198 |
} /** * Generate cars at a fixed rate (implemented by re-scheduling this method). */ protected final void generateCar() { try { boolean generateTruck = this.stream.nextDouble() > this.carProbability; Length vehicleLength = new Length(generateTruck ? 15 : 4, METER); LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.network.getGtuType(GTUType.DEFAULTS.CAR), vehicleLength, new Length(1.8, METER), new Speed(200, KM_PER_HOUR), vehicleLength.times(0.5), this.simulator, this.network); gtu.setParameters(generateTruck ? this.parametersTruck : this.parametersCar); gtu.setNoLaneChangeDistance(Length.ZERO); gtu.setMaximumAcceleration(Acceleration.instantiateSI(3.0)); gtu.setMaximumDeceleration(Acceleration.instantiateSI(-8.0)); // strategical planner LaneBasedStrategicalPlanner strategicalPlanner = generateTruck ? this.strategicalPlannerGeneratorTrucks.create(gtu, null, null, null) : this.strategicalPlannerGeneratorCars.create(gtu, null, null, null); Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1); Length initialPosition = new Length(20, METER); initialPositions.add(new DirectedLanePosition(this.lane, initialPosition, GTUDirectionality.DIR_PLUS)); |
File | Line |
---|---|
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java | 193 |
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java | 219 |
TrafficLight tl = new SimpleTrafficLight(String.format("%02d", stream), lane, lane.getLength().minus(stopLineMargin), this.simulator); trafficLights.add(tl); try { new TrafficLightAnimation(tl, this.simulator); } catch (RemoteException | NamingException exception) { throw new NetworkException(exception); } sensors.add(new TrafficLightSensor(String.format("D%02d1", stream), lane, lane.getLength().minus(headDetectorMargin), lane, lane.getLength().minus(headDetectorMargin).plus(headDetectorLength), null, RelativePosition.FRONT, RelativePosition.REAR, this.simulator, Compatible.EVERYTHING)); sensors.add(new TrafficLightSensor(String.format("D%02d2", stream), lane, lane.getLength().minus(longDetectorMargin), lane, lane.getLength().minus(longDetectorMargin).plus(longDetectorLength), null, RelativePosition.FRONT, RelativePosition.REAR, this.simulator, Compatible.EVERYTHING)); } |
File | Line |
---|---|
org\opentrafficsim\demo\FundamentalDiagrams.java | 244 |
org\opentrafficsim\demo\StraightModel.java | 125 |
FundamentalDiagramPlotsModel(final OTSSimulatorInterface simulator) { super(simulator); InputParameterHelper.makeInputParameterMapCarTruck(this.inputParameterMap, 1.0); } /** {@inheritDoc} */ @Override public final void constructModel() throws SimRuntimeException { try { OTSRoadNode from = new OTSRoadNode(this.network, "From", new OTSPoint3D(getMinimumDistance().getSI(), 0, 0), Direction.ZERO); OTSRoadNode to = new OTSRoadNode(this.network, "To", new OTSPoint3D(getMaximumDistance().getSI(), 0, 0), Direction.ZERO); OTSRoadNode end = new OTSRoadNode(this.network, "End", new OTSPoint3D(getMaximumDistance().getSI() + 50.0, 0, 0), Direction.ZERO); LaneType laneType = this.network.getLaneType(LaneType.DEFAULTS.TWO_WAY_LANE); this.lane = LaneFactory.makeLane(this.network, "Lane", from, to, null, laneType, this.speedLimit, this.simulator); |
File | Line |
---|---|
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java | 121 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java | 116 |
TrafCODDemo1 app = new TrafCODDemo1("TrafCOD demo simple crossing", animationPanel, trafcodModel); app.setExitOnClose(exitOnClose); } catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException exception) { exception.printStackTrace(); } } /** * Add tab with trafCOD status. */ @Override protected final void addTabs() { JScrollPane scrollPane = new JScrollPane(getModel().getControllerDisplayPanel()); JPanel wrapper = new JPanel(new BorderLayout()); wrapper.add(scrollPane); getAnimationPanel().getTabbedPane().addTab(getAnimationPanel().getTabbedPane().getTabCount() - 1, getModel().getTrafCOD().getId(), wrapper); } /** * The simulation model. */ public static class TrafCODModel extends AbstractOTSModel implements EventListenerInterface { /** */ private static final long serialVersionUID = 20161020L; /** The network. */ private OTSRoadNetwork network; /** The TrafCOD controller. */ private TrafCOD trafCOD; /** TrafCOD controller display. */ private JPanel controllerDisplayPanel = new JPanel(new BorderLayout()); /** The XML. */ private final String xml; /** * @param simulator OTSSimulatorInterface; the simulator * @param shortName String; name of the model * @param description String; description of the model * @param xml String; the XML string */ public TrafCODModel(final OTSSimulatorInterface simulator, final String shortName, final String description, final String xml) { super(simulator); |
File | Line |
---|---|
org\opentrafficsim\demo\network\xml\TestXMLParserA58.java | 141 |
org\opentrafficsim\demo\network\xml\TestXMLParserEindhoven.java | 142 |
URL xmlURL = URLResource.getResource("/xml/A58.xml"); this.network = new OTSRoadNetwork("Example network", true); try { XmlNetworkLaneParser.build(xmlURL, this.network, getSimulator()); } catch (NetworkException | ParserConfigurationException | SAXException | OTSGeometryException | JAXBException | URISyntaxException | XmlParserException | GTUException exception) { exception.printStackTrace(); } for (TrafficLight tl : this.network.getObjectMap(TrafficLight.class).values()) { tl.setTrafficLightColor(TrafficLightColor.GREEN); } URL gisURL = URLResource.getResource("/xml/A58/map.xml"); System.err.println("GIS-map file: " + gisURL.toString()); CoordinateTransform rdto0 = new CoordinateTransformWGS84toRDNew(0, 0); this.gisMap = new GisRenderable2D(this.simulator, gisURL, rdto0); } /** * @return gisMap */ public final GisRenderable2D getGisMap() { return this.gisMap; } /** {@inheritDoc} */ @Override public OTSRoadNetwork getNetwork() { return this.network; } /** {@inheritDoc} */ @Override public final String toString() { return "TestXMLModelA58 [simulator=" + this.simulator + "]"; |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneModel.java | 154 |
org\opentrafficsim\demo\CircularRoadModel.java | 178 |
new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); LaneType laneType = this.network.getLaneType(LaneType.DEFAULTS.TWO_WAY_LANE); OTSRoadNode start = new OTSRoadNode(this.network, "Start", new OTSPoint3D(radius, 0, 0), new Direction(90, DirectionUnit.EAST_DEGREE)); OTSRoadNode halfway = new OTSRoadNode(this.network, "Halfway", new OTSPoint3D(-radius, 0, 0), new Direction(270, DirectionUnit.EAST_DEGREE)); OTSPoint3D[] coordsHalf1 = new OTSPoint3D[127]; for (int i = 0; i < coordsHalf1.length; i++) { double angle = Math.PI * (1 + i) / (1 + coordsHalf1.length); coordsHalf1[i] = new OTSPoint3D(radius * Math.cos(angle), radius * Math.sin(angle), 0); } |
File | Line |
---|---|
org\opentrafficsim\demo\CrossingTrafficLightsModel.java | 277 |
org\opentrafficsim\demo\NetworksModel.java | 376 |
{ Distribution<LaneBasedTemplateGTUType> distribution = new Distribution<>(this.stream); Length initialPosition = new Length(16, METER); Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1); initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS)); LaneBasedTemplateGTUType template = makeTemplate(this.stream, lane, new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 3, 6), METER), new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 1.6, 2.0), METER), new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 140, 180), KM_PER_HOUR), initialPositions, this.strategicalPlannerFactoryCar, routeGenerator); |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneModel.java | 221 |
org\opentrafficsim\demo\FundamentalDiagrams.java | 325 |
org\opentrafficsim\demo\SequentialLanes.java | 379 |
org\opentrafficsim\demo\StraightModel.java | 206 |
{ // GTU itself boolean generateTruck = this.stream.nextDouble() > this.carProbability; Length vehicleLength = new Length(generateTruck ? 15 : 4, METER); LaneBasedIndividualGTU gtu = new LaneBasedIndividualGTU("" + (++this.carsCreated), this.network.getGtuType(GTUType.DEFAULTS.CAR), vehicleLength, new Length(1.8, METER), new Speed(200, KM_PER_HOUR), vehicleLength.times(0.5), this.simulator, this.network); gtu.setParameters(generateTruck ? this.parametersTruck : this.parametersCar); gtu.setNoLaneChangeDistance(Length.ZERO); gtu.setMaximumAcceleration(Acceleration.instantiateSI(3.0)); gtu.setMaximumDeceleration(Acceleration.instantiateSI(-8.0)); // strategical planner LaneBasedStrategicalPlanner strategicalPlanner; |
File | Line |
---|---|
org\opentrafficsim\demo\conflict\TJunctionDemo.java | 164 |
org\opentrafficsim\demo\conflict\TurboRoundaboutDemo.java | 185 |
this.simulator.scheduleEventRel(new Duration(30.0, DurationUnit.SECOND), this, this, "changePhase", new Object[] {trafficLight}); break; } case YELLOW: { trafficLight.setTrafficLightColor(TrafficLightColor.RED); this.simulator.scheduleEventRel(new Duration(56.0, DurationUnit.SECOND), this, this, "changePhase", new Object[] {trafficLight}); break; } case GREEN: { trafficLight.setTrafficLightColor(TrafficLightColor.YELLOW); this.simulator.scheduleEventRel(new Duration(4.0, DurationUnit.SECOND), this, this, "changePhase", new Object[] {trafficLight}); break; } default: { // } } } /** {@inheritDoc} */ @Override public OTSRoadNetwork getNetwork() { return this.network; } } } |
File | Line |
---|---|
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java | 74 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java | 68 |
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java | 57 |
public TrafCODDemo1(final String title, final OTSAnimationPanel panel, final TrafCODModel model) throws OTSDrawingException { super(model, panel); } /** * Main program. * @param args String[]; the command line arguments (not used) * @throws IOException ... */ public static void main(final String[] args) throws IOException { demo(true); } /** * Open an URL, read it and store the contents in a string. Adapted from * https://stackoverflow.com/questions/4328711/read-url-to-string-in-few-lines-of-java-code * @param url URL; the URL * @return String * @throws IOException when reading the file fails */ public static String readStringFromURL(final URL url) throws IOException { try (Scanner scanner = new Scanner(url.openStream(), StandardCharsets.UTF_8.toString())) { scanner.useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } } /** * Start the demo. * @param exitOnClose boolean; when running stand-alone: true; when running as part of a demo: false * @throws IOException when reading the file fails */ public static void demo(final boolean exitOnClose) throws IOException { try { OTSAnimator simulator = new OTSAnimator(); URL url = URLResource.getResource("/TrafCODDemo1/TrafCODDemo1.xml"); |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneModel.java | 143 |
org\opentrafficsim\demo\CircularRoadModel.java | 165 |
this.carProbability = (double) getInputParameter("generic.carProbability"); double radius = ((Length) getInputParameter("generic.trackLength")).si / 2 / Math.PI; double headway = 1000.0 / (double) getInputParameter("generic.densityMean"); double headwayVariability = (double) getInputParameter("generic.densityVariability"); this.parametersCar = InputParameterHelper.getParametersCar(getInputParameterMap()); this.parametersTruck = InputParameterHelper.getParametersTruck(getInputParameterMap()); this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); |
File | Line |
---|---|
org\opentrafficsim\demo\network\xml\Circuit.java | 54 |
org\opentrafficsim\demo\network\xml\FourStop.java | 58 |
org\opentrafficsim\demo\network\xml\NetworkTest.java | 54 |
public Circuit(final OTSModelInterface model, final OTSAnimationPanel animationPanel) throws OTSDrawingException { super(model, animationPanel); } /** * Main program. * @param args String[]; the command line arguments (not used) * @throws SimRuntimeException should never happen */ public static void main(final String[] args) throws SimRuntimeException { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { try { OTSAnimator simulator = new OTSAnimator(); TestXMLModel xmlModel = new TestXMLModel(simulator); simulator.initialize(Time.ZERO, Duration.ZERO, Duration.instantiateSI(3600.0), xmlModel); OTSAnimationPanel animationPanel = new OTSAnimationPanel(xmlModel.getNetwork().getExtent(), new Dimension(800, 600), simulator, xmlModel, DEFAULT_COLORER, xmlModel.getNetwork()); new Circuit(xmlModel, animationPanel); |
File | Line |
---|---|
strategies\LmrsStrategies.java | 599 |
strategies\StrategiesDemo.java | 687 |
origin, destination, VehicleModel.NONE); } } /** Perception factory. */ class LmrsStrategiesPerceptionFactory implements PerceptionFactory { /** {@inheritDoc} */ @Override public LanePerception generatePerception(final LaneBasedGTU gtu) { LanePerception perception = new CategoricalLanePerception(gtu); perception.addPerceptionCategory(new DirectEgoPerception<>(perception)); perception.addPerceptionCategory(new DirectInfrastructurePerception(perception)); perception.addPerceptionCategory(new DirectNeighborsPerception(perception, HeadwayGtuType.WRAP)); perception.addPerceptionCategory(new AnticipationTrafficPerception(perception)); return perception; } /** {@inheritDoc} */ @Override public Parameters getParameters() throws ParameterException { return new ParameterSet().setDefaultParameter(ParameterTypes.LOOKAHEAD) .setDefaultParameter(ParameterTypes.LOOKBACKOLD).setDefaultParameter(ParameterTypes.PERCEPTION) .setDefaultParameter(ParameterTypes.LOOKBACK); } } |
File | Line |
---|---|
org\opentrafficsim\demo\FundamentalDiagrams.java | 272 |
org\opentrafficsim\demo\SequentialLanes.java | 328 |
org\opentrafficsim\demo\StraightModel.java | 154 |
this.carProbability = (double) getInputParameter("generic.carProbability"); this.parametersCar = InputParameterHelper.getParametersCar(getInputParameterMap()); this.parametersTruck = InputParameterHelper.getParametersTruck(getInputParameterMap()); this.strategicalPlannerGeneratorCars = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); this.strategicalPlannerGeneratorTrucks = new LaneBasedStrategicalRoutePlannerFactory( new LMRSFactory(new IDMPlusFactory(this.stream), new DefaultLMRSPerceptionFactory())); // 1500 [veh / hour] == 2.4s headway this.headway = new Duration(3600.0 / 1500.0, SECOND); // Schedule creation of the first car (this will re-schedule itself one headway later, etc.). this.simulator.scheduleEventAbs(Time.ZERO, this, this, "generateCar", null); |
File | Line |
---|---|
org\opentrafficsim\demo\web\OTSDemoServer.java | 324 |
org\opentrafficsim\demo\web\OTSFederatedDemoServer.java | 221 |
else if (modelId.toLowerCase().contains("trafcoddemosimple")) { URL url = URLResource.getResource("/TrafCODDemo1/TrafCODDemo1.xml"); String xml = TrafCODDemo2.readStringFromURL(url); model = new TrafCODDemo1.TrafCODModel(simulator, "TrafCODDemo1", "TrafCODDemo1", xml); } else if (modelId.toLowerCase().contains("trafcoddemocomplex")) { URL url = URLResource.getResource("/TrafCODDemo2/TrafCODDemo2.xml"); String xml = TrafCODDemo2.readStringFromURL(url); model = new TrafCODDemo2.TrafCODModel(simulator, "TrafCODDemo2", "TrafCODDemo2", xml); } else if (modelId.toLowerCase().contains("tjunction")) |
File | Line |
---|---|
org\opentrafficsim\demo\CircularLaneModel.java | 229 |
org\opentrafficsim\demo\CircularRoadModel.java | 255 |
gtu.setNoLaneChangeDistance(Length.ZERO); gtu.setMaximumAcceleration(Acceleration.instantiateSI(3.0)); gtu.setMaximumDeceleration(Acceleration.instantiateSI(-8.0)); // strategical planner LaneBasedStrategicalPlanner strategicalPlanner; Route route = null; if (!generateTruck) { strategicalPlanner = this.strategicalPlannerGeneratorCars.create(gtu, route, null, null); } else { strategicalPlanner = this.strategicalPlannerGeneratorTrucks.create(gtu, route, null, null); } // init Set<DirectedLanePosition> initialPositions = new LinkedHashSet<>(1); initialPositions.add(new DirectedLanePosition(lane, initialPosition, GTUDirectionality.DIR_PLUS)); Speed initialSpeed = new Speed(0, KM_PER_HOUR); |
File | Line |
---|---|
org\opentrafficsim\demo\CrossingTrafficLightsModel.java | 287 |
org\opentrafficsim\demo\NetworksModel.java | 386 |
initialPositions, this.strategicalPlannerFactoryCar, routeGenerator); // System.out.println("Constructed template " + template); distribution.add(new FrequencyAndObject<>(this.carProbability, template)); template = makeTemplate(this.stream, lane, new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 8, 14), METER), new ContinuousDistDoubleScalar.Rel<Length, LengthUnit>(new DistUniform(this.stream, 2.0, 2.5), METER), new ContinuousDistDoubleScalar.Rel<Speed, SpeedUnit>(new DistUniform(this.stream, 100, 140), KM_PER_HOUR), initialPositions, this.strategicalPlannerFactoryTruck, routeGenerator); |
File | Line |
---|---|
org\opentrafficsim\demo\web\SuperDemoWebApplication.java | 334 |
org\opentrafficsim\demo\web\SuperDemoWebApplication.java | 389 |
org\opentrafficsim\demo\web\SuperDemoWebApplication.java | 426 |
} catch (Exception e) { status = false; error = e.getMessage(); } byte[] mc2Message = new MC2AckNakMessage(this.federationRunId, this.modelId, message.getSenderId(), ++this.messageCount, message.getMessageId(), status, error).createByteArray(); this.fsSocket.sendMore(identity); this.fsSocket.sendMore(""); this.fsSocket.send(mc2Message, 0); System.out.println("Sent MC.2"); System.out.flush(); } /** * Process FM.3 message and send MC.2 message back. * @param identity reply id for REQ-ROUTER pattern * @param message the FM3 message * @throws Sim0MQException on error * @throws SerializationException on serialization problem */ private void processSetParameter(final String identity, final FM3SetParameterMessage message) |
File | Line |
---|---|
org\opentrafficsim\demo\web\OTSDemoServer.java | 560 |
org\opentrafficsim\demo\web\OTSDemoServer.java | 577 |
org\opentrafficsim\demo\web\OTSFederatedDemoServer.java | 440 |
org\opentrafficsim\demo\web\OTSFederatedDemoServer.java | 457 |
answer.append("<doubleScalar key='" + pds.getExtendedKey() + "' name='" + pds.getShortName() + "' description='" + pds.getDescription() + "'><value>" + val + "</value>\n"); for (String unit : units) { Unit<?> unitValue = pds.getUnitParameter().getOptions().get(unit); if (unitValue.equals(pds.getUnitParameter().getValue())) answer.append("<unit chosen='true'>" + unit + "</unit>\n"); else answer.append("<unit chosen='false'>" + unit + "</unit>\n"); } answer.append("</doubleScalar>\n"); |