This SolidWorks World 2010 presentation by Paul Gimbel from Razorleaf Corporation explores using the SolidWorks API and the tools available within SolidWorks and SolidWorks Simulation to validate automatically generated, and manually configured designs.
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automated Design Validation The Solid Works Api
1. Automated Design Validation with the SolidWorks API Paul Gimbel, Business Process Sherpa Razorleaf Corporation
2. What You Will Hear In This Session Automating SolidWorks Simulation programmatically BUT THAT’S NOT IT Tools within SolidWorks to do design validations This an ADVANCED session Assumes that you know SolidWorks user interface Assumes that you know the basics of SolidWorks API programming ALL CODE EXAMPLES IN VB.NET Presentation will be available at www.razorleaf.com
3. Who Is This Guy and Where Did He Come From? Razorleaf Corporation SolidWorks Service Partner Services ONLY (we’re not trying to sell you anything, we’re neutral) Data Management (EPDM, SmarTeam, Aras) Design Automation (DriveWorks, Tacton) Workflow Automation (Microsoft SharePoint and Tools) Paul Gimbel (aka “The Sherpa”) 10+ years as Demo Jock, Applications Engineer, Trainer, Support Tech 5 years as Design Automation Implementer Specializing in SolidWorks, DriveWorks, Tacton, Custom Programming (THERE! Now I can report this trip as reimbursable.) The Sherpa
4. What is Design Validation? Ensuring that the suggested design meets requirements Form/Fit/Function Durability Weight Performance Manufacturability Maintenanceability Packaging/Shipping Limitations And so on… It’s more than just fea!!
5. What Forms Can Validation Take? Equations The most accurate method to determine values Can be difficult to apply to complex geometries Code Calculations Many have to meet and publish them…it’s the law Simulation Iterative Prototype Digital Somewhat time consuming Physical Expensive and time consuming Lesson from Programming: Rule out the easy stuff before you start sucking up CPU.
6. How Does This Work With Design Automation? Frequent Goal of Design Automation Allow NON-SolidWorks USERS to design/configure valid products Therefore: Cannot use any interactive tools Methods must not require SolidWorks on their machine May use a 3rd party solution
41. Measure Tool Separate Measure object - swDoc.Extension.CreateMeasure Must use Measure.CALCULATE(object) If Object Is Nothing, SolidWorks will use the current selection set Alternatively, you can use the Selection Manager object Set options before you call the calculate method Returns are fairly specific DimswMeasAs Measure = Ctype(swDoc.Extension.CreateMeasure, Measure) swMeas.ArcOption = _ swMeasureArcCircleOption_e.swMeasureArcCircle_MinimumDistance swMeas.Calculate(Nothing) MsgBox(swMeas.Distance) Don’t forget to test all objects and results! Check out the options here
43. Section Properties Requires an Array of FACE or SKETCH object as input ModelDoc2.Extension.GetSectionProperties2(objSections) Returns a 24 item array Need to look up which index corresponds to what you’re interested in Use API Help topic IGetSectionProperties2 Clumsy throwback to VBA DimswSelMgrAsSelectionMgr = swDoc.SelectionManager DimswFaceAs Face = swSelMgr.GetSelectedObject6(0, 0) DimswSectionProps(23) AsDouble swSectionProps = swDoc.Extension.GetSectionProperties2(swFace) MsgBox("Area (index 1) = " & swSectionProps(1)) Don’t forget to test all objects and results!
55. Working with Sensors in Code Get the sensor object from the Sensor Feature (use MD2.GetFirstFeature) DimswSensorAsSensor = swFeature.GetSpecificFeature2 Critical sensor properties and methods SelectCaseswSensor.SensorType CaseswSensorType_e.swSensorSimulation CaseswSensorType_e.swSensorMassProperty CaseswSensorType_e.swSensorDimension CaseswSensorType_e.swSensorInterfaceDetection EndSelect Be sure to Update the sensor with the UpdateSensor method Check the AlertState to see if the sensor has picked up on a problem Use the AlertType to see what kind of a problem SW2009 SP2 and before only supported Dimension Sensors
56. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger)AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify Note who your event belongs to Check out all available events in API Help
57. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger) AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify (Don’t think you can ignore me) Note who your event belongs to Check out all available events in API Help
58. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger) AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify (I’m not going away) Note who your event belongs to Check out all available events in API Help
59. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger) AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify (I’m not going away) Note who your event belongs to Check out all available events in API Help
60. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger) AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify (Keep it up. Your iPhone is next.) Note who your event belongs to Check out all available events in API Help
61. Using SolidWorks Events Create a class Declare a variable WITHEVENTS for the object that holds your events PublicWithEventsswPartAsSolidWorks.interop.sldworks.PartDoc Create a Function for whatever event you want to monitor FunctionswPart_SensorAlertPreNotify(ByValswSensorAsObject, ByVal _ SensorAlertTypeAsInteger) AsInteger Shell("http://www.twitter.com/?'#SW Sensor!'", AppWinStyle.Hide, False) EndFunction 'swPart_SensorAlertPreNotify In your main code – Activate the handler (RemoveHandler to discontinue) AddHandlerswPart.SensorAlertPreNotify, AddressOf _ Me.swPart_SensorAlertPreNotify Fine! I’ll do it myself. Rebooting in: Note who your event belongs to Check out all available events in API Help
62. Applying Update 1 of 9,278,029….0% Complete Do Not Turn Off Computer
63. Applying Update 1 of 9,278,029….0.001% Complete Don’t Even Think About It. I’ll restart when I’m good and ready.
67. Automating SolidWorks Simulation Evaluate what you are trying to automate Can it be done with sensors? Can it be done with Optimization? Not all of SolidWorks Simulation is documented in API Help Extra SDKs or Installation options may be required (ex. Flow)
68. Gimme an S, Gimme an R, Gimme an A, Gimme a C! Must add SolidWorks 2010 Simulation Type Library as a reference to each project You can also add SolidWorks.Interop.cosworks.dll You will need to BROWSE for it …SolidWorksPIedist (cosworks? There’s your proof that all the product renames are marketing)
69. Possible Applications Record iterative results Run iterations and send results out to Excel or other system Allow code or outside tool control when to iterate and how
70. Possible Applications Attach / create / modify study components (loads, connections, etc.) Create 400 pin locations in a regular (or slightly irregular) array Create an unknown number of loads based on driven geometry Allow 3rd party solutions to kick off simulation as part of automation More complex iterative optimizations using your own optimization algorithm Change what YOU want to change, how YOU want to change it
72. RMB in the Project Explorer to add a Reference You will not find it in the .NET tab You MAY find it under COM You will most likely need to browse for it Adding The Reference
73. The Process Fetch the SolidWorks Simulation (CosmosWorks) Add-In object DimcwAddInAsSolidWorks.interop.cosworks.CWAddInCallBack = _ swApp.GetAddInObject("CosmosWorks.CosmosWorks") Fetch the cwModelDoc DimCWorksAsObject = cwAddIn.CosmosWorks DimcwDocAsCWModelDoc = Ctype(CWorks.ActiveDoc(), CWModelDoc) Fetch the CWStudyManager object DimcwStudyMgrAsCWStudyManager = cwDoc.StudyManager() Imports SolidWorks.interop.cosworksis implied
74. More of The Process Fetch the CWStudy object Test for study existence with StudyCount DimcwStudyCountAsInteger = cwStudyMgr.StudyCount DimcwCurStudyAsCWStudy Dim iErrors As Integer IFcwStudyCount > 0 Then cwCurStudy = CWStudyManager.GetStudy(0) Else cwCurStudy = CWStudyManager.CreateNewStudy2 _ (“StudyName”, type, iErrors) EndIf TIP: Don’t create studies when you can preset and drive them Imports SolidWorks.interop.cosworksis implied
75. Add Material Need to apply the material to the Solid Body Object Study gets the SolidManager SolidManager gets the SolidComponent SolidComponent gets the SolidBody Circle gets the square DimcwSolidMgrAsCosmosWorksLib.CWSolidManager cwSolidMgr = cwCurStudy.SolidManager DimCompCountAsInteger = cwSolidMgr.ComponentCount DimcwCompAsCWSolidComponent = cwSolidMgr.GetComponentAt(0, cwStudyErrors) DimcwBodyAsCWSolidBody = cwComp.GetSolidBodyAt(0, cwStudyErrors) cwStudyErrors = cwBody.SetLibraryMaterial("M:yMatlLibLMatl.sldmatlib", "Unobtainium")
76. Even More of The Process All ReadOnly!! Get the next Manager or Options object All properties and options reside one level down DimcwStaticOptionsAsCWStaticStudyOptions cwStaticOptions = cwCurStudy.StaticStudyOptions cwStaticOptions.SolverType = _ CosmosWorksLib.swsSolverType_e.swsSolverTypeFFEPlus DimcwCurMeshAsCWMesh = cwCurStudy.Mesh cwCurMesh.Quality = _ CosmosWorksLib.swsMeshQuality_e.swsMeshQualityHigh Imports SolidWorks.interop.cosworksis implied
77. Even Still More of The Process Update components, mesh and run the analysis Update is for any geometry changes since last run 'We'll typically calculate or get these as inputs DimdElementSizeAsDouble = 0.0012 DimdToleranceAsDouble = 0.005 cwCurStudy.UpdateAllComponents() cwCurStudy.CreateMesh(CosmosWorksLib.swsUnit_e.swsUnitEnglish, _ dElementSize, dTolerance) cwCurStudy.RunAnalysis() Imports SolidWorks.interop.cosworksis implied
78. Mandatory Charts (Gratuitous Chart of Fictitious Data)(per Microsoft PowerPoint code 2009 Section XXIV Subsection 441.K.9.ii.v) Activities Past Midnight Reaction to Subtle Jokes In Slides by Demographic
79. Even Yet Still More of The Process Retrieve the Results object Most Results methods return arrays These are typically brought in with generic options DimcwCurResultsAsCWResults cwCurResults = cwCurStudy.Results Dim cwResultsErrors As Integer Dim cwStress As Object cwStress = cwCurResults.GetMinMaxStress _ (0, 0, 1, Nothing, 0, cwResultsErrors) Imports SolidWorks.interop.cosworksis implied
80. Dealing with Arrays Return types are VERY vague Always the possibility of a null return Most samples stay generic VBA dim as VARIANT VB.NET/C#.NET dim as OBJECT Run once or twice or check sample to find out return type Fetch as generic object then recast the variable to get the array ERROR TRAP THE SNOT OUT OF IT!!! Make separate functions wherever possible to use Try…Catch blocks Allows you to handle the errors differently
81. Array Sample TRY ‘Define as generic object DimcwStressAsObject ‘Retrieve the object cwStress = cwCurResults.GetMinMaxStress(0, 0, 1, Nothing, 0, cwResultErrors) IfcwStressIsNotNothing ‘Declare your array DimcwStressArray() AsDouble ‘Recast your generic object as an array cwStressArray = CType(cwStress, Double()) IfcwStressArray.Length > 0 Then ForEachdStressAsDoubleIncwStressArray NextdStress EndIf‘Array.Length > 0 EndIf‘we have a stress results object
82. Array Sample Catch ‘Handle the fact that we did not get usable stress results End Catch Try ‘Define as generic object DimcwDisplacementAsObject ‘Retrieve the object cwDisplacement = cwCurResults.GetMinMaxDisplacement(0, 0, Nothing, _ CosmosWorksLib.swsUnit_e.swsUnitEnglish, cwStudyErrors) IfcwDisplacementIsNotNothing ‘Declare your array DimcwDispArray() AsDouble ‘Recast your generic object as an array cwStressArray = CType(cwStress, Double()) And so on…
83. Getting Back Visual Results “A picture is worth a thousand lines of code” – Michaelangelo (…I think) The absolute most beneficial feature of automating simulations!!! API has the ability to activate plots, delete plots, and tell you how many there are and their names There appears to be no way to Save plots or animations out to files. End of slide
91. Questions? Comments? Suggestions? Soup Recipes? If you have questions you would like to discuss, please find me Now…At any time during the conference…or After the conference Presentation available on www.razorleaf.com Free newsletter with tech tips, industry insiders and more… Catch me in my upcoming tour dates!! Wednesday @ 1:30 – Automating Your Designs with Excel and the SW API Friday @ Miffy’s Muffin Palace – Drury Lane The Sherpa Paul Gimbel Business Process Sherpa Paul.Gimbel@razorleaf.com www.razorleaf.com TheProcesSherpa on Twitter
95. Let’s see if the SolidWorks folks read these:PLEASE PLEASEPLEASE fill out your survey It takes practically no time at all I HONESTLY want your feedback and I do apply it Let’s see if the SolidWorks folks read these: In the comments section, add: “OK, I’m stumped. How did he pull my card out of THERE?” SURVEY TIME!!!
Editor's Notes
I was a little worried about the title for this one. I tried to word it carefully, because when people hear design validation, they immediately think FEA. Are we going to cover SolidWorks Simulation, yes. We will, but we will also cover other stuff. This is listed as an advanced session because it does assume that you know SolidWorks and it assumes that you know your way around SolidWorks Simulation and it assumes that you understand the basics of the SolidWorks API. If you came to my session yesterday on the API, and you got it, then I think you should be fine as well. The presentation will be made available as quickly as I can on the Razorleaf web site.
Here’s the obligatory and cliché review of me and my company. Razorleaf is a services-only company providing implementation and customization, training and support for PDM including EPDM, SmarTeam, Aras, and Matrix, as well as Design Automation (that’s my specialty) including DriveWorks, Tacton, and custom solutions. As I said, services-only, so I won’t be trying to sell you anything, don’t worry.I am Paul Gimbel, known in the SolidWorks community as simply “The Sherpa.” I’ve been to every SolidWorks World, presented at quite a few of them. A trainer and demojock since the original, SolidWorks 95. So yes, I’m old, and starting to look it.
So let’s start out with a little bit of a philosophical question. What is design validation? Well, what I mean is ensuring that your design meets the requirements of the job. That could mean form/fit/function, it could mean that it meets minimum weight requirements, like a Tour de France bike, it lives up to performance requirements like the electric hot rod. The requirements could encompass any number of things. Not just will it break.
The first way that we were taught to validate is to use formulae. This is the most accurate way to determine values because there’s no approximation. If Roark’s guide to Stress and Strain says that beam will deflect f*h/4 at x/3 from the end, that’s what it’s going to do and where it’s going to do it. But we can’t always come up with an equation, especially for tough geometries. In a lot of industries, there are code calculations that must be met. When I was designing pressure vessels, we had to ship every unit with a copy of the calcs from Section VIII of the B&PV Code. Simulations can be used to validate. Iterations can be used to optimize. Digital Prototyping is the next level and physical prototyping after that. What we learn from programming, though, is don’t bother building a physical prototype and testing it if the standard calculations prove that it’s going to fail. So test early, and test often.
Now the other half of the title is Automating. As I said in my intro, I specialize in Design Automation with tools like Tacton and DriveWorks. In these cases, we are rarely interacting with SolidWorks. In most cases, we are having sales folks put info into a system that will have a server automate the design and solid model and 2D drawing construction. So in these cases, we cannot have anything interactive. We can’t have anything that requires the user to have SolidWorks. And in a lot of these cases, there may be a 3rd party product involved. But I’ll tell you right now, none of the design automation solutions that I know of are designed to give you the option to use any of the tools that I’m going to show you today.
So there are a bunch of different things that we can do that would fall under this validation umbrella. SolidWorks Simulation, certainly, but I’m a firm believer that before you even get to simulation, there are a bunch of validations that you should be doing that could validate portions of your design to the point that you wouldn’t need to run simulation on those areas. Sensors are a new tool that was pioneered, well, by CATIA. They allow SolidWorks to pop up warnings to the user when criteria are met. They were introduced into SW2009 and I’m sure that they will be improved in further releases of EnoviaWorks. Interference is a validation that we take for granted because we can see them. In automation, though, we can’t. Quite often we need to measure clearances, as well. Mass Props are a big one, too. All, well almost all, of these are basic functionality. But they’re functions that are simply skipped over in an automated environment. Simulation is generally used for two purposes: To generate reports proving/disproving validity, or generating numbers that will be used to modify the design.Other tools outside of SolidWorks should be considered as well. Calculation programs like MathCAD or Maple, or even systems that validate against empirical or tabular data. Only these sizes of o-ring are available. Well, if we’re automatically designing a groove, we need to make sure that the ID is within the stretchy-stretchy range of a standard O-ring. Why not have SolidWorks look it up in a SQL or Access or Excel table? It’s actually not that hard.
Let’s take a look at some of these tools and how to automate them for the sake of design validation.
OK, this is the list that I would like to address first. Some of them are going to be pretty quick.
You can add driven dimensions in a sketch and you can add reference dimensions in any 3D view. When you do this, you will get a reference dimension. Like any other dimension, it has a name. But unlike driving dimensions, you cannot change the name of a reference dimension. Even a driven dimension cannot be changed. Cheap workaround for driven dims is to make it driving, ignore the overdefined messages, change the name, then change it back to driven. Changing ref dimensions is a bit more difficult, and generally not all that important. In terms of the automation, with reference dimensions, all we generally do is to retrieve the value. That’s done fairly easily. Here we’re grabbing a parameter object directly (in other words without declaring a separate variable for a parameter object), and using the GetValue2 method.
The measure tool is a little more involved. These is a measure class. You create a measure object. You don’t retrieve it. The Accessor – CreateMeasure on the ModelDoc2.Extension object - actually creates a new object. You then set up the measure the way that you like it. Apply whatever settings you want. Arc options, number of decimal places, and so on. Then you tell it what to calculate, by passing it an array with objects of all of the selections to measure. If this parameter is nothing, then SolidWorks will use the current selection set. Once you calculate, then you can just pull your properties off of the measure object. Just remember that this can be highly dependent upon your view orientation.
Mass properties are very similar. You create a mass properties object from the ModelDoc2.Extension object using the CreateMassProperty method. The difference here is that the Create method actually includes a CALCULATE in there. There is no Separate Calculate method.
And as you would expect, section properties are totally different from mass properties. Section Properties are retrieved through the GetSectionProperties2 method. You must pass that method an object to get the section properties of, but what you get back is an array with 24 items. Naturally it would be silly of SolidWorks to create a class for something that only has 24 properties. But it’s ok. I’m not bitter.
What I DID do, however, was to develop my own enumeration for the results. I just paste this in the class with my code and I can refer to the results with intelligent names, as shown here with this Intellisense capture.
Interference Detection is more like mass properties. The ToolsCheckInterference method simply opens the interference detection tool in the property manager. So that is generally not the one that you want. If you want to do things in an automated fashion, get the InterferenceDetectionManager object from your AssemblyDoc, set your properties, then use the GetInterferences method to kick off the calculation. There are actually a few other methods for the interference detection manager object that will also kick off the calculation. Watch what you’re getting back, though. When you GetInterferences, you are getting an array of interference objects. Those objects have their own properties. GetInterferenceCount just gives you back a number.
Interference Detection is more like mass properties. The ToolsCheckInterference method simply opens the interference detection tool in the property manager. So that is generally not the one that you want. If you want to do things in an automated fashion, get the InterferenceDetectionManager object from your AssemblyDoc, set your properties, then use the GetInterferences method to kick off the calculation. There are actually a few other methods for the interference detection manager object that will also kick off the calculation. Watch what you’re getting back, though. When you GetInterferences, you are getting an array of interference objects. Those objects have their own properties. GetInterferenceCount just gives you back a number.
This is one of my favorite functions in CATIA. I’m glad to see that it’s finally made its way over to SolidWorks. This could, potentially, do away with some of your need to code validation as it really does it for you. This is one of the few that I will review the functionality for, because it’s really underutilized. Sensors sit in your Feature Manager and allow you to put a watch on a value and have SolidWorks let you know when the value goes outside of the acceptable range. For parts, you can watch a dimension, like a clearance or overall length. You then give SolidWorks the REFERENCE DIMENSION to watch, and tell SolidWorks the conditions when/if to notify you. You can watch mass properties like those listed here and the simulation results listed there. Assemblies add proximity and interference detection sensors. For all of them, you specify how often to check the values. For Simulations, mass props and Interferences, that could be a significant performance issue.
Working with sensors in code is fairly easy, except for getting the features themselves. In earlier versions, only Dimension sensors would be picked up by the regular GetFirstFeature – GetNextFeature methodology. Other sensors just act as if they’re not there. Once you are able to get the correct object, you need to use GetSpecificFeature2, to actually get the sensor object. Once you have the sensor object, you can change the sensor type, and change the values that the sensor is watching for. You can also disable the alert and change the alert state. So your code can trip the sensor or clear the sensor as needed.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
The other thing that’s really cool about Sensors is that there is an event notification associated with them. For those that are not familiar with events, they are triggers that you can use in your programs or macros to kick off some code when a particular event happens. The process is pretty simple. You need to define a class that declares the object WITHEVENTS. It’s important to note which SolidWorks object has the notification that you want. The sensor events are on the PartDoc and AssemblyDoc objects. Also in this class, you want to define the code to be executed when the event is triggered. You do this by defining a function with the name of your object, underscore, the name of the event. Be sure that you lookup the parameters for the event and map those to your new function with the correct data types. That’s it for the class. Then, in your main code, just instantiate that class, and pass the active object, whether it’s a partdoc, assemblydoc, or even the SolidWorks app itself. From that point on, the events will be monitored.
OK, this is what most of you came to see.
OK, as you can tell, my thought on the subject is that you should save simulation for when you really need it because it is quite CPU intensive and takes a lot of time. Further, before you start coding simulation through the API, take a look at whether you can automate it naturally using a Sensor or create a simulation optimization to automatically do the iterating and updating of dimensions for you. The next thing to know is that you may not find the API Help quite as helpful as you do with standard SolidWorks functionality. The API is newer and has fewer examples, and many of the simulation areas, like Flow, will have their own SDKs (that’s a Software Development Kit) that you have to install and/or download separately. You will see these as options in the Installation screen. At least until SolidWorks goes cloud, then who knows where it will be.
The next step is that there are separate libraries that you will need to add to gain access to the SolidWorks Simulation classes. Here’s the big one right here, SolidWorks.Interop.cosworks.dll. And when you’re adding this dll, you may need to browse for it.
So what are good reasons to automate simulation? Well iteration is certainly a great reason. As I said, SolidWorks does provide optimization functionality, but you may not get the collected results that you want. If you want to graph the trends of several variables as the iterations run, for example…I’m optimizing the weight on this part by changing these two dimensions. You will want to know where the weight and the values of those two variables were in each iteration, but you may also want to watch where the CG goes. Or maybe you have other criteria. Iterate, but don’t let these two get closer than… Or optimize lateral stiffness while keeping weight above 6.5 pounds
Or maybe you’re not automating the simulation so much as using the API to BUILD the simulation for you. What if you need to create a whole mess of pin locations or hundreds of loads. Or maybe your conditions are unknown to you and need to be calculated. You can have DriveWorks or Tacton build a model for you and your code figure out the loading and restraint conditions.
OK, so here is the basic object model for simulation. You’ve got your application object, your SldWorks of the simulation world. That is the CosmosWorks Add-In object. That leads to a CosmosWorksModelDoc. I’m sure it’ll be ModelDoc2 in no time. From there, you grab the study manager which begets your individual study objects. You can create these objects or you can latch onto an existing study. I would suggest the latter. Within your study, you will find objects for your loads and restraints, they actually function a lot like features in SolidWorks API examples. Then you will run that study and grab your results object.
So let’s take a look in a bit more detail. First is your declaration and assignment (I’m very fond of doing them in a single statement, by the way), of your CosmosWorks Add-In. The add-in should be turned on through Tools Add-Ins. Do not try to use your code to enable that. Once you have that, you fetch your ModelDoc. And there’s an ActiveDoc accessor, just like in the SldWorks object for just that purpose. One more step, and that’s the CWStudyManager object. Very similar to grabbing the SelectionManager or FeatureManager object from a ModelDoc. Just an accessor called StudyManager. And of course, you folks are all ACE programmers so you’re going to test for object IS NOTHING after each statement right? Yeha, I thought so. Even if you’re not, just nod and make me feel better.
Here we ramp it up a bit. We need to grab or create a study. I do not recommend creating studies. That is everyone’s first impulse. But one thing that you learn doing design implementations is that the more you can preset, the better. So I would recommend finding an existing study. The best way to do that is to grab the studycount. Then you can test that study count to make sure that it is what you expect it to be. Test early, test often. From there, you can cycle through the studies if you want to or you can grab a study by index. There is no explicit, get study by name accessor. So grab them by index and check the name.
Adding the material to the STUDY object (note where it is, it’s on the STUDY object) is also a critical step and it’s a bit of a traversal. You need to grab the SolidManger object from the Study, then the SolidComponent from that, then the SolidBody from that. Setting the material here is very similar to setting the material for a SolidWorks model. You need to specify the full path to the material library.
So if you’re looking for the actual valuable objects that you’re going to need, those will be down one more level. All of the options for your study will be in a separate StudyOptions object. Different objects for different types of analysis. Again, in the SolidWorks API Help, you will not see all of your study types. The help files and the sample files are all in those SDKs. If you didn’t fork up the dough for the modules, they don’t want you to have the help files. Notice here that most of the methods are properties. There are very few methods, with the exception of the bigunCreateMesh and the grandpappy, RunAnalysis. And speaking of mesh, you will find yet another option for your mesh.Another tip, use that intellisense for all of your enumerations, and there are tons. So type in CosmosWorksLib dot and you will get the full list of enumerations to choose from.
So in the mesh, you do have options to control ElementSize and tolerance. One method here that is critical to note is the Study object’s UpdateAllComponents method. Simulation and SolidWorks do have a small disconnect in them. If you want your SolidWorks model updates to be pushed to the analysis, then you’re going to need to kick off that method. ALWAYS DO IT BEFORE YOU CREATE YOUR MESH AND RUN THE ANALYSIS.
So once you have run your analysis, it’s time to get the results. Getting results is a bit more challenging. Think about the results. We have reams of green bar paper worth of values to choose from and in SolidWorks, what do we do? We look at pictures. Automation can’t really do that all too well. So here’s how we go about getting our numeric results. The first step is to grab your results object. It is a generic results object for standard simulations. Flow and motion are different.
Unfortunately, the results will typically come back as an array. A very poorly documented array. It is important that you check the values in this array very carefully before you use them.
So the big question on everyone’s mind is, how do you get SolidWorks to save out the BMPs and JPEGs and AVIs for the deflection and stress results? Well, the bad news is that there really is no way to do that. You can activate them and get a list of them, and even delete them. But saving them or publishing a report cannot be done from the API at this point.
So where else in the API should we be looking to get other validation code ideas?
Most of the add-ins for SolidWorks that are included in the Office suite have at least some level of API. The tools in SolidWorks Utilities that compare geometry and features are accessible. Analysis tools to look for invalid geometry and thickness inconsistencies, and even the molding parting line draft analysis are available via the API. The Xpress tools, however, do not have API functionality. These tools are all pretty interactive in their nature, using Microsoft wizard interfaces. So not having API access to these is not all that surprising.
Quite often, we see people that have outside validation tools. Perhaps an old piece of Fortran or BASIC code that was written so many years ago that nobody knows how or why it works, but it has become an integral part of the design process. These tools can be integrated into SolidWorks code through an external call, by declaring the external function, or by writing a .NET wrapper for that old code. The approach depends heavily upon the type of application and how it interacts with the system. There are also a lot of web-based calculation and lookup tools on the web that allow you to send code, typically as parameters in the URL or JAVA, and let the site do industry-specific calculations, conversions, or other such generics.