示例#1
0
        private void button1_Click_1(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button1.Text    = "Proceeding...";
            // preventing empty fields
            if (string.IsNullOrWhiteSpace(textBox1.Text) || string.IsNullOrWhiteSpace(textBox2.Text) ||
                string.IsNullOrWhiteSpace(textBox3.Text) || string.IsNullOrWhiteSpace(textBox4.Text) ||
                string.IsNullOrWhiteSpace(textBox5.Text) || string.IsNullOrWhiteSpace(textBox6.Text) ||
                string.IsNullOrWhiteSpace(textBox7.Text) || string.IsNullOrWhiteSpace(textBox8.Text))
            {
                MessageBox.Show("Enter all values", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            int    time    = Convert.ToInt32(textBox1.Text);
            int    step    = Convert.ToInt32(textBox2.Text);
            int    initt1  = Convert.ToInt32(textBox3.Text);
            int    initt2  = Convert.ToInt32(textBox4.Text);
            int    initt3  = Convert.ToInt32(textBox7.Text);
            int    conv    = Convert.ToInt32(textBox5.Text);
            double bulk    = Convert.ToDouble(textBox8.Text) + 273.15; // converting to Kelvin units
            int    heatpow = Convert.ToInt32(textBox6.Text);

            DisposeSW();

            // Opening SW 2017
            // Additional GUID: F16137AD-8EE8-4D2A-8CAC-DFF5D1F67522
            Guid Guid1 = new Guid("6B36082E-677B-49E8-BCB2-76698EBD2906");

            object processSW = System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid1));

            swApp         = (SldWorks)processSW;
            swApp.Visible = true;

            CosmosWorks           COSMOSWORKS    = default(CosmosWorks);
            CwAddincallback       CWObject       = default(CwAddincallback);
            CWModelDoc            ActDoc         = default(CWModelDoc);
            CWStudyManager        StudyMngr      = default(CWStudyManager);
            CWStudy               Study          = default(CWStudy);
            CWThermalStudyOptions ThermalOptions = default(CWThermalStudyOptions);
            CWConvection          CWConv         = default(CWConvection);
            CWMesh        CwMesh               = default(CWMesh);
            CWResults     CWResult             = default(CWResults);
            CWTemperature CWTemp               = default(CWTemperature);
            ModelDoc2     Part                 = default(ModelDoc2);
            CWLoadsAndRestraintsManager LBCMgr = default(CWLoadsAndRestraintsManager);
            CWHeatPower CWHeatPower            = default(CWHeatPower);
            ModelDoc2   swDoc        = null;
            int         bApp         = 0;
            int         longstatus   = 0;
            int         longwarnings = 0;
            int         errCode      = 0;
            double      el           = 0;
            double      tl           = 0;
            string      cwpath       = "";

            Part = swApp.OpenDoc6("G:\\assem(simple).SLDASM", (int)swDocumentTypes_e.swDocASSEMBLY,
                                  (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref longstatus, ref longwarnings);
            if (Part == null)
            {
                MessageBox.Show("Failed to open document");
            }

            swDoc = swApp.IActiveDoc2;

            // connecting Simulation to SW
            cwpath  = swApp.GetExecutablePath() + @"\Simulation\cosworks.dll";
            errCode = swApp.LoadAddIn(cwpath);
            if (errCode != 0 && errCode != 2)
            {
                MessageBox.Show("Failed to load Simulation library");
                swApp.ExitApp();
                DisposeSW();
                Application.Exit();
            }

            // ready-check Simulation add-on
            CWObject = (CwAddincallback)swApp.GetAddInObject("CosmosWorks.CosmosWorks");
            if (CWObject == null)
            {
                MessageBox.Show("Failed to start Simulation");
            }

            // ready-check add-on object
            COSMOSWORKS = CWObject.CosmosWorks;
            if (COSMOSWORKS == null)
            {
                MessageBox.Show("Failed to create CosmosWorks object");
            }

            // connecting add-on to document
            ActDoc = COSMOSWORKS.ActiveDoc;
            if (ActDoc == null)
            {
                MessageBox.Show("Failed to open document");
            }

            // creating thermal analysis
            bApp      = ActDoc.AddDefaultThermalStudyPlot((int)swsThermalResultComponentTypes_e.swsThermalResultComponentTypes_TEMP, true);
            StudyMngr = ActDoc.StudyManager;
            if (StudyMngr == null)
            {
                MessageBox.Show("Failed to start analysis manager");
            }

            Study = StudyMngr.CreateNewStudy3("CPU Usage", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeThermal,
                                              (int)swsMeshType_e.swsMeshTypeSolid, out errCode);
            if (Study == null)
            {
                MessageBox.Show("Failed to create thermal analysis");
            }

            ThermalOptions = Study.ThermalStudyOptions;
            Study.ThermalStudyOptions.SolutionType = 0;
            if (ThermalOptions == null)
            {
                MessageBox.Show("No analysis parameters");
            }

            // analysis duration
            ThermalOptions.CheckFlowConvectionCoef = 0;
            ThermalOptions.SolverType    = 2;
            ThermalOptions.TotalTime     = time;
            ThermalOptions.TimeIncrement = step;

            LBCMgr = Study.LoadsAndRestraintsManager;
            if (LBCMgr == null)
            {
                MessageBox.Show("Failed to load loads and restraints manager");
            }

            // lit coordinates
            swDoc.ShowNamedView2("*Top", 5);
            swDoc.ViewZoomtofit2();
            ISelectionMgr selectionMgr = (ISelectionMgr)swDoc.SelectionManager;
            bool          isSelected   = swDoc.Extension.SelectByRay(-0.28387922510520769, 0.081999999999993634,
                                                                     -0.14613487203691797, 0, -1, 0, 0.0047546274155552031, 2, false, 0, 0);

            if (isSelected)
            {
                Entity     swEntity  = selectionMgr.GetSelectedObject6(1, -1);
                Component2 swComp    = (Component2)swEntity.GetComponent();
                object[]   fixedpart = { swComp };
                CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add temperature indicator");
                }
            }

            CWTemp.TemperatureBeginEdit();
            CWTemp.TemperatureType  = 0;
            CWTemp.Unit             = 2;
            CWTemp.TemperatureValue = initt2;

            errCode = CWTemp.TemperatureEndEdit();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to edit temperature indicator");
            }

            swDoc.ClearSelection2(true);

            // silicon board coordinates
            isSelected = swDoc.Extension.SelectByRay(-0.41952594843134139, 0.02199999999999136,
                                                     -0.41742831868918501, 0, -1, 0, 0.0047546274155552031, 2, false, 0, 0);
            if (isSelected)
            {
                Entity     swEntity  = selectionMgr.GetSelectedObject6(1, -1);
                Component2 swComp    = (Component2)swEntity.GetComponent();
                object[]   fixedpart = { swComp };
                CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add temperature indicator");
                }
            }

            CWTemp.TemperatureBeginEdit();
            CWTemp.TemperatureType  = 0;
            CWTemp.Unit             = 2;
            CWTemp.TemperatureValue = initt1;

            errCode = CWTemp.TemperatureEndEdit();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to edit temperature indicator");
            }

            swDoc.ClearSelection2(true);

            // stalks coordinates
            swDoc.ShowNamedView2("*Bottom", 6);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(-0.42931488722807265, -0.050999999999987722, 0.28597685484736474, 0, 1, 0, 0.0047546274155552031, 2, false, 0, 0);
            if (isSelected)
            {
                Entity     swEntity  = selectionMgr.GetSelectedObject6(1, -1);
                Component2 swComp    = (Component2)swEntity.GetComponent();
                object[]   fixedpart = { swComp };
                CWTemp = LBCMgr.AddTemperature(fixedpart, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to edit temperature indicator");
                }
            }

            CWTemp.TemperatureBeginEdit();
            CWTemp.TemperatureType  = 0;
            CWTemp.Unit             = 2;
            CWTemp.TemperatureValue = initt3;

            errCode = CWTemp.TemperatureEndEdit();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to edit temperature indicator");
            }

            swDoc.ClearSelection2(true);

            // all faces coordinates
            swDoc.ShowNamedView2("*Front", 1);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(-0.38382731822234351, 0.04982938298755997, 0.40017589628916994, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.18695037482381383, 0.049829382987560122, 0.42176499999999351, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.35735646868976789, 0.0713369482327776, 0.41521684512093771, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.10505618408240869, 0.010950322736590109, 0.4415000000000191, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.43015130490435044, -0.017174954891772284, 0.29464212540386825, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.42932409085645729, -0.016347740843879296, 0.29483222724246616, 0, 0, -1, 0.0028125277628361371, 2, false, 0, 0);

            swDoc.ShowNamedView2("*Back", 2);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(0.3581836827376611, 0.063064807753847776, -0.4148975912216315, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.14558967242916476, 0.053138239179132019, -0.42176499999999351, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.37969124798287845, 0.047347740843881027, -0.40327910794843547, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.033088561915719295, 0.012604750832376084, -0.4415000000000191, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.42766966276067148, -0.014693312748093316, -0.29499856062381014, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.42766966276067131, -0.022138239179130152, -0.29499856062381014, 0, 0, 1, 0.0028125277628361371, 2, false, 0, 0);

            swDoc.ShowNamedView2("*Left", 3);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(-0.42176499999999351, 0.046520526795988171, -0.081066976693512371, 1, 0, 0, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.4415000000000191, 0.0084686805929112003, -0.082721404789298347, 1, 0, 0, 0.0028125277628361371, 2, false, 0, 0);

            swDoc.ShowNamedView2("*Right", 4);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(0.42176499999999351, 0.052311025131239031, 0.1158099667050172, -1, 0, 0, 0.0028125277628361371, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.4415000000000191, 0.010123108688697121, 0.12490932123184006, -1, 0, 0, 0.0028125277628361371, 2, false, 0, 0);

            swDoc.ShowNamedView2("*Top", 5);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(-0.19376272580646192, 0.081999999999993634, -0.13541980560506936, 0, -1, 0, 0.0036397418107291194, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.41535877134202892, 0.02199999999999136, -0.42017607667975893, 0, -1, 0, 0.0036397418107291194, 2, false, 0, 0);

            swDoc.ShowNamedView2("*Bottom", 6);
            swDoc.ViewZoomtofit2();
            isSelected = swDoc.Extension.SelectByRay(-0.20232682418464809, -0.00099999999997635314, 0.23818898614330264, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.42713440661203494, -0.050999999999987722, 0.28743255181787342, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.42713440661203483, -0.050999999999987722, 0.28529152722332685, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(0.4292754312065814, -0.050999999999987722, -0.28422101492605301, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0);
            isSelected = swDoc.Extension.SelectByRay(-0.42499338201748837, -0.050999999999987722, -0.28636203952059958, 0, 1, 0, 0.0036397418107291194, 2, false, 0, 0);
            if (isSelected)
            {
                object   selectedFace1  = (object)selectionMgr.GetSelectedObject6(1, -1);
                object   selectedFace2  = (object)selectionMgr.GetSelectedObject6(2, -1);
                object   selectedFace3  = (object)selectionMgr.GetSelectedObject6(3, -1);
                object   selectedFace4  = (object)selectionMgr.GetSelectedObject6(4, -1);
                object   selectedFace5  = (object)selectionMgr.GetSelectedObject6(5, -1);
                object   selectedFace6  = (object)selectionMgr.GetSelectedObject6(6, -1);
                object   selectedFace7  = (object)selectionMgr.GetSelectedObject6(7, -1);
                object   selectedFace8  = (object)selectionMgr.GetSelectedObject6(8, -1);
                object   selectedFace9  = (object)selectionMgr.GetSelectedObject6(9, -1);
                object   selectedFace10 = (object)selectionMgr.GetSelectedObject6(10, -1);
                object   selectedFace11 = (object)selectionMgr.GetSelectedObject6(11, -1);
                object   selectedFace12 = (object)selectionMgr.GetSelectedObject6(12, -1);
                object   selectedFace13 = (object)selectionMgr.GetSelectedObject6(13, -1);
                object   selectedFace14 = (object)selectionMgr.GetSelectedObject6(14, -1);
                object   selectedFace15 = (object)selectionMgr.GetSelectedObject6(15, -1);
                object   selectedFace16 = (object)selectionMgr.GetSelectedObject6(16, -1);
                object   selectedFace17 = (object)selectionMgr.GetSelectedObject6(17, -1);
                object   selectedFace18 = (object)selectionMgr.GetSelectedObject6(18, -1);
                object   selectedFace19 = (object)selectionMgr.GetSelectedObject6(19, -1);
                object   selectedFace20 = (object)selectionMgr.GetSelectedObject6(20, -1);
                object   selectedFace21 = (object)selectionMgr.GetSelectedObject6(21, -1);
                object   selectedFace22 = (object)selectionMgr.GetSelectedObject6(22, -1);
                object   selectedFace23 = (object)selectionMgr.GetSelectedObject6(23, -1);
                object[] fixedpart      = { selectedFace1, selectedFace2,  selectedFace3,  selectedFace4,  selectedFace5,  selectedFace6,  selectedFace7,  selectedFace8,  selectedFace9,  selectedFace10,
                                            selectedFace11,     selectedFace12, selectedFace13, selectedFace14, selectedFace15, selectedFace16, selectedFace17, selectedFace18, selectedFace19, selectedFace20,selectedFace21,
                                            selectedFace22,     selectedFace23 };
                CWConv = LBCMgr.AddConvection(fixedpart, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add convection coefficient indicator");
                }
            }

            CWConv.ConvectionBeginEdit();
            CWConv.Unit = 0;
            CWConv.ConvectionCoefficient  = conv;
            CWConv.BulkAmbientTemperature = bulk;

            errCode = CWConv.ConvectionEndEdit();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to edit convection coefficient indicator");
            }

            swDoc.ClearSelection2(true);

            // stalks coordinates
            isSelected = swDoc.Extension.SelectByRay(-0.42931488722807265, -0.050999999999987722, 0.28597685484736474, 0, 1, 0, 0.0047546274155552031, 2, false, 0, 0);
            if (isSelected)
            {
                Entity     swEntity  = selectionMgr.GetSelectedObject6(1, -1);
                Component2 swComp    = (Component2)swEntity.GetComponent();
                object[]   fixedpart = { swComp };
                CWHeatPower = LBCMgr.AddHeatPower(fixedpart, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add thermal power indicator");
                }
            }

            CWHeatPower.HeatPowerBeginEdit();
            CWHeatPower.Unit              = 0;
            CWHeatPower.HPValue           = heatpow;
            CWHeatPower.ReverseDirection  = 0;
            CWHeatPower.IncludeThermostat = 0;
            errCode = CWHeatPower.HeatPowerEndEdit();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to edit thermal power indicator");
            }

            swDoc.ShowNamedView2("*Isometric", 7);
            swDoc.ViewZoomtofit2();

            // creating mesh model
            CwMesh = Study.Mesh;
            if (CwMesh == null)
            {
                MessageBox.Show("No mesh model");
            }

            CwMesh.Quality = 1;
            CwMesh.GetDefaultElementSizeAndTolerance(0, out el, out tl);
            errCode = Study.CreateMesh(0, el, tl);
            if (errCode != 0)
            {
                MessageBox.Show("Failed to create mesh model");
            }

            // analysis start
            errCode = Study.RunAnalysis();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to start analysi: " + errCode);
            }

            CWResult = Study.Results;
            if (CWResult == null)
            {
                MessageBox.Show("No results");
            }
            else
            {
                MessageBox.Show("Done", "Results");
                button1.Enabled = true;
                button1.Text    = "Thermal analysis";
            }
            double[] max = new double[time / step];
            double[] min = new double[time / step];
            double[] avg = new double[4];

            for (int i = 1; i <= time / step; i++)
            {
                CWPlot plot = CWResult.GetPlot("Thermal" + i.ToString(), out errCode);
                plot.SetComponentUnitAndValueByElem(0, 2, false);
                object[] results = null;
                results    = (object[])plot.GetMinMaxResultValues(out errCode);
                max[i - 1] = Convert.ToDouble(results[3].ToString());
                min[i - 1] = Convert.ToDouble(results[1].ToString());
                if (i == 1)
                {
                    avg[0] = Convert.ToDouble(results[1].ToString());
                    avg[1] = Convert.ToDouble(results[3].ToString());
                }
                if (i == time / step)
                {
                    avg[2] = Convert.ToDouble(results[1].ToString());
                    avg[3] = Convert.ToDouble(results[3].ToString());
                }
            }

            double maxValue = max.Max();
            double minValue = min.Min();

            textBox9.Text  = maxValue.ToString("#.##");
            textBox10.Text = minValue.ToString("#.##");

            double heatdens = Math.Abs(conv * (((initt2 + initt3) / 2) - (initt3 - (maxValue - minValue))));

            textBox12.Text = heatdens.ToString("#.##");

            double avg1 = (avg[0] + avg[1]) / 2;
            double avg2 = (avg[2] + avg[3]) / 2;
            double avgr = avg1 - avg2;

            textBox15.Text = avgr.ToString("#.##");
        }
示例#2
0
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            studyName = nameTextBox.Text;
            if (string.IsNullOrWhiteSpace(studyName))
            {
                studyName = "Freq_Cantilever";
            }

            analysisLabel.Invoke((MethodInvoker) delegate
            {
                analysisLabel.Visible = true;
            });

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Disposing of SW processes...";
            });

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Visible = true;
            });

            // manual cancelling of the analysis
            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            DisposeSW();

            resGrid.Invoke((MethodInvoker) delegate
            {
                resGrid.Rows.Clear();
                resGrid.Refresh();
            });

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(5);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Launching SW...";
            });

            object processSW = System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid1));

            swApp         = (SldWorks)processSW;
            swApp.Visible = true;

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Loading Simulation library...";
            });

            // connecting Simulation to SW
            cwpath  = swApp.GetExecutablePath() + @"\Simulation\cosworks.dll";
            errCode = swApp.LoadAddIn(cwpath);
            if (errCode != 0 && errCode != 2)
            {
                MessageBox.Show("Failed to load Simulation library");
                swApp.ExitApp();
                DisposeSW();
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Creating cantilever...";
            });

            // opening cantilever model
            Part = swApp.OpenDoc6("G:\\Cantilever.SLDPRT", 1, 0, "", ref longstatus, ref longwarnings);
            if (Part == null)
            {
                MessageBox.Show("Failed to load cantilever model");
                swApp.ExitApp();
                Dispose();
                Application.Exit();
            }

            swDoc = swApp.IActiveDoc2;
            swDoc.ShowNamedView2("*Isometric", 7);
            swDoc.ViewZoomtofit2();

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(10);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Check for Simulation readiness...";
            });

            // ready-check Simulation add-on
            CWAddinCallBack = (CwAddincallback)swApp.GetAddInObject("CosmosWorks.CosmosWorks");
            if (CWAddinCallBack == null)
            {
                MessageBox.Show("Failed to open Simulation");
                Application.Exit();
            }

            // ready-check add-on object
            COSMOSWORKS = CWAddinCallBack.CosmosWorks;
            if (COSMOSWORKS == null)
            {
                MessageBox.Show("Failed to create CosmosWorks object");
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(14);

            // connecting add-on to the document
            ActDoc = COSMOSWORKS.ActiveDoc;
            if (ActDoc == null)
            {
                MessageBox.Show("Failed to load document");
                Application.Exit();
            }

            bwStudy.ReportProgress(16);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Setting up an analysis...";
            });

            // creating a frequency analysis
            StudyMngr = ActDoc.StudyManager;
            if (StudyMngr == null)
            {
                MessageBox.Show("Failed to load analysis manager");
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(18);

            // analysis creation
            Study = StudyMngr.CreateNewStudy3(studyName,
                                              (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeFrequency,
                                              (int)swsMeshType_e.swsMeshTypeSolid, out errCode);
            if (Study == null)
            {
                MessageBox.Show("Failed to create a frequency analysis");
                Application.Exit();
            }

            // analysis settings
            CWOptions = Study.FrequencyStudyOptions;
            // finite element method solver
            // 1 - Automatic Solver Selection, 0 - Direct sparse solver, 2 - FFEPlus, 7 - Intel Direct Sparse
            Study.FrequencyStudyOptions.SolverType      = SolverDict[solverIndex];
            Study.FrequencyStudyOptions.NoOfFrequencies = freqNumber;
            if (CWOptions == null)
            {
                MessageBox.Show("No analysis settings");
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(20);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Setting cantilever material...";
            });

            // using silicon as the material (don't know why)
            string matLib = swApp.GetExecutablePath() +
                            @"\lang\english\sldmaterials\solidworks materials.sldmat";

            SolidMgr  = (CWSolidManager)Study.SolidManager;
            SolidComp = SolidMgr.GetComponentAt(0, out errCode);
            if (errCode == 0)
            {
                SolidBody = (CWSolidBody)SolidComp.GetSolidBodyAt(0, out errCode);
                errCode   = (int)SolidBody.SetLibraryMaterial(matLib, "Silicon");
            }
            else
            {
                MessageBox.Show("Failed to apply material");
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Adding restraints...";
            });

            // loading loads and restraints manager
            LBCMgr = Study.LoadsAndRestraintsManager;
            if (LBCMgr == null)
            {
                MessageBox.Show("Failed to load loads and restraints manager");
                Application.Exit();
            }

            bwStudy.ReportProgress(25);

            // face selection followed by applying restraints
            ISelectionMgr selectionMgr = (ISelectionMgr)swDoc.SelectionManager;
            bool          isSelected   = swDoc.Extension.SelectByRay(0.018229940747914952, 0.051969523507693793,
                                                                     0.0020000000000095497, -0.57738154519998097, -0.5772877120855483, -0.57738154519997897,
                                                                     0.00085899699451767535, 2, false, 0, 0);

            if (isSelected)
            {
                object   face_bind = selectionMgr.GetSelectedObject6(1, -1);
                object[] fixedpart = { face_bind };
                CWBind = (CWRestraint)LBCMgr.AddRestraint(0, (fixedpart), null, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add restraints");
                    Application.Exit();
                }
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(35);

            swDoc.ClearSelection2(true);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Creating mesh object...";
            });

            swDoc.ClearSelection2(true);

            // mesh object options
            CWMesh         = ((CWMesh)(Study.Mesh));
            CWMesh.Quality = 1;
            CWMesh.UseJacobianCheckForSolids = 1;
            CWMesh.MesherType                 = 0;
            CWMesh.AutomaticTransition        = 0;
            CWMesh.AutomaticLooping           = 0;
            CWMesh.NumberOfLoops              = 3;
            CWMesh.SaveSettingsWithoutMeshing = 0;
            CWMesh.Unit = 0;

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(50);

            // create mesh object
            errCode = Study.CreateMesh(0, 13.3821, 0.669103);
            if (errCode != 0)
            {
                MessageBox.Show("Failed to create mesh object");
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Analysing...";
            });

            // start of analysis
            errCode = Study.RunAnalysis();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to start analysis");
                Application.Exit();
            }

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text  = "Analysis has been stopped by user";
                    startBtn.Text          = "Start analysis";
                    solverComboBox.Enabled = true;
                    freqComboBox.Enabled   = true;
                });

                e.Cancel = true;
                return;
            }

            bwStudy.ReportProgress(90);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Receiving results of analysis...";
            });

            // getting results
            CWResult = (CWResults)Study.Results;
            if (CWResult == null)
            {
                MessageBox.Show("Failed to receive results of analysis");
                return;
            }

            double[] res = new double[10];

            // getting results from the graph
            for (int i = 0; i < freqNumber; i++)
            {
                plot = CWResult.GetPlot("Amplitude" + (i + 1).ToString(), out errCode);
                if (plot == null)
                {
                    MessageBox.Show("Failed to load an information from the graph");
                    return;
                }
                plot.SetComponentUnitAndValueByElem(9, 3, false);
                results = (object[])plot.GetMinMaxResultValues(out errCode);
                res[i]  = Convert.ToDouble(results[3].ToString());
            }

            for (int k = 0; k < freqNumber; k++)
            {
                resGrid.Invoke((MethodInvoker) delegate
                {
                    int n = resGrid.Rows.Add();
                    resGrid.Rows[n].Cells[0].Value = k + 1;
                    resGrid.Rows[n].Cells[1].Value = res[k];
                });
            }

            bwStudy.ReportProgress(100);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Done";
            });

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                startBtn.Text          = "Review results";
                solverComboBox.Enabled = true;
                freqComboBox.Enabled   = true;
            });
        }
示例#3
0
        // another thread work
        void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;

            // banning empty fields
            if (string.IsNullOrWhiteSpace(strBox.Text))
            {
                MessageBox.Show("Enter force value", "Error",
                                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate {
                processNameLabel.Text = "Launching SolidWorks...";
            });

            // check for manual cancelling of analysis
            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // opening SW 2017
            Guid   Guid1     = new Guid("6B36082E-677B-49E8-BCB2-76698EBD2906");
            object processSW = System.Activator.CreateInstance(System.Type.GetTypeFromCLSID(Guid1));

            swApp         = (SldWorks)processSW;
            swApp.Visible = true;

            processNameLabel.Invoke((MethodInvoker) delegate {
                processNameLabel.Text = "Preparing Simulation...";
            });

            CosmosWorks                 COSMOSWORKS     = default(CosmosWorks);
            CwAddincallback             CWAddinCallBack = default(CwAddincallback);
            CWModelDoc                  ActDoc          = default(CWModelDoc);
            CWStudyManager              StudyMngr       = default(CWStudyManager);
            CWStudy                     Study           = default(CWStudy);
            CWStaticStudyOptions        CWOptions       = default(CWStaticStudyOptions);
            CWLoadsAndRestraintsManager LBCMgr          = default(CWLoadsAndRestraintsManager);
            CWRestraint                 CWBind          = default(CWRestraint);
            CWForce                     CWStr           = default(CWForce);
            CWMesh    CWMesh   = default(CWMesh);
            CWResults CWResult = default(CWResults);
            CWPlot    plot     = default(CWPlot);

            ModelDoc2 Part         = default(ModelDoc2);
            ModelDoc2 swDoc        = null;
            int       longstatus   = 0;
            int       longwarnings = 0;
            int       errCode      = 0;

            object[] results = null;

            // analysis name
            string study_name = studyNameBox.Text;

            if (string.IsNullOrWhiteSpace(study_name))
            {
                study_name = "Static_beam";
            }

            bwStudy.ReportProgress(5);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate {
                processNameLabel.Text = "Creating beam model...";
            });

            // opening SLDPRT file containing beam model
            Part = swApp.OpenDoc6("C:\\Beam.SLDPRT", 1, 0, "", ref longstatus, ref longwarnings);
            if (Part == null)
            {
                MessageBox.Show("Failed to open model");
                Application.Exit();
            }

            string path_to_cosworks_dll = swApp.GetExecutablePath() + @"\Simulation\cosworks.dll";

            longstatus = swApp.LoadAddIn(path_to_cosworks_dll);

            // isometric view
            swDoc = swApp.IActiveDoc2;
            swDoc.ShowNamedView2("*Isometric", 7);
            swDoc.ViewZoomtofit2();

            bwStudy.ReportProgress(10);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Starting Simulation...";
            });

            // ready-check Simulation add-on
            CWAddinCallBack = (CwAddincallback)swApp.GetAddInObject("CosmosWorks.CosmosWorks");
            if (CWAddinCallBack == null)
            {
                MessageBox.Show("Failed to start Simulation");
                Application.Exit();
            }

            bwStudy.ReportProgress(12);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // ready-check add-on object
            COSMOSWORKS = CWAddinCallBack.CosmosWorks;
            if (COSMOSWORKS == null)
            {
                MessageBox.Show("Failed to create CosmosWorks object");
                Application.Exit();
            }

            bwStudy.ReportProgress(14);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // connecting add-on to document
            ActDoc = COSMOSWORKS.ActiveDoc;
            if (ActDoc == null)
            {
                MessageBox.Show("Failed to connect to document");
                Application.Exit();
            }

            bwStudy.ReportProgress(16);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Creating analysis...";
            });

            // creating static analysis
            StudyMngr = ActDoc.StudyManager;
            if (StudyMngr == null)
            {
                MessageBox.Show("Failed to start analysis manager");
                Application.Exit();
            }

            bwStudy.ReportProgress(18);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            Study = StudyMngr.CreateNewStudy3(study_name, (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeStatic, (int)swsMeshType_e.swsMeshTypeSolid, out errCode);
            if (Study == null)
            {
                MessageBox.Show("Failed to create static analysis");
                Application.Exit();
            }

            bwStudy.ReportProgress(20);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Adding attachment object...";
            });

            // loading indicator manager
            LBCMgr = Study.LoadsAndRestraintsManager;
            if (LBCMgr == null)
            {
                MessageBox.Show("Failed to load indicator manager");
                Application.Exit();
            }

            bwStudy.ReportProgress(25);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // selecting face for attachment and adding it to indicator manager
            ISelectionMgr selectionMgr = (ISelectionMgr)swDoc.SelectionManager;
            bool          isSelected   = swDoc.Extension.SelectByRay(-0.023870052576342005, 0.064003232713616853, 0, -0.57738154519998108, -0.57728771208554841, -0.57738154519997897, 0.0037366684901689287, 2, true, 0, 0);

            if (isSelected)
            {
                object   face_bind = selectionMgr.GetSelectedObject6(1, -1);
                object[] fixedpart = { face_bind };
                CWBind = (CWRestraint)LBCMgr.AddRestraint(0, (fixedpart), null, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add attachment object");
                    Application.Exit();
                }
            }

            bwStudy.ReportProgress(35);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Adding force indicator...";
            });

            swDoc.ClearSelection2(true);

            isSelected = swDoc.Extension.SelectByRay(0.00094849719312151137, 0.029999999999915872, 0.97601905600942018, -0.57738154519998108, -0.57728771208554841, -0.57738154519997897, 0.0037366684901689287, 2, true, 0, 0);
            if (isSelected)
            {
                object   face_force      = selectionMgr.GetSelectedObject6(1, -1);
                object[] fixedpart       = { face_force };
                object[] DistanceValues  = { };
                object[] ForceValues     = { };
                object[] ComponentValues = { };
                CWStr = (CWForce)LBCMgr.AddForce3(1, 0, -1, 0, 0, 0, DistanceValues, ForceValues, false, false, 0, 0, 0, Convert.ToInt32(strBox.Text), ComponentValues, false, false, (fixedpart), null, false, out errCode);
                if (errCode != 0)
                {
                    MessageBox.Show("Failed to add force indicator");
                    Application.Exit();
                }
                CWStr.ForceBeginEdit();
                CWStr.Unit = 2;
                CWStr.ForceEndEdit();
            }

            bwStudy.ReportProgress(50);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Creating mesh object...";
            });

            swDoc.ClearSelection2(true);

            // mesh object parameters
            CWMesh         = ((CWMesh)(Study.Mesh));
            CWMesh.Quality = 1;
            CWMesh.UseJacobianCheckForSolids = 1;
            CWMesh.MesherType                 = 0;
            CWMesh.AutomaticTransition        = 0;
            CWMesh.AutomaticLooping           = 0;
            CWMesh.NumberOfLoops              = 3;
            CWMesh.SaveSettingsWithoutMeshing = 0;
            CWMesh.Unit = 0;

            bwStudy.ReportProgress(70);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // creating mesh object
            errCode = Study.CreateMesh(0, 13.3821, 0.669103);
            if (errCode != 0)
            {
                MessageBox.Show("Failed to create mesh object");
                Application.Exit();
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Starting analysis...";
            });

            // starting analysis
            errCode = Study.RunAnalysis();
            if (errCode != 0)
            {
                MessageBox.Show("Failed to start analysis");
                Application.Exit();
            }

            bwStudy.ReportProgress(90);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Receiving analysis results...";
            });

            // obtaining results
            CWResult = (CWResults)Study.Results;
            if (CWResult == null)
            {
                MessageBox.Show("Failed to receive results");
                return;
            }

            // stress graph results
            plot = CWResult.GetPlot("Stress1", out errCode);
            if (plot == null)
            {
                MessageBox.Show("Failed to receive stress results");
                return;
            }
            plot.SetComponentUnitAndValueByElem(9, 3, false);
            results = (object[])plot.GetMinMaxResultValues(out errCode);

            max_tens = Convert.ToDouble(results[3].ToString());
            min_tens = Convert.ToDouble(results[1].ToString());

            bwStudy.ReportProgress(93);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // displacement graph results
            plot = CWResult.GetPlot("Displacement1", out errCode);
            if (plot == null)
            {
                MessageBox.Show("Failed to receive displacement results");
                return;
            }
            plot.SetComponentUnitAndValueByElem(3, 0, false);
            results = (object[])plot.GetMinMaxResultValues(out errCode);

            max_move = Convert.ToDouble(results[3].ToString());
            min_move = Convert.ToDouble(results[1].ToString());

            bwStudy.ReportProgress(96);

            if (bwStudy.CancellationPending == true)
            {
                processNameLabel.Invoke((MethodInvoker) delegate
                {
                    processNameLabel.Text = "Analysis has been cancelled";
                });

                e.Cancel = true;
                return;
            }

            // strain graph results
            plot = CWResult.GetPlot("Strain1", out errCode);
            if (plot == null)
            {
                MessageBox.Show("Failed to receive strain results");
                return;
            }
            plot.SetComponentUnitAndValueByElem(6, 3, false);
            results = (object[])plot.GetMinMaxResultValues(out errCode);

            bwStudy.ReportProgress(99);

            max_deform = Convert.ToDouble(results[3].ToString());
            min_deform = Convert.ToDouble(results[1].ToString());

            maxTensBox.Invoke((MethodInvoker) delegate
            {
                maxTensBox.Text = max_tens.ToString();
            });

            minTensBox.Invoke((MethodInvoker) delegate
            {
                minTensBox.Text = min_tens.ToString();
            });

            maxMoveBox.Invoke((MethodInvoker) delegate
            {
                maxMoveBox.Text = max_move.ToString();
            });

            minMoveBox.Invoke((MethodInvoker) delegate
            {
                minMoveBox.Text = min_move.ToString();
            });

            maxDeformBox.Invoke((MethodInvoker) delegate
            {
                maxDeformBox.Text = max_deform.ToString();
            });

            minDeformBox.Invoke((MethodInvoker) delegate
            {
                minDeformBox.Text = min_deform.ToString();
            });

            bwStudy.ReportProgress(100);

            processNameLabel.Invoke((MethodInvoker) delegate
            {
                processNameLabel.Text = "Done";
            });
        }
        private void button_create_Geom_Click(object sender, RoutedEventArgs e)
        {
            #region a test example, not important
            m         = 9;
            width     = 8 / 1000.0;
            thickness = 1 / 1000.0;
            l1        = 30 / 1000.0;
            l2        = 16 / 1000.0;
            l3        = 21 / 1000.0;
            F1        = 1;
            F2        = 37;
            F3        = 49;

            l4          = l2;
            l1_         = l1 - 2 * width;
            l2_         = l2;
            l3_         = l3 + 2 * width;
            l4_         = l4;
            cell_length = l1 + l3;
            cell_height = l2 + width;
            #endregion

            Count = int.Parse(textBox_count.Text);
            Random randomSeed       = new Random();
            Random random_m         = new Random(randomSeed.Next());
            Random random_width     = new Random(randomSeed.Next());
            Random random_thickness = new Random(randomSeed.Next());
            Random random_l1        = new Random(randomSeed.Next());
            Random random_l2        = new Random(randomSeed.Next());
            Random random_l3        = new Random(randomSeed.Next());
            Random random_F1        = new Random(randomSeed.Next());
            Random random_F2        = new Random(randomSeed.Next());
            Random random_F3        = new Random(randomSeed.Next());

            for (int j = 0; j < Count; j++)
            {
                Console.WriteLine(string.Format("---------------------------------now No.{0}", j));

                #region generate random Data
                try
                {
                    /* change to double
                     * ran_m = random_m.Next(int.Parse(textBox_hm_cells_min.Text), int.Parse(textBox_hm_cellls_max.Text));
                     * ran_width = random_width.Next(int.Parse(textBox_width_min.Text), int.Parse(textBox_width_max.Text));
                     * ran_thickness = random_thickness.Next(int.Parse(textBox_thickness_min.Text), int.Parse(textBox_thickness_max.Text));
                     * ran_l1 = random_l1.Next(int.Parse(textBox_l1_min.Text), int.Parse(textBox_l1_max.Text));
                     * ran_l2 = random_l2.Next(int.Parse(textBox_l2_min.Text), int.Parse(textBox_l2_max.Text));
                     * ran_l3 = random_l3.Next(int.Parse(textBox_l3_min.Text), int.Parse(textBox_l3_max.Text));
                     * ran_F1 = random_F1.Next(int.Parse(textBox_F1_min.Text), int.Parse(textBox_F1_max.Text));
                     * ran_F2 = random_F2.Next(int.Parse(textBox_F2_min.Text), int.Parse(textBox_F2_max.Text));
                     * ran_F3 = random_F3.Next(int.Parse(textBox_F3_min.Text), int.Parse(textBox_F3_max.Text));
                     */
                    ran_m         = random_m.Next(int.Parse(textBox_hm_cells_min.Text), int.Parse(textBox_hm_cellls_max.Text));
                    ran_width     = random_width.NextDouble() * (int.Parse(textBox_width_max.Text) - int.Parse(textBox_width_min.Text)) + double.Parse(textBox_width_min.Text);
                    ran_thickness = random_thickness.NextDouble() * (int.Parse(textBox_thickness_max.Text) - int.Parse(textBox_thickness_min.Text)) + double.Parse(textBox_thickness_min.Text);
                    ran_l1        = random_l1.NextDouble() * (int.Parse(textBox_l1_max.Text) - int.Parse(textBox_l1_min.Text)) + double.Parse(textBox_l1_min.Text);
                    ran_l2        = random_l2.NextDouble() * (int.Parse(textBox_l2_max.Text) - int.Parse(textBox_l2_min.Text)) + double.Parse(textBox_l2_min.Text);
                    ran_l3        = random_l3.NextDouble() * (int.Parse(textBox_l3_max.Text) - int.Parse(textBox_l3_min.Text)) + double.Parse(textBox_l3_min.Text);
                    ran_F1        = random_F1.NextDouble() * (int.Parse(textBox_F1_max.Text) - int.Parse(textBox_F1_min.Text)) + double.Parse(textBox_F1_min.Text);
                    ran_F2        = random_F2.NextDouble() * (int.Parse(textBox_F2_max.Text) - int.Parse(textBox_F2_min.Text)) + double.Parse(textBox_F2_min.Text);
                    ran_F3        = random_F3.NextDouble() * (int.Parse(textBox_F3_max.Text) - int.Parse(textBox_F3_min.Text)) + double.Parse(textBox_F3_min.Text);
                }
                catch (Exception)
                {
                    Console.WriteLine("Input Format Error");
                    return;
                }


                m         = ran_m;
                width     = (double)(ran_width / 1000.0);
                thickness = (double)(ran_thickness / 1000.0);
                l1        = (double)(ran_l1 / 1000.0);
                l2        = (double)(ran_l2 / 1000.0);
                l3        = (double)(ran_l3 / 1000.0);

                F1 = (double)ran_F1;
                F2 = (double)ran_F2;
                F3 = (double)ran_F3;
                F3 = 0;

                l4          = l2;
                l1_         = l1 - 2 * width;
                l2_         = l2;
                l3_         = l3 + 2 * width;
                l4_         = l4;
                cell_length = l1 + l3;
                cell_height = l2 + width;


                #endregion



                Console.WriteLine(string.Format("{0},{1},{2},{3},{4},{5}", m, width, thickness, l1, l2, l3));

                #region geometrie
                Console.WriteLine("Start creating new Germetrie");

                try
                {
                    swModel = swApp.NewPart();
                }
                catch (Exception)
                {
                    Console.WriteLine("starting SolidWorks");
                    try
                    {
                        swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application");
                    }
                    catch (Exception)
                    {
                        swApp         = new SldWorks();
                        swApp.Visible = false;
                    }

                    //get MaterialLib
                    strMaterialLib = swApp.GetExecutablePath() + "\\lang\\english\\sldmaterials\\solidworks materials.sldmat";

                    Console.WriteLine("SolidWorks successfully started");
                    j--;
                    continue;
                }

                swModel.Extension.SelectByID("前视基准面", "PLANE", 0, 0, 0, false, 1, null);
                swModel.InsertSketch2(true);
                #region sketch
                for (int i = 0; i < m; i++)
                {
                    if (i == 0)
                    {
                        swModel.SketchManager.CreateLine(0, 0, 0, l1 - width, 0, 0);
                        swModel.SketchManager.CreateLine(l1 - width, 0, 0, l1 - width, -l2, 0);
                        swModel.SketchManager.CreateLine(l1 - width, -l2, 0, l1 + l3 - width, -l2, 0);
                        swModel.SketchManager.CreateLine(l1 + l3 - width, -l2, 0, l1 + l3 - width, 0, 0);

                        swModel.SketchManager.CreateLine(0, 0, 0, 0, -width, 0);
                        swModel.SketchManager.CreateLine(0, -width, 0, l1_, -width, 0);
                        swModel.SketchManager.CreateLine(l1_, -width, 0, l1_, -(width + l2_), 0);
                        swModel.SketchManager.CreateLine(l1_, -(width + l2_), 0, l1_ + l3_, -(width + l2_), 0);
                        swModel.SketchManager.CreateLine(l1_ + l3_, -(width + l2_), 0, l1_ + l3_, -width, 0);
                    }
                    else
                    {
                        x_o  = i * cell_length - width;
                        y_o  = 0;
                        x_o_ = x_o + width;
                        y_o_ = y_o - width;

                        swModel.SketchManager.CreateLine(x_o, y_o, 0, x_o + l1, 0, 0);
                        swModel.SketchManager.CreateLine(x_o + l1, 0, 0, x_o + l1, -l2, 0);
                        swModel.SketchManager.CreateLine(x_o + l1, -l2, 0, x_o + l1 + l3, -l2, 0);
                        swModel.SketchManager.CreateLine(x_o + l1 + l3, -l2, 0, x_o + l1 + l3, 0, 0);

                        swModel.SketchManager.CreateLine(x_o_, y_o_, 0, x_o_ + l1_, y_o_, 0);
                        swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_, 0, x_o_ + l1_, y_o_ - l2_, 0);
                        swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_ - l2_, 0);
                        swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_, 0);
                    }
                }
                swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_, 0, x_o_ + l1_ + l3_, 0, 0);
                swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, 0, 0, x_o + l1 + l3, 0, 0);

                #endregion
                swModel.FeatureManager.FeatureExtrusion2(
                    true, false, false, 0, 0, thickness, 0, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, true
                    );

                swModel.SaveAsSilent("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\Geometrie.sldprt", true);
                swApp.CloseAllDocuments(true);
                swApp.OpenDoc("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\Geometrie.sldprt", (int)swOpenDocOptions_e.swOpenDocOptions_Silent);
                Console.WriteLine("Geometrie success");


                #endregion

                #region simulaiton
                string path_to_cosworks_dll = @"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\Simulation\cosworks.dll";
                errors       = swApp.LoadAddIn(path_to_cosworks_dll);
                COSMOSObject = (CwAddincallback)swApp.GetAddInObject("SldWorks.Simulation");
                try
                {
                    COSMOSWORKS = (CosmosWorks)COSMOSObject.CosmosWorks;
                }
                catch (Exception)
                {
                    Console.WriteLine("something wrong in Simulaiton Add In, start a new one");
                    continue;
                }


                COSMOSWORKS = COSMOSObject.CosmosWorks;
                //Get active document
                ActDoc = (CWModelDoc)COSMOSWORKS.ActiveDoc;

                //Create new static study
                StudyMngr = (CWStudyManager)ActDoc.StudyManager;
                Study     = (CWStudy)StudyMngr.CreateNewStudy("static study", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeStatic, 0, out errCode);

                //Add materials
                SolidMgr  = Study.SolidManager;
                SolidComp = SolidMgr.GetComponentAt(0, out errCode);
                SolidBody = SolidComp.GetSolidBodyAt(0, out errCode);
                intStatus = SolidBody.SetLibraryMaterial(strMaterialLib, "AISI 1020");

                //fixed restraints
                LBCMgr = Study.LoadsAndRestraintsManager;

                swModel = (ModelDoc2)swApp.ActiveDoc;
                swModel.ShowNamedView2("", (int)swStandardViews_e.swIsometricView);

                selectionMgr = (SelectionMgr)swModel.SelectionManager;
                isSelected   = swModel.Extension.SelectByID2("", "FACE", 0, -width / 2.0, thickness / 2.0, false, 0, null, 0);
                if (isSelected)
                {
                    object      selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1);
                    object[]    fixedFaces   = { selectedFace };
                    CWRestraint restraint    = (CWRestraint)LBCMgr.AddRestraint((int)swsRestraintType_e.swsRestraintTypeFixed, fixedFaces, null, out errCode);
                }
                swModel.ClearSelection2(true);

                //add force
                selectionMgr = (SelectionMgr)swModel.SelectionManager;
                isSelected   = swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + (width / 2.0), 0, thickness / 2.0, false, 0, null, 0);
                if (isSelected)
                {
                    object   selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1);
                    object[] forceAdd     = { selectedFace };
                    selectionMgr = (SelectionMgr)swModel.SelectionManager;
                    swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + width, -(l4 + width) / 2.0, thickness / 2.0, false, 0, null, 0);
                    object   selectedFaceToForceDir = (object)selectionMgr.GetSelectedObject6(1, -1);
                    double[] distValue  = null;
                    double[] forceValue = null;
                    double[] Force      = { F2, F3, F1 };
                    cwForce = (CWForce)LBCMgr.AddForce3((int)swsForceType_e.swsForceTypeForceOrMoment, (int)swsSelectionType_e.swsSelectionFaceEdgeVertexPoint,
                                                        2, 0, 0, 0,
                                                        (distValue),
                                                        (forceValue),
                                                        false, true,
                                                        (int)swsBeamNonUniformLoadDef_e.swsTotalLoad,
                                                        0, 7, 0.0,
                                                        Force,
                                                        false, false,
                                                        (forceAdd),
                                                        (selectedFaceToForceDir),
                                                        false, out errCode); //i have tried to figure out these arguments for one day, keep them and dont't change them.
                                                                             //the way to check cwForce : cwForce.GetForceComponentValues()
                                                                             //ForceComponet: [int b1, // 1 if x-direction hat Force-komponent, else 0
                                                                             //                int b2, // 1 if y-direction hat Force-komponent, else 0
                                                                             //                int b3, // 1 if z-direction hat Force-komponent, else 0
                                                                             //                double d1, // Force-komponent in x
                                                                             //                double d2, // Force-komponent in y
                                                                             //                double d3 // Force-komponent in z
                                                                             //                          ]
                                                                             //PS: the definition of xyz seems like not the same as the global XYZ system in SW.
                    swModel.ClearSelection2(true);

                    //meshing
                    CWMesh CWMeshObj = default(CWMesh);
                    CWMeshObj            = Study.Mesh;
                    CWMeshObj.MesherType = (int)swsMesherType_e.swsMesherTypeStandard;
                    CWMeshObj.Quality    = (int)swsMeshQuality_e.swsMeshQualityDraft;
                    errCode   = Study.CreateMesh(0, MeshEleSize, MeshTol);
                    CWMeshObj = null;

                    //run analysis
                    errCode = Study.RunAnalysis();
                    if (errCode != 0)
                    {
                        Console.WriteLine(string.Format("RunAnalysis errCode = {0}", errCode));
                        Console.WriteLine(string.Format("RunAnalysis failed"));



                        swApp.CloseAllDocuments(true);
                        errors = swApp.UnloadAddIn(path_to_cosworks_dll);
                        Console.WriteLine(string.Format("ready to start a new one"));
                        continue;
                    }
                    Console.WriteLine("RunAnalysis successed, ready to get results");

                    //get results
                    CWFeatobj = Study.Results;
                    //get max von Mieses stress
                    Stress = (object[])CWFeatobj.GetMinMaxStress((int)swsStressComponent_e.swsStressComponentVON,
                                                                 0, 0, null,
                                                                 (int)swsStrengthUnit_e.swsStrengthUnitNewtonPerSquareMillimeter,
                                                                 out errCode);
                    maxStress = (float)Stress[3]; //Stress: {node_with_minimum_stress, minimum_stress, node_with_maximum_stress, maximum_stress}
                    Console.WriteLine(maxStress);

                    /*
                     * if (maxStress >= 351.6)
                     * {
                     *  Console.WriteLine("out of yield stress, start a new example");
                     *  errors = swApp.UnloadAddIn(path_to_cosworks_dll);
                     *  swApp.CloseAllDocuments(true);
                     *  j--;
                     *  continue;
                     * }
                     */
                    //get max URES displacement
                    Disp = (object[])CWFeatobj.GetMinMaxDisplacement((int)swsDisplacementComponent_e.swsDisplacementComponentURES,
                                                                     0, null,
                                                                     (int)swsLinearUnit_e.swsLinearUnitMillimeters,
                                                                     out errCode);
                    maxDisp   = (float)Disp[3]; //Disp: {node_with_minimum_displacement, minimum_displacement, node_with_maximum_displacement, maximum_displacement}
                    CWFeatobj = null;
                    Console.WriteLine(string.Format("max Displacement: {0:f4} mm", maxDisp));


                    //output to Excel
                    exlSheet.Cells[j + 2, 1]  = m;
                    exlSheet.Cells[j + 2, 2]  = width * 1000;
                    exlSheet.Cells[j + 2, 3]  = thickness * 1000;
                    exlSheet.Cells[j + 2, 4]  = l1 * 1000;
                    exlSheet.Cells[j + 2, 5]  = l2 * 1000;
                    exlSheet.Cells[j + 2, 6]  = l3 * 1000;
                    exlSheet.Cells[j + 2, 7]  = F1;
                    exlSheet.Cells[j + 2, 8]  = F2;
                    exlSheet.Cells[j + 2, 9]  = F3;
                    exlSheet.Cells[j + 2, 10] = maxStress;
                    exlSheet.Cells[j + 2, 11] = maxDisp;
                    if (j % 5 == 0)
                    {
                        exlBook.Save();//C:\Users\Zhao\Documents\工作簿1.xlsx
                    }

                    errors = swApp.UnloadAddIn(path_to_cosworks_dll);
                    swApp.CloseAllDocuments(true);
                }
                #endregion
            }
            exlBook.SaveCopyAs("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_get_TrainingDaten\\W_Form_simulationDaten_" + GetTimeStamp() + "_F3=0" + ".xlsx");
            exlBook.Save();//C:\Users\zhaojie\Documents\工作簿1.xlsx
            exlApp.Quit();
        }
        private void Button_generateFEM_Click(object sender, RoutedEventArgs e)
        {
            #region Variable definition

            int              m;     //how many cells
            int              Count; // how many data
            double           width, thickness, l1, l2, l3, F1, F2, F3;
            double           l4, l1_, l2_, l3_, l4_, cell_length, cell_height;
            double           x_o            = 0.0;
            double           y_o            = 0.0;
            double           x_o_           = 0.0;
            double           y_o_           = 0.0;
            const double     MeshEleSize    = 2.0;
            const double     MeshTol        = 0.1;
            string           strMaterialLib = null;
            object[]         Disp           = null;
            object[]         Stress         = null;
            ModelDoc2        swModel        = null;
            SelectionMgr     selectionMgr   = null;
            CosmosWorks      COSMOSWORKS    = null;
            CwAddincallback  COSMOSObject   = default(CwAddincallback);
            CWModelDoc       ActDoc         = default(CWModelDoc);
            CWStudyManager   StudyMngr      = default(CWStudyManager);
            CWStudy          Study          = default(CWStudy);
            CWSolidManager   SolidMgr       = default(CWSolidManager);
            CWSolidBody      SolidBody      = default(CWSolidBody);
            CWSolidComponent SolidComp      = default(CWSolidComponent);


            CWForce cwForce = default(CWForce);
            CWLoadsAndRestraintsManager LBCMgr = default(CWLoadsAndRestraintsManager);
            CWResults CWFeatobj = default(CWResults);
            bool      isSelected;
            float     maxDisp   = 0.0f;
            float     maxStress = 0.0f;
            int       intStatus = 0;
            int       errors    = 0;
            int       errCode   = 0;
            int       warnings  = 0;



            int ran_m, ran_width, ran_thickness, ran_l1, ran_l2, ran_l3, ran_F1, ran_F2, ran_F3;
            Excel.Application exlApp;
            Excel.Workbook    exlBook;
            Excel.Worksheet   exlSheet;



            #endregion

            #region read data from UI
            try
            {
                m         = int.Parse(textBox_hm_cells.Text);
                width     = double.Parse(textBox_width.Text) / 1000.0;
                thickness = double.Parse(textBox_thickness.Text) / 1000.0;
                l1        = double.Parse(textBox_l1.Text) / 1000.0;
                l2        = double.Parse(textBox_l2.Text) / 1000.0;
                l3        = double.Parse(textBox_l3.Text) / 1000.0;
                F1        = double.Parse(textBox_F1.Text);
                F2        = double.Parse(textBox_F2.Text);
                F3        = double.Parse(textBox_F3.Text);
            }
            catch (Exception)
            {
                MessageBox.Show("input format error, check input data");
                return;
            }

            l4          = l2;
            l1_         = l1 - 2 * width;
            l2_         = l2;
            l3_         = l3 + 2 * width;
            l4_         = l4;
            cell_length = l1 + l3;
            cell_height = l2 + width;
            #endregion

            #region geometrie
            Console.WriteLine("Start creating new Germetrie");
            swModel = swApp.NewPart();
            swModel.Extension.SelectByID("前视基准面", "PLANE", 0, 0, 0, false, 1, null);
            swModel.InsertSketch2(true);
            #region sketch
            for (int i = 0; i < m; i++)
            {
                if (i == 0)
                {
                    swModel.SketchManager.CreateLine(0, 0, 0, l1 - width, 0, 0);
                    swModel.SketchManager.CreateLine(l1 - width, 0, 0, l1 - width, -l2, 0);
                    swModel.SketchManager.CreateLine(l1 - width, -l2, 0, l1 + l3 - width, -l2, 0);
                    swModel.SketchManager.CreateLine(l1 + l3 - width, -l2, 0, l1 + l3 - width, 0, 0);

                    swModel.SketchManager.CreateLine(0, 0, 0, 0, -width, 0);
                    swModel.SketchManager.CreateLine(0, -width, 0, l1_, -width, 0);
                    swModel.SketchManager.CreateLine(l1_, -width, 0, l1_, -(width + l2_), 0);
                    swModel.SketchManager.CreateLine(l1_, -(width + l2_), 0, l1_ + l3_, -(width + l2_), 0);
                    swModel.SketchManager.CreateLine(l1_ + l3_, -(width + l2_), 0, l1_ + l3_, -width, 0);
                }
                else
                {
                    x_o  = i * cell_length - width;
                    y_o  = 0;
                    x_o_ = x_o + width;
                    y_o_ = y_o - width;

                    swModel.SketchManager.CreateLine(x_o, y_o, 0, x_o + l1, 0, 0);
                    swModel.SketchManager.CreateLine(x_o + l1, 0, 0, x_o + l1, -l2, 0);
                    swModel.SketchManager.CreateLine(x_o + l1, -l2, 0, x_o + l1 + l3, -l2, 0);
                    swModel.SketchManager.CreateLine(x_o + l1 + l3, -l2, 0, x_o + l1 + l3, 0, 0);

                    swModel.SketchManager.CreateLine(x_o_, y_o_, 0, x_o_ + l1_, y_o_, 0);
                    swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_, 0, x_o_ + l1_, y_o_ - l2_, 0);
                    swModel.SketchManager.CreateLine(x_o_ + l1_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_ - l2_, 0);
                    swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_ - l2_, 0, x_o_ + l1_ + l3_, y_o_, 0);
                }
            }
            swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, y_o_, 0, x_o_ + l1_ + l3_, 0, 0);
            swModel.SketchManager.CreateLine(x_o_ + l1_ + l3_, 0, 0, x_o + l1 + l3, 0, 0);

            #endregion
            swModel.FeatureManager.FeatureExtrusion2(
                true, false, false, 0, 0, thickness, 0, false, false, false, false, 0, 0, false, false, false, false, true, true, true, 0, 0, true
                );

            swModel.SaveAsSilent("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_FEM_NN_GUI\\Geometrie.sldprt", true);
            swApp.CloseAllDocuments(true);
            swApp.OpenDoc("D:\\TUD\\7.Semeter\\SA\\SA_code\\c#\\W_Form_analyse_FEM_NN_GUI\\Geometrie.sldprt", (int)swOpenDocOptions_e.swOpenDocOptions_Silent);
            Console.WriteLine("Geometrie success");


            #endregion

            #region simulaiton
            string path_to_cosworks_dll = @"C:\Program Files\SOLIDWORKS Corp\SOLIDWORKS\Simulation\cosworks.dll";
            errors       = swApp.LoadAddIn(path_to_cosworks_dll);
            COSMOSObject = (CwAddincallback)swApp.GetAddInObject("SldWorks.Simulation");
            try
            {
                COSMOSWORKS = (CosmosWorks)COSMOSObject.CosmosWorks;
            }
            catch (Exception)
            {
                Console.WriteLine("something wrong in Simulaiton Add In, start a new one");
                swApp.CloseAllDocuments(true);

                return;
            }


            COSMOSWORKS = COSMOSObject.CosmosWorks;
            //Get active document
            ActDoc = (CWModelDoc)COSMOSWORKS.ActiveDoc;

            //Create new static study
            StudyMngr = (CWStudyManager)ActDoc.StudyManager;
            Study     = (CWStudy)StudyMngr.CreateNewStudy("static study", (int)swsAnalysisStudyType_e.swsAnalysisStudyTypeStatic, 0, out errCode);

            //Add materials
            //get MaterialLib
            strMaterialLib = swApp.GetExecutablePath() + "\\lang\\english\\sldmaterials\\solidworks materials.sldmat";
            SolidMgr       = Study.SolidManager;
            SolidComp      = SolidMgr.GetComponentAt(0, out errCode);
            SolidBody      = SolidComp.GetSolidBodyAt(0, out errCode);
            intStatus      = SolidBody.SetLibraryMaterial(strMaterialLib, "AISI 1020");

            //fixed restraints
            LBCMgr = Study.LoadsAndRestraintsManager;

            swModel = (ModelDoc2)swApp.ActiveDoc;
            swModel.ShowNamedView2("", (int)swStandardViews_e.swIsometricView);

            selectionMgr = (SelectionMgr)swModel.SelectionManager;
            isSelected   = swModel.Extension.SelectByID2("", "FACE", 0, -width / 2.0, thickness / 2.0, false, 0, null, 0);
            if (isSelected)
            {
                object      selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1);
                object[]    fixedFaces   = { selectedFace };
                CWRestraint restraint    = (CWRestraint)LBCMgr.AddRestraint((int)swsRestraintType_e.swsRestraintTypeFixed, fixedFaces, null, out errCode);
            }
            swModel.ClearSelection2(true);

            //add force
            selectionMgr = (SelectionMgr)swModel.SelectionManager;
            isSelected   = swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + (width / 2.0), 0, thickness / 2.0, false, 0, null, 0);
            if (isSelected)
            {
                object   selectedFace = (object)selectionMgr.GetSelectedObject6(1, -1);
                object[] forceAdd     = { selectedFace };
                selectionMgr = (SelectionMgr)swModel.SelectionManager;
                swModel.Extension.SelectByID2("", "FACE", x_o + l1 + l3 + width, -(l4 + width) / 2.0, thickness / 2.0, false, 0, null, 0);
                object   selectedFaceToForceDir = (object)selectionMgr.GetSelectedObject6(1, -1);
                double[] distValue  = null;
                double[] forceValue = null;
                double[] Force      = { F2, F3, F1 };
                cwForce = (CWForce)LBCMgr.AddForce3((int)swsForceType_e.swsForceTypeForceOrMoment, (int)swsSelectionType_e.swsSelectionFaceEdgeVertexPoint,
                                                    2, 0, 0, 0,
                                                    (distValue),
                                                    (forceValue),
                                                    false, true,
                                                    (int)swsBeamNonUniformLoadDef_e.swsTotalLoad,
                                                    0, 7, 0.0,
                                                    Force,
                                                    false, false,
                                                    (forceAdd),
                                                    (selectedFaceToForceDir),
                                                    false, out errCode); //i have tried to figure out these arguments for one day, keep them and dont't change them.
                                                                         //the way to check cwForce : cwForce.GetForceComponentValues()
                                                                         //ForceComponet: [int b1, // 1 if x-direction hat Force-komponent, else 0
                                                                         //                int b2, // 1 if y-direction hat Force-komponent, else 0
                                                                         //                int b3, // 1 if z-direction hat Force-komponent, else 0
                                                                         //                double d1, // Force-komponent in x
                                                                         //                double d2, // Force-komponent in y
                                                                         //                double d3 // Force-komponent in z
                                                                         //                          ]
                                                                         //PS: the definition of xyz seems like not the same as the global XYZ system in SW.
                swModel.ClearSelection2(true);

                //meshing
                CWMesh CWMeshObj = default(CWMesh);
                CWMeshObj            = Study.Mesh;
                CWMeshObj.MesherType = (int)swsMesherType_e.swsMesherTypeStandard;
                CWMeshObj.Quality    = (int)swsMeshQuality_e.swsMeshQualityDraft;
                errCode   = Study.CreateMesh(0, MeshEleSize, MeshTol);
                CWMeshObj = null;

                //run analysis
                errCode = Study.RunAnalysis();
                if (errCode != 0)
                {
                    Console.WriteLine(string.Format("RunAnalysis errCode = {0}", errCode));
                    Console.WriteLine(string.Format("RunAnalysis failed"));

                    errors = swApp.UnloadAddIn(path_to_cosworks_dll);
                    swApp.CloseAllDocuments(true);
                    Console.WriteLine(string.Format("please start a new one"));
                    return;
                }
                Console.WriteLine("RunAnalysis successed, ready to get results");

                //get results
                CWFeatobj = Study.Results;
                //get max von Mieses stress
                Stress = (object[])CWFeatobj.GetMinMaxStress((int)swsStressComponent_e.swsStressComponentVON,
                                                             0, 0, null,
                                                             (int)swsStrengthUnit_e.swsStrengthUnitNewtonPerSquareMillimeter,
                                                             out errCode);
                maxStress = (float)Stress[3]; //Stress: {node_with_minimum_stress, minimum_stress, node_with_maximum_stress, maximum_stress}
                Console.WriteLine(maxStress);
                if (maxStress >= 351.6)
                {
                    Console.WriteLine("out of yield stress, start a new example");
                    errors = swApp.UnloadAddIn(path_to_cosworks_dll);
                    swApp.CloseAllDocuments(true);
                    textBox_FEM_result.Text = "out of yield stress";
                    return;
                }
                //get max URES displacement
                Disp = (object[])CWFeatobj.GetMinMaxDisplacement((int)swsDisplacementComponent_e.swsDisplacementComponentURES,
                                                                 0, null,
                                                                 (int)swsLinearUnit_e.swsLinearUnitMillimeters,
                                                                 out errCode);
                maxDisp   = (float)Disp[3]; //Disp: {node_with_minimum_displacement, minimum_displacement, node_with_maximum_displacement, maximum_displacement}
                CWFeatobj = null;
                Console.WriteLine(string.Format("max Displacement: {0:f4} mm", maxDisp));
                textBox_FEM_result.Text = maxDisp.ToString();
            }
            else
            {
                Console.WriteLine("not selected");
            }
            #endregion
            errors = swApp.UnloadAddIn(path_to_cosworks_dll);
            swApp.CloseAllDocuments(true);
        }
示例#6
0
文件: Form1.cs 项目: a-vodka/ics
        private void button1_Click(object sender, EventArgs e)
        {
            SldWorks sw = new SldWorks();

            sw.Visible = true;
            int       err = 0, war = 0;
            ModelDoc2 swModel = sw.OpenDoc6(Application.StartupPath + "\\beam.sldprt", 1, 0, "", ref err, ref war);

            double a  = Convert.ToDouble(textBox1.Text);
            double b  = Convert.ToDouble(textBox2.Text);
            double l  = Convert.ToDouble(textBox3.Text);
            double E  = Convert.ToDouble(textBox4.Text);
            double nu = Convert.ToDouble(textBox5.Text);
            double q  = Convert.ToDouble(textBox6.Text);

            if (pictureBox1.Image != null)
            {
                pictureBox1.Image.Dispose();
                pictureBox1.Image = null;
//                pictureBox1.Load();
                pictureBox1.Update();
                pictureBox1.Invalidate();
            }

            if (pictureBox2.Image != null)
            {
                pictureBox2.Image.Dispose();
                pictureBox2.Image = null;
                //                pictureBox1.Load();
                pictureBox2.Update();
                pictureBox2.Invalidate();
            }



            double sigma = 3 * q * l * l / b / b / 1e6;

            label8.Text = sigma.ToString();

            swModel.Parameter("D1@Эскиз1").Value            = a * 1e3;
            swModel.Parameter("D2@Эскиз1").Value            = b * 1e3;
            swModel.Parameter("D1@Бобышка-Вытянуть1").Value = l * 1e3;

            swModel.EditRebuild3();
            swModel.ViewZoomtofit2();

            CwAddincallback COSMOSObject = (CwAddincallback)sw.GetAddInObject("SldWorks.Simulation");
            ICosmosWorks    cw           = (ICosmosWorks)COSMOSObject.CosmosWorks;

            CWModelDoc     ActDoc    = cw.ActiveDoc;
            CWStudyManager StudyMngr = ActDoc.StudyManager;
            CWStudy        Study     = StudyMngr.GetStudy(0); // 0 - номер уже созданного расчета

            CWSolidManager SolidMgr  = Study.SolidManager;
            int            CompCount = SolidMgr.ComponentCount; // кол-во деталей в расчете
            int            errorCode = 0;

            for (int i = 0; i < CompCount; i++) // Присваеваем свойства материала
            {
                CWSolidComponent SolidComponent = SolidMgr.GetComponentAt(i, out errorCode);
                CWSolidBody      SolidBody      = SolidComponent.GetSolidBodyAt(0, out errorCode);
                CWMaterial       CWMat          = SolidBody.GetSolidBodyMaterial();
                CWMat.MaterialUnits = 0;
                CWMat.MaterialName  = "Alloy Steel";
                CWMat.SetPropertyByName("EX", E, 0);
                CWMat.SetPropertyByName("NUXY", nu, 0);
                SolidBody.SetSolidBodyMaterial(CWMat);
                SolidBody = null;
            }

            CWLoadsAndRestraintsManager LBCMgr = Study.LoadsAndRestraintsManager;

            for (int i = 0; i < LBCMgr.Count; i++)
            {
                CWLoadsAndRestraints CWP = LBCMgr.GetLoadsAndRestraints(i, out errorCode);
                if (CWP.Type == 1) // давление
                {
                    CWPressure CWPressure = (CWPressure)CWP;
                    CWPressure.PressureBeginEdit();
                    CWPressure.Unit  = 3;
                    CWPressure.Value = q;
                    CWPressure.PressureEndEdit();
                }
            }

            double esize = 0, dtol = 0;
            CWMesh CwMesh = Study.Mesh; // Remesh geometry

            CwMesh.Quality = 1;
            CwMesh.GetDefaultElementSizeAndTolerance(0, out esize, out dtol);
            Study.CreateMesh(0, esize, dtol);

            errorCode = Study.RunAnalysis(); // Run analysis

            ModelDocExtension swModelDocExt = swModel.Extension;

            CWResults CWResult = Study.Results; // Get results

            ActDoc.DeleteAllDefaultStaticStudyPlots();

            //Create displacement plot
            CWPlot CWCFf = CWResult.CreatePlot((int)swsPlotResultTypes_e.swsResultDisplacementOrAmplitude, (int)swsStaticResultDisplacementComponentTypes_e.swsStaticDisplacement_URES, (int)swsUnit_e.swsUnitSI, false, out err);

            //Activate plot
            err = CWCFf.ActivatePlot();

            //Get min/max resultant displacements from plot
            object[] Disp = (object[])CWCFf.GetMinMaxResultValues(out err);

            double MinDisp = Convert.ToDouble(Disp[1]);
            double MaxDisp = Convert.ToDouble(Disp[3]);

            swModelDocExt.SaveAs(Application.StartupPath + "\\Displacement.analysis.jpg", 0, 0, null, ref err, ref war);

            //Create stress plot
            CWCFf = CWResult.CreatePlot((int)swsPlotResultTypes_e.swsResultStress, (int)swsStaticResultNodalStressComponentTypes_e.swsStaticNodalStress_VON, (int)swsUnit_e.swsUnitSI, false, out err);

            //Get min/max von Mises stresses from plot
            object[] Stress = (object[])CWCFf.GetMinMaxResultValues(out err);

            double MinStress = Convert.ToDouble(Stress[1]);
            double MaxStress = Convert.ToDouble(Stress[3]);

            swModelDocExt.SaveAs(Application.StartupPath + "\\vmStress.analysis.jpg", 0, 0, null, ref err, ref war);


            pictureBox1.Image = System.Drawing.Image.FromFile(Application.StartupPath + "\\vmStress.analysis.jpg");
            pictureBox2.Image = System.Drawing.Image.FromFile(Application.StartupPath + "\\Displacement.analysis.jpg");

            label10.Text = (MaxStress / 1e6).ToString();
        }