CPD Results

The following document contains the results of PMD's CPD 6.21.0.

Duplications

File Line
org\opentrafficsim\demo\web\OTSDemoServer.java 428
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&lt;?,?&gt;; 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 102
org\opentrafficsim\ahfe\AHFESimulation.java 90
        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 405
org\opentrafficsim\ahfe\AHFESimulation.java 385
        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 = RoadSampler.build(this.network).registerExtendedDataType(new TimeToCollision()).create();
            try
            {
                URL xmlURL = URLResource.getResource("/AHFE/Network.xml");
                this.network = new OTSRoadNetwork("AHFE", true, getSimulator());
                XmlNetworkLaneParser.build(xmlURL, this.network, false);

                // 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\ahfe\AHFEAnimation.java 309
org\opentrafficsim\ahfe\AHFESimulation.java 296
                        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().getSamplerData().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 | DSOLException exception)
File Line
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java 253
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java 176
                        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
        {
            EventTypeInterface 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("]");
            }
        }

        /** {@inheritDoc} */
        @Override
        public Serializable getSourceId()
        {
            return "TrafCODModel";
        }
    }
}
File Line
org\opentrafficsim\demo\CircularLaneSwing.java 100
org\opentrafficsim\demo\StraightSwing.java 97
                CircularLaneSwing app = new CircularLaneSwing("Circular Lane", animationPanel, otsModel);
                app.setExitOnClose(exitOnClose);
                animationPanel.enableSimulationControlButtons();
            }
            else
            {
                if (exitOnClose)
                {
                    System.exit(0);
                }
            }
        }
        catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException | DSOLException 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(getModel().getNetwork());
        GraphPath.initRecording(sampler, path);
        ContourDataSource<?> dataPool = new ContourDataSource<>(sampler.getSamplerData(), path);
        TablePanel charts = new TablePanel(3, 2);
        SwingPlot plot = null;

        plot = new SwingTrajectoryPlot(
                new TrajectoryPlot("TrajectoryPlot", Duration.instantiateSI(10.0), simulator, sampler.getSamplerData(), 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 100
org\opentrafficsim\demo\SequentialLanes.java 139
org\opentrafficsim\demo\StraightSwing.java 97
                CircularLaneSwing app = new CircularLaneSwing("Circular Lane", animationPanel, otsModel);
                app.setExitOnClose(exitOnClose);
                animationPanel.enableSimulationControlButtons();
            }
            else
            {
                if (exitOnClose)
                {
                    System.exit(0);
                }
            }
        }
        catch (SimRuntimeException | NamingException | RemoteException | OTSDrawingException | DSOLException 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(getModel().getNetwork());
        GraphPath.initRecording(sampler, path);
        ContourDataSource<?> dataPool = new ContourDataSource<>(sampler.getSamplerData(), path);
        TablePanel charts = new TablePanel(3, 2);
        SwingPlot plot = null;

        plot = new SwingTrajectoryPlot(
                new TrajectoryPlot("TrajectoryPlot", Duration.instantiateSI(10.0), simulator, sampler.getSamplerData(), 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\ahfe\AHFEAnimation.java 514
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;
        }

        /** {@inheritDoc} */
        @Override
        public Serializable getSourceId()
        {
            return "AHFEAnimation.Model";
File Line
org\opentrafficsim\remotecontrol\Sim0MQRemoteController.java 133
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 134
                        gui = new Sim0MQRemoteController();
                        gui.setVisible(true);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                        System.exit(ERROR);
                    }
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();
            System.exit(ERROR);
        }
        // We don't get here until the GUI is fully running.
        Options options = new Options();
        CliUtil.execute(options, args); // register Unit converters, parse the command line, etc..
        gui.processArguments(options.getHost(), options.getPort());
    }

    /** ... */
    private ZContext zContext = new ZContext(1);

    /** Message relayer. */
    private Thread pollerThread;

    /**
     * Poller thread for relaying messages between the remote OTS and local AWT.
     */
    class PollerThread extends Thread
    {
        /** The ZContext. */
        private final ZContext context;

        /** The host that runs the OTS simulation. */
        private final String slaveHost;

        /** The port on which to connect to the OTS simulation. */
        private final int slavePort;

        /**
         * Construct a new PollerThread for relaying messages.
         * @param context ZContext; the ZMQ context
         * @param slaveHost String; host name of the OTS server machine
         * @param slavePort int; port number on which to connect to the OTS server machine
         */
        PollerThread(final ZContext context, final String slaveHost, final int slavePort)
        {
            this.context = context;
            this.slaveHost = slaveHost;
            this.slavePort = slavePort;
        }

        @Override
        public final void run()
        {
            int nextExpectedPacket = 0;
            ZMQ.Socket slaveSocket = this.context.createSocket(SocketType.PAIR); // changed to PAIR
            slaveSocket.setHWM(100000);
            ZMQ.Socket awtSocketIn = this.context.createSocket(SocketType.PULL);
            awtSocketIn.setHWM(100000);
            ZMQ.Socket awtSocketOut = this.context.createSocket(SocketType.PUSH);
            awtSocketOut.setHWM(100000);
            slaveSocket.connect("tcp://" + this.slaveHost + ":" + this.slavePort);
            awtSocketIn.bind("inproc://fromAWT");
            awtSocketOut.bind("inproc://toAWT");
            ZMQ.Poller items = this.context.createPoller(2);
            items.register(slaveSocket, ZMQ.Poller.POLLIN);
            items.register(awtSocketIn, ZMQ.Poller.POLLIN);
            while (!Thread.currentThread().isInterrupted())
            {
File Line
org\opentrafficsim\remotecontrol\Sim0MQRemoteController.java 293
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 292
    Sim0MQRemoteController()
    {
        // Construct the GUI
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        setBounds(100, 100, 1000, 800);
        JPanel panelAll = new JPanel();
        panelAll.setBorder(new EmptyBorder(5, 5, 5, 5));
        panelAll.setLayout(new BorderLayout(0, 0));
        setContentPane(panelAll);
        JPanel panelControls = new JPanel();
        panelAll.add(panelControls, BorderLayout.PAGE_START);
        JTextArea textArea = new JTextArea();
        textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
        JScrollPane scrollPane = new JScrollPane(textArea);
        scrollPane.setPreferredSize(new Dimension(800, 400));
        panelAll.add(scrollPane, BorderLayout.PAGE_END);
        this.output = new PrintStream(new TextAreaOutputStream(textArea), true);
        JPanel controls = new JPanel();
        controls.setLayout(new FlowLayout());
        JButton sendNetwork = new JButton("Send network");
        sendNetwork.setActionCommand("SendNetwork");
        sendNetwork.addActionListener(this);
        controls.add(sendNetwork);
        this.stepTo = new JButton("Step to 10 s");
        this.stepTo.setActionCommand("StepTo");
        this.stepTo.addActionListener(this);
        controls.add(this.stepTo);
        JButton step100TimesTo = new JButton("Step 100 times 10 s");
        step100TimesTo.setActionCommand("Step100To");
        step100TimesTo.addActionListener(this);
        controls.add(step100TimesTo);
        JButton getGTUPositions = new JButton("Get all GTU positions");
        getGTUPositions.setActionCommand("GetAllGTUPositions");
        getGTUPositions.addActionListener(this);
        controls.add(getGTUPositions);
File Line
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java 310
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java 234
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java 224
        }

        /** {@inheritDoc} */
        @Override
        public void notify(final EventInterface event) throws RemoteException
        {
            EventTypeInterface 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("]");
            }
        }

        /** {@inheritDoc} */
        @Override
        public Serializable getSourceId()
        {
            return "TrafCODModel";
        }
    }
}
File Line
org\opentrafficsim\demo\FundamentalDiagrams.java 320
org\opentrafficsim\demo\SequentialLanes.java 376
        }

        /**
         * 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 197
org\opentrafficsim\demo\conflictAndControl\DemoTrafcodAndTurbo.java 223
                                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\remotecontrol\Sim0MQControlledOTS.java 198
org\opentrafficsim\remotecontrol\Sim0MQControlledOTSNew.java 43
    }

    /**
     * The command line options.
     */
    @Command(description = "Sim0MQ Remotely Controlled OTS", name = "Sim0MQOTS", mixinStandardHelpOptions = true,
            version = "1.0")
    public static class Options implements Checkable
    {
        /** The IP port. */
        @Option(names = { "-p", "--port" }, description = "Internet port to use", defaultValue = "8888")
        private int port;

        /**
         * Retrieve the port.
         * @return int; the port
         */
        public final int getPort()
        {
            return this.port;
        }

        @Override
        public final void check() throws Exception
        {
            if (this.port <= 0 || this.port > 65535)
            {
                throw new Exception("Port should be between 1 and 65535");
            }
        }
    }

    /**
     * Program entry point.
     * @param args String[]; the command line arguments
     * @throws OTSGeometryException on error
     * @throws NetworkException on error
     * @throws NamingException on error
     * @throws ValueRuntimeException on error
     * @throws SimRuntimeException on error
     * @throws ParameterException on error
     * @throws SerializationException on error
     * @throws Sim0MQException on error
     * @throws IOException on error
     */
    public static void main(final String[] args) throws NetworkException, OTSGeometryException, NamingException,
            ValueRuntimeException, ParameterException, SimRuntimeException, Sim0MQException, SerializationException, IOException
    {
        CategoryLogger.setAllLogLevel(Level.WARNING);
        CategoryLogger.setLogCategories(LogCategory.ALL);
        Options options = new Options();
        CliUtil.execute(options, args); // register Unit converters, parse the command line, etc..
        int port = options.getPort();
        System.out.println("Creating OTS server listening on port " + port);
File Line
org\opentrafficsim\remotecontrol\Sim0MQRemoteController.java 232
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 231
                    message = awtSocketIn.recv(0);
                    // System.out.println("poller has received a message on the fromAWT PULL socket; transmitting to OTS");
                    slaveSocket.send(message);
                }
            }

        }

    }

    /**
     * Open connections as specified on the command line, then start the message transfer threads.
     * @param host String; host to connect to (listening OTS server should already be running)
     * @param port int; port to connect to (listening OTS server should be listening on that port)
     */
    public void processArguments(final String host, final int port)
    {
        this.output.println("host is " + host + ", port is " + port);

        this.pollerThread = new PollerThread(this.zContext, host, port);

        this.pollerThread.start();

        this.toOTS = this.zContext.createSocket(SocketType.PUSH);
        this.toOTS.setHWM(100000);

        new OTS2AWT(this.zContext).start();

        this.toOTS.connect("inproc://fromAWT");
    }

    /**
     * Write something to the remote OTS.
     * @param command String; the command to write
     * @throws IOException when communication fails
     */
    public void write(final String command) throws IOException
    {
        this.toOTS.send(command);
        // output.println("Wrote " + command.getBytes().length + " bytes");
        this.output.println("Sent string \"" + command + "\"");
    }

    /**
     * Write something to the remote OTS.
     * @param bytes byte[]; the bytes to write
     * @throws IOException when communication fails
     */
    public void write(final byte[] bytes) throws IOException
    {
        this.toOTS.send(bytes);
        // output.println("Wrote " + command.getBytes().length + " bytes");
        // output.println(HexDumper.hexDumper(bytes));
    }

    /** Step to button. */
    private JButton stepTo;
File Line
org\opentrafficsim\remotecontrol\Sim0MQRemoteController.java 477
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 531
                        Sim0MQRemoteController.this.output.println(HexDumper.hexDumper(bytes));
                    }
                }
                catch (ZMQException | Sim0MQException | SerializationException e)
                {
                    e.printStackTrace();
                    return;
                }
            }
            while (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() : "";
        }
    }

    /** {@inheritDoc} */
    @Override
    public void actionPerformed(final ActionEvent e)
    {
        switch (e.getActionCommand())
        {
            case "SendNetwork":
            {
                String networkFile = "/TrafCODDemo2/TrafCODDemo2.xml";
                Duration warmupDuration = Duration.ZERO;
                Duration runDuration = new Duration(3600, DurationUnit.SECOND);
                Long seed = 123456L;
                URL url = URLResource.getResource(networkFile);
                // System.out.println("url is " + url);
                try
                {
                    String xml = readStringFromURL(url);
File Line
org\opentrafficsim\remotecontrol\Sim0MQRemoteController.java 327
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 330
        controls.add(getGTUPositions);
        panelAll.add(controls, BorderLayout.CENTER);
    }

    /** Debugging and other output goes here. */
    @SuppressWarnings("checkstyle:visibilitymodifier")
    PrintStream output = null;

    /**
     * Shut down this application.
     */
    public void shutDown()
    {
        // Do we have to kill anything for a clean exit?
    }

    /** {@inheritDoc} */
    @Override
    public void windowOpened(final WindowEvent e)
    {
        // Do nothing
    }

    /** {@inheritDoc} */
    @Override
    public final void windowClosing(final WindowEvent e)
    {
        shutDown();
    }

    /** {@inheritDoc} */
    @Override
    public void windowClosed(final WindowEvent e)
    {
        // Do nothing
    }

    /** {@inheritDoc} */
    @Override
    public void windowIconified(final WindowEvent e)
    {
        // Do nothing
    }

    /** {@inheritDoc} */
    @Override
    public void windowDeiconified(final WindowEvent e)
    {
        // Do nothing
    }

    /** {@inheritDoc} */
    @Override
    public void windowActivated(final WindowEvent e)
    {
        // Do nothing
    }

    /** {@inheritDoc} */
    @Override
    public void windowDeactivated(final WindowEvent e)
    {
        // Do nothing
    }

    /**
     * Thread that reads results from OTS and (for now) writes those to the textArea.
     */
    class OTS2AWT extends Thread
    {
        /** Socket where the message from OTS will appear. */
        private final ZMQ.Socket fromOTS;

        /**
         * Construct a new OTS2AWT thread.
         * @param zContext ZContext; the ZContext that is needed to construct the PULL socket to read the messages
         */
        OTS2AWT(final ZContext zContext)
        {
            this.fromOTS = zContext.createSocket(SocketType.PULL);
            this.fromOTS.setHWM(100000);
            this.fromOTS.connect("inproc://toAWT");
        }
File Line
org\opentrafficsim\demo\CircularLaneModel.java 156
org\opentrafficsim\demo\CircularRoadModel.java 215
                    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\remotecontrol\Sim0MQRemoteController.java 59
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 60
public class Sim0MQRemoteController extends JFrame implements WindowListener, ActionListener
{
    /** ... */
    private static final long serialVersionUID = 20200304L;

    /**
     * The command line options.
     */
    @Command(description = "Test program for Remote Control OTS", name = "Remote Control OTS", mixinStandardHelpOptions = true,
            version = "1.0")
    public static class Options implements Checkable
    {
        /** The IP port. */
        @Option(names = {"-p", "--port"}, description = "Internet port to use", defaultValue = "8888")
        private int port;

        /**
         * Retrieve the port.
         * @return int; the port
         */
        public final int getPort()
        {
            return this.port;
        }

        /** The host name. */
        @Option(names = {"-H", "--host"}, description = "Internet host to use", defaultValue = "localhost")
        private String host;

        /**
         * Retrieve the host name.
         * @return String; the host name
         */
        public final String getHost()
        {
            return this.host;
        }

        @Override
        public final void check() throws Exception
        {
            if (this.port <= 0 || this.port > 65535)
            {
                throw new Exception("Port should be between 1 and 65535");
            }
        }
    }

    /** The instance of the RemoteControl. */
    @SuppressWarnings("checkstyle:visibilitymodifier")
    static Sim0MQRemoteController gui = null;
File Line
org\opentrafficsim\demo\CrossingTrafficLightsModel.java 279
org\opentrafficsim\demo\NetworksModel.java 377
    {
        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\conflict\TJunctionDemo.java 167
org\opentrafficsim\demo\conflict\TurboRoundaboutDemo.java 182
                    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;
        }

        /** {@inheritDoc} */
        @Override
        public Serializable getSourceId()
        {
            return "TJunctionModel";
File Line
org\opentrafficsim\demo\CircularLaneModel.java 223
org\opentrafficsim\demo\FundamentalDiagrams.java 328
org\opentrafficsim\demo\SequentialLanes.java 384
    {
        // 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\CircularLaneModel.java 145
org\opentrafficsim\demo\CircularRoadModel.java 202
            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\conflictAndControl\DemoTrafcodAndTurbo.java 254
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo1.java 195
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java 177
                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;
        }
File Line
strategies\LmrsStrategies.java 600
strategies\StrategiesDemo.java 695
                        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\trafficcontrol\TrafCODDemo1.java 66
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2.java 66
org\opentrafficsim\demo\trafficcontrol\TrafCODDemo2_Generators.java 59
    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("TrafCODDemo1");
File Line
org\opentrafficsim\demo\FundamentalDiagrams.java 275
org\opentrafficsim\demo\SequentialLanes.java 333
                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 323
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\remotecontrol\Sim0MQRemoteController.java 210
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 210
                    message = slaveSocket.recv(0);
                    String expectedSenderField = String.format("slave_%05d", ++nextExpectedPacket);
                    try
                    {
                        Object[] messageFields = Sim0MQMessage.decode(message).createObjectArray();
                        String senderTag = (String) messageFields[3];
                        if (!senderTag.equals(expectedSenderField))
                        {
                            System.err.println("Got message " + senderTag + " , expected " + expectedSenderField
                                    + ", message is " + messageFields[5]);
                        }
                    }
                    catch (Sim0MQException | SerializationException e)
                    {
                        e.printStackTrace();
                    }

                    // System.out.println("poller has received a message on the fromOTS DEALER socket; transmitting to AWT");
                    awtSocketOut.send(message);
                }
                if (items.pollin(1))
                {
File Line
org\opentrafficsim\demo\CircularLaneModel.java 231
org\opentrafficsim\demo\CircularRoadModel.java 290
        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 289
org\opentrafficsim\demo\NetworksModel.java 387
                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\FundamentalDiagrams.java 288
org\opentrafficsim\demo\StraightModel.java 188
                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\remotecontrol\Sim0MQRemoteController.java 569
org\opentrafficsim\remotecontrol\Sim0MQRemoteControllerNew.java 634
                    button.setText(caption.substring(0, position)
                            + String.format("%.0f %s", toTime.getInUnit(), toTime.getDisplayUnit()));
                }
                catch (IOException | Sim0MQException | SerializationException e1)
                {
                    e1.printStackTrace();
                }
                break;
            }

            case "Step100To":
            {
                for (int i = 0; i < 100; i++)
                {
                    actionPerformed(new ActionEvent(this.stepTo, 0, "StepTo"));
                }
                break;
            }

            case "GetAllGTUPositions":
            {
                try
                {
                    write(Sim0MQMessage.encodeUTF8(true, 0, "RemoteControl", "OTS", "SENDALLGTUPOSITIONS", 0));
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 559
org\opentrafficsim\demo\web\OTSDemoServer.java 576
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");