private void DisplayPage_Results() { var page = new WizardPage(); var checks = new List <CheckBox>(); var tboxes = new List <TextBox>(); page.hasBackButton = true; page.hasCancelButton = true; page.hasNextButton = true; page.hasFinishButton = false; page.cancelAction = () => { page.Close(); }; page.backAction = () => { page.Close(); DisplayPage_ML(); }; page.nextAction = () => { Application.Instance.Invoke(() => DisplayPage_SaveModel()); page.Close(); }; page.Title = "Neural Network Model Wizard"; page.HeaderTitle = "Step 7 - Trained Model Predictions"; page.HeaderDescription = "View and Compare the Results Predicted by the Trained Model"; page.FooterText = "Click 'Next' to Continue."; var dl = c.GetDefaultContainer(); dl.Width = Width; var plot = new Eto.OxyPlot.Plot(); plot.Model = new PlotModel(); plot.Model.Background = OxyPlot.OxyColors.White; plot.Model.TitleFontSize = 12; plot.Model.SubtitleFontSize = 10; plot.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Bottom, FontSize = 10, Title = "Input Value (Scaled)", Key = "x", }); plot.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Left, FontSize = 10, Title = "Predicted Value (Scaled)", }); plot.Model.LegendFontSize = 11; plot.Model.LegendPlacement = OxyPlot.LegendPlacement.Outside; plot.Model.LegendOrientation = OxyPlot.LegendOrientation.Horizontal; plot.Model.LegendPosition = OxyPlot.LegendPosition.BottomCenter; plot.Model.TitleHorizontalAlignment = OxyPlot.TitleHorizontalAlignment.CenteredWithinView; plot.Model.Title = "Training Dataset"; plot.Width = 380; var plot2 = new Eto.OxyPlot.Plot(); plot2.Model = new PlotModel(); plot2.Model.Background = OxyPlot.OxyColors.White; plot2.Model.TitleFontSize = 12; plot2.Model.SubtitleFontSize = 10; plot2.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Bottom, FontSize = 10, Title = "Input Value (Scaled)", Key = "x", }); plot2.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Left, FontSize = 10, Title = "Predicted Value (Scaled)" }); plot2.Model.LegendFontSize = 11; plot2.Model.LegendPlacement = OxyPlot.LegendPlacement.Outside; plot2.Model.LegendOrientation = OxyPlot.LegendOrientation.Horizontal; plot2.Model.LegendPosition = OxyPlot.LegendPosition.BottomCenter; plot2.Model.TitleHorizontalAlignment = OxyPlot.TitleHorizontalAlignment.CenteredWithinView; plot2.Model.Title = "Testing Dataset"; plot2.Width = 380; var minscale = CurrentModel.Parameters.MinScale; var maxscale = CurrentModel.Parameters.MaxScale; // training plot plot.Model.AddLineSeries(new double[] { minscale, maxscale }, new double[] { minscale, maxscale }, OxyColors.Black); for (var i = 0; i < CurrentModel.y_train_unscaled.shape[1]; i++) { var xseries = new List <float>(); for (var j = 0; j < CurrentModel.y_train_unscaled.shape[0]; j++) { xseries.Add(CurrentModel.y_train_unscaled[j][i]); } var yseries = new List <float>(); for (var j = 0; j < CurrentModel.yp_train_unscaled.shape[0]; j++) { yseries.Add(CurrentModel.yp_train_unscaled[j][i]); } var min = xseries.Min(); var max = xseries.Max(); var xseries2 = xseries.Select(x => (double)x).ToList(); xseries2 = xseries2.Select(x => Utils.Scale(x, min, max, minscale, maxscale)).ToList(); var yseries2 = yseries.Select(x => (double)x).ToList(); yseries2 = yseries2.Select(y => Utils.Scale(y, min, max, minscale, maxscale)).ToList(); plot.Model.AddScatterSeries(xseries2, yseries2); plot.Model.Series.Last().Title = CurrentModel.Parameters.Labels_Outputs[i]; ((ScatterSeries)plot.Model.Series.Last()).MarkerSize = 3.0; ((ScatterSeries)plot.Model.Series.Last()).MarkerType = MarkerType.Circle; ((ScatterSeries)plot.Model.Series.Last()).Title = CurrentModel.Parameters.Labels_Outputs[i]; } // testing plot plot2.Model.AddLineSeries(new double[] { minscale, maxscale }, new double[] { minscale, maxscale }, OxyColors.Black); for (var i = 0; i < CurrentModel.y_test_unscaled.shape[1]; i++) { var xseries = new List <float>(); for (var j = 0; j < CurrentModel.y_test_unscaled.shape[0]; j++) { xseries.Add(CurrentModel.y_test_unscaled[j][i]); } var yseries = new List <float>(); for (var j = 0; j < CurrentModel.yp_test_unscaled.shape[0]; j++) { yseries.Add(CurrentModel.yp_test_unscaled[j][i]); } var min = xseries.Min(); var max = xseries.Max(); var xseries2 = xseries.Select(x => (double)x).ToList(); xseries2 = xseries2.Select(x => Utils.Scale(x, min, max, minscale, maxscale)).ToList(); var yseries2 = yseries.Select(x => (double)x).ToList(); yseries2 = yseries2.Select(y => Utils.Scale(y, min, max, minscale, maxscale)).ToList(); plot2.Model.AddScatterSeries(xseries2, yseries2); plot2.Model.Series.Last().Title = CurrentModel.Parameters.Labels_Outputs[i]; ((ScatterSeries)plot2.Model.Series.Last()).MarkerSize = 3.0; ((ScatterSeries)plot2.Model.Series.Last()).MarkerType = MarkerType.Circle; ((ScatterSeries)plot2.Model.Series.Last()).Title = CurrentModel.Parameters.Labels_Outputs[i]; } plot.Model.InvalidatePlot(true); plot2.Model.InvalidatePlot(true); var tl = new TableLayout(new TableRow(plot, plot2)) { Spacing = new Size(10, 10), Height = 440 }; dl.CreateAndAddControlRow(tl); page.Init(Width, Height); page.Topmost = false; var scrollable = new Scrollable { Content = dl, Border = BorderType.None, Size = new Size(Width, Height), ExpandContentHeight = true }; page.ContentContainer.Add(scrollable); page.Show(); }
void Initialize() { var su = SimObject.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem; var nf = SimObject.GetFlowsheet().FlowsheetOptions.NumberFormat; if (SimObject is Pipe) { var pipe = (Pipe)SimObject; string[] datatype = { "Length", "Inclination", "Pressure", "Temperature", "Liquid Velocity", "Vapor Velocity", "Heat Flow", "Liquid Holdup", "Overall HTC", "Internal HTC", "Wall k/L", "Insulation k/L", "External HTC" }; string[] units = { su.distance, "degrees", su.pressure, su.temperature, su.velocity, su.velocity, su.heatflow, "", su.heat_transf_coeff, su.heat_transf_coeff, su.heat_transf_coeff, su.heat_transf_coeff, su.heat_transf_coeff }; var btn = new Button { Text = "View Pipe Properties Profile" }; container.Rows.Add(new TableRow(btn)); btn.Click += (sender, e) => { var plotcontainer = s.GetDefaultContainer(); var chart = new Eto.OxyPlot.Plot() { Height = 400, BackgroundColor = Colors.White }; chart.Visible = true; List <double> px, py; var txtres = s.CreateAndAddMultilineMonoSpaceTextBoxRow(plotcontainer, "", 400, true, null); s.CreateAndAddLabelRow(plotcontainer, "Pipe Segment Profiles: " + SimObject.GraphicObject.Tag); var xsp = s.CreateAndAddDropDownRow(plotcontainer, "X Axis Data", datatype.ToList(), 0, null); var ysp = s.CreateAndAddDropDownRow(plotcontainer, "Y Axis Data", datatype.ToList(), 2, null); s.CreateAndAddButtonRow(plotcontainer, "Update Chart/Table", null, (sender2, e2) => { px = PopulateData(pipe, xsp.SelectedIndex); py = PopulateData(pipe, ysp.SelectedIndex); var model = CreatePipeResultsModel(px.ToArray(), py.ToArray(), datatype[xsp.SelectedIndex] + " (" + units[xsp.SelectedIndex] + ")", datatype[ysp.SelectedIndex] + " (" + units[ysp.SelectedIndex] + ")"); chart.Model = model; chart.Visible = true; chart.Model.InvalidatePlot(true); chart.Invalidate(); int i = 0; var txt = new System.Text.StringBuilder(); txt.AppendLine(datatype[xsp.SelectedIndex] + " (" + units[xsp.SelectedIndex] + ")\t\t" + datatype[ysp.SelectedIndex] + " (" + units[ysp.SelectedIndex] + ")"); for (i = 0; i <= px.Count - 1; i++) { txt.AppendLine(px[i].ToString(nf) + "\t\t" + py[i].ToString(nf)); } txtres.Text = txt.ToString(); }); s.CreateAndAddLabelRow(plotcontainer, "Results Chart"); s.CreateAndAddControlRow(plotcontainer, chart); s.CreateAndAddEmptySpace(plotcontainer); s.CreateAndAddLabelRow(plotcontainer, "Results Table"); s.CreateAndAddControlRow(plotcontainer, txtres); var form = s.GetDefaultEditorForm("Pipe Properties Profile: " + SimObject.GraphicObject.Tag, 400, 500, plotcontainer); form.Topmost = true; form.Show(); }; } else if (SimObject is Column) { var column = (Column)SimObject; string[] datatype = { "Stage", "Pressure", "Temperature", "Vapor Molar Flow", "Liquid Molar Flow" }; string[] units = { "", su.pressure, su.temperature, su.molarflow, su.molarflow }; var btn = new Button { Text = "View Column Properties Profile" }; container.Rows.Add(new TableRow(btn)); btn.Click += (sender, e) => { var plotcontainer = s.GetDefaultContainer(); var chart = new Eto.OxyPlot.Plot() { Height = 400, BackgroundColor = Colors.White }; chart.Visible = true; List <double> px, py; s.CreateAndAddLabelRow(plotcontainer, "Column Profile Results: " + SimObject.GraphicObject.Tag); var xsp = s.CreateAndAddDropDownRow(plotcontainer, "X Axis Data", datatype.ToList(), 2, null); var ysp = s.CreateAndAddDropDownRow(plotcontainer, "Y Axis Data", datatype.ToList(), 0, null); s.CreateAndAddButtonRow(plotcontainer, "Update Chart", null, (sender2, e2) => { px = PopulateColumnData(column, xsp.SelectedIndex); py = PopulateColumnData(column, ysp.SelectedIndex); string xunits, yunits; xunits = " (" + units[xsp.SelectedIndex] + ")"; yunits = " (" + units[ysp.SelectedIndex] + ")"; if (xsp.SelectedIndex == 0) { xunits = ""; } if (ysp.SelectedIndex == 0) { yunits = ""; } var model = CreateColumnResultsModel(px.ToArray(), py.ToArray(), datatype[xsp.SelectedIndex] + xunits, datatype[ysp.SelectedIndex] + yunits); chart.Model = model; chart.Visible = true; chart.Model.InvalidatePlot(true); chart.Invalidate(); }); s.CreateAndAddLabelRow(plotcontainer, "Results Chart"); s.CreateAndAddControlRow(plotcontainer, chart); s.CreateAndAddEmptySpace(plotcontainer); var form = s.GetDefaultEditorForm("Column Profile: " + SimObject.GraphicObject.Tag, 400, 500, plotcontainer); form.Topmost = true; form.Show(); }; } else if (SimObject is Reactor_PFR) { var reactor = (Reactor_PFR)SimObject; if (reactor.points != null && reactor.points.Count > 0) { var btn = new Button { Text = "View PFR Properties Profile" }; container.Rows.Add(new TableRow(btn)); btn.Click += (sender, e) => { var chart = new Eto.OxyPlot.Plot() { Height = 400, BackgroundColor = Colors.White }; chart.Visible = true; var model = CreatePFRResultsModel(reactor); chart.Model = model; chart.Model.InvalidatePlot(true); chart.Invalidate(); var form = new Form() { Icon = Eto.Drawing.Icon.FromResource(imgprefix + "DWSIM_ico.ico"), Content = new Scrollable { Content = chart, Border = BorderType.None, ExpandContentWidth = true, ExpandContentHeight = true }, Title = "PFR Profile: " + SimObject.GraphicObject.Tag, ClientSize = new Size(800, 600), ShowInTaskbar = false, Maximizable = false, Minimizable = false, Topmost = true, Resizable = true }; form.Show(); }; } } else if (SimObject is HeatExchanger) { var hx = (HeatExchanger)SimObject; if (hx.CalculationMode == HeatExchangerCalcMode.PinchPoint && hx.HeatProfile.Length > 0) { var btn = new Button { Text = "View Heat Exchanged Profile" }; container.Rows.Add(new TableRow(btn)); btn.Click += (sender, e) => { var chart = new Eto.OxyPlot.Plot() { Height = 400, BackgroundColor = Colors.White }; chart.Visible = true; var model = s.CreatePlotModel(hx.HeatProfile.ToList().ConvertFromSI(su.heatflow).ToArray(), hx.TemperatureProfileCold.ToList().ConvertFromSI(su.temperature).ToArray(), hx.TemperatureProfileHot.ToList().ConvertFromSI(su.temperature).ToArray(), "Heat Profile", hx.GraphicObject.Tag, "Heat Exchanged (" + su.heatflow + ")", "Temperature (" + su.temperature + ")", "Cold Fluid", "Hot Fluid"); chart.Model = model; chart.Model.InvalidatePlot(true); chart.Invalidate(); var form = new Form() { Icon = Eto.Drawing.Icon.FromResource(imgprefix + "DWSIM_ico.ico"), Content = new Scrollable { Content = chart, Border = BorderType.None, ExpandContentWidth = true, ExpandContentHeight = true }, Title = "Heat Profile: " + SimObject.GraphicObject.Tag, ClientSize = new Size(800, 600), ShowInTaskbar = false, Maximizable = false, Minimizable = false, Topmost = true, Resizable = true }; form.Show(); }; } } var obj = (ISimulationObject)SimObject; var structreport = obj.GetStructuredReport(); if (structreport.Count > 0) { var containerd = UI.Shared.Common.GetDefaultContainer(); container.Rows.Add(new TableRow(containerd)); foreach (var item in structreport) { switch (item.Item1) { case Interfaces.Enums.ReportItemType.Label: containerd.CreateAndAddLabelRow(item.Item2[0]); break; case Interfaces.Enums.ReportItemType.Description: containerd.CreateAndAddDescriptionRow(item.Item2[0]); break; case Interfaces.Enums.ReportItemType.SingleColumn: containerd.CreateAndAddLabelRow2(item.Item2[0]); break; case Interfaces.Enums.ReportItemType.DoubleColumn: containerd.CreateAndAddThreeLabelsRow(item.Item2[0], item.Item2[1], ""); break; case Interfaces.Enums.ReportItemType.TripleColumn: containerd.CreateAndAddThreeLabelsRow(item.Item2[0], item.Item2[1], item.Item2[2]); break; } } } else { var txtcontrol = new TextArea { ReadOnly = true }; txtcontrol.Font = GlobalSettings.Settings.RunningPlatform() == GlobalSettings.Settings.Platform.Mac ? new Font("Menlo", GlobalSettings.Settings.ResultsReportFontSize) : Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize); container.Rows.Add(new TableRow(txtcontrol)); try { if (obj.Calculated) { txtcontrol.Text = "Object successfully calculated on " + obj.LastUpdated.ToString() + "\n\n"; txtcontrol.Text += obj.GetReport(SimObject.GetFlowsheet().FlowsheetOptions.SelectedUnitSystem, System.Globalization.CultureInfo.InvariantCulture, SimObject.GetFlowsheet().FlowsheetOptions.NumberFormat); } else { if (obj.ErrorMessage != "") { txtcontrol.Text = "An error occured during the calculation of this object. Details:\n\n" + obj.ErrorMessage; } else { txtcontrol.Text = "This object hasn't been calculated yet."; } } } catch (Exception ex) { txtcontrol.Text = "Report generation failed. Please recalculate the flowsheet and try again."; txtcontrol.Text += "\n\nError details: " + ex.ToString(); } } }
void Init() { Padding = new Padding(10); var su = flowsheet.FlowsheetOptions.SelectedUnitSystem; var nf = flowsheet.FlowsheetOptions.NumberFormat; var mslist = flowsheet.SimulationObjects.Values.Where((x) => x.GraphicObject.ObjectType == ObjectType.MaterialStream).Select((x2) => x2.GraphicObject.Tag).ToList(); mslist.Insert(0, ""); this.CreateAndAddDescriptionRow("The Phase Envelope utility calculates various VLE envelopes for mixtures."); var spinner = this.CreateAndAddDropDownRow("Material Stream", mslist, 0, (arg3, arg2) => { }); var spinnerPE = this.CreateAndAddDropDownRow("Envelope Type", Shared.StringArrays.envelopetype().ToList(), 0, null); var button = this.CreateAndAddButtonRow("Build Envelope", null, null); var chart = new Eto.OxyPlot.Plot { Height = 400, BackgroundColor = Colors.White }; this.CreateAndAddControlRow(chart); var txtResults = this.CreateAndAddMultilineMonoSpaceTextBoxRow("", 400, true, null); button.Click += (sender, e) => { if (spinnerPE.SelectedIndex >= 0 && spinner.SelectedIndex > 0) { var ms = (MaterialStream)flowsheet.GetFlowsheetSimulationObject(mslist[spinner.SelectedIndex]); var calc = new DWSIM.Thermodynamics.ShortcutUtilities.Calculation(ms); switch (spinnerPE.SelectedIndex + 1) { case 1: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePT; break; case 2: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePH; break; case 3: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePS; break; case 4: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeTH; break; case 5: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeTS; break; case 6: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeVP; break; case 7: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeVT; break; } DWSIM.Thermodynamics.ShortcutUtilities.CalculationResults results = null; Task.Factory.StartNew(() => { Application.Instance.Invoke(() => txtResults.Text = "Please wait..."); results = calc.Calculate(); }).ContinueWith((t) => { Application.Instance.Invoke(() => { if (results.ExceptionResult == null) { if (results.PlotModels.Count > 0) { chart.Model = (OxyPlot.PlotModel)results.PlotModels[0]; chart.Invalidate(); txtResults.Text = results.TextOutput; } else { chart.Model = null; txtResults.Text = "Invalid result"; } } else { txtResults.Text = results.ExceptionResult.Message; } }); }); } }; }
private void DisplayPage_ML() { var page = new WizardPage(); var checks = new List <CheckBox>(); var tboxes = new List <TextBox>(); page.hasBackButton = true; page.hasCancelButton = true; page.hasNextButton = true; page.hasFinishButton = false; page.cancelAction = () => { page.Close(); }; page.backAction = () => { Application.Instance.Invoke(() => DisplayPage_ModelParameters()); page.Close(); }; page.nextAction = () => { Application.Instance.Invoke(() => DisplayPage_Results()); page.Close(); }; page.Title = "Neural Network Model Wizard"; page.HeaderTitle = "Step 6 - Model Training and Evaluation"; page.HeaderDescription = "Click on the 'Train and Evaluate' Button to Train your Model"; page.FooterText = "Click 'Next' to Continue."; var dl = c.GetDefaultContainer(); dl.Width = Width; TextArea tb = new TextArea { Width = 350, Font = new Font(FontFamilies.Monospace, 10.0f) }; var plot = new Eto.OxyPlot.Plot(); plot.Model = new PlotModel(); plot.Model.Background = OxyPlot.OxyColors.White; plot.Model.TitleFontSize = 12; plot.Model.SubtitleFontSize = 10; plot.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Bottom, FontSize = 10, Title = "Epoch", Key = "x", }); plot.Model.Axes.Add(new OxyPlot.Axes.LinearAxis() { MajorGridlineStyle = OxyPlot.LineStyle.Dash, MinorGridlineStyle = OxyPlot.LineStyle.Dot, Position = OxyPlot.Axes.AxisPosition.Left, FontSize = 10, Title = "MSE" }); plot.Model.LegendFontSize = 11; plot.Model.LegendPlacement = OxyPlot.LegendPlacement.Outside; plot.Model.LegendOrientation = OxyPlot.LegendOrientation.Horizontal; plot.Model.LegendPosition = OxyPlot.LegendPosition.BottomCenter; plot.Model.TitleHorizontalAlignment = OxyPlot.TitleHorizontalAlignment.CenteredWithinView; plot.Model.AddLineSeries(new double[] { }, new double[] { }, OxyColors.Red, "Training"); plot.Model.AddLineSeries(new double[] { }, new double[] { }, OxyColors.Blue, "Testing"); plot.Model.Title = "Model Training Results"; var tl = new TableLayout(new TableRow(tb, plot)) { Spacing = new Size(10, 10), Height = 440 }; dl.CreateAndAddLabelAndButtonRow("Training Results", "Train and Evaluate", null, (btn, e) => { Task.Factory.StartNew(() => { CurrentModel.PrepareData(); CurrentModel.Train(null, tb, plot); }); }); dl.CreateAndAddControlRow(tl); page.Init(Width, Height); page.Topmost = false; var scrollable = new Scrollable { Content = dl, Border = BorderType.None, Size = new Size(Width, Height), ExpandContentHeight = true }; page.ContentContainer.Add(scrollable); page.Show(); }
void Init() { Spacing = new Size(5, 5); DynamicLayout p1; TableLayout p2; p1 = UI.Shared.Common.GetDefaultContainer(); p2 = new TableLayout() { Spacing = new Size(5, 5), Padding = new Padding(15) }; Rows.Add(new TableRow(p1, p2)); p1.Width = 420; var l1 = p1.CreateAndAddLabelRow("Envelope Setup"); var tabcontainer = new TabControl(); Eto.OxyPlot.Plot chart = null; var su = flowsheet.FlowsheetOptions.SelectedUnitSystem; var nf = flowsheet.FlowsheetOptions.NumberFormat; var complist = flowsheet.SelectedCompounds.Values.Select((x2) => x2.Name).ToList(); complist.Insert(0, ""); p1.CreateAndAddDescriptionRow("The Binary Envelope utility calculates Temperature and Pressure VLE/VLLE envelopes for binary mixtures."); var spinnerComp1 = p1.CreateAndAddDropDownRow("Compound 1", complist, 0, null); var spinnerComp2 = p1.CreateAndAddDropDownRow("Compound 2", complist, 0, null); var spinnerPE = p1.CreateAndAddDropDownRow("Envelope Type", Shared.StringArrays.binaryenvelopetype().ToList(), 1, null); var tval = p1.CreateAndAddTextBoxRow(nf, "Temperature (" + su.temperature + ")", cv.ConvertFromSI(su.temperature, 298.15f), null); var pval = p1.CreateAndAddTextBoxRow(nf, "Pressure (" + su.pressure + ")", cv.ConvertFromSI(su.pressure, 101325.0f), null); bool vle = true, lle = false, sle = false, critical = false, areas = false; p1.CreateAndAddLabelRow("Display Options"); p1.CreateAndAddCheckBoxRow("VLE", vle, (arg1a, arg2a) => { vle = arg1a.Checked.GetValueOrDefault(); }); p1.CreateAndAddDescriptionRow("VLE calculation works on all diagram types."); p1.CreateAndAddCheckBoxRow("LLE", lle, (arg1a, arg2a) => { lle = arg1a.Checked.GetValueOrDefault(); }); p1.CreateAndAddDescriptionRow("LLE calculation works on T-x/y and P-x/y diagrams if the selected Property Package is associated with a Flash Algorithm which supports Liquid-Liquid equilibria."); p1.CreateAndAddCheckBoxRow("SLE", sle, (arg1a, arg2a) => { sle = arg1a.Checked.GetValueOrDefault(); }); p1.CreateAndAddDescriptionRow("SLE calculation works on T-x/y diagrams only."); p1.CreateAndAddCheckBoxRow("Critical Line", critical, (arg1a, arg2a) => { critical = arg1a.Checked.GetValueOrDefault(); }); p1.CreateAndAddDescriptionRow("Critical Line calculation works on T-x/y diagrams only."); p1.CreateAndAddCheckBoxRow("Highlight Regions", areas, (arg1a, arg2a) => { areas = arg1a.Checked.GetValueOrDefault(); }); p1.CreateAndAddDescriptionRow("Highlights the different phase regions in the envelope."); var pplist = flowsheet.PropertyPackages.Values.Select((x2) => x2.Tag).ToList(); pplist.Insert(0, ""); var spinnerpp = p1.CreateAndAddDropDownRow("Property Package", pplist, 0, null); var button = p1.CreateAndAddButtonRow("Build Envelope", null, null); chart = new Eto.OxyPlot.Plot { BackgroundColor = Colors.White }; var txtResults = new TextArea() { ReadOnly = true, Font = Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize) }; tabcontainer.Pages.Add(new TabPage(new TableRow(chart)) { Text = "Chart" }); tabcontainer.Pages.Add(new TabPage(new TableRow(txtResults)) { Text = "Data" }); p2.CreateAndAddLabelRow("Results"); p2.CreateAndAddControlRow(tabcontainer); button.Click += (sender, e) => { if (spinnerPE.SelectedIndex >= 0 && spinnerComp1.SelectedIndex > 0 && spinnerComp2.SelectedIndex > 0 && spinnerpp.SelectedIndex > 0) { var comp1 = flowsheet.SelectedCompounds[complist[spinnerComp1.SelectedIndex]]; var comp2 = flowsheet.SelectedCompounds[complist[spinnerComp2.SelectedIndex]]; var ms = new MaterialStream("", ""); ms.SetFlowsheet(flowsheet); ms.PropertyPackage = (PropertyPackage)flowsheet.PropertyPackages.Values.Where(x => x.Tag == spinnerpp.SelectedValue.ToString()).First(); ms.SetFlowsheet(flowsheet); foreach (var phase in ms.Phases.Values) { phase.Compounds.Add(comp1.Name, new DWSIM.Thermodynamics.BaseClasses.Compound(comp1.Name, "")); phase.Compounds[comp1.Name].ConstantProperties = comp1; phase.Compounds.Add(comp2.Name, new DWSIM.Thermodynamics.BaseClasses.Compound(comp2.Name, "")); phase.Compounds[comp2.Name].ConstantProperties = comp2; } double val; if (Double.TryParse(tval.Text, out val)) { ms.Phases[0].Properties.temperature = cv.ConvertToSI(su.temperature, Double.Parse(tval.Text)); } if (Double.TryParse(pval.Text, out val)) { ms.Phases[0].Properties.pressure = cv.ConvertToSI(su.pressure, Double.Parse(pval.Text)); } var calc = new DWSIM.Thermodynamics.ShortcutUtilities.Calculation(ms); calc.DisplayEnvelopeAreas = areas; calc.BinaryEnvelopeOptions = new object[] { "", 0, 0, vle, lle, sle, critical, false }; switch (spinnerPE.SelectedIndex) { case 0: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.BinaryEnvelopePxy; break; case 1: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.BinaryEnvelopeTxy; break; } DWSIM.Thermodynamics.ShortcutUtilities.CalculationResults results = null; var token = new System.Threading.CancellationTokenSource(); var pg = ProgressDialog.ShowWithAbort(this, "Please Wait", "Calculating Envelope Lines...", false, "Abort/Cancel", (s, e1) => { token.Cancel(); }); Task.Factory.StartNew(() => { Application.Instance.Invoke(() => { txtResults.Text = "Please wait..."; }); results = calc.Calculate(); }, token.Token).ContinueWith((t) => { Application.Instance.Invoke(() => { pg.Close(); pg = null; if (results.ExceptionResult == null) { if (results.PlotModels.Count > 0) { chart.Model = (OxyPlot.PlotModel)results.PlotModels[0]; chart.Model.Padding = new OxyPlot.OxyThickness(5, 5, 20, 5); chart.Invalidate(); txtResults.Text = results.TextOutput; } else { chart.Model = null; txtResults.Text = "Invalid result"; } } else { txtResults.Text = results.ExceptionResult.Message; } }); }); } }; }
void Init() { DynamicLayout p1, p2; StackLayout t1; p1 = UI.Shared.Common.GetDefaultContainer(); p2 = UI.Shared.Common.GetDefaultContainer(); p1.Width = 380; p2.Width = 380; t1 = new StackLayout(); t1.Items.Add(new StackLayoutItem(p1)); t1.Items.Add(new StackLayoutItem(p2)); t1.Orientation = Orientation.Horizontal; Padding = new Padding(10); if (flowsheet.SensAnalysisCollection.Count == 0) { flowsheet.SensAnalysisCollection.Add(new DWSIM.SharedClasses.Flowsheet.Optimization.SensitivityAnalysisCase()); } mycase = flowsheet.SensAnalysisCollection.First(); var su = flowsheet.FlowsheetOptions.SelectedUnitSystem; var nf = flowsheet.FlowsheetOptions.NumberFormat; s.CreateAndAddLabelRow2(this, "Use the Sensitivity Analysis tool to study/analyze the influence of a process variable on other variables in the flowsheet."); this.Add(t1); s.CreateAndAddLabelRow(p1, "Case ID"); s.CreateAndAddFullTextBoxRow(p1, mycase.name, (arg3, arg2) => { mycase.name = arg3.Text; }); s.CreateAndAddLabelRow(p1, "Case Description"); s.CreateAndAddFullTextBoxRow(p1, mycase.description, (arg3, arg2) => { mycase.description = arg3.Text; }); s.CreateAndAddLabelRow(p1, "Independent Variable"); var objlist = flowsheet.SimulationObjects.Values.Select((x2) => x2.GraphicObject.Tag).ToList(); objlist.Insert(0, ""); var spinner = s.CreateAndAddDropDownRow(p1, "Object", objlist, 0, null); var spinner2 = s.CreateAndAddDropDownRow(p1, "Property", new List <string>(), 0, null); List <string> proplist = new List <string>(); spinner.SelectedIndexChanged += (sender, e) => { if (spinner.SelectedIndex > 0) { mycase.iv1.objectID = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).Name; mycase.iv1.objectTAG = objlist[spinner.SelectedIndex]; proplist = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).GetProperties(PropertyType.WR).ToList(); proplist.Insert(0, ""); spinner2.Items.Clear(); spinner2.Items.AddRange(proplist.Select(x => new ListItem { Key = x, Text = flowsheet.GetTranslatedString(x) }).ToList()); spinner2.SelectedIndex = (proplist.IndexOf(mycase.iv1.propID)); } else { spinner2.Items.Clear(); } }; if (flowsheet.SimulationObjects.ContainsKey(mycase.iv1.objectID)) { spinner.SelectedIndex = (objlist.IndexOf(flowsheet.SimulationObjects[mycase.iv1.objectID].GraphicObject.Tag)); } var txtLowerLimit = s.CreateAndAddTextBoxRow(p1, nf, "Initial Value", 0, null); var txtUpperLimit = s.CreateAndAddTextBoxRow(p1, nf, "Final Value", 0, null); var txtSteps = s.CreateAndAddTextBoxRow(p1, "0", "Number of Steps", 0, null); txtLowerLimit.Text = mycase.iv1.lowerlimit.GetValueOrDefault().ToString(nf); txtUpperLimit.Text = mycase.iv1.upperlimit.GetValueOrDefault().ToString(nf); txtSteps.Text = mycase.iv1.points.ToString(); var labelUnits = s.CreateAndAddTwoLabelsRow(p1, "Property Units", ""); spinner2.SelectedIndexChanged += (sender, e) => { if (spinner2.SelectedIndex > 0) { mycase.iv1.propID = proplist[spinner2.SelectedIndex]; mycase.iv1.unit = flowsheet.GetFlowsheetSimulationObject(objlist[spinner.SelectedIndex]).GetPropertyUnit(proplist[spinner2.SelectedIndex], su); labelUnits.Text = mycase.iv1.unit; } }; double dummy = 0.0f; txtLowerLimit.TextChanged += (sender2, e2) => { if (double.TryParse(txtLowerLimit.Text.ToString(), out dummy)) { mycase.iv1.lowerlimit = Double.Parse(txtLowerLimit.Text); } }; txtUpperLimit.TextChanged += (sender2, e2) => { if (double.TryParse(txtUpperLimit.Text.ToString(), out dummy)) { mycase.iv1.upperlimit = Double.Parse(txtUpperLimit.Text); } }; txtSteps.TextChanged += (sender2, e2) => { if (double.TryParse(txtSteps.Text.ToString(), out dummy)) { mycase.iv1.points = Int32.Parse(txtSteps.Text); } }; s.CreateAndAddEmptySpace(p1); s.CreateAndAddEmptySpace(p1); s.CreateAndAddEmptySpace(p1); s.CreateAndAddEmptySpace(p1); s.CreateAndAddEmptySpace(p1); s.CreateAndAddEmptySpace(p1); var btnAddDepVar = s.CreateAndAddBoldLabelAndButtonRow(p2, "Dependent Variables", "Add New", null, null); var ll = new StackLayout { Orientation = Orientation.Vertical, Padding = new Eto.Drawing.Padding(2), Spacing = 10 }; ll.RemoveAll(); var sc = new Scrollable { Border = BorderType.None, Content = ll }; s.CreateAndAddControlRow(p2, sc); t1.SizeChanged += (sender, e) => { if (p1.ParentWindow != null) { p1.Width = (int)(p1.ParentWindow.Width / 2 - 10); p2.Width = (int)(p2.ParentWindow.Width / 2 - 10); p1.Height = p1.ParentWindow.Height - 170; p2.Height = p1.Height; sc.Height = p2.Height - btnAddDepVar.Height - 30; foreach (var item in ll.Items) { item.Control.Width = sc.Width - 25; } } }; foreach (var dvar in mycase.depvariables.Values) { AddDepVar(ll, dvar, objlist); } btnAddDepVar.Click += (sender2, e2) => { var depvar = new DWSIM.SharedClasses.Flowsheet.Optimization.SAVariable(); depvar.id = Guid.NewGuid().ToString(); mycase.depvariables.Add(depvar.id, depvar); AddDepVar(ll, depvar, objlist); }; var btnRun = s.CreateAndAddButtonRow(this, "Run Analysis", null, null); var btnAbort = s.CreateAndAddButtonRow(this, "Abort Run", null, null); btnAbort.Enabled = false; resulttextbox = new TextArea { Height = 400, Text = "", Font = Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize), ReadOnly = true }; s.CreateAndAddLabelRow(this, "Results"); var btnrt = s.CreateAndAddLabelAndButtonRow(this, "View Results Report", "View Report", null, (sender, e) => { var form = s.GetDefaultEditorForm("Sensitivity Analysis Report", 500, 500, resulttextbox, true); form.Show(); }); btnrt.Enabled = false; resultschart = new Eto.OxyPlot.Plot { Height = 400 }; var btnrc = s.CreateAndAddLabelAndButtonRow(this, "View Results Chart", "View Chart", null, (sender, e) => { var form = s.GetDefaultEditorForm("Sensitivity Analysis Result", 500, 500, resultschart, true); form.Show(); }); btnrc.Enabled = false; btnRun.Click += (sender2, e2) => { int iv1np, i; double iv1ll, iv1ul, iv1val, iv1val0; string iv1id, iv1prop; List <List <double> > results = new List <List <double> >(); iv1ll = Converter.ConvertToSI(mycase.iv1.unit, mycase.iv1.lowerlimit.GetValueOrDefault()); iv1ul = Converter.ConvertToSI(mycase.iv1.unit, mycase.iv1.upperlimit.GetValueOrDefault()); iv1np = mycase.iv1.points - 1; iv1id = mycase.iv1.objectID; iv1prop = mycase.iv1.propID; flowsheet.SupressMessages = true; Application.Instance.Invoke(() => { btnAbort.Enabled = true; btnrt.Enabled = false; btnrc.Enabled = false; flowsheet.ShowMessage("Starting Sensitivity Analysis, please wait...", IFlowsheet.MessageType.Information); }); var task = new Task(() => { flowsheet.SolveFlowsheet(true); iv1val0 = Convert.ToDouble(flowsheet.SimulationObjects[iv1id].GetPropertyValue(iv1prop)); for (i = 0; i <= iv1np; i++) { iv1val = iv1ll + i * (iv1ul - iv1ll) / iv1np; flowsheet.SimulationObjects[iv1id].SetPropertyValue(iv1prop, iv1val); flowsheet.SolveFlowsheet(true); List <double> depvarvals = new List <double>(); foreach (var depvar in mycase.depvariables.Values) { depvar.currentvalue = Convert.ToDouble(flowsheet.SimulationObjects[depvar.objectID].GetPropertyValue(depvar.propID)); depvarvals.Add(depvar.currentvalue); } results.Add(depvarvals); } mycase.results = new System.Collections.ArrayList(); foreach (var res in results) { mycase.results.Add(res.ToArray()); } flowsheet.SimulationObjects[iv1id].SetPropertyValue(iv1prop, iv1val0); flowsheet.SolveFlowsheet(true); }, GlobalSettings.Settings.TaskCancellationTokenSource.Token); task.ContinueWith((t) => { flowsheet.SupressMessages = false; if (t.Exception != null) { Application.Instance.Invoke(() => { btnAbort.Enabled = false; btnrt.Enabled = false; btnrc.Enabled = false; flowsheet.ShowMessage("Error: " + t.Exception.Message, IFlowsheet.MessageType.GeneralError); }); } else { Application.Instance.Invoke(() => { btnAbort.Enabled = false; btnrt.Enabled = true; btnrc.Enabled = true; flowsheet.ShowMessage("Sensitivity Analysis finished successfully.", IFlowsheet.MessageType.Information); if (t.Status == TaskStatus.RanToCompletion) { var str = new System.Text.StringBuilder(); str.AppendLine("Sensitivity Analysis Run Results"); str.AppendLine(); str.AppendLine("Independent Variable: " + flowsheet.SimulationObjects[iv1id].GraphicObject.Tag + " / " + flowsheet.GetTranslatedString(mycase.iv1.propID)); str.AppendLine(); str.AppendLine("Range: " + mycase.iv1.lowerlimit.GetValueOrDefault() + " to " + mycase.iv1.upperlimit.GetValueOrDefault() + " " + mycase.iv1.unit + ", " + mycase.iv1.points + " steps"); str.AppendLine(); str.AppendLine("Dependent Variables:"); int count = 1; str.AppendLine(); foreach (var dvar in mycase.depvariables.Values) { str.AppendLine(count + " - " + flowsheet.SimulationObjects[dvar.objectID].GraphicObject.Tag + " / " + flowsheet.GetTranslatedString(dvar.propID) + " (" + dvar.unit + ")"); count += 1; } str.AppendLine(); str.AppendLine("Ind var\t\tDep. vars"); int cnt = 0; List <double> px = new List <double>(); List <List <double> > py = new List <List <double> >(); foreach (var dvar in mycase.depvariables.Values) { py.Add(new List <double>()); } foreach (double[] res in mycase.results) { var dv = Converter.ConvertFromSI(mycase.iv1.unit, iv1ll + cnt * (iv1ul - iv1ll) / iv1np); px.Add(dv); string line = dv.ToString(nf) + "\t\t"; int j = 0; foreach (var d in res) { py[j].Add(Converter.ConvertFromSI(mycase.depvariables.Values.ElementAt(j).unit, d)); line += Converter.ConvertFromSI(mycase.depvariables.Values.ElementAt(j).unit, d).ToString(nf) + "\t\t"; j += 1; } str.AppendLine(line); cnt += 1; } Application.Instance.Invoke(() => resulttextbox.Text = str.ToString()); var model = new PlotModel() { Subtitle = "Sensitivity Analysis Run Results", Title = flowsheet.FlowsheetOptions.SimulationName }; model.TitleFontSize = 14; model.SubtitleFontSize = 11; model.Axes.Add(new LinearAxis() { MajorGridlineStyle = LineStyle.Dash, MinorGridlineStyle = LineStyle.Dot, Position = AxisPosition.Bottom, FontSize = 12, Title = mycase.iv1.objectTAG + " / " + flowsheet.GetTranslatedString(mycase.iv1.propID) + " (" + mycase.iv1.unit + ")" }); int cnt2 = 0; foreach (var dvar in mycase.depvariables.Values) { model.Axes.Add(new LinearAxis() { MajorGridlineStyle = LineStyle.Dash, MinorGridlineStyle = LineStyle.Dot, FontSize = 12, Title = dvar.objectTAG + " / " + flowsheet.GetTranslatedString(dvar.propID) + " (" + dvar.unit + ")" }); model.Axes[cnt2 + 1].Key = cnt2.ToString(); model.Axes[cnt2 + 1].PositionTier = cnt2; model.Axes[cnt2 + 1].AxislineStyle = LineStyle.Solid; model.AddLineSeries(px, py[cnt2]); model.Series[cnt2].Title = dvar.objectTAG + " / " + flowsheet.GetTranslatedString(dvar.propID); ((OxyPlot.Series.LineSeries)(model.Series[cnt2])).YAxisKey = cnt2.ToString(); cnt2 += 1; } model.LegendFontSize = 11; model.LegendPlacement = LegendPlacement.Outside; model.LegendOrientation = LegendOrientation.Vertical; model.LegendPosition = LegendPosition.BottomCenter; model.TitleHorizontalAlignment = TitleHorizontalAlignment.CenteredWithinView; Application.Instance.Invoke(() => { resultschart.Model = model; resultschart.Invalidate(); }); } }); } }); btnAbort.Click += (sender, e) => { GlobalSettings.Settings.TaskCancellationTokenSource.Cancel(); }; task.Start(); }; }
void Init() { Spacing = new Size(5, 5); DynamicLayout p1; TableLayout p2; p1 = UI.Shared.Common.GetDefaultContainer(); p2 = new TableLayout() { Spacing = new Size(5, 5), Padding = new Padding(15) }; Rows.Add(new TableRow(p1, p2)); p1.Width = 420; var su = flowsheet.FlowsheetOptions.SelectedUnitSystem; var nf = flowsheet.FlowsheetOptions.NumberFormat; var mslist = flowsheet.SimulationObjects.Values.Where((x) => x.GraphicObject.ObjectType == ObjectType.MaterialStream).Select((x2) => x2.GraphicObject.Tag).ToList(); mslist.Insert(0, ""); p1.CreateAndAddLabelRow("Setup"); p1.CreateAndAddDescriptionRow("The Phase Envelope utility calculates various VLE envelopes for mixtures."); var spinner = p1.CreateAndAddDropDownRow("Material Stream", mslist, 0, (arg3, arg2) => { }); var spinnerPE = p1.CreateAndAddDropDownRow("Envelope Type", Shared.StringArrays.envelopetype().ToList(), 0, null); var EnvelopeOptions = new PhaseEnvelopeOptions(); var ft = new List <string>() { "PVF", "TVF" }; var tabcontainer0 = new TabControl() { }; var c1 = UI.Shared.Common.GetDefaultContainer(); var c3 = UI.Shared.Common.GetDefaultContainer(); var c2 = UI.Shared.Common.GetDefaultContainer(); c1.CreateAndAddCheckBoxRow("Quality Line", EnvelopeOptions.QualityLine, (arg3, arg1) => { EnvelopeOptions.QualityLine = arg3.Checked.GetValueOrDefault(); }); c1.CreateAndAddDescriptionRow("Includes a Quality Line in the chart (TP only)."); c1.CreateAndAddTextBoxRow("G6", "Quality Value", EnvelopeOptions.QualityValue, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.QualityValue = arg3.Text.ToDoubleFromCurrent(); } }); c1.CreateAndAddDescriptionRow("Vapor Phase Mole Fraction for Quality Line, between 0.0 and 1.0."); c1.CreateAndAddCheckBoxRow("Stability Curve", EnvelopeOptions.StabilityCurve, (arg3, arg1) => { EnvelopeOptions.StabilityCurve = arg3.Checked.GetValueOrDefault(); }); c1.CreateAndAddDescriptionRow("Includes the Stability Curve in the chart (TP only). Works with PR and SRK Property Packages."); c1.CreateAndAddCheckBoxRow("Phase Identification Curve", EnvelopeOptions.PhaseIdentificationCurve, (arg3, arg1) => { EnvelopeOptions.PhaseIdentificationCurve = arg3.Checked.GetValueOrDefault(); }); c1.CreateAndAddDescriptionRow("Calculates the PI curve (TP only), where the region above the curve is for a liquid-like phase and the region beyond the curve is for a vapor-like phase. Calculated using the PR EOS."); c1.CreateAndAddCheckBoxRow("Operation Point", EnvelopeOptions.OperatingPoint, (arg3, arg1) => { EnvelopeOptions.OperatingPoint = arg3.Checked.GetValueOrDefault(); }); c1.CreateAndAddDescriptionRow("Includes the operating point in the chart."); c2.CreateAndAddCheckBoxRow("Custom Initialization", EnvelopeOptions.BubbleUseCustomParameters, (arg3, arg1) => { EnvelopeOptions.BubbleUseCustomParameters = arg3.Checked.GetValueOrDefault(); }); c2.CreateAndAddDescriptionRow("Use the custom initialization options if the generated curve for bubble points has invalid points."); c2.CreateAndAddDropDownRow("Initial Flash", ft, 0, (arg3, arg1) => { EnvelopeOptions.BubbleCurveInitialFlash = ft[arg3.SelectedIndex]; }); c2.CreateAndAddTextBoxRow("G6", "Initial Pressure (" + su.pressure + ")", EnvelopeOptions.BubbleCurveInitialPressure, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveInitialPressure = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c2.CreateAndAddTextBoxRow("G6", "Initial Temperature (" + su.temperature + ")", EnvelopeOptions.BubbleCurveInitialTemperature, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveInitialTemperature = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c2.CreateAndAddTextBoxRow("G6", "Maximum Temperature (" + su.temperature + ")", EnvelopeOptions.BubbleCurveMaximumTemperature, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveMaximumTemperature = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c2.CreateAndAddTextBoxRow("G6", "Pressure Step (" + su.deltaP + ")", EnvelopeOptions.BubbleCurveDeltaP, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveDeltaP = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.deltaP); } }); c2.CreateAndAddTextBoxRow("G6", "Temperature Step (" + su.deltaT + ")", EnvelopeOptions.BubbleCurveDeltaT, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveDeltaT = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.deltaT); } }); c2.CreateAndAddTextBoxRow("N0", "Maximum Points", EnvelopeOptions.BubbleCurveMaximumPoints, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.BubbleCurveMaximumPoints = int.Parse(arg3.Text); } }); c3.CreateAndAddCheckBoxRow("Custom Initialization", EnvelopeOptions.DewUseCustomParameters, (arg3, arg1) => { EnvelopeOptions.DewUseCustomParameters = arg3.Checked.GetValueOrDefault(); }); c3.CreateAndAddDescriptionRow("Use the custom initialization options if the generated curve for dew points has invalid points."); c3.CreateAndAddDropDownRow("Initial Flash", ft, 0, (arg3, arg1) => { EnvelopeOptions.DewCurveInitialFlash = ft[arg3.SelectedIndex]; }); c3.CreateAndAddTextBoxRow("G6", "Initial Pressure (" + su.pressure + ")", EnvelopeOptions.DewCurveInitialPressure, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveInitialPressure = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c3.CreateAndAddTextBoxRow("G6", "Initial Temperature (" + su.temperature + ")", EnvelopeOptions.DewCurveInitialTemperature, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveInitialTemperature = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c3.CreateAndAddTextBoxRow("G6", "Maximum Temperature (" + su.temperature + ")", EnvelopeOptions.DewCurveMaximumTemperature, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveMaximumTemperature = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.pressure); } }); c3.CreateAndAddTextBoxRow("G6", "Pressure Step (" + su.deltaP + ")", EnvelopeOptions.DewCurveDeltaP, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveDeltaP = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.deltaP); } }); c3.CreateAndAddTextBoxRow("G6", "Temperature Step (" + su.deltaT + ")", EnvelopeOptions.DewCurveDeltaT, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveDeltaT = arg3.Text.ToDoubleFromCurrent().ConvertToSI(su.deltaT); } }); c3.CreateAndAddTextBoxRow("N0", "Maximum Points", EnvelopeOptions.DewCurveMaximumPoints, (arg3, arg1) => { if (arg3.Text.IsValidDouble()) { EnvelopeOptions.DewCurveMaximumPoints = int.Parse(arg3.Text); } }); tabcontainer0.Pages.Add(new TabPage(new TableRow(c1)) { Text = "Envelope Options" }); tabcontainer0.Pages.Add(new TabPage(new TableRow(c2)) { Text = "BP Initialization" }); tabcontainer0.Pages.Add(new TabPage(new TableRow(c3)) { Text = "DP Initialization" }); p1.CreateAndAddControlRow(tabcontainer0); var button = p1.CreateAndAddButtonRow("Build Envelope", null, null); p1.CreateAndAddEmptySpace(); p1.CreateAndAddEmptySpace(); var tabcontainer = new TabControl() { Height = 400 }; var chart = new Eto.OxyPlot.Plot { BackgroundColor = Colors.White }; var txtResults = new TextArea() { ReadOnly = true, Font = Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize) }; tabcontainer.Pages.Add(new TabPage(new TableRow(chart)) { Text = "Chart" }); tabcontainer.Pages.Add(new TabPage(new TableRow(txtResults)) { Text = "Data" }); p2.CreateAndAddLabelRow("Results"); p2.CreateAndAddControlRow(tabcontainer); button.Click += (sender, e) => { if (spinnerPE.SelectedIndex >= 0 && spinner.SelectedIndex > 0) { var ms = (MaterialStream)flowsheet.GetFlowsheetSimulationObject(mslist[spinner.SelectedIndex]); var calc = new DWSIM.Thermodynamics.ShortcutUtilities.Calculation(ms); switch (spinnerPE.SelectedIndex + 1) { case 1: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePT; break; case 2: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePH; break; case 3: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopePS; break; case 4: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeTH; break; case 5: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeTS; break; case 6: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeVP; break; case 7: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.PhaseEnvelopeVT; break; } calc.PhaseEnvelopeOptions = EnvelopeOptions; DWSIM.Thermodynamics.ShortcutUtilities.CalculationResults results = null; var token = new System.Threading.CancellationTokenSource(); var pg = ProgressDialog.ShowWithAbort(this, "Please Wait", "Calculating Envelope Lines...", false, "Abort/Cancel", (s, e1) => { token.Cancel(); }); Task.Factory.StartNew(() => { Application.Instance.Invoke(() => txtResults.Text = "Please wait..."); results = calc.Calculate(); }, token.Token).ContinueWith((t) => { Application.Instance.Invoke(() => { pg.Close(); pg = null; if (results.ExceptionResult == null) { if (results.PlotModels.Count > 0) { chart.Model = (OxyPlot.PlotModel)results.PlotModels[0]; chart.Model.Padding = new OxyPlot.OxyThickness(5, 5, 20, 5); chart.Invalidate(); txtResults.Text = results.TextOutput; } else { chart.Model = null; txtResults.Text = "Invalid result"; } } else { txtResults.Text = results.ExceptionResult.Message; } }); }); } }; }
void Init() { Padding = new Padding(10); var su = flowsheet.FlowsheetOptions.SelectedUnitSystem; var nf = flowsheet.FlowsheetOptions.NumberFormat; var complist = flowsheet.SelectedCompounds.Values.Select((x2) => x2.Name).ToList(); complist.Insert(0, ""); this.CreateAndAddLabelRow("Setup"); this.CreateAndAddDescriptionRow("The Binary Envelope utility calculates Temperature and Pressure VLE/VLLE envelopes for binary mixtures."); var spinnerComp1 = this.CreateAndAddDropDownRow("Compound 1", complist, 0, null); var spinnerComp2 = this.CreateAndAddDropDownRow("Compound 2", complist, 0, null); var spinnerPE = this.CreateAndAddDropDownRow("Envelope Type", Shared.StringArrays.binaryenvelopetype().ToList(), 0, null); var tval = this.CreateAndAddTextBoxRow(nf, "Temperature (" + su.temperature + ")", cv.ConvertFromSI(su.temperature, 298.15f), null); var pval = this.CreateAndAddTextBoxRow(nf, "Pressure (" + su.pressure + ")", cv.ConvertFromSI(su.pressure, 101325.0f), null); var pplist = flowsheet.PropertyPackages.Values.Select((x2) => x2.Tag).ToList(); pplist.Insert(0, ""); var spinnerpp = this.CreateAndAddDropDownRow("Property Package", pplist, 0, null); var button = this.CreateAndAddButtonRow("Build Envelope", null, null); var tabcontainer = new TabControl() { Height = 400 }; var chart = new Eto.OxyPlot.Plot { BackgroundColor = Colors.White }; var txtResults = new TextArea() { ReadOnly = true, Font = Fonts.Monospace(GlobalSettings.Settings.ResultsReportFontSize) }; tabcontainer.Pages.Add(new TabPage(new TableRow(txtResults)) { Text = "Data" }); tabcontainer.Pages.Add(new TabPage(new TableRow(chart)) { Text = "Chart" }); this.CreateAndAddLabelRow("Results"); this.CreateAndAddControlRow(tabcontainer); button.Click += (sender, e) => { if (spinnerPE.SelectedIndex >= 0 && spinnerComp1.SelectedIndex > 0 && spinnerComp2.SelectedIndex > 0 && spinnerpp.SelectedIndex > 0) { var comp1 = flowsheet.SelectedCompounds[complist[spinnerComp1.SelectedIndex]]; var comp2 = flowsheet.SelectedCompounds[complist[spinnerComp2.SelectedIndex]]; var ms = new MaterialStream("", ""); ms.SetFlowsheet(flowsheet); ms.PropertyPackage = (PropertyPackage)flowsheet.PropertyPackages.Values.Where(x => x.Tag == spinnerpp.SelectedValue.ToString()).First(); ms.SetFlowsheet(flowsheet); foreach (var phase in ms.Phases.Values) { phase.Compounds.Add(comp1.Name, new DWSIM.Thermodynamics.BaseClasses.Compound(comp1.Name, "")); phase.Compounds[comp1.Name].ConstantProperties = comp1; phase.Compounds.Add(comp2.Name, new DWSIM.Thermodynamics.BaseClasses.Compound(comp2.Name, "")); phase.Compounds[comp2.Name].ConstantProperties = comp2; } double val; if (Double.TryParse(tval.Text, out val)) { ms.Phases[0].Properties.temperature = cv.ConvertToSI(su.temperature, Double.Parse(tval.Text)); } if (Double.TryParse(pval.Text, out val)) { ms.Phases[0].Properties.pressure = cv.ConvertToSI(su.pressure, Double.Parse(pval.Text)); } var calc = new DWSIM.Thermodynamics.ShortcutUtilities.Calculation(ms); switch (spinnerPE.SelectedIndex) { case 0: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.BinaryEnvelopePxy; break; case 1: calc.CalcType = Thermodynamics.ShortcutUtilities.CalculationType.BinaryEnvelopeTxy; break; } DWSIM.Thermodynamics.ShortcutUtilities.CalculationResults results = null; Task.Factory.StartNew(() => { Application.Instance.Invoke(() => txtResults.Text = "Please wait..."); results = calc.Calculate(); }).ContinueWith((t) => { Application.Instance.Invoke(() => { if (results.ExceptionResult == null) { if (results.PlotModels.Count > 0) { chart.Model = (OxyPlot.PlotModel)results.PlotModels[0]; chart.Invalidate(); txtResults.Text = results.TextOutput; } else { chart.Model = null; txtResults.Text = "Invalid result"; } } else { txtResults.Text = results.ExceptionResult.Message; } }); }); } }; }
public void Train(IFlowsheet flowsheet, TextArea ta = null, Eto.OxyPlot.Plot plot = null) { var nl = Environment.NewLine; var g = tf.Graph(); g.as_default(); if (session != null) { session.Dispose(); session = null; } session = tf.Session(graph: g); tf_with(tf.variable_scope("Train"), delegate { if (flowsheet != null) { flowsheet.ShowMessage("Training Started...", IFlowsheet.MessageType.Information); } else { Application.Instance.Invoke(() => { ta.Append("Training Started..." + nl, true); }); } // tf Graph Input var X = tf.placeholder(tf.float32, shape: (-1, n_x), name: "X"); var Y = tf.placeholder(tf.float32, shape: (-1, n_y), name: "Y"); Tensor outlayer = null; var sigma = 1.0f; var weight_initializer = tf.variance_scaling_initializer(mode: "FAN_AVG", uniform: true, factor: sigma); var bias_initializer = tf.zeros_initializer; var n_neurons_1 = Parameters.NumberOfNeuronsOnFirstLayer; var n_neurons_2 = n_neurons_1 / 2; var n_neurons_3 = n_neurons_2 / 2; var n_neurons_4 = n_neurons_3 / 2; RefVariable W_hidden_1, W_hidden_2, W_hidden_3, W_hidden_4, W_out; RefVariable bias_hidden_1, bias_hidden_2, bias_hidden_3, bias_hidden_4, bias_out; Tensor hidden_1, hidden_2, hidden_3, hidden_4; switch (Parameters.NumberOfLayers) { case 2: // Hidden weights W_hidden_1 = tf.Variable(weight_initializer.call(new int[] { n_x, n_neurons_1 }, dtype: TF_DataType.TF_FLOAT), name: "W1"); bias_hidden_1 = tf.Variable(bias_initializer.call(n_neurons_1, dtype: TF_DataType.TF_FLOAT), name: "b1"); W_hidden_2 = tf.Variable(weight_initializer.call(new int[] { n_neurons_1, n_neurons_2 }, dtype: TF_DataType.TF_FLOAT), name: "W2"); bias_hidden_2 = tf.Variable(bias_initializer.call(n_neurons_2, dtype: TF_DataType.TF_FLOAT), name: "b2"); // Output weights W_out = tf.Variable(weight_initializer.call(new int[] { n_neurons_2, n_y }, dtype: TF_DataType.TF_FLOAT), name: "Wout"); bias_out = tf.Variable(bias_initializer.call(n_y, dtype: TF_DataType.TF_FLOAT), name: "bout"); // Hidden layer hidden_1 = tf.nn.relu(tf.add(tf.matmul(X, W_hidden_1), bias_hidden_1), name: "h1"); hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, W_hidden_2), bias_hidden_2), name: "h2"); // Output layer outlayer = tf.add(tf.matmul(hidden_2, W_out), bias_out, name: "out"); break; case 3: // Hidden weights W_hidden_1 = tf.Variable(weight_initializer.call(new int[] { n_x, n_neurons_1 }, dtype: TF_DataType.TF_FLOAT), name: "W1"); bias_hidden_1 = tf.Variable(bias_initializer.call(n_neurons_1, dtype: TF_DataType.TF_FLOAT), name: "b1"); W_hidden_2 = tf.Variable(weight_initializer.call(new int[] { n_neurons_1, n_neurons_2 }, dtype: TF_DataType.TF_FLOAT), name: "W2"); bias_hidden_2 = tf.Variable(bias_initializer.call(n_neurons_2, dtype: TF_DataType.TF_FLOAT), name: "b2"); W_hidden_3 = tf.Variable(weight_initializer.call(new int[] { n_neurons_2, n_neurons_3 }, dtype: TF_DataType.TF_FLOAT), name: "W3"); bias_hidden_3 = tf.Variable(bias_initializer.call(n_neurons_3, dtype: TF_DataType.TF_FLOAT), name: "b3"); // Output weights W_out = tf.Variable(weight_initializer.call(new int[] { n_neurons_3, n_y }, dtype: TF_DataType.TF_FLOAT), name: "Wout"); bias_out = tf.Variable(bias_initializer.call(n_y, dtype: TF_DataType.TF_FLOAT), name: "bout"); // Hidden layer hidden_1 = tf.nn.relu(tf.add(tf.matmul(X, W_hidden_1), bias_hidden_1), name: "h1"); hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, W_hidden_2), bias_hidden_2), name: "h2"); hidden_3 = tf.nn.relu(tf.add(tf.matmul(hidden_2, W_hidden_3), bias_hidden_3), name: "h3"); // Output layer outlayer = tf.add(tf.matmul(hidden_3, W_out), bias_out, name: "out"); break; case 4: // Hidden weights W_hidden_1 = tf.Variable(weight_initializer.call(new int[] { n_x, n_neurons_1 }, dtype: TF_DataType.TF_FLOAT), name: "W1"); bias_hidden_1 = tf.Variable(bias_initializer.call(n_neurons_1, dtype: TF_DataType.TF_FLOAT), name: "b1"); W_hidden_2 = tf.Variable(weight_initializer.call(new int[] { n_neurons_1, n_neurons_2 }, dtype: TF_DataType.TF_FLOAT), name: "W2"); bias_hidden_2 = tf.Variable(bias_initializer.call(n_neurons_2, dtype: TF_DataType.TF_FLOAT), name: "b2"); W_hidden_3 = tf.Variable(weight_initializer.call(new int[] { n_neurons_2, n_neurons_3 }, dtype: TF_DataType.TF_FLOAT), name: "W3"); bias_hidden_3 = tf.Variable(bias_initializer.call(n_neurons_3, dtype: TF_DataType.TF_FLOAT), name: "b3"); W_hidden_4 = tf.Variable(weight_initializer.call(new int[] { n_neurons_3, n_neurons_4 }, dtype: TF_DataType.TF_FLOAT), name: "W4"); bias_hidden_4 = tf.Variable(bias_initializer.call(n_neurons_4, dtype: TF_DataType.TF_FLOAT), name: "b4"); // Output weights W_out = tf.Variable(weight_initializer.call(new int[] { n_neurons_4, n_y }, dtype: TF_DataType.TF_FLOAT), name: "Wout"); bias_out = tf.Variable(bias_initializer.call(n_y, dtype: TF_DataType.TF_FLOAT), name: "bout"); // Hidden layer hidden_1 = tf.nn.relu(tf.add(tf.matmul(X, W_hidden_1), bias_hidden_1), name: "h1"); hidden_2 = tf.nn.relu(tf.add(tf.matmul(hidden_1, W_hidden_2), bias_hidden_2), name: "h2"); hidden_3 = tf.nn.relu(tf.add(tf.matmul(hidden_2, W_hidden_3), bias_hidden_3), name: "h3"); hidden_4 = tf.nn.relu(tf.add(tf.matmul(hidden_3, W_hidden_4), bias_hidden_4), name: "h4"); // Output layer outlayer = tf.add(tf.matmul(hidden_4, W_out), bias_out, name: "out"); break; } // Mean squared error var mse = tf.reduce_sum(tf.pow(outlayer - Y, 2.0f), name: "mse"); var learn_rate = tf.constant(Parameters.LearningRate); var opt = tf.train.AdamOptimizer(learn_rate).minimize(mse); // Fit neural net var batch_size = Parameters.BatchSize; var mse_train = new List <float>(); var mse_test = new List <float>(); // Initialize the variables (i.e. assign their default value) var init = tf.global_variables_initializer(); // Run the initializer session.run(init); // Start training var epochs = Parameters.NumberOfEpochs; foreach (var e in range(epochs)) { // Shuffle training data var shuffle_indices = np.random.permutation(np.arange(len(x_train))); var shuffled_x = new NDArray(np.float32, x_train.shape); var shuffled_y = new NDArray(np.float32, y_train.shape); int i0 = 0; foreach (var idx0 in shuffle_indices) { shuffled_x[i0] = x_train[idx0]; shuffled_y[i0] = y_train[idx0]; i0 += 1; } // Minibatch training foreach (var i in range(0, len(y_train) / batch_size)) { var start = i * batch_size; var batch_x = shuffled_x[start.ToString() + ":" + (start + batch_size).ToString(), Slice.All]; var batch_y = shuffled_y[start.ToString() + ":" + (start + batch_size).ToString(), Slice.All]; // Run optimizer with batch session.run(opt, (X, batch_x), (Y, batch_y)); // Show progress var divrem = 0; Math.DivRem(e, 5, out divrem); if (divrem == 0) { // MSE train and test mse_train.Add(session.run(mse, (X, x_train), (Y, y_train))); mse_test.Add(session.run(mse, (X, x_test), (Y, y_test))); if (flowsheet != null) { flowsheet.ShowMessage("Epoch: " + e.ToString(), IFlowsheet.MessageType.Information); flowsheet.ShowMessage("MSE (training): " + mse_train.Last().ToString(), IFlowsheet.MessageType.Information); flowsheet.ShowMessage("MSE (testing): " + mse_test.Last().ToString(), IFlowsheet.MessageType.Information); } else { Application.Instance.Invoke(() => { ta.Append("Epoch: " + e.ToString() + nl, true); ta.Append("MSE (training): " + mse_train.Last().ToString() + nl, true); ta.Append("MSE (testing): " + mse_test.Last().ToString() + nl, true); (plot.Model.Series[0] as OxyPlot.Series.LineSeries).Points.Add(new DataPoint(e, mse_train.Last())); (plot.Model.Series[1] as OxyPlot.Series.LineSeries).Points.Add(new DataPoint(e, mse_test.Last())); plot.Model.InvalidatePlot(true); }); } if (e > 10 && (Math.Abs(mse_train.Last() - mse_train[mse_train.Count - 2]) / mse_train[mse_train.Count - 2] < Parameters.RelativeMSETolerance)) { break; } } } } if (flowsheet != null) { flowsheet.ShowMessage("Training Finished!", IFlowsheet.MessageType.Information); } else { Application.Instance.Invoke(() => { ta.Append("Training Finished!" + nl, true); }); } x_test_unscaled = new NDArray(np.float32, x_test.shape); x_train_unscaled = new NDArray(np.float32, x_train.shape); for (var i = 0; i < x_test.shape[0]; i++) { for (var j = 0; j < x_test.shape[1]; j++) { x_test_unscaled[i][j] = Classes.Utils.UnScale(x_test[i][j], Parameters.MinValues[j], Parameters.MaxValues[j], Parameters.MinScale, Parameters.MaxScale); } } for (var i = 0; i < x_train.shape[0]; i++) { for (var j = 0; j < x_train.shape[1]; j++) { x_train_unscaled[i][j] = Classes.Utils.UnScale(x_train[i][j], Parameters.MinValues[j], Parameters.MaxValues[j], Parameters.MinScale, Parameters.MaxScale); } } var idx = Parameters.Labels.IndexOf(Parameters.Labels_Outputs.First()); y_test_unscaled = new NDArray(np.float32, y_test.shape); y_train_unscaled = new NDArray(np.float32, y_train.shape); for (var i = 0; i < y_test.shape[0]; i++) { for (var j = 0; j < y_test.shape[1]; j++) { y_test_unscaled[i][j] = Classes.Utils.UnScale(y_test[i][j], Parameters.MinValues[idx + j], Parameters.MaxValues[idx + j], Parameters.MinScale, Parameters.MaxScale); } } for (var i = 0; i < y_train.shape[0]; i++) { for (var j = 0; j < y_train.shape[1]; j++) { y_train_unscaled[i][j] = Classes.Utils.UnScale(y_train[i][j], Parameters.MinValues[idx + j], Parameters.MaxValues[idx + j], Parameters.MinScale, Parameters.MaxScale); } } yp_test = session.run(outlayer, (X, x_test)); yp_train = session.run(outlayer, (X, x_train)); yp_test_unscaled = new NDArray(np.float32, yp_test.shape); yp_train_unscaled = new NDArray(np.float32, yp_train.shape); for (var i = 0; i < yp_test.shape[0]; i++) { for (var j = 0; j < yp_test.shape[1]; j++) { yp_test_unscaled[i][j] = Classes.Utils.UnScale(yp_test[i][j], Parameters.MinValues[idx + j], Parameters.MaxValues[idx + j], Parameters.MinScale, Parameters.MaxScale); } } for (var i = 0; i < yp_train.shape[0]; i++) { for (var j = 0; j < yp_train.shape[1]; j++) { yp_train_unscaled[i][j] = Classes.Utils.UnScale(yp_train[i][j], Parameters.MinValues[idx + j], Parameters.MaxValues[idx + j], Parameters.MinScale, Parameters.MaxScale); } } // Testing example var training_cost = session.run(mse, (X, x_train), (Y, y_train)); var testing_cost = session.run(mse, (X, x_test), (Y, y_test)); var diff = Math.Abs((float)training_cost - (float)testing_cost); if (flowsheet != null) { flowsheet.ShowMessage($"Training Cost = {testing_cost}", IFlowsheet.MessageType.Information); flowsheet.ShowMessage($"Testing Cost = {testing_cost}", IFlowsheet.MessageType.Information); flowsheet.ShowMessage($"Absolute MSE = {diff}", IFlowsheet.MessageType.Information); } else { Application.Instance.Invoke(() => { ta.Append($"Training Cost = {testing_cost}" + nl, true); ta.Append($"Testing Cost = {testing_cost}" + nl, true); ta.Append($"Absolute MSE = {diff}" + nl, true); }); } });