Exemplo n.º 1
0
        private void OptResultsWindow_OnIndividualSelected(Individual ind)
        {
            AbstractMotor motor    = null;
            string        infotext = "";
            string        log      = "";

            analyzeAnIndividual(ind, out infotext, out log, out motor);
            if (motor == null)
            {
                return;
            }

            rtb_results.Clear();
            rtb_results.AppendText(log);

            if (previewWindow == null || previewWindow.IsDisposed)
            {
                previewWindow = new PreviewWindow();
                previewWindow.Show();
            }

            previewWindow.SetMotor(motor);
            previewWindow.SetInfoText(infotext);
            previewWindow.Text = "Preview window";
            previewWindow.refreshPreview();
        }
Exemplo n.º 2
0
        private void updateID_MD5_inParamsTable()
        {
            // copy params from original
            ParametersCollection swParams = MotorToParams(CurrentMotor);

            // sweep variants, setting ID, MD5
            foreach (DataRow paramRow in ParamsTable.Rows)
            {
                int variantNum = ParamsTable.Rows.IndexOf(paramRow);
                paramRow[COL_ID] = variantNum;

                // 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 motor from parameters
                AbstractMotor motor = ParamsToMotor(swParams);

                paramRow[COL_MD5] = motor.GetMD5String();
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create new motor with type base on what currently have
        /// </summary>
        private void createNewProjectBaseOnCurrent(Type newMotorType)
        {
            // check if already this type?
            if (CurrentMotorType.Equals(newMotorType))
            {
                return;
            }

            // check if type in the list, if not throw exception since this maybe programming mistake
            if (!ListMotorType.Contains(newMotorType))
            {
                throw new ArgumentException("Type " + newMotorType.Name + " is not in the list.");
            }

            BindingFlags flag       = BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public;
            PropertyInfo pnewStator = newMotorType.GetProperty("Stator", flag);
            PropertyInfo pnewRotor  = newMotorType.GetProperty("Rotor", flag);
            PropertyInfo pnewAirgap = newMotorType.GetProperty("Airgap", flag);

            AbstractMotor oldMotor     = Motor;
            var           oldTrans     = TransAnalysisGroup;
            var           oldmma       = mmAnalyser;
            var           olddqa       = dqcurrentAnalyser;
            Type          oldTransType = TypeForTransientAnalyser[oldMotor.GetType()];
            Type          oldmmaType   = TypeForMMAnalyser[oldMotor.GetType()];
            Type          olddqaType   = TypeForDQCurrentAnalyser[oldMotor.GetType()];

            // create sample project with motortype, Motor is new
            createNewSampleProject(newMotorType);

            Type newTransType = TypeForTransientAnalyser[Motor.GetType()];
            Type newmmaType   = TypeForMMAnalyser[Motor.GetType()];
            Type newdqaType   = TypeForDQCurrentAnalyser[Motor.GetType()];

            // copy from old one if type is match
            if (oldMotor.Stator.GetType().Equals(pnewStator.PropertyType))
            {
                Motor.Stator = oldMotor.Stator;
            }
            if (oldMotor.Rotor.GetType().Equals(pnewRotor.PropertyType))
            {
                Motor.Rotor = oldMotor.Rotor;
            }
            if (oldMotor.Airgap.GetType().Equals(pnewAirgap.PropertyType))
            {
                Motor.Airgap = oldMotor.Airgap;
            }
            if (oldTransType.Equals(newTransType))
            {
                TransAnalysisGroup = oldTrans;
            }
            if (oldmmaType.Equals(newmmaType))
            {
                mmAnalyser = oldmma;
            }
            if (olddqaType.Equals(newdqaType))
            {
                dqcurrentAnalyser = olddqa;
            }
        }
Exemplo n.º 4
0
        private void PreviewWindow_Paint(object sender, PaintEventArgs e)
        {
            if (IsProjectMotor)
            {
                Motor = ProjectManager.GetInstance().Motor;
            }

            label1.Text = String.Format("{0:F1} : {1:F1} @ {2:F1}", Ox, Oy, scale);
            Motor.DrawPreview(e.Graphics, Ox, Oy, scale);
        }
Exemplo n.º 5
0
        public static PM_ACAnalyser GetSampleMe(AbstractMotor motor)
        {
            PM_ACAnalyser aca = new PM_ACAnalyser();

            aca.AnalysisName = "ACAnalysis";
            aca.Motor        = motor;
            aca.Current      = 10;
            aca.Freq         = 100;

            return(aca);
        }
Exemplo n.º 6
0
        public static PM_MMAnalyser GetSampleMe(AbstractMotor motor)
        {
            PM_MMAnalyser mma = new PM_MMAnalyser();

            mma.AnalysisName = "MMAnalysis";
            mma.Motor        = motor;
            mma.Beta         = 135;
            mma.MaxCurrent   = 160;
            mma.RotorAngle   = 40;
            mma.StepCount    = 10;

            return(mma);
        }
Exemplo n.º 7
0
        public static PM_DQCurrentAnalyser GetSampleMe(AbstractMotor motor)
        {
            PM_DQCurrentAnalyser dqa = new PM_DQCurrentAnalyser();

            dqa.AnalysisName = "DQCAnalysis";
            dqa.Motor        = motor;

            dqa.BaseSpeed          = 3000;
            dqa.MaxCurrent         = 100;
            dqa.CurrentSampleCount = 10;
            dqa.StepCount          = 60;

            return(dqa);
        }
        new public static PMTransientAnalyser GetSampleMe(AbstractMotor motor)
        {
            PMTransientAnalyser ta = new PMTransientAnalyser();

            ta.AnalysisName = "Transient\\sample";
            ta.Motor        = motor;
            ta.RotorSpeed   = -3000;//rpm
            ta.EndTime      = Math.Abs(120 / ta.RotorSpeedDegreeSecond);
            ta.StepCount    = 120;
            ta.StartAngle   = 40;
            ta.IA           = "80";
            ta.IB           = "-40";
            ta.IC           = "-40";

            return(ta);
        }
Exemplo n.º 9
0
        public AbstractMotor ParamsToMotor(ParametersCollection pc)
        {
            AbstractMotor motor = GetSampleMotor();//new default
            Dictionary <String, object> objs = new Dictionary <string, object>();

            objs.Add("Motor\\General(" + motor.GeneralParams.GetType().Name + ")", motor.GeneralParams);
            objs.Add("Motor\\Rotor(" + motor.Rotor.GetType().Name + ")", motor.Rotor);
            objs.Add("Motor\\Stator(" + motor.Stator.GetType().Name + ")", motor.Stator);
            //objs.Add("Motor\\Materials", motor.MaterialParams);
            objs.Add("Motor\\Airgap(" + motor.Airgap.GetType().Name + ")", motor.Airgap);
            foreach (String objname in objs.Keys)
            {
                pc.putValuesToObject(objname, objs[objname]);
            }

            return(motor);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Execute lua_script that should modify a motor using given gens
        /// </summary>
        /// <param name="gens">Genomes</param>
        /// <param name="lua_script">lua_script</param>
        /// <returns></returns>
        private void lua_constructMotorfromGens(double[] gens, string lua_script, out AbstractMotor motor, out AbstractMMAnalyser mma)
        {
            // deep copy a motor from project manager
            var pm = ProjectManager.GetInstance();
            var pc = originParams;

            motor = pm.ParamsToMotor(pc);
            mma   = motor.GetMMAnalyser();

            lock (lock_dostring)
            {
                lua["gens"]  = gens;
                lua["motor"] = motor;
                lua["mma"]   = mma;

                lua.DoString(lua_script);
            }
        }
Exemplo n.º 11
0
        private AbstractMotor ParamsToMotor(ParametersCollection pc)
        {
            ProjectManager pm                = ProjectManager.GetInstance();
            AbstractMotor  motor             = pm.GetSampleMotor();//new default
            Dictionary <String, object> objs = new Dictionary <string, object>();

            objs.Add("Motor\\General", motor.GeneralParams);
            objs.Add("Motor\\Rotor", motor.Rotor);
            objs.Add("Motor\\Stator", motor.Stator);
            //objs.Add("Motor\\Materials", motor.MaterialParams);
            objs.Add("Motor\\Airgap", motor.Airgap);
            foreach (String objname in objs.Keys)
            {
                pc.putValuesToObject(objname, objs[objname]);
            }

            return(motor);
        }
Exemplo n.º 12
0
        private void OptResultsWindow_OnApplyIndividualClick(Individual ind)
        {
            if (optimizationIsRunning)
            {
                return;
            }

            AbstractMotor motor    = null;
            string        infotext = "";
            string        log      = "";

            analyzeAnIndividual(ind, out infotext, out log, out motor);
            if (motor == null)
            {
                return;
            }

            applyOptimalResult(motor);
        }
Exemplo n.º 13
0
        public ParametersCollection MotorToParams(AbstractMotor motor)
        {
            // Parameters from motor
            Dictionary <String, object> objs = new Dictionary <string, object>();

            objs.Add("Motor\\General(" + motor.GeneralParams.GetType().Name + ")", motor.GeneralParams);
            objs.Add("Motor\\Rotor(" + motor.Rotor.GetType().Name + ")", motor.Rotor);
            objs.Add("Motor\\Stator(" + motor.Stator.GetType().Name + ")", motor.Stator);
            //objs.Add("Motor\\Materials", motor.MaterialParams);
            objs.Add("Motor\\Airgap(" + motor.Airgap.GetType().Name + ")", motor.Airgap);

            ParametersCollection motorParams = new ParametersCollection();

            foreach (String objname in objs.Keys)
            {
                motorParams.AddRange(ParametersCollection.FromObject(objname, objs[objname]));
            }

            return(motorParams);
        }
Exemplo n.º 14
0
        private void applyOptimalResult(AbstractMotor optimalMotor)
        {
            ProjectManager pm = ProjectManager.GetInstance();

            var pc = pm.MotorToParams(optimalMotor);

            foreach (var p_dest in pm.MotorParams)
            {
                foreach (var p_src in pc)
                {
                    if (p_src.fullname == p_dest.fullname && p_src.valueType == p_dest.valueType)
                    {
                        p_dest.text  = p_src.text;
                        p_dest.value = p_src.value;
                    }
                }
            }

            // update motor
            pm.InvalidateParams();
        }
Exemplo n.º 15
0
        /// <summary>
        /// Get the default motor of current researching type
        /// </summary>
        /// <returns></returns>
        public AbstractMotor GetSampleMotor(Type motorType = null)
        {
            if (motorType == null)
            {
                motorType = CurrentMotorType;
            }

            MethodInfo mi = motorType.GetMethod("GetSampleMotor");

            if (mi == null)
            {
                throw new NotImplementedException("public static AbstractMotor GetSampleMotor() methods is not implemented in " + CurrentMotorType.Name);
            }

            AbstractMotor motor = mi.Invoke(null, null) as AbstractMotor;

            if (motor == null)
            {
                throw new NotImplementedException("public static AbstractMotor GetSampleMotor() methods return not the AbstractMotor (" + CurrentMotorType.Name + ")");
            }

            return(motor);
        }
Exemplo n.º 16
0
        /// <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);
        }
Exemplo n.º 17
0
 public void SetMotor(AbstractMotor motor)
 {
     Motor          = motor;
     IsProjectMotor = false;
 }
Exemplo n.º 18
0
        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();
        }
Exemplo n.º 19
0
        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();
        }