Exemplo n.º 1
0
        public void Init()
        {
            TempDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(TempDir);

            UnLoad += (s, e) =>
            {
                try
                {
                    Directory.Delete(TempDir, true);
                }
                catch
                {
                }
            };

            var tl2 = new TableLayout {
                Spacing = new Size(10, 10)
            };

            btnImport = new Button()
            {
                ImagePosition = ButtonImagePosition.Overlay, Height = 24, Width = 24, ToolTip = "Import Files", Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-import.png", this.GetType().Assembly)).WithSize(16, 16)
            };
            btnExport = new Button()
            {
                ImagePosition = ButtonImagePosition.Overlay, Height = 24, Width = 24, ToolTip = "Export Selected File", Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-export.png", this.GetType().Assembly)).WithSize(16, 16)
            };
            btnDelete = new Button()
            {
                ImagePosition = ButtonImagePosition.Overlay, Height = 24, Width = 24, ToolTip = "Delete Selected File", Image = new Bitmap(Eto.Drawing.Bitmap.FromResource(imgprefix + "icons8-delete2.png", this.GetType().Assembly)).WithSize(16, 16)
            };

            ListBox1 = new ListBox();

            if (Application.Instance.Platform.IsGtk)
            {
                btnImport.Size = new Size(30, 30);
                btnExport.Size = new Size(30, 30);
                btnDelete.Size = new Size(30, 30);
            }

            var menu1 = new StackLayout
            {
                Items       = { btnImport, btnExport, btnDelete },
                Orientation = Orientation.Horizontal,
                Spacing     = 4,
                HorizontalContentAlignment = HorizontalAlignment.Stretch,
                VerticalContentAlignment   = VerticalAlignment.Bottom,
                Padding = 5,
                Height  = 34
            };

            tl2.Rows.Add(new TableRow(menu1));

            tl2.Rows.Add(new TableRow(ListBox1)
            {
                ScaleHeight = true
            });

            LabelSize = new Label();

            tl2.Rows.Add(new TableRow(LabelSize));

            tl2.Padding = new Padding(5, 5, 5, 5);
            tl2.Spacing = new Size(0, 0);

            var splitpanel = new Splitter();

            splitpanel.Panel1 = tl2;

            if (!Application.Instance.Platform.IsGtk)
            {
                Viewer            = new WebView();
                splitpanel.Panel2 = Viewer;
            }

            splitpanel.FixedPanel   = SplitterFixedPanel.Panel1;
            splitpanel.Panel1.Width = 300;

            Rows.Add(new TableRow(splitpanel));

            ListBox1.SelectedIndexChanged += (s, e) =>
            {
                if (ListBox1.SelectedIndex < 0)
                {
                    return;
                }
                Flowsheet.RunCodeOnUIThread(() =>
                {
                    if (IsLoaded)
                    {
                        var provider = Flowsheet.FileDatabaseProvider;
                        if (provider.CheckIfExists(ListBox1.SelectedValue.ToString()))
                        {
                            try
                            {
                                string TempFilePath = Path.Combine(TempDir, ListBox1.SelectedValue.ToString());
                                provider.ExportFile(ListBox1.SelectedValue.ToString(), TempFilePath);
                                if (Viewer != null)
                                {
                                    Viewer.Url = new Uri(TempFilePath);
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ListBox1.SelectedValue.ToString() + ": " + ex.Message, "Error",
                                                MessageBoxButtons.OK, MessageBoxType.Error);
                            }
                        }
                    }
                });
            };

            btnExport.Click += (s, e) =>
            {
                if (ListBox1.SelectedIndex >= 0)
                {
                    var sfd1 = new SaveFileDialog();
                    sfd1.FileName = ListBox1.SelectedValue.ToString();
                    sfd1.Title    = "Export File";
                    sfd1.Filters.Add(new FileFilter("All Files", new[] { "*.*" }));
                    if (sfd1.ShowDialog(this) == DialogResult.Ok)
                    {
                        var provider = Flowsheet.FileDatabaseProvider;
                        try
                        {
                            provider.ExportFile(ListBox1.SelectedValue.ToString(), sfd1.FileName);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ListBox1.SelectedValue.ToString() + ": " + ex.Message, "Error",
                                            MessageBoxButtons.OK, MessageBoxType.Error);
                        }
                    }
                }
            };

            btnImport.Click += (s, e) =>
            {
                var ofd1 = new OpenFileDialog();
                ofd1.Title = "Import Files";
                ofd1.Filters.Add(new FileFilter("All Supported Files", new[] { "*.pdf", "*.jpg", "*.png", "*.txt", "*.py", "*.html",
                                                                               "*.dwxmz", "*.dwxml", "*.xml", "*.json", "*.dwcsd2", "*.dwrsd2", "*.xlsx", "*.xls", "*.pxml" }));
                if (ofd1.ShowDialog(this) == DialogResult.Ok)
                {
                    var provider = Flowsheet.FileDatabaseProvider;
                    foreach (var file in ofd1.Filenames)
                    {
                        try
                        {
                            provider.PutFile(file);
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(file + ": " + ex.Message, "Error",
                                            MessageBoxButtons.OK, MessageBoxType.Error);
                        }
                    }
                    Flowsheet.RunCodeOnUIThread(() =>
                    {
                        ListFiles();
                        UpdateSize();
                    });
                }
            };

            btnDelete.Click += (s, e) =>
            {
                if (ListBox1.SelectedIndex >= 0)
                {
                    if ((MessageBox.Show("Confirm Operation?", "Remove File", MessageBoxButtons.YesNo, MessageBoxType.Question) == DialogResult.Yes))
                    {
                        var provider = Flowsheet.FileDatabaseProvider;
                        try
                        {
                            provider.DeleteFile(ListBox1.SelectedValue.ToString());
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ListBox1.SelectedValue.ToString() + ": " + ex.Message, "Error",
                                            MessageBoxButtons.OK, MessageBoxType.Error);
                        }
                        Flowsheet.RunCodeOnUIThread(() =>
                        {
                            ListFiles();
                            UpdateSize();
                        });
                    }
                }
            };

            IsLoaded = true;

            UpdateSize();
            ListFiles();
        }
        public Task RunIntegrator(bool realtime, bool waittofinish)
        {
            btnPlay.Enabled = false;

            btnRT.Enabled = false;

            btnViewResults.Enabled = false;

            Abort = false;

            var schedule = Flowsheet.DynamicsManager.ScheduleList[Flowsheet.DynamicsManager.CurrentSchedule];

            var integrator = Flowsheet.DynamicsManager.IntegratorList[schedule.CurrentIntegrator];

            integrator.RealTime = realtime;

            var Controllers = Flowsheet.SimulationObjects.Values.Where(x => x.ObjectClass == SimulationObjectClass.Controllers).ToList();

            if (!waittofinish)
            {
                if (!realtime)
                {
                    if (!schedule.UseCurrentStateAsInitial)
                    {
                        RestoreState(schedule.InitialFlowsheetStateID);
                    }
                }
            }

            pbProgress.Value = 0;

            pbProgress.MinValue = 0;

            integrator.MonitoredVariableValues.Clear();

            lbStatus.Text = "00:00:00/" + integrator.Duration.ToString("c");

            if (realtime)
            {
                pbProgress.MaxValue = int.MaxValue;
            }
            else
            {
                pbProgress.MaxValue = (int)integrator.Duration.TotalSeconds;
            }

            var interval = integrator.IntegrationStep.TotalSeconds;

            if (realtime)
            {
                interval = Convert.ToDouble(integrator.RealTimeStepMs) / 1000.0;
            }

            var final = pbProgress.MaxValue;

            foreach (PIDController controller in Controllers)
            {
                controller.Reset();
            }

            if (schedule.ResetContentsOfAllObjects)
            {
                foreach (var obj in Flowsheet.SimulationObjects.Values)
                {
                    if (obj.HasPropertiesForDynamicMode)
                    {
                        if (obj is DWSIM.SharedClasses.UnitOperations.BaseClass)
                        {
                            var bobj = (DWSIM.SharedClasses.UnitOperations.BaseClass)obj;
                            if (bobj.GetDynamicProperty("Reset Content") != null)
                            {
                                bobj.SetDynamicProperty("Reset Content", 1);
                            }
                            if (bobj.GetDynamicProperty("Reset Contents") != null)
                            {
                                bobj.SetDynamicProperty("Reset Contents", 1);
                            }
                            if (bobj.GetDynamicProperty("Initialize using Inlet Stream") != null)
                            {
                                bobj.SetDynamicProperty("Initialize using Inlet Stream", 1);
                            }
                            if (bobj.GetDynamicProperty("Initialize using Inlet Streams") != null)
                            {
                                bobj.SetDynamicProperty("Initialize using Inlet Streams", 1);
                            }
                        }
                    }
                }
            }

            integrator.CurrentTime = new DateTime();

            integrator.MonitoredVariableValues.Clear();

            double controllers_check = 100000;
            double streams_check     = 100000;
            double pf_check          = 100000;

            Flowsheet.SupressMessages = true;

            var exceptions = new List <Exception>();

            var maintask = new Task(() =>
            {
                int j = 0;

                double i = 0;

                while (i <= final)
                {
                    int i0 = (int)i;

                    var sw = new Stopwatch();

                    sw.Start();

                    Flowsheet.RunCodeOnUIThread(() =>
                    {
                        pbProgress.Value = i0;
                        lbStatus.Text    = new TimeSpan(0, 0, i0).ToString("c") + "/" + integrator.Duration.ToString("c");;
                    });

                    controllers_check += interval;
                    streams_check     += interval;
                    pf_check          += interval;

                    if (controllers_check >= integrator.CalculationRateControl * interval)
                    {
                        controllers_check = 0.0;
                        integrator.ShouldCalculateControl = true;
                    }
                    else
                    {
                        integrator.ShouldCalculateControl = false;
                    }

                    if (streams_check >= integrator.CalculationRateEquilibrium * interval)
                    {
                        streams_check = 0.0;
                        integrator.ShouldCalculateEquilibrium = true;
                    }
                    else
                    {
                        integrator.ShouldCalculateEquilibrium = false;
                    }

                    if (pf_check >= integrator.CalculationRatePressureFlow * interval)
                    {
                        pf_check = 0.0;
                        integrator.ShouldCalculatePressureFlow = true;
                    }
                    else
                    {
                        integrator.ShouldCalculatePressureFlow = false;
                    }

                    GlobalSettings.Settings.CalculatorActivated = true;
                    GlobalSettings.Settings.CalculatorBusy      = false;

                    exceptions = FlowsheetSolver.FlowsheetSolver.SolveFlowsheet(Flowsheet, GlobalSettings.Settings.SolverMode);

                    while (GlobalSettings.Settings.CalculatorBusy)
                    {
                        Task.Delay(200).Wait();
                    }

                    if (exceptions.Count > 0)
                    {
                        break;
                    }

                    StoreVariableValues((DynamicsManager.Integrator)integrator, j, integrator.CurrentTime);

                    Flowsheet.RunCodeOnUIThread(() =>
                    {
                        Flowsheet.UpdateInterface();
                        Flowsheet.FlowsheetControl.Invalidate();
                    });

                    integrator.CurrentTime = integrator.CurrentTime.AddSeconds(interval);

                    if (integrator.ShouldCalculateControl)
                    {
                        foreach (PIDController controller in Controllers)
                        {
                            if (controller.Active)
                            {
                                Flowsheet.ProcessScripts(Scripts.EventType.ObjectCalculationStarted, Scripts.ObjectType.FlowsheetObject, controller.Name);
                                try
                                {
                                    controller.Solve();
                                    Flowsheet.ProcessScripts(Scripts.EventType.ObjectCalculationFinished, Scripts.ObjectType.FlowsheetObject, controller.Name);
                                }
                                catch (Exception ex)
                                {
                                    Flowsheet.ProcessScripts(Scripts.EventType.ObjectCalculationError, Scripts.ObjectType.FlowsheetObject, controller.Name);
                                    throw ex;
                                }
                            }
                        }
                    }

                    var waittime = integrator.RealTimeStepMs - sw.ElapsedMilliseconds;

                    if (waittime > 0 && realtime)
                    {
                        Task.Delay((int)waittime).Wait();
                    }

                    sw.Stop();

                    if (Abort)
                    {
                        break;
                    }

                    if (!realtime)
                    {
                        if (schedule.UsesEventList)
                        {
                            ProcessEvents(schedule.CurrentEventList, integrator.CurrentTime, integrator.IntegrationStep);
                        }

                        if (schedule.UsesCauseAndEffectMatrix)
                        {
                            ProcessCEMatrix(schedule.CurrentCauseAndEffectMatrix);
                        }
                    }

                    j += 1;

                    i += interval;
                }

                if (exceptions.Count > 0)
                {
                    throw exceptions[0];
                }
            });

            maintask.ContinueWith(t =>
            {
                Flowsheet.RunCodeOnUIThread(() =>
                {
                    btnPlay.Enabled           = true;
                    btnViewResults.Enabled    = true;
                    btnRT.Enabled             = true;
                    pbProgress.Value          = 0;
                    Flowsheet.SupressMessages = false;
                    Flowsheet.UpdateEditorPanels.Invoke();
                    if (t.Exception != null)
                    {
                        Exception baseexception;
                        foreach (var ex in t.Exception.Flatten().InnerExceptions)
                        {
                            string euid = Guid.NewGuid().ToString();
                            SharedClasses.ExceptionProcessing.ExceptionList.Exceptions.Add(euid, ex);
                            if (ex is AggregateException)
                            {
                                baseexception = ex.InnerException;
                                foreach (var iex in ((AggregateException)ex).Flatten().InnerExceptions)
                                {
                                    while (iex.InnerException != null)
                                    {
                                        baseexception = iex.InnerException;
                                    }
                                    Flowsheet.ShowMessage(baseexception.Message.ToString(), Interfaces.IFlowsheet.MessageType.GeneralError, euid);
                                }
                            }
                            else
                            {
                                baseexception = ex;
                                if (baseexception.InnerException != null)
                                {
                                    while (baseexception.InnerException.InnerException != null)
                                    {
                                        baseexception = baseexception.InnerException;
                                        if ((baseexception == null))
                                        {
                                            break;
                                        }
                                        if ((baseexception.InnerException == null))
                                        {
                                            break;
                                        }
                                    }
                                    Flowsheet.ShowMessage(baseexception.Message.ToString(), Interfaces.IFlowsheet.MessageType.GeneralError, euid);
                                }
                            }
                        }
                    }
                });
            });

            if (waittofinish)
            {
                maintask.RunSynchronously();
            }
            else
            {
                maintask.Start();
            }

            return(maintask);
        }
Exemplo n.º 3
0
        public PIDTuningTool(Shared.Flowsheet fs, DynamicsIntegratorControl intcontrol) : base()
        {
            Flowsheet = fs;
            intc      = intcontrol;
            Padding   = new Eto.Drawing.Padding(5);
            Spacing   = new Size(5, 5);

            Padding = new Eto.Drawing.Padding(5);
            Spacing = new Size(10, 10);

            var leftcontainer = new DynamicLayout {
                Width = 300
            };

            leftcontainer.CreateAndAddLabelRow("Schedule");

            var schlist = Flowsheet.DynamicsManager.ScheduleList.Values.ToList();

            var cbSchedule = leftcontainer.CreateAndAddDropDownRow("Schedule", schlist.Select((x) => x.Description).ToList(), 0,
                                                                   (dd, e) => schedule = schlist[dd.SelectedIndex]);

            leftcontainer.CreateAndAddLabelRow("Controllers");

            leftcontainer.CreateAndAddDescriptionRow("Select the PID Controllers to tune.");

            var listb = new CheckBoxList()
            {
                Height = 200
            };

            foreach (var obj in Flowsheet.SimulationObjects.Values.Where((x) => x.ObjectClass == Interfaces.Enums.SimulationObjectClass.Controllers))
            {
                listb.Items.Add(obj.GraphicObject.Tag, obj.Name);
            }

            leftcontainer.CreateAndAddControlRow(listb);

            leftcontainer.CreateAndAddNumericEditorRow("Maximum Iterations", iterations, 5, 100, 0,
                                                       (ns, e) =>
            {
                iterations = (int)ns.Value;
            });

            var btnRun = leftcontainer.CreateAndAddButtonRow("Begin Tuning", null, null);

            var btnCancel = leftcontainer.CreateAndAddButtonRow("Cancel", null, (btn, e) => Abort = true);

            txtResults = new TextArea {
                ReadOnly = true, Wrap = true
            };

            Rows.Add(new TableRow(leftcontainer, new Scrollable {
                Content = txtResults
            }));

            btnRun.Click += (s, e) =>
            {
                Flowsheet.RunCodeOnUIThread(() =>
                {
                    txtResults.Text = "";

                    if (!Flowsheet.DynamicMode)
                    {
                        txtResults.Text += "Error: Dynamic Mode is not activated. Activate Dynamic Mode and try again.";
                        return;
                    }

                    intc.cbsc.SelectedIndex = cbSchedule.SelectedIndex;

                    var schedule = Flowsheet.DynamicsManager.ScheduleList[Flowsheet.DynamicsManager.CurrentSchedule];

                    List <OptSimplexBoundVariable> vars = new List <OptSimplexBoundVariable>();
                    List <PIDController> controllers    = new List <PIDController>();

                    foreach (var item in listb.SelectedKeys)
                    {
                        var controller = (PIDController)Flowsheet.SimulationObjects[item];
                        controllers.Add(controller);
                        vars.Add(new OptSimplexBoundVariable(controller.Kp, 0.0, controller.Kp * 10));
                        vars.Add(new OptSimplexBoundVariable(controller.Ki, 0.0, 100.0));
                        vars.Add(new OptSimplexBoundVariable(controller.Kd, 0.0, 100.0));
                    }

                    btnRun.Enabled    = false;
                    btnCancel.Enabled = true;

                    Simplex simplex = new Simplex();

                    simplex.MaxFunEvaluations = iterations;

                    Abort = false;

                    int counter = 1;

                    if (schedule.InitialFlowsheetStateID == "" | schedule.UseCurrentStateAsInitial)
                    {
                        txtResults.Text  += "The selected schedule must have a valid initial state to start from.";
                        btnRun.Enabled    = true;
                        btnCancel.Enabled = false;
                        return;
                    }

                    var result = simplex.ComputeMin(x =>
                    {
                        if (Abort)
                        {
                            return(0.0);
                        }
                        Flowsheet.RunCodeOnUIThread(() =>
                        {
                            txtResults.Text += (string.Format("Beginning Iteration #{0}...\n", counter));
                        });
                        intc.RestoreState(schedule.InitialFlowsheetStateID);
                        var i = 0;
                        foreach (var controller in controllers)
                        {
                            controller.Kp = x[i];
                            controller.Ki = x[i + 1];
                            controller.Kd = x[i + 2];
                            Flowsheet.RunCodeOnUIThread(() =>
                            {
                                txtResults.Text += (string.Format("Controller: {0} - Kp = {1}, Ki = {2}, Kd = {3}\n", controller.GraphicObject.Tag, controller.Kp, controller.Ki, controller.Kd));
                            });
                            i += 3;
                        }
                        intc.RunIntegrator(false, true);
                        var totalerror = controllers.Select(c => c.CumulativeError).ToArray().AbsSumY();
                        Flowsheet.RunCodeOnUIThread(() =>
                        {
                            txtResults.Text      += (string.Format("Total Error: {0}\n", totalerror));
                            txtResults.CaretIndex = txtResults.Text.Length - 1;
                        });
                        Application.Instance.RunIteration();
                        counter += 1;
                        return(totalerror);
                    }, vars.ToArray());

                    if (Abort)
                    {
                        txtResults.Text += (string.Format("Tuning aborted by the user. Results:\n"));
                    }
                    else
                    {
                        txtResults.Text += (string.Format("Tuning finished successfully. Results:\n"));
                    }

                    var j = 0;
                    foreach (var controller in controllers)
                    {
                        controller.Kp    = result[j];
                        controller.Ki    = result[j + 1];
                        controller.Kd    = result[j + 2];
                        txtResults.Text += (string.Format("Controller: {0} - Kp = {1}, Ki = {2}, Kd = {3}\n", controller.GraphicObject.Tag, controller.Kp, controller.Ki, controller.Kd));
                        j += 3;
                    }

                    btnRun.Enabled    = true;
                    btnCancel.Enabled = false;

                    Flowsheet.UpdateInterface();
                });
            };
        }