private void analyzeAnIndividual(Individual ind, out string infotext, out string log, out AbstractMotor motor) { double[] gens = ind.Genes; StringBuilder sb = new StringBuilder(); sb.AppendLine("Took " + (sw.ElapsedMilliseconds / 1000) + " secs. Dict size = " + dict_fitness.Count); infotext = ""; AbstractMMAnalyser mma = null; try { lua_constructMotorfromGens(gens, currentConfig.luascript_constructMotor, out motor, out mma); } catch (Exception ex) { sb.AppendLine("Motor constructing script failed: " + ex.Message); motor = null; } // finish script if (motor != null && currentConfig.luascript_finish != null && currentConfig.luascript_finish != "") { try { //lua["fitness"] = fitness; var a = motor.GetAnalyticalAnalyser(); a.RunAnalysis(); // finite elements analysis if available object fem_results = null; if (lua["useFEM"] != null && a.isDataValid() && mma != null) { // static analysis String outdir = OutputFolderFEM + "\\" + motor.GetMD5String(); Directory.CreateDirectory(outdir); String femFile = outdir + "\\static.FEM"; if (!motor.isFEMModelReady(femFile)) { motor.BuildFEMModel(femFile); } AbstractStaticAnalyser staticAnalyser = motor.GetStaticAnalyser(); staticAnalyser.Path_OriginalFEMFile = femFile; staticAnalyser.OutputPath = outdir; staticAnalyser.DoAnalysisOnOriginalFEMFile = true; staticAnalyser.RunAnalysis(); // mma analysis mma.Path_OriginalFEMFile = femFile; mma.CustomOutputDir = outdir; mma.RunAnalysis(); fem_results = mma.Results; FEMM.CloseFemm(); } object[] o = null; lock (lock_dostring) { lua["motor"] = motor; lua["gens"] = gens; lua["results"] = a.Results; lua["femresults"] = fem_results; o = lua.DoString(currentConfig.luascript_finish, "FinishScript"); } if (o != null && o.Length > 0 && o[0] is string) { infotext = o[0].ToString(); sb.AppendLine("FinishScript:\r\n" + (o[0] as string)); } } catch (Exception ex) { sb.AppendLine("Finish script failed: " + ex.Message); } // sb.AppendLine("Motor details:"); sb.AppendLine(JSON.Beautify(JSON.ToJSON(motor))); } log = sb.ToString(); }
public void doSweep() { // update ID and MD5 in params table before do sweep updateID_MD5_inParamsTable(); // copy params from original ParametersCollection swParams = MotorToParams(CurrentMotor); // new result table ResultsTable = new DataTable(); ResultsTable.TableName = RESULTS_TABLE; ResultsTable.Columns.Add(COL_ID, typeof(int)); ResultsTable.Columns.Add(COL_MD5, typeof(string)); ResultsTable.Columns.Add(COL_STATUS, typeof(string)); bool newlyTable = true; // apply sweeping param from table // each variant foreach (DataRow paramRow in ParamsTable.Rows) { int variantNum = ParamsTable.Rows.IndexOf(paramRow); // update params from this row (variant) foreach (DataColumn dc in ParamsTable.Columns) { String colname = dc.ColumnName; foreach (Parameter p in swParams) { if (p.fullname == colname) { p.text = paramRow[colname].ToString(); p.EvaluateValue(); break; } } } // create new motor from parameters AbstractMotor motor = ParamsToMotor(swParams); // motor calculation motor.CalcPointsCoordinates(); // if params invalid, just move on if (!motor.IsParamsValid()) { log.Error(String.Format("Variant {0} invalid:", variantNum)); paramRow[COL_STATUS] = "Error: "; foreach (ParamValidationInfo pvi in motor.ListParamsValidation) { if (pvi.msgType == ParamValidationInfo.MessageType.Error) { log.Error("\t+ " + pvi.message); } //update error in param row paramRow[COL_STATUS] += pvi.message + "; "; } //resultRow also DataRow rr = ResultsTable.NewRow(); rr[COL_ID] = paramRow[COL_ID]; rr[COL_MD5] = paramRow[COL_MD5]; rr[COL_STATUS] = paramRow[COL_STATUS]; ResultsTable.Rows.Add(rr); continue; } else { paramRow[COL_STATUS] = "OK"; } //// organize results ParametersCollection pc = new ParametersCollection(); // calc gmc AbstractAnalyticalAnalyser aa = motor.GetAnalyticalAnalyser(); aa.RunAnalysis(); pc.AddRange(ParametersCollection.FromObject("analytic", aa.Results)); // femm if (EnableFEMAnalysis) { String outdir = OutputFolder; String femFile = outdir + "\\" + motor.GetMD5String() + ".FEM"; Directory.CreateDirectory(outdir); if (!motor.isFEMModelReady(femFile)) { motor.BuildFEMModel(femFile); } AbstractStaticAnalyser staticAnalyser = motor.GetStaticAnalyser(); staticAnalyser.Path_OriginalFEMFile = femFile; staticAnalyser.OutputPath = outdir; staticAnalyser.DoAnalysisOnOriginalFEMFile = true; staticAnalyser.RunAnalysis(); pc.AddRange(ParametersCollection.FromObject("fem", staticAnalyser.Results)); } Dictionary <String, int> countsParam = new Dictionary <string, int>(); // find params match by name between analytic and fem foreach (Parameter p in pc) { if (countsParam.ContainsKey(p.name)) { countsParam[p.name]++; } else { countsParam[p.name] = 1; } } // add comparison columns foreach (String name in countsParam.Keys) { if (countsParam[name] == 2) { Parameter p = new Parameter(); p.group = "xCompare"; p.name = name; double d1 = (double)pc.FindParameter("analytic", name).value; double d2 = (double)pc.FindParameter("fem", name).value; p.value = String.Format("{0:F3}%", (d1 - d2) / d2 * 100.0); p.valueType = typeof(String); pc.Add(p); } } // sort columns pc = new ParametersCollection(pc.OrderBy(param => param.name).ThenBy(param => param.group).ToList()); // 1 times create if (newlyTable) { foreach (Parameter p in pc) { if (!p.valueType.IsArray)//don't care about array (airgap flux-density distribution) for now { ResultsTable.Columns.Add(p.fullname, p.valueType); } } newlyTable = false; } // assign this variant results to row of results table DataRow resultRow = ResultsTable.NewRow(); foreach (Parameter p in pc) { if (resultRow.Table.Columns.Contains(p.fullname)) { resultRow[p.fullname] = p.value; } } resultRow[COL_ID] = paramRow[COL_ID]; resultRow[COL_MD5] = paramRow[COL_MD5]; resultRow[COL_STATUS] = paramRow[COL_STATUS]; ResultsTable.Rows.Add(resultRow); }// for each variant // raise event ParamSweeperResults r = new ParamSweeperResults(); r.ResultsTable = ResultsTable; OnFinishSweep(this, r); saveDataToDisk(); }
/// <summary> /// Calculate fitness from gens, return value is nullable /// </summary> /// <param name="gens"></param> /// <returns></returns> private double[] fitnessFunction(double[] gens) { double d = 0; for (int i = 0; i < gens.Length; i++) { d += gens[i] * Math.Pow(10, i); } if (dict_fitness.ContainsKey(d)) { return(dict_fitness[d]); } // construct motor from gens, using Lua script AbstractMotor motor = null; AbstractMMAnalyser mma = null; lua_constructMotorfromGens(gens, currentConfig.luascript_constructMotor, out motor, out mma); // motor calculate points coordinates motor.CalcPointsCoordinates(); // if params invalid, return fitness as null if (!motor.IsParamsValid()) { foreach (ParamValidationInfo pvi in motor.ListParamsValidation) { if (pvi.msgType == ParamValidationInfo.MessageType.Error) { Console.WriteLine("Error: \t+ " + pvi.message); } } return(dict_fitness[d] = null); } // analytical analysis var a = motor.GetAnalyticalAnalyser(); a.RunAnalysis(); if (!a.isDataValid()) { return(dict_fitness[d] = null); } // finite elements analysis if available object fem_results = null; if (lua["useFEM"] != null && mma != null) { // static analysis String outdir = OutputFolderFEM + "\\" + motor.GetMD5String(); Directory.CreateDirectory(outdir); String femFile = outdir + "\\static.FEM"; if (!motor.isFEMModelReady(femFile)) { motor.BuildFEMModel(femFile, FEMMToUse[0]); } AbstractStaticAnalyser staticAnalyser = motor.GetStaticAnalyser(); staticAnalyser.Path_OriginalFEMFile = femFile; staticAnalyser.OutputPath = outdir; staticAnalyser.DoAnalysisOnOriginalFEMFile = true; staticAnalyser.FEMMToUse = FEMMToUse; staticAnalyser.RunAnalysis(); // for some reason, analysis was not succesful? if (!File.Exists(staticAnalyser.WorkingANSFile)) { return(dict_fitness[d] = null); } // mma analysis mma.Path_OriginalFEMFile = femFile; mma.CustomOutputDir = outdir; mma.FEMMToUse = FEMMToUse; mma.RunAnalysis(); fem_results = mma.Results; // to take pictures of progress //FEMMToUse[0].open(femFile); //Invoke((Action)delegate () //{ // individualCount++; // Bitmap bmp = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height); // Graphics gr = Graphics.FromImage(bmp); // gr.CopyFromScreen(0, 0, 0, 0, bmp.Size); // bmp.Save("D:\\captures\\" + string.Format("{0:D8}", individualCount) + ".png", System.Drawing.Imaging.ImageFormat.Png); //}); //FEMMToUse[0].mi_close(); } var f = lua_fitnessFunction(a.Results, fem_results, currentConfig.luascript_fitness_function); dict_fitness[d] = f; return(f); }