/* * - - iter=10:proc=1:fastlink:start=100:change=10 * iter=10:proc=1:link:start=100:change=10 * iter=10:proc=1:list:start=100:change=10 * iter=10:proc=2:fastlink:start=100:change=10 */ namespace OpenTraffic { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Tcp; using System.Security.Principal; using System.Xml.Serialization; using OpenTraffic.Model; using OpenTraffic.Model.Result; using OpenTraffic.Model.Route; using OpenTraffic.Model.Simulator; using OpenTraffic.Network; class StaticClientAndServer { private static bool remote = false; private static int nClientsStarted = 0; private static string output = ""; private static string outfile = null; private static string logfile = null; public static void log(string str) { output += str + System.Environment.NewLine; } public static void SaveLog() { Console.Write("Saving logfile {0} ...", logfile); if (logfile != null) File.WriteAllText(logfile, output); Console.WriteLine("done"); } public class ClientAuthorized : IAuthorizeRemotingConnection { public bool IsConnectingEndPointAuthorized(EndPoint endPoint) { return true; } public bool IsConnectingIdentityAuthorized(IIdentity identity) { return true; } } private static List GetClientsDescriptions(string filename) { if (!System.IO.File.Exists(filename)) return null; List clients; using (TextReader reader = new StreamReader(filename)) { XmlSerializer serializer = new XmlSerializer(typeof(List)); clients = (List)serializer.Deserialize(reader); // reader.Close(); } return clients; } delegate Object parameterFunc(string values); static parameterFunc intFunc(int i) { return delegate(string value) { if (value != null) return int.Parse(value); return i; }; } static parameterFunc floatFunc(float i) { NumberFormatInfo nfi = new CultureInfo("en-US", false).NumberFormat; return delegate(string value) { return value != null ? float.Parse(value, nfi) : i; }; } static Dictionary parseModelParameter(string str, out string outStr) { parameterFunc falseFunc = delegate { return false; }; parameterFunc trueFunc = delegate { return true; }; Dictionary> lookup = new Dictionary>(); lookup.Add("short", new KeyValuePair("ra", delegate { return new OpenTraffic.Model.Simulator.RouteAssigner.ShortestPath(); })); lookup.Add("kirch", new KeyValuePair("ra", delegate(string value) { float v = value != null ? float.Parse(value) : -3.0f; return new OpenTraffic.Model.Simulator.RouteAssigner.Kirchnoff(v); } )); lookup.Add("logit", new KeyValuePair("ra", delegate { return new OpenTraffic.Model.Simulator.RouteAssigner.Logit(-1.0f, true); })); lookup.Add("nosmoothing", new KeyValuePair("smoothing", floatFunc(float.NaN))); lookup.Add("smoothing", new KeyValuePair("smoothing", floatFunc(0.2f))); lookup.Add("fastlink", new KeyValuePair("fastlink", trueFunc)); lookup.Add("link", new KeyValuePair("fastlink", falseFunc)); lookup.Add("list", new KeyValuePair("heap", trueFunc)); lookup.Add("heap", new KeyValuePair("heap", falseFunc)); lookup.Add("routes", new KeyValuePair("routes", trueFunc)); lookup.Add("noroutes", new KeyValuePair("routes", falseFunc)); lookup.Add("giveaway", new KeyValuePair("giveaway", trueFunc)); lookup.Add("nogiveaway", new KeyValuePair("giveaway", falseFunc)); lookup.Add("signal", new KeyValuePair("signal", trueFunc)); lookup.Add("nosignal", new KeyValuePair("signal", falseFunc)); lookup.Add("proc", new KeyValuePair("proc", intFunc(1))); lookup.Add("iter", new KeyValuePair("iter", intFunc(30))); lookup.Add("change", new KeyValuePair("change", floatFunc(-1.0f))); lookup.Add("start", new KeyValuePair("start", floatFunc(30f))); lookup.Add("noshockwave", new KeyValuePair("shockwave", falseFunc)); lookup.Add("shockwave", new KeyValuePair("shockwave", trueFunc)); Dictionary d = new Dictionary(); Dictionary descDict = new Dictionary(); foreach (KeyValuePair> kv in lookup) { if (!d.ContainsKey(kv.Value.Key)) { d.Add(kv.Value.Key, kv.Value.Value(null)); descDict.Add(kv.Value.Key, kv.Key); } } foreach (string s in str.Split(new Char[] { ':' })) { String[] arr = s.Split(new Char[] { '=' }); string key = arr[0]; string value = arr.Length > 1 ? arr[1] : null; KeyValuePair kv; if (lookup.TryGetValue(key, out kv)) { d[kv.Key] = kv.Value(value); descDict[kv.Key] = s; } else { Console.WriteLine("\tParameter not found: " + key); } } outStr = ""; foreach (KeyValuePair kv in d) { if (kv.Value is bool) { bool b = (bool)kv.Value; outStr += (b ? "" : "!") + kv.Key + ":"; } else { outStr += kv.Key + "=" + kv.Value + ":"; } } /*foreach (KeyValuePair kv in descDict) { outStr += kv.Key + "=" + d[kv.Key] + ":"; }*/ return d; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "c")] static void Main(string[] args) { List clients = null; Model.TrafficModel m = new Model.TrafficModel(); Network.TrafficServer server = new Network.TrafficServer(m); if (args.Length < 3) { Console.WriteLine("staticClientAndServer ... "); Console.WriteLine("\twhere ni is number of clients used"); } if (args[0] != "-") { try { LoadModel(args[0], m); } catch (Exception exp) { System.Console.WriteLine("Problem with network input file" + exp); return; } } else { // LoadModel("C:\\CONTRAM8 Examples\\stockholm3\\30a.net", m); LoadModel("C:\\CONTRAM8 Examples\\stockholm3\\30a.otx.gz", m); // LoadModel("C:\\CONTRAM8 Examples\\seatown\\seatown.otx.gz", m); // LoadModel("C:\\CONTRAM8 Examples\\seatown\\seatown.net", m); // LoadModel("C:\\CONTRAM8 Examples\\shockwave\\test.net", m); // LoadModel("C:\\CONTRAM8 Examples\\Seatown_!prio_!signal_!vary\\seatown.net", m); //LoadModel("C:\\CONTRAM8 Examples\\Seatown_!prio_!signal\\seatown.net", m); //LoadModel("C:\\CONTRAM8 Examples\\Seatown_!prio\\seatown.net", m); //LoadModel("C:\\CONTRAM8 Examples\\signal_test\\test.net", m); //LoadModel("C:\\CONTRAM8 Examples\\speed_flow_4\\test.net", m); //LoadModel("C:\\CONTRAM8 Examples\\test_max_capacity\\test.net", m); //LoadModel("c:\\Contram8 Examples\\giveaway\\giveaway.net", m); //LoadModel("c:\\Contram8 Examples\\route_assigner\\test.net", m); } ResultData orgRes = m.ResultStore.GetResult("Contram"); server.ResultToCompare = orgRes; if (args[1] == "rg") { List routes = m.Routes; m.Routes = new List(); // Generate all possible routes Model.TrafficGenerator.ODTrafficGenerator otg = m.TrafficGenerator as Model.TrafficGenerator.ODTrafficGenerator; if (otg != null) { RouteFactory rf = new RouteFactory(m, orgRes, 0.07f); RouteFactory rfFreeFlow = new RouteFactory(m, null); RouteGenerator rg = new RouteGenerator(otg.Demands, m.Routes, otg.Times); Console.WriteLine(rg); m.Routes.AddRange(rg.GenerateFreeFlowRoutes(rfFreeFlow)); Console.WriteLine(rg); Console.WriteLine("Press d key to abort and save result."); while (!(Console.KeyAvailable && (Console.ReadKey(true).Key == ConsoleKey.D))) { Console.WriteLine("Check if all routes are valid"); foreach (RouteContainer rc in m.Routes) { if (!rc.IsValid()) { Console.WriteLine("Found invalid route" + rc); throw new InvalidDataException(); } } if (!Console.KeyAvailable) { m.Routes.AddRange(rg.GenerateAsManyRoutesAsPosible(rf, 1, m.VehicleClasses)); Console.WriteLine(rg.ToString(routes, false)); } } Console.WriteLine(rg.ToString(routes, false)); m.Routes.AddRange(rg.AddRoutes(routes)); //log(rg.ToString(routes, true)); } StaticClientAndServer.SaveFile(m); SaveLog(); Console.ReadKey(); return; } if (args[1] != "-") { if (args[1] == "*") { clients = ClientDescription.Scan(); Console.WriteLine("Found"); } else { Console.Write("Loading client list..."); clients = GetClientsDescriptions(args[1]); Console.WriteLine(" Done"); } foreach (ClientDescription cd in clients) { Console.WriteLine("Client found: " + cd.name + ":" + cd.port); } } m.SignalLight = true; m.Giveaway = true; List times = new List(); for (int i = 2; i < args.Length; i++) { string inStr = args[i]; Model.SimulatorFactory.AbstractSimulatorFactory sf; string str = null; Dictionary d = parseModelParameter(inStr, out str); int n = (int)d["proc"]; sf = new Model.SimulatorFactory.QueueFactory((float)d["change"], (float)d["start"], (Model.Simulator.RouteAssigner.TrafficRouteAssigner)d["ra"]); m.Optimize = (bool)d["fastlink"]; m.AssumeOnlyOneClass = !(bool)d["heap"]; m.Giveaway = (bool)d["giveaway"]; m.SignalLight = (bool)d["signal"]; m.Shockwave = (bool)d["shockwave"]; int iter = (int)d["iter"]; bool routes = (bool)d["routes"]; server.smoothing = (float)d["smoothing"]; log("*** running simulation with " + str); Console.WriteLine("*** running simulation with " + str); n = n - nClientsStarted; long start = DateTime.Now.Ticks; if (!StartClient(n, server, clients)) break; ResultData res = TestModel(server, iter, routes, sf); foreach (VehicleClass c in m.VehicleClasses) { // res.PrintRouteChooseInformation(c, m.Routes); } if (res == null) break; res.Name = str; m.ResultStore.AddResult(res); long stop = DateTime.Now.Ticks; times.Add(stop - start); } StaticClientAndServer.SaveFile(m); Console.WriteLine("TIMES: "); foreach (long t in times) System.Console.Write(t / TimeSpan.TicksPerSecond + "s\t"); SaveLog(); Console.WriteLine("Finished"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static ResultData TestModel( Network.TrafficServer server, int nIter, bool generateRoutes, Model.SimulatorFactory.AbstractSimulatorFactory sf) { System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker(); bw.DoWork += server.Work; bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted); System.ComponentModel.DoWorkEventArgs e = new System.ComponentModel.DoWorkEventArgs(null); server.SimulatorFactory = sf; server.NumberOfIteration = nIter; server.GenerateRoutes = generateRoutes; server.Work(bw, e); foreach (TrafficProfile p in server.Profiles) { log(p.ToString()); } ResultData res = e.Result as ResultData; return res; } static void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { throw new Exception("The method or operation is not implemented."); } private static void SaveFile(Model.TrafficModel m) { Model.Importer.Native.NativeFileImporter nav = new OpenTraffic.Model.Importer.Native.NativeFileImporter(); if (outfile == null) { Console.WriteLine("no filename defined to save file"); return; } string filename = outfile; Console.Write("Saving {0} ... ", outfile); nav.SaveFile(new FileInfo(filename), m); Console.WriteLine("done"); } private static void LoadModel(string infile, Model.TrafficModel m) { //string ext = null; String[] arr = infile.Split(new Char[] { '.' }, 2); string ext = arr[arr.Length - 1]; Model.Importer.IImporterModel imp = null; string filename = infile.Substring(0, infile.Length - ext.Length - 1); Console.Write("Loading {0} ... ", filename); outfile = filename + ".otx.gz"; logfile = filename + ".otx.log"; switch (ext) { case "otx": case "otx.gz": imp = new Model.Importer.Native.NativeFileImporter(); break; case "mezzo": imp = new Model.Importer.Mezzo.MezzoImporter(); break; case "net": imp = new Model.Importer.ContramNetwork(); break; } if (imp == null) return; imp.LoadFile(new FileInfo(infile), m); if (imp.GetType() == typeof(Model.Importer.ContramNetwork)) { new Model.Importer.ContramRoute().LoadFile(new FileInfo(filename + ".rte"), m); FileInfo fi = new FileInfo(filename + ".res"); if (fi.Exists) { ResultData res = new Model.Importer.ContramResult().LoadResult(new FileInfo(filename + ".res"), m); res.Name = "Contram"; m.ResultStore.AddResult(res); } } Console.WriteLine("done"); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "objrefWellKnown"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private static bool StartClient(int nClients, Network.TrafficServer server, List clients) { if (clients == null) { for (int i = 0; i < nClients; i++) { int port = 6665 + nClientsStarted++; if (remote) { Hashtable props = new Hashtable(); props["name"] = "OpenTrafficChannel_" + port; props["port"] = port; // props["impersonate"] = true; props["secure"] = false; TcpServerChannel channel = new TcpServerChannel(props, new BinaryServerFormatterSinkProvider(), new ClientAuthorized()); ChannelServices.RegisterChannel(channel, false); ObjRef objrefWellKnown = RemotingServices.Marshal(new Network.Client(port), "client" + port + ".rem"); server.AddClient("127.0.0.1", port, 1.0f); } else { server.Clients.Add(new ClientDescription("127.0.0.1", port, 1.0f, false)); } } } else { for (int i = 0; i < nClients; i++) { Console.Write("Trying to start client..." + (nClientsStarted + 1) + "/" + clients.Count); if (nClientsStarted < clients.Count) { server.AddClient(clients[nClientsStarted].name, clients[nClientsStarted].port, 1.0f); } else { return false; } nClientsStarted++; Console.WriteLine("Done"); } } return true; } } }