static void Run(string fileName, int repeats, string type, float invaderStat, int numInvaders, int burnIn, string outputPath) { Stopwatch Local = new Stopwatch(); Local.Start(); Console.WriteLine(fileName); //Prepare data holders StringBuilder Output = new StringBuilder(); Simulations.InvasionData Temp = new Simulations.InvasionData(); //Get Parameters and run appropriate Simulation SimParams Par = new SimParams(reload: true, path: fileName); for (int j = 0; j < repeats; j++) { Temp = Simulations.Invasion(Par, type, invaderStat, numInvaders, burnIn); Output.Append(Temp.Steps.ToString()); Output.AppendLine(string.Format(",{0}", Temp.TraitAve)); } //Save data string Tag = Utils.GetTag(fileName); File.WriteAllText(outputPath + "/" + Tag + "-" + invaderStat + ".csv", Output.ToString()); Console.WriteLine("{0}-{1}", fileName, Local.ElapsedMilliseconds); }
static void Main(String[] args) { Stopwatch Global = new Stopwatch(); Global.Start(); Console.WriteLine("Start"); //do not check the distributions. Control.CheckDistributionParameters = false; String ParamPath = "D:/Documents/R/AgentBasedModel/Comparison/"; String OutputPath = "C:/Users/Karar/Desktop/Output"; String[] ParamFiles = Utils.GetValidParams(ParamPath); //Prepare naming Scheme string Tag = Utils.GetTag(ParamFiles[0]); SimParams Par = new SimParams(localBreeding: true); WriteData Full = Simulations.Basic(Par); /* WriteData Temp; * WriteData Full = Simulations.Interval(Par, 200, false); * for(int j=1;j<2;j++){ * Temp = Simulations.Interval(Par, 200, false); * Full.ConCat(Temp, Par); * }*/ Full.Output(Par, OutputPath, Tag, true); Console.WriteLine(Global.ElapsedMilliseconds); Console.WriteLine("All simulations completed."); }
static void Main(String[] args) { Stopwatch Global = new Stopwatch(); Global.Start(); Console.WriteLine("Start"); //do not check the distributions. Control.CheckDistributionParameters = false; String ParamPath = "D:/Documents/ECK"; String OutputPath = "D:/Documents/ECK"; String[] ParamFiles = Utils.GetValidParams(ParamPath); //Prepare naming Scheme string Tag = Utils.GetTag(ParamFiles[0]); SimParams Par = new SimParams(reload: true, path: ParamFiles[0]); //int x = 1000000; //float[] sampler = new float[6]{.8f,.8f,.9f,.5f,.4f,.2f}; //int[] lol = Par.RandomSampleUnequal(sampler,x,true); WriteData Full = Simulations.Basic(Par); /* WriteData Temp; * WriteData Full = Simulations.Interval(Par, 200, false); * for(int j=1;j<2;j++){ * Temp = Simulations.Interval(Par, 200, false); * Full.ConCat(Temp, Par); * }*/ Full.Output(Par, OutputPath, Tag, true); Console.WriteLine(Global.ElapsedMilliseconds); Console.WriteLine("All simulations completed."); }
protected override void DrawCore(DxRenderContext renderContext, Cell cell, SimParams parameters) { EffectPass pass = DeviceContext.Effect.GetTechniqueByName(renderContext.StyleAspect.TechniqueName).GetPassByName("P0"); pass.Apply(DeviceContext.Device.ImmediateContext); if (cell != null) { using (InputLayout layout = new InputLayout(DeviceContext.Device, pass.Description.Signature, new[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0) })) { float normalizer = 0.8f / (float)parameters.GetValue(SimParameter.Double.R_Cell, true); DeviceContext.Device.ImmediateContext.InputAssembler.InputLayout = layout; DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology = PrimitiveTopology.TriangleList; DrawCell(renderContext, cell, parameters, normalizer); DrawTubes(renderContext, cell, parameters, normalizer); DrawPoles(renderContext, cell, normalizer); DrawChromosomes(renderContext, cell, parameters, normalizer); DrawSprings(renderContext, cell, parameters, normalizer); } } }
private void DrawCell(DxRenderContext renderContext, Cell cell, SimParams parameters, float normalizer) { SlimDX.Direct3D11.Device device = DeviceContext.Device; DxMesh shSphere = Meshes.GetMesh("emptyHalfSphere"); ConstBuffer.Material = renderContext.StyleAspect.Resolve <CellStyle>(cell).Cell; Vector3 oldPos = Camera.Position; Vector3 oldUp = Camera.Up; Vector4 oldLightDirection = ConstBuffer.LightDirection; Camera.Position = new Vector3(0.0f, 0.0f, -oldPos.Length()); Camera.Up = new Vector3(0.0f, 1.0f, 0.0f); ConstBuffer.LightDirection = new Vector4(Camera.Direction, 1.0f); ConstBuffer.View = Matrix.Transpose(Camera.ViewMatrix); float radius = (float)parameters.GetValue(SimParameter.Double.R_Cell, true) * normalizer; float dist = oldPos.Length(); float magicCoeff = dist / (float)Math.Sqrt(Math.Max(0.1, dist * dist - radius * radius)); Matrix transform = Matrix.Scaling(radius * magicCoeff, radius * magicCoeff, radius * magicCoeff); transform *= RotationVectors(new Vector3(0.0f, 0.0f, 1.0f), new Vector3(0.0f, 0.0f, -1.0f)); ConstBuffer.World = Matrix.Transpose(transform); SetBuffer(device, ConstBuffer); SetAndDrawMesh(device, shSphere); ClearDepthStencil(); Camera.Position = oldPos; Camera.Up = oldUp; ConstBuffer.LightDirection = oldLightDirection; ConstBuffer.View = Matrix.Transpose(Camera.ViewMatrix); }
public LaunchParameters() { Config = new SimParams(); Args = new CliArgs(); InitialStates = null; PoleCoords = null; }
public void Draw(DxRenderContext renderContext, Cell cell, SimParams parameters) { if (renderContext == null) { throw new ArgumentNullException("renderContext"); } Viewport viewPort; renderContext.RenderTargetAspect.GetTargets(out _depthStencilView, out _renderTargetView, out viewPort); ConstBuffer.View = Matrix.Transpose(Camera.ViewMatrix); ConstBuffer.Projection = Matrix.Transpose(Matrix.PerspectiveFovLH(FoV, renderContext.RenderTargetAspect.AspectRatio, 0.01f, 100.0f)); ConstBuffer.LightDirection = new Vector4(Camera.Direction, 1.0f); //ConstBuffer.CameraPosition = new Vector4(Camera.Position, 1.0f); // WTF? Looks like bugged shader DeviceContext.Device.ImmediateContext.OutputMerger.SetTargets(_depthStencilView, _renderTargetView); DeviceContext.Device.ImmediateContext.Rasterizer.SetViewports(viewPort); ClearDepthStencil(); ClearRenderTarget(); DrawCore(renderContext, cell, parameters); renderContext.RenderTargetAspect.OnCompleteRender(); _depthStencilView = null; _renderTargetView = null; }
static void Run(string fileName, int repeats, int frequency, string outputPath, bool repAll, bool matchAll, bool ageAll, bool lrnThrshAll, bool accAll, bool chanForAll, bool chanInvAll) { Stopwatch Local = new Stopwatch(); Local.Start(); //Get Parameters and run appropriate Simulation SimParams Par = new SimParams(reload: true, path: fileName); WriteData Temp; WriteData Full = Simulations.Interval(Par, frequency, repAll, matchAll, ageAll, lrnThrshAll, accAll, chanForAll, chanInvAll); for (int j = 1; j < repeats; j++) { Temp = Simulations.Interval(Par, frequency, repAll, matchAll, ageAll, lrnThrshAll, accAll, chanForAll, chanInvAll); Full.ConCat(Par, Temp); } //Save data string Tag = Utils.GetTag(fileName); Full.Output(Par, outputPath, Tag, true); Console.WriteLine("{0}-{1}", fileName, Local.ElapsedMilliseconds); }
static void Main(String[] args) //do not change this line! //Starts a timer. You can omit this. { Stopwatch Global = new Stopwatch(); Global.Start(); //warns that the simulation has started. You can omit this. Console.WriteLine("Start"); //prevents checks on the distributions; delete if you are changing the library, otherwise leave it alone. //I have internal checks to ensure distributions have appropriate boundaries, so this just wastes time. Control.CheckDistributionParameters = false; //assign arguments that are passed in the console into the right data types. //Add more arguments and assignments or deleted unwanted ones as needed. String ParamPath = args[0]; //Required argument! String OutputPath = args[1]; //Required argument! int Optional = args.Length > 2 ? System.Convert.ToInt32(args[2]) : 4; //optional argument with a default! //get the .SEMP files //Use the next two lines if you want to change the params here rather than load .SEMPs, //and comment out the following three lines. //SimParams Par = new SimParams(); //string Tag = 'new'; String[] ParamFiles = Utils.GetValidParams(ParamPath); //for(int i = 0; i < ParamFiles.length; i++){ SimParams Par = new SimParams(reload: true, path: ParamFiles[0]); //i instead of 0 string Tag = Utils.GetTag(ParamFiles[0]); //i instead of 0 //Basic is not the only simulation option, but should cover most of your needs WriteData Full = Simulations.Basic(Par); //Writes the data files (.SEMP and .csvs) Full.Output(Par, OutputPath, Tag, true); //} //Note that this code will only run one parameter file. To do all .SEMPS in a folder, //uncomment the for loop and its end bracket and change marked the 0's to i. //Also notice that parallelization is absent. See the IntervalSim program an example of code that parallelizes. //Warns how much time has ellasped and that the simulation is over. you can omit this. Console.WriteLine(Global.ElapsedMilliseconds); Console.WriteLine("All simulations completed."); }
private void DrawSprings(DxRenderContext renderContext, Cell cell, SimParams parameters, float normalizer) { SlimDX.Direct3D11.Device device = DeviceContext.Device; DxMesh tube = parameters.GetValue(SimParameter.Int.Spring_Type) == 0 ? Meshes.GetMesh("rod") : Meshes.GetMesh("spring"); SetMesh(device, tube); var prevMode = DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology; PrimitiveTopology[] modes = { PrimitiveTopology.LineList, PrimitiveTopology.TriangleList }; for (int j = 0; j < modes.Length; j++) { DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology = modes[j]; foreach (ChromosomePair pair in cell.ChromosomePairs) { Spring spring = pair.Spring; if (spring != null) { SpringStyle springStyle = renderContext.StyleAspect.Resolve <SpringStyle>(spring); ConstBuffer.Material = springStyle.Spring; float scale = (float)spring.Length * normalizer; Matrix transform = Matrix.Scaling((float)springStyle.Width, (float)springStyle.Width, scale); transform *= RotationVectors(new Vector3(0, 0, -1), new Vector3((float)(spring.RightJoint.X - spring.LeftJoint.X), (float)(spring.RightJoint.Y - spring.LeftJoint.Y), (float)(spring.RightJoint.Z - spring.LeftJoint.Z))); transform *= Matrix.Translation((float)spring.LeftJoint.X * normalizer, (float)spring.LeftJoint.Y * normalizer, (float)spring.LeftJoint.Z * normalizer); ConstBuffer.World = Matrix.Transpose(transform); SetBuffer(device, ConstBuffer); DrawMesh(device, tube); } } } DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology = prevMode; }
private static Tuple <SimParams, String> CreateConfig(int n) { // Some default config as template var config = new SimParams(); config[SimParameter.Int.N_MT_Total] = 1500; config[SimParameter.Int.N_Cr_Total] = 1; config[SimParameter.Int.Spring_Brake_Type] = 1; config[SimParameter.Int.Spring_Brake_MTs] = 1000; config[SimParameter.Int.Spring_Type] = 1; config[SimParameter.Double.Spring_Length] = 0.1; config[SimParameter.Double.Spring_K] = 13000; config[SimParameter.Double.L_Poles] = 10; config[SimParameter.Double.R_Cell] = 6; config[SimParameter.Double.Spring_Brake_Force] = 7000.0; config[SimParameter.Double.K_On] = 10.0; config[SimParameter.Double.K_Off] = 0.002; config[SimParameter.Double.Cr_L] = 3.0; config[SimParameter.Double.Cr_Kin_D] = 0.3; config[SimParameter.Double.Dt] = 0.1; config[SimParameter.Double.T_End] = 7200.0; config[SimParameter.Double.Save_Freq_Macro] = 0.5; // Tune it for the current case switch (n) { case 0: return(new Tuple <SimParams, String>(config, "Default")); case 1: case 2: { config[SimParameter.Int.N_MT_Total] = (n % 2 == 1) ? 1000 : 2000; return(new Tuple <SimParams, String>(config, String.Format(CultureInfo.InvariantCulture, "N_MT_Total={0}", config[SimParameter.Int.N_MT_Total]))); } // Append here your cases default: return(null); } }
private void DrawChromosomes(DxRenderContext renderContext, Cell cell, SimParams parameters, float normalizer) { SlimDX.Direct3D11.Device device = DeviceContext.Device; DxMesh halfCylinder = Meshes.GetMesh("halfCylinder"); SetMesh(device, halfCylinder); float kinScaleX = (float)parameters.GetValue(SimParameter.Double.Cr_Kin_D, true) / 2 * normalizer; float kinScaleY = (float)parameters.GetValue(SimParameter.Double.Cr_Kin_L, true) * normalizer; float handScaleX = (float)parameters.GetValue(SimParameter.Double.Cr_Hand_D, true) / 2 * normalizer; float handScaleY = (float)(parameters.GetValue(SimParameter.Double.Cr_L, true) - parameters.GetValue(SimParameter.Double.Cr_Kin_L, true)) / 2 * normalizer; float handOffsetY1 = (float)parameters.GetValue(SimParameter.Double.Cr_Kin_L, true) / 2 * normalizer + handScaleY; float handOffsetY2 = -(float)parameters.GetValue(SimParameter.Double.Cr_Kin_L, true) / 2 * normalizer; float[] scaleX = { kinScaleX, handScaleX, handScaleX }; float[] scaleY = { kinScaleY, handScaleY, handScaleY }; float[] offsetY = { kinScaleY / 2, handOffsetY1, handOffsetY2 }; Func <ChromosomeStyle, Material>[] materialSelectors = { style => style.Kinetohore, style => style.Hand, style => style.Hand }; foreach (var chr in cell.Chromosomes) { for (int i = 0; i < 3; i++) { ConstBuffer.Material = materialSelectors[i](renderContext.StyleAspect.Resolve <ChromosomeStyle>(chr)); Matrix transform = Matrix.Scaling(scaleX[i], scaleY[i], scaleX[i]); transform *= Matrix.Translation(0.0f, offsetY[i], 0.0f); transform *= FromMatrix3x3(chr.Orientation); transform *= Matrix.Translation((float)chr.Position.X * normalizer, (float)chr.Position.Y * normalizer, (float)chr.Position.Z * normalizer); ConstBuffer.World = Matrix.Transpose(transform); SetBuffer(device, ConstBuffer); DrawMesh(device, halfCylinder); } } }
static void Run(string fileName, int repeats, int frequency, string outputPath, bool repAll, bool matchAll, bool ageAll, bool lrnThrshAll, bool accAll, bool chanForAll, bool chanInvAll) { Stopwatch Local = new Stopwatch(); Local.Start(); Console.WriteLine("Begin-{0}", fileName); //Get Parameters and run appropriate Simulation SimParams Par = new SimParams(reload: true, path: fileName); WriteData Full = new WriteData(); WriteData Temp; int Success = 0; while (Success == 0) { try{ Full = Simulations.Interval(Par, frequency, repAll, matchAll, ageAll, lrnThrshAll, accAll, chanForAll, chanInvAll); Success += 1; }catch { Console.WriteLine("Fail-{0}, {1}", fileName, Success); } } while (Success < repeats) { try{ Temp = Simulations.Interval(Par, frequency, repAll, matchAll, ageAll, lrnThrshAll, accAll, chanForAll, chanInvAll); Full.ConCat(Par, Temp); Success += 1; }catch { Console.WriteLine("Fail-{0}, {1}", fileName, Success); } } //Save data string Tag = Utils.GetTag(fileName); Full.Output(Par, outputPath, Tag, true); Console.WriteLine("{0}-{1}", fileName, Local.ElapsedMilliseconds); }
private void DrawTubes(DxRenderContext renderContext, Cell cell, SimParams parameters, float normalizer) { float kin_d = (float)parameters.GetValue(SimParameter.Double.Cr_Kin_D, true) * normalizer; float kin_l = (float)parameters.GetValue(SimParameter.Double.Cr_Kin_L, true) * normalizer; SlimDX.Direct3D11.Device device = DeviceContext.Device; DxMesh tube = Meshes.GetMesh("tube"); SetMesh(device, tube); // Sorting tubes. List <MT>[] tubes = { new List <MT>(), new List <MT>(), new List <MT>(), new List <MT>() }; Func <TubeStyle, Material>[] materialSelectors = { style => style.FreeLeftPoleTube, style => style.BoundLeftPoleTube, style => style.FreeRightPoleTube, style => style.BoundRightPoleTube }; foreach (MT mt in cell.MTs) { int index = (mt.BoundChromosome == null ? 0 : 1) + (mt.Pole.Type == PoleType.Left ? 0 : 2); tubes[index].Add(mt); } var prevMode = DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology; PrimitiveTopology[] modes = { PrimitiveTopology.LineList, PrimitiveTopology.TriangleList }; for (int j = 0; j < modes.Length; j++) { DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology = modes[j]; for (int i = 0; i < 4; i++) { foreach (MT mt in tubes[i]) { TubeStyle tubeStyle = renderContext.StyleAspect.Resolve <TubeStyle>(mt); ConstBuffer.Material = materialSelectors[i](tubeStyle); // Converting anchor points. var _pole = mt.Pole.Position; var pole = new Vector3((float)_pole.X * normalizer, (float)_pole.Y * normalizer, (float)_pole.Z * normalizer); var _force = mt.ForcePoint; var force = new Vector3((float)_force.X * normalizer, (float)_force.Y * normalizer, (float)_force.Z * normalizer); var _end = mt.EndPoint; var end = new Vector3((float)_end.X * normalizer, (float)_end.Y * normalizer, (float)_end.Z * normalizer); // Generating list with curve's points. List <Vector3> points = new List <Vector3>(); points.Add(pole); points.Add(force); if (force != end && mt.BoundChromosome != null) { // Building new 2D coordinate system. System.Numerics.Vector3 _center = mt.BoundChromosome.Position; Vector3 center = new Vector3(_center.X * normalizer, _center.Y * normalizer, _center.Z * normalizer); Matrix orient = FromMatrix3x3(mt.BoundChromosome.Orientation); Vector4 _r1 = Vector3.Transform(new Vector3(0.0f, 0.0f, -kin_d / 2), orient); Vector3 r1 = new Vector3(_r1.X, _r1.Y, _r1.Z); Vector4 _r2 = Vector3.Transform(new Vector3(kin_d / 2, 0.0f, 0.0f), orient); Vector3 r2 = new Vector3(_r2.X, _r2.Y, _r2.Z); Vector3 ort1 = r1; ort1.Normalize(); Vector3 ort2 = r2; ort2.Normalize(); Vector4 _ort3 = Vector3.Transform(new Vector3(0.0f, 1.0f, 0.0f), orient); Vector3 ort3 = new Vector3(_ort3.X, _ort3.Y, _ort3.Z); // Building plane for point planting. Func <Vector3, Vector3> normalize = (e => { float dr1 = Vector3.Dot(ort1, e); float dr2 = Vector3.Dot(ort2, e); float l = (float)Math.Sqrt(dr1 * dr1 + dr2 * dr2); return(e * (kin_d / 2 / l)); }); Vector3 normal = Vector3.Cross(end - pole, force - pole); if (normal.Length() < (float)1e-3) { normal = ort3; } else { normal.Normalize(); } float t = -(normal.X * (center.X - end.X) + normal.Y * (center.Y - end.Y) + normal.Z * (center.Z - end.Z)) / (normal.X * ort3.X + normal.Y * ort3.Y + normal.Z * ort3.Z); Vector3 proj_center = center + ort3 * (float)Math.Min(kin_l / 2, Math.Max(-kin_l / 2, t)); // Selection direction - clockwise or not float l1 = 0.0f, l2 = 0.0f; { float dx = Vector3.Dot(end - center, ort2), dy = Vector3.Dot(end - center, ort1); float dl = (float)Math.Sqrt(dx * dx + dy * dy); float angle1 = (float)(Math.PI - Math.Asin(dy / dl)); dx = Vector3.Dot(force - center, ort2); dy = Vector3.Dot(force - center, ort1); dl = (float)Math.Sqrt(dx * dx + dy * dy); float angle2 = (float)(Math.PI - Math.Asin(dy / dl)); l1 = (float)(Math.Abs(angle2 - angle1) * kin_d / 2); l2 = (float)(Math.Abs(Math.Min(angle1, angle2) - Math.PI / 2) * kin_d / 2 + Math.Abs(Math.Max(angle1, angle2) - 3 * Math.PI / 2) * kin_d / 2 + kin_d); } if (l1 < l2) { // By curve. Vector3 v1 = force - proj_center; Vector3 v5 = end - proj_center; Vector3 v3 = normalize(v1 + v5); Vector3 v2 = normalize(v1 + v3); Vector3 v4 = normalize(v3 + v5); points.Add(proj_center + v2 * 1.02f); points.Add(proj_center + v3 * 1.02f); points.Add(proj_center + v4 * 1.02f); points.Add(proj_center + v5 * 1.02f); } else { // By back plane. Vector3 v2 = Vector3.Dot(force, ort1) > 0.0 ? -r1 : r1; v2 = normalize(v2); // don't work! Need to be fixed! Vector3 v3 = Vector3.Dot(force, ort1) > 0.0 ? r1 : -r1; v3 = normalize(v3); // don't work! Need to be fixed! Vector3 v4 = end - proj_center; points.Add(proj_center + v2 * 1.02f); points.Add(proj_center + v3 * 1.02f); points.Add(proj_center + v4 * 1.02f); } } // Drawing generated segments. for (int k = 0; k < points.Count - 1; k++) { var dir = points[k + 1] - points[k]; float scale = dir.Length(); Matrix transform = Matrix.Scaling((float)tubeStyle.Width, (float)tubeStyle.Width, scale); transform *= RotationVectors(new Vector3(0, 0, -1), dir); transform *= Matrix.Translation(points[k].X, points[k].Y, points[k].Z); ConstBuffer.World = Matrix.Transpose(transform); SetBuffer(device, ConstBuffer); DrawMesh(device, tube); } } } } DeviceContext.Device.ImmediateContext.InputAssembler.PrimitiveTopology = prevMode; }
protected abstract void DrawCore(DxRenderContext renderContext, Cell cell, SimParams parameters);
private static bool movePoles = true; // move poles from top to sides private static void Simulate(String testID, SimParams config, Random rnd) { // Prepare directory if (Directory.Exists(testID)) { Directory.Delete(testID, true); } Directory.CreateDirectory(testID); Directory.SetCurrentDirectory(testID); // Cache some values that we are goting to use for configuration double R_Cell = config[SimParameter.Double.R_Cell]; double L_Poles = config[SimParameter.Double.L_Poles]; int N_MT_Total = config[SimParameter.Int.N_MT_Total]; double Dt = config[SimParameter.Double.Dt]; double Save_Freq_Macro = config[SimParameter.Double.Save_Freq_Macro]; double T_End = config[SimParameter.Double.T_End]; int layerCount = (int)(T_End / Save_Freq_Macro) + 1; // Ready to start int[] res_mts = new int[layerCount * 4 * cellsPerCase]; double[] res_angles = new double[layerCount * 2 * cellsPerCase]; Stopwatch sw = new Stopwatch(); int batchSize = Math.Max(1, Environment.ProcessorCount); int simN = 0; while (simN < cellsPerCase) { var parameters = new LaunchParameters(); var cellCount = Math.Min(batchSize, cellsPerCase - simN); sw.Reset(); // Say greetings if (cellCount == 1) { Console.WriteLine("Cell #" + (simN + 1).ToString()); } else { Console.WriteLine(String.Format("Cells #{0}...#{1}", simN + 1, simN + cellCount)); } Console.Write(" Simulating ... "); // Update config in accordance with our flags sw.Start(); parameters.Config = config; config[SimParameter.Double.D_Trans] = hasDiff ? SimParams.GetDefaultValue(SimParameter.Double.D_Trans, false) : 0.0; config[SimParameter.Double.D_Rot] = hasDiff ? SimParams.GetDefaultValue(SimParameter.Double.D_Rot, false) : 0.0; // Set initial state parameters.InitialStates = new InitialStates(); parameters.InitialStates.AddChromosomePair(0.0, 0.0, 1e-6, Math.PI / 2, 0.0, 0.0); for (int i = 0; i < N_MT_Total * 2; i++) { double alpha = (rnd.NextDouble()) * Math.PI * 2; double dx = rnd.NextDouble() * (i < N_MT_Total ? 1 : -1); double dy = Math.Sqrt(1.0 - dx * dx) * Math.Cos(alpha); double dz = Math.Sqrt(1.0 - dx * dx) * Math.Sin(alpha); parameters.InitialStates.AddMT(i < N_MT_Total ? PoleType.Left : PoleType.Right, dx, dy, dz, 0.0, MTState.Polymerization); } // Set poles if (movePoles) { parameters.PoleCoords = new PoleCoordinates(); double t = 180.0; double pole_r = L_Poles / 2 * 1e-6; for (int i = 0; i < t; i++) { double angle = i / (t - 1) * Math.PI / 2; parameters.PoleCoords.AddRecord((double)i, -pole_r * Math.Sin(angle), pole_r * Math.Cos(angle), 0.0, pole_r * Math.Sin(angle), pole_r * Math.Cos(angle), 0.0); } } // Simulate parameters.Args.Mode = LaunchMode.New; parameters.Args.Solver = new SimulatorConfig(SimulatorType.CPU); parameters.Args.CellCount = cellCount; parameters.Args.CellFile = "results.cell"; using (Launcher ml = new Launcher(".", "../Mitosis.exe", parameters)) { var res = ml.StartAndWait(); if (res.ExitCode != 0 || !String.IsNullOrEmpty(res.Error)) { throw new ApplicationException(String.Format("Simulation failed, error #{0}: {1}, {2}", res.ExitCode, res.Error, res.Output)); } } sw.Stop(); Console.WriteLine(String.Format("{0} seconds", (int)sw.ElapsedMilliseconds / 1000)); // Analyze Console.Write(" Counting ... "); sw.Reset(); sw.Start(); for (int cellN = simN; cellN < simN + cellCount; cellN++) { var ts = TimeStream.Open(cellCount == 1 ? parameters.Args.CellFile : parameters.Args.CellFile.Replace("results.cell", String.Format("results_{0}.cell", cellN - simN))); if (ts.LayerCount != layerCount) { throw new ApplicationException("Unexpected count of time layers"); } ts.Reset(); int layerN = 0; while (ts.MoveNext()) { var cell = ts.Current.Cell; var chr0 = cell.Chromosomes.ElementAt(0); var chr1 = cell.Chromosomes.ElementAt(1); // Count MTs int c0l = 0, c0r = 0, c1l = 0, c1r = 0; var c0 = chr0.BoundMTs; foreach (var mt in c0) { if (mt.Pole.Type == PoleType.Left) { c0l += 1; } else { c0r += 1; } } var c1 = chr1.BoundMTs; foreach (var mt in c1) { if (mt.Pole.Type == PoleType.Left) { c1l += 1; } else { c1r += 1; } } int offset = layerCount * 4 * cellN + layerN * 4; res_mts[offset + 0] = c0l; res_mts[offset + 1] = c0r; res_mts[offset + 2] = c1l; res_mts[offset + 3] = c1r; // Count angles if (cell.AreSpringsBroken) { throw new ApplicationException("Wrong setup, springs were broken!"); } Vector3 dp = new Vector3(cell.GetPole(PoleType.Left).Position.X - cell.GetPole(PoleType.Right).Position.X, cell.GetPole(PoleType.Left).Position.Y - cell.GetPole(PoleType.Right).Position.Y, cell.GetPole(PoleType.Left).Position.Z - cell.GetPole(PoleType.Right).Position.Z); if (dp.Length() == 0.0f) { dp = new Vector3(-1.0f, 0.0f, 0.0f); } else { dp = dp / dp.Length(); } if (Math.Abs(dp.Y) + Math.Abs(dp.Z) > 1e-9) { throw new ApplicationException("Poles must be located symmetrically"); } Vector3 dc_x = new Vector3((float)-chr0.Orientation[0, 0], (float)-chr0.Orientation[1, 0], (float)-chr0.Orientation[2, 0]); if (dc_x.Length() == 0.0f) { dc_x = new Vector3(-1.0f, 0.0f, 0.0f); } else { dc_x = dc_x / dc_x.Length(); } Vector3 dc_y = new Vector3((float)-chr0.Orientation[0, 1], (float)-chr0.Orientation[1, 1], (float)-chr0.Orientation[2, 1]); if (dc_y.Length() == 0.0f) { dc_y = new Vector3(0.0f, 1.0f, 0.0f); } else { dc_y = dc_y / dc_y.Length(); } offset = (layerCount * cellN + layerN) * 2; res_angles[offset + 0] = Math.Acos(Math.Min(1.0, Math.Max(-1.0, Vector3.Dot(dp, dc_x)))); res_angles[offset + 1] = Math.Acos(Math.Min(1.0, Math.Max(-1.0, Vector3.Dot(dp, dc_y)))); layerN += 1; } ts.Dispose(); } // for cellN sw.Stop(); Console.WriteLine(String.Format("{0} seconds", sw.ElapsedMilliseconds / 1000)); simN += cellCount; } // while simN < cellsPerCase // Save results Console.WriteLine("Saving ..."); // A-results using (var csv = File.CreateText("results_A.csv")) { csv.WriteLine("Connected MTs (pcs)"); csv.Write("Time (seconds),Averaged,Min,Max"); for (int i = 0; i < cellsPerCase; i++) { csv.Write(",Cell #" + (i + 1).ToString()); } csv.WriteLine(); for (int layerN = 0; layerN < layerCount; layerN++) { StringBuilder str = new StringBuilder(); int min = Int32.MaxValue, max = Int32.MinValue, avg = 0; for (int cellN = 0; cellN < cellsPerCase; cellN++) { int offset = layerN * 4 + layerCount * 4 * cellN; int val = res_mts[offset] + res_mts[offset + 1] + res_mts[offset + 2] + res_mts[offset + 3]; str.Append(","); str.Append(val.ToString()); min = Math.Min(min, val); max = Math.Max(max, val); avg += val; } csv.WriteLine(String.Format("{0},{1},{2},{3}{4}", (Save_Freq_Macro * layerN).ToString(CultureInfo.InvariantCulture), ((double)avg / cellsPerCase).ToString(CultureInfo.InvariantCulture), min, max, str.ToString())); } } // B-results using (var csv = File.CreateText("results_B.csv")) { csv.WriteLine("Kinetochore types (%)"); csv.WriteLine("Time (seconds),No MTs,Monotelic,Syntelic,Bioriented,Merotelic"); for (int layerN = 0; layerN < layerCount; layerN++) { int noMTs = 0, monotelic = 0, syntelic = 0, bioriented = 0, merotelic = 0; for (int cellN = 0; cellN < cellsPerCase; cellN++) { int offset = layerN * 4 + layerCount * 4 * cellN; int c0l = res_mts[offset + 0]; int c0r = res_mts[offset + 1]; int c1l = res_mts[offset + 2]; int c1r = res_mts[offset + 3]; int c0m = Math.Min(c0l, c0r); int c0nm = Math.Max(c0l, c0r); int c1m = Math.Min(c1l, c1r); int c1nm = Math.Max(c1l, c1r); int c0_sum = c0m + c0nm; int c1_sum = c1m + c1nm; int sum = c0_sum + c1_sum; if (sum == 0) { noMTs += 1; } else if (c0m != 0 || c1m != 0) { merotelic += 1; } else if (c0_sum == 0 || c1_sum == 0) { monotelic += 1; } else if (Math.Min(c0l, c1l) != 0 || Math.Min(c0r, c1r) != 0) { syntelic += 1; } else if (c0m == 0 && c0nm != 0 && c1m == 0 && c1nm != 0) { bioriented += 1; } else { throw new ApplicationException("Internal error, unknown type of chromosome"); } } csv.WriteLine(String.Format("{0},{1},{2},{3},{4},{5}", (Save_Freq_Macro * layerN).ToString(CultureInfo.InvariantCulture), ((double)noMTs / cellsPerCase).ToString(CultureInfo.InvariantCulture), ((double)monotelic / cellsPerCase).ToString(CultureInfo.InvariantCulture), ((double)syntelic / cellsPerCase).ToString(CultureInfo.InvariantCulture), ((double)bioriented / cellsPerCase).ToString(CultureInfo.InvariantCulture), ((double)merotelic / cellsPerCase).ToString(CultureInfo.InvariantCulture))); } } // C-results using (var csv = File.CreateText("results_C.csv")) { csv.WriteLine("Merotelic MTs (pcs)"); csv.Write("Time (seconds),Averaged,Min,Max"); for (int i = 0; i < cellsPerCase; i++) { csv.Write(",Cell #" + (i + 1).ToString()); } csv.WriteLine(); for (int layerN = 0; layerN < layerCount; layerN++) { StringBuilder str = new StringBuilder(); int min = Int32.MaxValue, max = Int32.MinValue, avg = 0; for (int cellN = 0; cellN < cellsPerCase; cellN++) { int offset = layerN * 4 + layerCount * 4 * cellN; int val = Math.Min(res_mts[offset + 0], res_mts[offset + 1]) + Math.Min(res_mts[offset + 2], res_mts[offset + 3]); str.Append(","); str.Append(val.ToString()); min = Math.Min(min, val); max = Math.Max(max, val); avg += val; } csv.WriteLine(String.Format("{0},{1},{2},{3}{4}", (Save_Freq_Macro * layerN).ToString(CultureInfo.InvariantCulture), ((double)avg / cellsPerCase).ToString(CultureInfo.InvariantCulture), min, max, str.ToString())); } } // D-results using (var csv_x = File.CreateText("results_D_x.csv")) using (var csv_y = File.CreateText("results_D_y.csv")) { var csvs = new StreamWriter[] { csv_x, csv_y }; for (int l = 0; l < csvs.Length; l++) { var csv = csvs[l]; csv.WriteLine("Angle, degrees"); csv.Write("Time (seconds),Averaged,Min,Max"); for (int i = 0; i < cellsPerCase; i++) { csv.Write(",Cell #" + (i + 1).ToString()); } csv.WriteLine(); for (int layerN = 0; layerN < layerCount; layerN++) { StringBuilder str = new StringBuilder(); double min = Double.MaxValue, max = Double.MinValue, avg = 0.0; for (int cellN = 0; cellN < cellsPerCase; cellN++) { double angle = res_angles[l + (layerN + layerCount * cellN) * 2]; if (angle > Math.PI) { angle = 2 * Math.PI - angle; } if (angle > Math.PI / 2) { angle = Math.PI - angle; } angle *= 180.0 / Math.PI; str.Append(","); str.Append(String.Format(CultureInfo.InvariantCulture, "{0:F1}", angle)); min = Math.Min(min, angle); max = Math.Max(max, angle); avg += angle; } csv.WriteLine(String.Format(CultureInfo.InvariantCulture, "{0:F1},{1:F1},{2:F1},{3:F1}{4}", Save_Freq_Macro * layerN, (double)avg / cellsPerCase, min, max, str.ToString())); } } } Directory.SetCurrentDirectory(".."); }