コード例 #1
0
        public void Run()
        {
            vissim = new Vissim();
            //Load Vissim net work
            vissim.LoadNet(VissimSimulatorFilePath, false);

            //initialize the cellular network
            cellularNetwork.LoadFromFile(CellLinkRelationFilePath, Delimiter);

            CollectorWorker worker = new CollectorWorker(VissimEventsFilePath, cellularTowerEvents);
            //collector task: collecting the data from cellular events
            Task collectorTask = Task.Factory.StartNew(() => worker.Run(), token);

            //simulation thread: including vissim simulation, events generation and detection
            Task simulator = Task.Factory.StartNew(() => Execute(), token);

            try
            {
                Task.WaitAll(simulator, collectorTask);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("there are some exceptions happened: {0}", ex.Message));
                throw ex;
            }
        }
コード例 #2
0
        public Intersection(Vissim vis, int id, IDetectorContainer dc, string stpln_det_str, string overflow_det_str,
                            ISignalController SC, int[,] inter_graph, int[] real_key)
        {
            this.vis                = vis;
            this._id                = id;
            this.stpln_det          = new IDetector[Globals.SINGLE_PHASE_NUM][];
            this.stpln_det_vehno    = new int[Globals.SINGLE_PHASE_NUM][];
            this.overflow_det       = new IDetector[Globals.LINK_NUM_ALL][];
            this.overflow_det_vehno = new int[Globals.LINK_NUM_ALL][];

            this._SC = SC;
            this.configure_phases_all();

            this.config_det_str("stpln", stpln_det_str);
            this.config_det_str("overflow", overflow_det_str);
            this.config_det(dc, "stpln_det", real_key);
            this.config_det(dc, "overflow_det", real_key);

            this.clear_veh_counter();
            this.init_link_length(inter_graph);
            this.init_link_sat_flow();
            this.init_link_veh_list();
            this.init_link_avg_speed();
            this.init_link_connection(inter_graph);

            this.init_link_len_set();
        }
コード例 #3
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 ///
 /// </summary>
 /// <param name="eval"></param>
 /// <returns>Cached wrapper</returns>
 public static VissimWrapper Wrap(this Vissim vissim)
 {
     if (vissimWrapper == null)
     {
         vissimWrapper = new VissimWrapper(vissim);
     }
     return(vissimWrapper);
 }
コード例 #4
0
        public Network(Vissim vissim, int inter_num)
        {
            this.vissim = vissim;

            this.inter_num = inter_num;
            this.init_inter_graph();
            this.init_net_det_str();
            this.init_inters();
        }
コード例 #5
0
ファイル: Form1.cs プロジェクト: hujinghaoabcd/trafficP
        //加载路网
        private void InitialSystem()
        {
            vis = new Vissim();
            vis.LoadNet(@"E:\vissim4.3\Example\lianglukou.inp", 0);
            vis.Simulation.Resolution = 1;
            vis.Evaluation.set_AttValue("DATACOLLECTION", true); //软件激活datacollection检测器评价
            vis.Evaluation.set_AttValue("TRAVELTIME", true);     //软件激活traveltime检测器评价
            vis.Evaluation.set_AttValue("QUEUECOUNTER", true);   //软件激活queuecounter检测器评价
            vis.Evaluation.set_AttValue("DELAY", true);          //软件激活dealy检测器评价

            //设置各检测器的评价周期


            label15.Text         = "";                                     //仿真步数显示控件初始化
            progressBar1.Minimum = 0;                                      //进度条显示控件最小值设置
            progressBar1.Maximum = Convert.ToInt32(vis.Simulation.Period); //进度条显示控件最大值设置
            //仿真信息表格展示
            VehicleInputs vehins = vis.Net.VehicleInputs;

            listView2.Clear();
            listView2.View          = View.Details;
            listView2.FullRowSelect = true;
            listView2.Columns.Add("交叉口ID", 100, HorizontalAlignment.Center);
            listView2.Columns.Add("延时时间(s)", 100, HorizontalAlignment.Center);
            listView2.Columns.Add("仿真时间(s)", 100, HorizontalAlignment.Center);
            listView2.Columns.Add("输入交通量(pcu)", 100, HorizontalAlignment.Center);
            for (int i = 1; i <= vehins.Count; i++)
            {
                ListViewItem itm = listView2.Items.Add(vehins[i].ID.ToString());
                itm.SubItems.AddRange(new string[] { (vehins[i].AttValue["TIMEFROM"]).ToString(), vis.Simulation.Period.ToString(), (string)(vehins[i].AttValue["VOLUME"]).ToString() });
            }

            //修改vissim中各交叉口信号机周期

            for (int i = 1; i <= 4; i++)
            {
                vis.Net.SignalControllers.GetSignalControllerByNumber(i).AttValue["CYCLETIME"] = infoArr[i - 1];
                groups = vis.Net.SignalControllers[i].SignalGroups;

                for (int j = 1; j <= Convert.ToInt32(groups.Count); j++)
                {
                    group = groups.GetSignalGroupByNumber(j);
                    if (j == 1)
                    {
                        group.AttValue["GREENEND"] = firstgreenArr[i - 1];
                        group.AttValue["REDEND"]   = 0;
                        group.AttValue["AMBER"]    = 3;
                    }
                    else
                    {
                        group.AttValue["GREENEND"] = infoArr[i - 1] - 3;
                        group.AttValue["REDEND"]   = infoArr[i - 1] - secondgreenArr[i - 1] - 3;
                        group.AttValue["AMBER"]    = 3;
                    }
                }
            }
        }
コード例 #6
0
ファイル: Form1.cs プロジェクト: hujinghaoabcd/trafficP
 //加载路网文件
 private void intialRoadNet()
 {
     vis = new Vissim();
     vis.LoadNet(@"E:\vissim4.3\Exe\node2.inp", 0);
     vis.Simulation.Resolution = 1;
     vis.Evaluation.set_AttValue("DATACOLLECTION", true); //软件激活datacollection检测器评价
     vis.Evaluation.set_AttValue("TRAVELTIME", true);     //软件激活traveltime检测器评价
     vis.Evaluation.set_AttValue("QUEUECOUNTER", true);   //软件激活queuecounter检测器评价
     vis.Evaluation.set_AttValue("DELAY", true);          //软件激活dealy检测器评价
 }
コード例 #7
0
        static void runVissimSimulation(string s_inpx, string s_layx, int sim_random_seed, int index)
        {
            Vissim vissim = new Vissim();

            vissim.LoadNet(s_inpx);
            vissim.LoadLayout(s_layx);
            ISimulation simulation = config_simulation(vissim, s_inpx, s_layx, sim_random_seed);
            Network     net        = new Network(vissim, Globals.INTER_NUM);

            start_simulation(simulation, net, index);
        }
コード例 #8
0
 /// <summary>
 /// Attempts to load network into VISSIM
 /// </summary>
 /// <param name="vissimInstance">Vissim object with COM established</param>
 /// <param name="inpxPath">Full path to the .inpx VISSIM file</param>
 public static void LoadVissimNetwork(Vissim vissimInstance, string inpxPath)
 {
     try
     {
         vissimInstance.LoadNet(inpxPath);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error while loading Vissim network!");
     }
 }
コード例 #9
0
 /// <summary>
 /// Attempts to load layout into VISSIM
 /// </summary>
 /// <param name="vissimInstance">Vissim object with COM established</param>
 /// <param name="layxPath">Full path to the .layx VISSIM file</param>
 public static void LoadVissimLayout(Vissim vissimInstance, string layxPath)
 {
     try
     {
         vissimInstance.LoadLayout(layxPath);
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error while loading Vissim layout!");
     }
 }
コード例 #10
0
 public void test_control_link_veh_speed(Vissim vis, double target_speed)
 {
     for (int i = 0; i < this.inter_link_veh_set.Count; i++)
     {
         foreach (var veh_id in this.inter_link_veh_set[i])
         {
             IVehicle veh   = vis.Net.Vehicles.get_ItemByKey(veh_id);
             double   speed = veh.get_AttValue("SPEED");
             veh.set_AttValue("SPEED", target_speed);
         }
     }
 }
コード例 #11
0
        public void Run()
        {
            Vissim vissim = new Vissim();
            ///Load Vissim net work
            VissimSimulator.LoadNet(@"C:\Users\Public\Documents\PTV Vision\PTV Vissim 6\Examples Demo\Urban Intersection Beijing.CN\Intersection Beijing.inpx");
            ///Read table contains Cellular tower information and correspoing link information
            var cellTowerInformation = new StreamReader(File.OpenRead(@"C:\test.csv"));
            CellularTowerEvent cte = new CellularTowerEvent();
            while (!cellTowerInformation.EndOfStream)
            {
                var line = cellTowerInformation.ReadLine();
                var values = line.Split(';');

                cte.CellularTowerId = CellTower.AddLink(Int32.Parse(values[0]));
                cte.LocationId = Location.AddCellTower(Int32.Parse(values[1]));
            }
            ///Generate the random event, when vehicle passing a fixed location and the Timespan is satisfied.
            foreach (IVehicle vehicle in vissim.Net.Vehicles)
            {
                ///Select Random Vehicle
                int vehiclePossible = rnd.Next(0, 10);
                //Only Selected Vehicle can generate the Event.
                if (vehiclePossible == 0)
                {
                    Event evet = new Event();
                    ///Create random event type.
                    int i = rnd.Next(0, 1);
                    evet.TimeSpan = EventFactory.CreateTimeSpan();
                    evet.EventType = EventFactory.CreateEventType;
                    cte.Event = evet;
                }
                ///record the event information 
                CollectorWorker collect = new CollectorWorker();
                if (vehicle.Location == cte.CellTowerId & cte.Event.TimeSpan == simulationTime)
                {
                    collect.ProcessEvent(cte);
                }
            ///Make the program check the all vehicle in Vissim network every 1 sec.
            for (int i = 0; i < simulationTime; i++)
            {
                vissim.Simulation.RunSingleStep();
                foreach (CollectorWorker worker in CollectorWorkers)
                {
                    Task workerTask = Task.Run(() =>
                    {
                        worker.ProcessEvent(CellularTowerEvents);
                    });

                    workerTask.Wait();
                }
            }
        }
コード例 #12
0
 /// <summary>
 /// Performs one step, activates proper phase
 /// </summary>
 /// <param name="resolution">Simulation resolution</param>
 /// <param name="vissim">Vissim instance</param>
 public void Step(int resolution, Vissim vissim)
 {
     if (currentPhase.Step(resolution, signalControllerId, vissim))
     {
         currentPhaseIndex++;
         if (currentPhaseIndex == phaseCount)
         {
             currentPhaseIndex = 0;
             currentDuration   = 0;
             currentPhase      = phases[currentPhaseIndex];
         }
         currentPhase = phases[currentPhaseIndex];
     }
     currentDuration += 1 / resolution;
 }
コード例 #13
0
        static ISimulation config_simulation(Vissim vissim, string s_inpx, string s_layx, int random_seed)
        {
            ISimulation simulation = vissim.Simulation;

            simulation.set_AttValue("SimRes", Globals.SIM_RES);
            simulation.set_AttValue("RandSeed", random_seed);
            simulation.set_AttValue("SimPeriod", Globals.SIM_TIME);
            simulation.set_AttValue("SimSpeed", Globals.SIM_SPEED);

            IEvaluation eva = vissim.Evaluation;

            eva.set_AttValue("DelaysCollectData", true);

            return(simulation);
        }
コード例 #14
0
        private void button6_Click(object sender, EventArgs e)
        {
            Vissim vis             = vissim.GetVissimInstance();
            int    controllercount = vis.Net.SignalControllers.Count;

            foreach (ISignalController controller in vis.Net.SignalControllers)
            {
                int numSGS = controller.SGs.Count;
                MessageBox.Show("" + numSGS, "OP OP");
                foreach (ISignalGroup signalGroup in controller.SGs)
                {
                    MessageBox.Show("My name is: " + signalGroup.get_AttValue("Name"), "OP OP");
                }
            }
        }
コード例 #15
0
        public Vehicle[] vehicle = new Vehicle[4];             //车辆对象

        //初始化各个对象并设置相关参数
        public JVissim()
        {
            vissim = new Vissim();
            vissim.LoadNet(System.Environment.CurrentDirectory + @"\JVissim\jvissim.inp");
            vissim.LoadLayout(System.Environment.CurrentDirectory + @"\JVissim\jvissim.ini");
            net            = vissim.Net;
            simulation     = vissim.Simulation;
            links          = net.Links;
            signalGroup[0] = net.SignalControllers.GetSignalControllerByNumber(1).SignalGroups.GetSignalGroupByNumber(1);
            signalGroup[0].set_AttValue("type", 2); //初始状态为绿灯,即允许车辆通过
            signalGroup[1] = net.SignalControllers.GetSignalControllerByNumber(2).SignalGroups.GetSignalGroupByNumber(1);
            signalGroup[1].set_AttValue("type", 2); //初始状态为绿灯,即允许车辆通过
            initializeLinks();
            initializeDetectors();
            startSimulation();
        }
コード例 #16
0
ファイル: Phase.cs プロジェクト: MladenMiletic/NET_TO_VISSIM
 /// <summary>
 /// Activates required subphase
 /// </summary>
 /// <param name="resolution">Simulation resolution</param>
 /// <param name="vissim">Vissim instance</param>
 /// <param name="signalControllerId">Id of the signal controller</param>
 /// <returns>True if phase is over, false if not</returns>
 public bool Step(int resolution, int signalControllerId, Vissim vissim)
 {
     if (currentSubPhase.Step(resolution, signalControllerId, vissim))
     {
         currentSubPhaseIndex++;
         if (currentSubPhaseIndex == subPhaseCount)
         {
             currentSubPhaseIndex = 0;
             currentDuration      = 0;
             currentSubPhase      = subPhases[currentSubPhaseIndex];
             return(true);
         }
         currentSubPhase = subPhases[currentSubPhaseIndex];
     }
     currentDuration += 1 / resolution;
     return(false);
 }
コード例 #17
0
        };                                                    //东进口左转车道的最小空隙间隔内的车辆数目

        //构造方法
        public Intersection()
        {
            fPath  = System.Environment.CurrentDirectory;
            vissim = new Vissim();
            vissim.LoadNet(fPath + @"\Intersection\intersection.inp");
            vissim.LoadLayout(fPath + @"\Intersection\intersection.ini");
            net = vissim.Net;
            //vissim.Evaluation.set_AttValue("travelTime", true);  //在Evaluation对话框中选中TRAVELTIME
            //travelTimeEvaluation = vissim.Evaluation.TravelTimeEvaluation;
            //travelTimeEvaluation.set_AttValue("compiled", true);  //设置文件为.rsz格式(编译格式)
            //travelTimeEvaluation.set_AttValue("raw", false);  //设置.rsr文件不可写
            //travelTimeEvaluation.set_AttValue("file", true);  //设置文件可写
            traveltimes = net.TravelTimes;
            simulation  = vissim.Simulation;
            links       = net.Links;
            initializeSignalGroups();
            initializeDetectors();
            initializeTraveltimes();
            startSimulation();
        }
コード例 #18
0
        void initNet()
        {
            vissim = new Vissim();
            vissim.LoadNet(vissimMapFilePath);
            net                   = vissim.Net;
            simulation            = vissim.Simulation;
            simulation.Resolution = 4;

            if (net.SignalControllers.Count != 0)
            {
                signalController = net.SignalControllers.GetSignalControllerByNumber(1);
                signalGroup      = signalController.SignalGroups.GetSignalGroupByNumber(1);
            }


            check();
            while ((vehicle = getVehicle(1)) == null)
            {
                RunSingle();
            }
        }
コード例 #19
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// Disable the main menu.
 /// </summary>
 public static void DisableMenu(this Vissim v)
 {
     v.set_AttValue("MENU", 0);
 }
コード例 #20
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// Disable all toolbars except Zoom (File, Selection, Run Control, Network Elements, Animation, Test, and Simulation).
 /// </summary>
 public static void DisableToolbar(this Vissim v)
 {
     v.set_AttValue("TOOLBAR", 0);
 }
コード例 #21
0
        /// <summary>
        /// The main entry point for the application.
        /// <summary>
        static void Main()
        {
            // Connecting the COM Server => Open a new Vissim Window:
            Vissim Vissim = new Vissim();
            // If you have installed muliple Vissim Versions, you have to set the reference to the Vissim Version you want to open.

            string Path_of_COM_example_network = Directory.GetCurrentDirectory();

            Path_of_COM_example_network = "C:\\Users\\Public\\Documents\\PTV Vision\\PTV Vissim 7\\Examples Training\\COM\\Basic Commands\\"; // always use \\ at the end !!
            string Filename = Path_of_COM_example_network + "COM_example.inpx";

            Vissim.LoadNet(Filename, false);

            // Load a Layout:
            Filename = Path_of_COM_example_network + "COM_example.layx";
            Vissim.LoadLayout(Filename);

            //// ========================================================================
            // Read and Set attributes
            //==========================================================================
            // Note: All of the following commands can also be executed during a
            // simulation.

            // Read Link Name:
            int    Link_number  = 1;
            string Name_of_Link = (string)Vissim.Net.Links.get_ItemByKey(Link_number).AttValue["Name"];

            Console.WriteLine("Name of Link(" + Link_number + "): " + Name_of_Link);

            // Set Link Name:
            string new_Name_of_Link = "New Link Name";

            Vissim.Net.Links.get_ItemByKey(Link_number).set_AttValue("Name", new_Name_of_Link);

            // Set a signal controller program:
            int SC_number = 1; // SC = SignalController
            ISignalController SignalController = Vissim.Net.SignalControllers.get_ItemByKey(SC_number);
            int new_signal_programm_number     = 2;

            SignalController.set_AttValue("ProgNo", new_signal_programm_number);


            // Set relative flow of a static vehilce route of a static vehicle routing desision:
            int    SVRD_number      = 1; // SVRD = Static Vehicle Routing Desision
            int    SVR_number       = 1; // SVR = Static Vehicle Route (of a specific Static Vehicle Routing Desision)
            double new_relativ_flow = 0.6;

            Vissim.Net.VehicleRoutingDecisionsStatic.get_ItemByKey(SVRD_number).VehRoutSta.get_ItemByKey(SVR_number).set_AttValue("RelFlow(1)", new_relativ_flow);
            // "RelFlow(1)" means the first defined time interval; to access the third definded time intervall: "RelFlow(3)"

            // Set vehicle input:
            int    VI_number  = 1;   // VI = Vehicle Input
            double new_volume = 600; // vehicles per hour

            Vissim.Net.VehicleInputs.get_ItemByKey(VI_number).set_AttValue("Volume(1)", new_volume);
            // "Volume(1)" means the first defined time interval
            // Hint: The Volumes of following intervals Volume(i) i = 2...n can only be
            // edited, if continous is deactivated: (otherwise error: "AttValue failed: Object 2: Attribute Volume (300) is no subject to changes.")
            Vissim.Net.VehicleInputs.get_ItemByKey(VI_number).set_AttValue("Cont(2)", false);
            Vissim.Net.VehicleInputs.get_ItemByKey(VI_number).set_AttValue("Volume(2)", 400);

            // Set vehicle composition:
            int Veh_composition_number = 1;

            object[] Rel_Flows = (object[])Vissim.Net.VehicleCompositions.get_ItemByKey(Veh_composition_number).VehCompRelFlows.GetAll();
            IVehicleCompositionRelativeFlow Rel_Flow0 = (IVehicleCompositionRelativeFlow)Rel_Flows[0];
            IVehicleCompositionRelativeFlow Rel_Flow1 = (IVehicleCompositionRelativeFlow)Rel_Flows[1];

            Rel_Flow0.set_AttValue("VehType", 100);      // Changing the vehicle type
            Rel_Flow0.set_AttValue("DesSpeedDistr", 50); // Changing the disired speeed distribution
            Rel_Flow0.set_AttValue("RelFlow", 0.9);      // Changing the relative flow
            Rel_Flow1.set_AttValue("RelFlow", 0.1);      // Changing the relative flow of the 2nd Relative Flow.


            //// ========================================================================
            // Accessing Multiple Attributes:
            //========================================================================

            // GetMultiAttValues         Read one attribut of all objects:
            string Attribute = "Name";

            object[,] Name_of_Links = (object[, ])Vissim.Net.Links.GetMultiAttValues(Attribute);

            // SetMultiAttValues         Set one attribute of multiple (not necessarily all) objects
            object[,] Link_No_Name = { { 1, "New Link Name of Link #1" }, { 2, "New Link Name of Link #2" }, { 4, "New Link Name of Link #4" } };
            Vissim.Net.Links.SetMultiAttValues(Attribute, Link_No_Name); // 1st input is the Link number, 2nd the link name

            // GetMultipleAttributes     Read multiple attributes of all objects:
            object[] Attributes1 = { "Name", "Length2D" };
            object[,] Name_Length_of_Links = (object[, ])Vissim.Net.Links.GetMultipleAttributes(Attributes1);
            //
            // SetMultipleAttributes     Set multiple attribute of multiple (always the first x) objects:
            object[] Attributes2 = { "Name", "CostPerKm" };
            object[,] Link_Name_Cost = { { "Name1", 12 }, { "Name2", 7 }, { "Name3", 5 }, { "Name4", 3 } };
            Vissim.Net.Links.SetMultipleAttributes(Attributes2, Link_Name_Cost);

            // SetAllAttValues           Set all attributes of one object to one value:
            Attribute = "Name";
            string Link_Name = "All Links have the same Name";

            Vissim.Net.Links.SetAllAttValues(Attribute, Link_Name);
            Attribute = "CostPerKm";
            double Cost = 5.5;

            Vissim.Net.Links.SetAllAttValues(Attribute, Cost);
            // Note the method SetAllAttValues has a 3rd optional input: Optional ByVal add As Boolean = False; Use only for numbers!
            Vissim.Net.Links.SetAllAttValues(Attribute, Cost, true); // setting the 3rd input to true, will add 5.5 to all previous costs!


            //// ========================================================================
            // Simulation
            //==========================================================================

            // Chose Random Seed
            int Random_Seed = 42;

            Vissim.Simulation.set_AttValue("RandSeed", Random_Seed);

            // To start a simulation you can run a single step:
            Vissim.Simulation.RunSingleStep();
            // Or run the simulation continuous (it stops at breakpoint or end of simulation)
            double End_of_simulation = 600; // Simulationsecond [s]

            Vissim.Simulation.set_AttValue("SimPeriod", End_of_simulation);
            double Sim_break_at = 200; // Simulationsecond [s]

            Vissim.Simulation.set_AttValue("SimBreakAt", Sim_break_at);
            // Set maximum speed:
            Vissim.Simulation.set_AttValue("UseMaxSimSpeed", true);
            // Hint: to change the speed use: Vissim.Simulation.set_AttValue("SimSpeed", 10); // 10 => 10 Sim.sec. / s
            Vissim.Simulation.RunContinuous();

            // To stop the simulation:
            Vissim.Simulation.Stop();

            //// ========================================================================
            // Access during simulation
            //==========================================================================
            // Note: All of commands of "Read and Set attributes (vehicles)" can also be executed during a
            // simulation (e.g. changing signal controller program, setting relative flow of a static vehilce route,
            // changing the vehicle input, changing the vehicle composition).

            Sim_break_at = 198;                // Simulationsecond [s]
            Vissim.Simulation.set_AttValue("SimBreakAt", Sim_break_at);
            Vissim.Simulation.RunContinuous(); // Start the simulation until SimBreakAt (198s)

            // Get the state of a signal head:
            int    SH_number   = 1;                                                                             // SH = SignalHead
            string State_of_SH = (string)Vissim.Net.SignalHeads.get_ItemByKey(SH_number).get_AttValue("State"); // possible output: 'GREEN', 'RED', 'AMBER', 'REDAMBER'

            Console.WriteLine("Actual state of SignalHead(" + SH_number + ") is: " + State_of_SH);

            // Set the state of a signal controller:
            // Note: Once a state of a signal group is set, the attribute "ContrByCOM" is automatically set to True. Meaning the signal group will keep this state until another state is set by COM or the end of the simulation
            // To switch back to the defined signal controller, set the attribute signal "ContrByCOM" to False (example see below).
            SC_number = 1;     // SC = SignalController
            int SG_number = 1; // SG = SignalGroup

            SignalController = Vissim.Net.SignalControllers.get_ItemByKey(SC_number);
            ISignalGroup SignalGroup = SignalController.SGs.get_ItemByKey(SG_number);
            string       new_state   = "GREEN"; //possible values: "GREEN", "RED", "AMBER", "REDAMBER"

            SignalGroup.set_AttValue("State", new_state);
            // Note: The signal controller can only be called at whole simulation seconds, so the state will be set in Vissim at the next whole sim-second, here 199s
            // Simulate so that the new state is activ in the Vissim simulation:
            Sim_break_at = 200;                // Simulationsecond [s]
            Vissim.Simulation.set_AttValue("SimBreakAt", Sim_break_at);
            Vissim.Simulation.RunContinuous(); // Start the simulation until SimBreakAt (200s)
            // Give the control back:
            SignalGroup.set_AttValue("ContrByCOM", false);

            int    veh_number;
            string veh_type;
            double veh_speed;
            double veh_position;
            string veh_linklane;

            // Information about all vehicles in the network (in the current simulation second):
            // In the following, 4 different methods to access attributes are shown:
            // Method #1: Loop over all Vehicles using "GetAll"
            // Method #2: Loop over all Vehicles using Object Enumeration
            // Method #3: Using the Iterator
            // Method #4: Accessing all attributes directly using "GetMultiAttValues" (fastest way if you want the attributes of all vehicles)
            // Method #5: Accessing all attributes directly using "GetMultipleAttributes" (even more faster)
            // The result of the four methods is the same (except the format).

            // Method #1: Loop over all Vehicles:
            object[] All_Vehicles = (object[])Vissim.Net.Vehicles.GetAll(); // get all vehicles in the network at the actual simulation second
            for (int cnt_Veh = 0; cnt_Veh < Vissim.Net.Vehicles.Count; cnt_Veh++)
            {
                IVehicle Vehicle = (IVehicle)All_Vehicles[cnt_Veh];
                veh_number   = (int)Vehicle.get_AttValue("No");
                veh_type     = (string)Vehicle.get_AttValue("VehType");
                veh_speed    = (double)Vehicle.get_AttValue("Speed");
                veh_position = (double)Vehicle.get_AttValue("Pos");
                veh_linklane = (string)Vehicle.get_AttValue("Lane");
                Console.WriteLine("{0}  |  {1}  |  {2:F}  |  {3:F}  |  {4}", veh_number, veh_type, veh_speed, veh_position, veh_linklane);
            }

            // Method #2: Loop over all Vehicles using Object Enumeration
            foreach (IVehicle Vehicle in Vissim.Net.Vehicles)
            {
                veh_number   = (int)Vehicle.get_AttValue("No");
                veh_type     = (string)Vehicle.get_AttValue("VehType");
                veh_speed    = (double)Vehicle.get_AttValue("Speed");
                veh_position = (double)Vehicle.get_AttValue("Pos");
                veh_linklane = (string)Vehicle.get_AttValue("Lane");
                Console.WriteLine("{0}  |  {1}  |  {2:F}  |  {3:F}  |  {4}", veh_number, veh_type, veh_speed, veh_position, veh_linklane);
            }

            // Method #3: Using the Iterator (this method is a little bit slower)
            IIterator Vehicles_Iterator = Vissim.Net.Vehicles.Iterator;

            while (Vehicles_Iterator.Valid)
            {
                IVehicle Vehicle = (IVehicle)Vehicles_Iterator.Item;
                veh_number   = (int)Vehicle.get_AttValue("No");
                veh_type     = (string)Vehicle.get_AttValue("VehType");
                veh_speed    = (double)Vehicle.get_AttValue("Speed");
                veh_position = (double)Vehicle.get_AttValue("Pos");
                veh_linklane = (string)Vehicle.get_AttValue("Lane");
                Console.WriteLine("{0}  |  {1}  |  {2:F}  |  {3:F}  |  {4}", veh_number, veh_type, veh_speed, veh_position, veh_linklane);
                Vehicles_Iterator.Next();
            }

            // Method #4: Accessing all Attributes directly using "GetMultiAttValues" (fastest way)
            object[,] veh_numbers   = (object[, ])Vissim.Net.Vehicles.GetMultiAttValues("No");      // Output 1. column:consecutive number; 2. column: AttValue
            object[,] veh_types     = (object[, ])Vissim.Net.Vehicles.GetMultiAttValues("VehType"); // Output 1. column:consecutive number; 2. column: AttValue
            object[,] veh_speeds    = (object[, ])Vissim.Net.Vehicles.GetMultiAttValues("Speed");   // Output 1. column:consecutive number; 2. column: AttValue
            object[,] veh_positions = (object[, ])Vissim.Net.Vehicles.GetMultiAttValues("Pos");     // Output 1. column:consecutive number; 2. column: AttValue
            object[,] veh_linklanes = (object[, ])Vissim.Net.Vehicles.GetMultiAttValues("Lane");    // Output 1. column:consecutive number; 2. column: AttValue
            for (int cnt_Veh = 0; cnt_Veh < veh_numbers.GetLength(0); cnt_Veh++)
            {
                Console.WriteLine("{0}  |  {1}  |  {2:F}  |  {3:F}  |  {4}", veh_numbers[cnt_Veh, 1], veh_types[cnt_Veh, 1], veh_speeds[cnt_Veh, 1], veh_positions[cnt_Veh, 1], veh_linklanes[cnt_Veh, 1]);
            }

            // Method #5: Accessing all attributes directly using "GetMultipleAttributes" (even more faster)
            object[] Attributes_veh = new object[5];
            Attributes_veh[0]            = "No";
            Attributes_veh[1]            = "VehType";
            Attributes_veh[2]            = "Speed";
            Attributes_veh[3]            = "Pos";
            Attributes_veh[4]            = "Lane";
            object[,] all_veh_attributes = (object[, ])Vissim.Net.Vehicles.GetMultipleAttributes(Attributes_veh);
            for (int cnt_Veh = 0; cnt_Veh < all_veh_attributes.GetLength(0); cnt_Veh++)
            {
                Console.WriteLine("{0}  |  {1}  |  {2:F}  |  {3:F}  |  {4}", all_veh_attributes[cnt_Veh, 0], all_veh_attributes[cnt_Veh, 1], all_veh_attributes[cnt_Veh, 2], all_veh_attributes[cnt_Veh, 3], all_veh_attributes[cnt_Veh, 4]);
            }

            //// Operations at one spezific vehicle:
            All_Vehicles = (object[])Vissim.Net.Vehicles.GetAll(); // get all vehicles in the network at the actual simulation second
            IVehicle Vehicle1 = (IVehicle)All_Vehicles[1];
            // alternativly with ItemByKey:
            // veh_number = 66; // the same as: All_Vehicles[1].get_AttValue("No");
            // IVehicle Vehicle1 = Vissim.Net.Vehicles.get_ItemByKey(veh_number);

            // Set desired speed to a vehicle:
            double new_desspeed = 30;

            Vehicle1.set_AttValue("DesSpeed", new_desspeed);

            // Move a vehicle:
            int    link_number     = 1;
            int    lane_number     = 1;
            double link_coordinate = 70;

            Vehicle1.MoveToLinkPosition(link_number, lane_number, link_coordinate); // This function will operate during the next simulation step
            // Hint: In earlier Vissim releases, the name of the function was: MoveToLinkCoordinate

            Vissim.Simulation.RunSingleStep(); // Next Step, so that the vehicle gets moved.

            // Remove a vehicle:
            veh_number = (int)Vehicle1.get_AttValue("No");
            Vissim.Net.Vehicles.RemoveVehicle(veh_number);

            // Putting a new vehicle to the network:
            int      vehicle_type  = 100;
            double   desired_speed = 53; // unit according to the user setting in Vissim [km/h or mph]
            int      link          = 1;
            int      lane          = 1;
            double   xcoordinate   = 15;   // unit according to the user setting in Vissim [m or ft]
            bool     interaction   = true; // optional boolean
            IVehicle new_Vehicle   = Vissim.Net.Vehicles.AddVehicleAtLinkPosition(vehicle_type, link, lane, xcoordinate, desired_speed, interaction);
            // Note: In earlier Vissim releases, the name of the function was: AddVehicleAtLinkCoordinate

            // Make Screenshots of the intersection 2D and 3D:
            // ZoomTo:
            // Zooms the view to the rectangle defined by the two points  (x1, y1) and (x2,y2),  which  are  given  in  world coordinates.  If  the  rectangle  proportions  differ
            // from  the  proportions  of  the  network  window,  the  specified  rectangle  will  be centered in the network editor window.
            int X1 = 250;
            int Y1 = 30;
            int X2 = 350;
            int Y2 = 135;

            Vissim.Graphics.CurrentNetworkWindow.ZoomTo(X1, Y1, X2, Y2);

            // Make a Screenshot in 2D:
            // It  creates  a  graphic  file  of  the  VISSIM  main  window  formatted  according  to its extension: PNG, TIFF, GIF, JPG, JPEG or BMP. A BMP file will be written if the extension can not be recognized.
            string Filename_screenshot = "screenshot2D.jpg"; // to set to a specific path: "C:\\Screenshots\\screenshot2D.jpg"
            int    sizeFactor          = 1;                  // 1: orginal Size, 2: doubles size

            Vissim.Graphics.CurrentNetworkWindow.Screenshot(Filename_screenshot, sizeFactor);

            // Make a Screenshot in 3D:
            // Set 3D Mode:
            Vissim.Graphics.CurrentNetworkWindow.set_AttValue("3D", 1);
            // Set the camera position (viewing angle):
            int xPos       = 270;
            int yPos       = 30;
            int zPos       = 15;
            int yawAngle   = 45;
            int pitchAngle = 10;

            Vissim.Graphics.CurrentNetworkWindow.SetCameraPositionAndAngle(xPos, yPos, zPos, yawAngle, pitchAngle);
            Filename_screenshot = "screenshot3D.jpg"; // to set to a specific path: "C:\\Screenshots\\screenshot3D.jpg"
            Vissim.Graphics.CurrentNetworkWindow.Screenshot(Filename_screenshot, sizeFactor);

            // Set 2D Mode and old Network position:
            Vissim.Graphics.CurrentNetworkWindow.set_AttValue("3D", 0);
            X1 = -10;
            Y1 = -10;
            X2 = 600;
            Y2 = 300;
            Vissim.Graphics.CurrentNetworkWindow.ZoomTo(X1, Y1, X2, Y2);

            // Continue the simulation until end of simulation (get(Vissim.Simulation, 'AttValue', 'SimPeriod'))
            Vissim.Simulation.RunContinuous();


            //// ========================================================================
            // Results of Simulations:
            //==========================================================================

            // Run 3 Simulations at maximum speed:
            // Activate QuickMode:
            Vissim.Graphics.CurrentNetworkWindow.set_AttValue("QuickMode", 1);
            Vissim.SuspendUpdateGUI(); // stop updating of the complete Vissim workspace (network editor, list, chart and signal time table windows)
            // Alternativly, load a Layoutfile where dynamic elements (vehicles and pedestrians) are not visible:
            // Vissim.LoadLayout(Path_of_COM_example_network + "COM_example_without_vehicles.layx"); // loading a layout where vehicles are not displayed => much faster simulation
            End_of_simulation = 600;
            Vissim.Simulation.set_AttValue("SimPeriod", End_of_simulation);
            Sim_break_at = 0; // Simulationsecond [s] => 0 means no break!
            Vissim.Simulation.set_AttValue("SimBreakAt", Sim_break_at);
            // Set maximum speed:
            Vissim.Simulation.set_AttValue("UseMaxSimSpeed", true);
            for (int cnt_Sim = 1; cnt_Sim <= 3; cnt_Sim++)
            {
                Vissim.Simulation.set_AttValue("RandSeed", cnt_Sim);
                Vissim.Simulation.RunContinuous();
            }
            Vissim.ResumeUpdateGUI(false);                                     // allow updating of the complete Vissim workspace (network editor, list, chart and signal time table windows)
            Vissim.Graphics.CurrentNetworkWindow.set_AttValue("QuickMode", 0); // deactivate QuickMode
            // Vissim.LoadLayout(Path_of_COM_example_network + "COM_example.layx"); // loading a layout to display vehicles again


            // List of all Simulation runs:
            object[] Attributes = new object[3];
            Attributes[0]           = "Timestamp";
            Attributes[1]           = "RandSeed";
            Attributes[2]           = "SimEnd";
            object[,] List_Sim_Runs = (object[, ])Vissim.Net.SimulationRuns.GetMultipleAttributes(Attributes);
            int number_of_Sim_Runs = Vissim.Net.SimulationRuns.Count;

            // Write the List:
            for (int cnt_C = 0; cnt_C < number_of_Sim_Runs; cnt_C++)
            {
                Console.WriteLine("{0} | {1} | {2}", List_Sim_Runs[cnt_C, 0], List_Sim_Runs[cnt_C, 1], List_Sim_Runs[cnt_C, 2]); // show the List
            }


            // Get the results of Vehicle Travel Time Measurements:
            double TT;
            int    No_Veh;
            int    Veh_TT_measurement_number = 2;
            IVehicleTravelTimeMeasurement Veh_TT_measurement = Vissim.Net.VehicleTravelTimeMeasurements.get_ItemByKey(Veh_TT_measurement_number);

            // Syntax to get the travel times:
            //   Veh_TT_measurement.get_AttValue("TravTm(sub_attribut_1, sub_attribut_2, sub_attribut_3)");
            //
            // sub_attribut_1: SimulationRun
            //       1, 2, 3, ... Current:     the value of one sepcific simulation (number according to the atribute "No" of Simulation Runs (see List of Simulation Runs))
            //       Avg, StdDev, Min, Max:    aggregated value of all simulations runs: Avg, StdDev, Min, Max
            // sub_attribut_2: TimeInterval
            //       1, 2, 3, ... Last:        the value of one sepcific time intervall (number of time interval always starts at 1 (first time interval), 2 (2nd TI), 3 (3rd TI), ...)
            //       Avg, StdDev, Min, Max:    aggregated value of all time interval of one simulation: Avg, StdDev, Min, Max
            //       Total:                    sum of all time interval of one simulation
            // sub_attribut_3: VehicleClass
            //       10, 20 or All             values only from vehicles of the defined vehicle class number (accoring to the attribute "No" of Vehicle Classes)
            //                                 Note: You can only access the results of specific vehicle classes if you configurated it in Evaluation > Configuration > Result Attributes
            //
            // The value of on time intervall is the arithmetic mean of all single travel times of the vehicles.

            // Example #1:
            // Average of all simulations (1. input = Avg)
            //   of the average of all time intervalls  (2. input = Avg)
            //   of all vehicle classes (3. input = All)
            TT     = (double)Veh_TT_measurement.get_AttValue("TravTm(Avg,Avg,All)");
            No_Veh = (int)Veh_TT_measurement.get_AttValue("Vehs  (Avg,Avg,All)");
            Console.WriteLine("Average travel time all time intervalls of all simulation of all vehicle classes: {0:F} (number of vehicles: {1})", TT, No_Veh);

            // Example #2:
            // Value of the Current simulation (1. input = Current)
            //   of the maximum of all time intervalls (2. input = Max)
            //   of vehicle class HGV (3. input = 20)
            TT     = (double)Veh_TT_measurement.get_AttValue("TravTm(Current,Max,20)");
            No_Veh = (int)Veh_TT_measurement.get_AttValue("Vehs  (Current,Max,20)");
            Console.WriteLine("Maximum travel time of all time intervalls of the current simulation of vehicle class HGV: {0:F} (number of vehicles: {1})", TT, No_Veh);

            // Example #3: Note: A Travel times from 2nd simulation run must be availible
            // Value of the 2nd simulation (1. input = 2)
            //   of the 1st time interval (2. input = 1)
            //   of all vehicle classes (3. input = All)
            // TT = (double)Veh_TT_measurement.get_AttValue("TravTm(2,1,All)");
            // No_Veh = (int)Veh_TT_measurement.get_AttValue("Vehs  (2,1,All)");
            // Console.WriteLine("Travel time of the 1st time interval of the 2nd simulation of all vehicle classes: {0:F} (number of vehicles: {1})", TT, No_Veh);


            // Data Collection
            int DC_measurement_number = 1;
            IDataCollectionMeasurement DC_measurement = Vissim.Net.DataCollectionMeasurements.get_ItemByKey(DC_measurement_number);

            // Syntax to get the data:
            //   DC_measurement.get_AttValue("Vehs(sub_attribut_1, sub_attribut_2, sub_attribut_3)");
            //
            // sub_attribut_1: SimulationRun (same as described at Vehicle Travel Time Measurements)
            // sub_attribut_2: TimeInterval  (same as described at Vehicle Travel Time Measurements)
            // sub_attribut_3: VehicleClass  (same as described at Vehicle Travel Time Measurements)
            //
            // The value of on time intervall is the arithmetic mean of all single values of the vehicles.

            // Example #1:
            // Average value of all simulations (1. input = Avg)
            //   of the 1st time interval (2. input = 1)
            //   of all vehicle classes (3. input = All)
            No_Veh = (int)DC_measurement.get_AttValue("Vehs        (Avg,1,All)");                 // number of vehicles
            double Speed        = (double)DC_measurement.get_AttValue("Speed       (Avg,1,All)"); // Speed of vehicles
            double Acceleration = (double)DC_measurement.get_AttValue("Acceleration(Avg,1,All)"); // Acceleration of vehicles
            double Length       = (double)DC_measurement.get_AttValue("Length      (Avg,1,All)"); // Length of vehicles

            Console.WriteLine("Data Collection #" + DC_measurement_number + ": Average values of all Simulations runs of 1st time intervall of all vehicle classes:");
            Console.WriteLine("#vehicles: {0}; Speed: {1:F}; Acceleration: {2:F}; Length: {3:F}", No_Veh, Speed, Acceleration, Length);


            // Queue length
            // Syntax to get the data:
            //   get(QueueCounter.get_AttValue("QLen(sub_attribut_1, sub_attribut_2)");
            //
            // sub_attribut_1: SimulationRun (same as described at Vehicle Travel Time Measurements)
            // sub_attribut_2: TimeInterval  (same as described at Vehicle Travel Time Measurements)
            //

            // Example #1:
            // Average value of all simulations (1. input = Avg)
            //  of the average of all time intervals (2. input = Avg)
            int    QC_number = 1;
            double maxQ      = (double)Vissim.Net.QueueCounters.get_ItemByKey(QC_number).get_AttValue("QLenMax(Avg, Avg)");

            Console.WriteLine("Average maximum Queue length of all simulations and time intervals of Queue Counter #{0}: {1:F}", QC_number, maxQ);

            //// ========================================================================
            // Saving
            //==========================================================================
            Filename = Path_of_COM_example_network + "COM_example_saved.inpx";
            Vissim.SaveNetAs(Filename);
            Filename = Path_of_COM_example_network + "COM_example_saved.layx";
            Vissim.SaveLayout(Filename);


            //// ========================================================================
            // End Vissim
            //==========================================================================
            // Vissim.Exit();
        }
コード例 #22
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// The name of the currently loaded input file
 /// </summary>
 public static string GetInputFileName(this Vissim v)
 {
     return(v.get_AttValue("INPUTFILE").ToString());
 }
コード例 #23
0
 /// <summary>
 /// Default VissimConnection constructor which starts Vissim instance
 /// </summary>
 public VissimConnection()
 {
     vissimInstance = COM.InitialConnection();
     isVissimOpen   = true;
 }
コード例 #24
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// The exe folder where VISSIM is started from
 /// </summary>
 public static string GetExecutionDirectory(this Vissim v)
 {
     return(v.get_AttValue("EXEFOLDER").ToString());
 }
コード例 #25
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// Enable the main menu.
 /// </summary>
 public static void EnableMenu(this Vissim v)
 {
     v.set_AttValue("MENU", 1);
 }
コード例 #26
0
ファイル: VissimSingleton.cs プロジェクト: slowmickey/VISLAB
 private static void CreateNewInstance()
 {
     instance = new Vissim();
     VissimExtensions.DropCache();
 }
コード例 #27
0
        /// <summary>
        /// This method attempts to create the OUTPUT QRACLE table.
        /// If will do nothing but print an error if the table already exists.
        /// </summary>
        //public void TryCreateTbale()
        //{

        //    using (SqlConnection con = new SqlConnection())
        //    {
        //        con.ConnectionString = ConfigurationManager.AppSettings["SqlConnectionString"];
        //        con.Open();
        //        try
        //        {
        //            using (SqlCommand command = new SqlCommand(
        //                "CREATE TBALE OUTPUT1(LocationId INT, CellularTowerId INT, EventType TEXT, EventTimeSpan TEXT)", con))
        //            {
        //                command.ExecuteNonQuery();
        //            }
        //        }
        //        catch
        //        {
        //            Console.WriteLine("Table already exists, or something wrong with the connection");
        //        }
        //    }
        //}

        public void Run()
        {
            vissim = new Vissim();
            ///Load Vissim net work
            vissim.LoadNet(VissimSimulatorFilePath, false);

            //initialize the cellular network
            cellularNetwork.LoadFromFile(CellLinkRelationFilePath, Delimiter);
            ///initialize the table
            //TryCreateTbale();
            //set up the collector threads. For now, only need one thread on this
            //for now, we only need 1 worker to collect the event

            using (StreamWriter writer = new StreamWriter(VissimEventsFilePath))
            {
                CollectorWorker worker        = new CollectorWorker(writer);
                Task            collectorTask = Task.Factory.StartNew(() =>
                {
                    foreach (CellularTowerEvent cEvent in cellularTowerEvents.GetConsumingEnumerable())
                    {
                        worker.Process(cEvent);
                    }
                });

                //simulation thread: including vissim simulation, events generation and detection
                Task simulator = Task.Factory.StartNew(() =>
                {
                    for (int currentTick = 0; currentTick < SimulationTicks; currentTick++)
                    {
                        foreach (IVehicle vehicle in vissim.Net.Vehicles)
                        {
                            //get the vehicle id+
                            int vehicleId = (int)vehicle.AttValue["No"];
                            //get the current vehicle link
                            ILane lane    = vehicle.Lane;
                            string linkId = lane.AttValue["Link"];
                            //Console.WriteLine(string.Format("vehicle {0} at link {1}", vehicleId, linkId));
                            //first check if this vehicle has event
                            if (vehicleEvents.ContainsKey(vehicleId.ToString()))
                            {
                                CellularTowerEvent cEvent = DetectEvent(vehicleId.ToString(), linkId, currentTick);
                                if (cEvent != null)
                                {
                                    cellularTowerEvents.Add(cEvent);
                                }
                            }
                            else //if no vehicle event, that means this is new vehicle entering the vissim network
                            {
                                GenerateEvent(vehicleId.ToString(), currentTick);
                            }
                        }
                        //make the Vissim simulation move forward one tick
                        vissim.Simulation.RunSingleStep();
                    }
                });
                try
                {
                    Task.WaitAll(simulator, collectorTask);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format("there are some exceptions happened: {0}", ex.Message));
                    throw ex;
                }
            }
        }
コード例 #28
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// VISSIM version in text format.
 /// </summary>
 public static string GetVersion(this Vissim v)
 {
     return(v.get_AttValue("VERSION").ToString());
 }
コード例 #29
0
ファイル: VissimSingleton.cs プロジェクト: A-n-d-r-e-y/VISLAB
 private static void CreateNewInstance()
 {
     instance = new Vissim();
     VissimExtensions.DropCache();
 }
コード例 #30
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// The current working directory
 /// </summary>
 public static string GetWorkingDirectory(this Vissim v)
 {
     return(v.get_AttValue("WORKINGFOLDER").ToString());
 }
コード例 #31
0
ファイル: VissimWrapper.cs プロジェクト: A-n-d-r-e-y/VISLAB
 public VissimWrapper(Vissim vissim)
 {
     this.vissim = vissim;
 }
コード例 #32
0
ファイル: VissimExtensions.cs プロジェクト: slowmickey/VISLAB
 /// <summary>
 /// VISSIM revision number in text format.
 /// </summary>
 public static string GetRevisionNumber(this Vissim v)
 {
     return(v.get_AttValue("REVISION").ToString());
 }