├── .gitignore ├── CAD ├── AddPartToAssembly.py ├── CreateCsysFromDatum.py ├── list_objects_on_layer.py └── print_model_history_tree.py ├── CSE_Python_debugging.pdf ├── Journals ├── journalCombineResults.py ├── journalCreateBoundaryCondition.py ├── journalCreateGroupsFromCad.py ├── journalCreateMeshCollector.py ├── journalCreateNodalForce.py ├── journalCreateSolution.py ├── journalCreateSolutionNoSubcase.py ├── journalCreateSubcase.py ├── journalEnvelopeResults.py ├── journalMakeSolutionInactive.py ├── journal_3d_mesh.py ├── journal_add_part_to_assembly.cs ├── journal_apply_post_group_user_visibility.py ├── journal_body_from_copy_feature.cs ├── journal_create_post_group.py ├── journal_selection_recipe.cs ├── journal_show_group_post_first_last.py ├── journal_show_group_post_first_last_second_time.py └── journal_show_group_post_temp.py ├── README.md ├── Tools ├── Excel │ ├── Sample1.xlsx │ ├── read_excel.py │ └── read_excel_xlwings.py ├── create_groups_from_cad.py ├── points_to_csv.py ├── print_assembly_structure.py └── read_simcenter_log_file.py ├── hello_world.py ├── intellisense.py ├── post_processing ├── export_all_solutions.py ├── export_shell_thickness_as_unv.py ├── list_nodal_results.py ├── post_processing.py ├── post_processing_pre_1980.py └── screen_shot_creator.py └── pre_processing ├── add_related_nodes_and_elements.py ├── create_mesh_collector.py ├── create_nodes.py ├── force_bc.py ├── solution_subcase.py └── solve_solution.py /.gitignore: -------------------------------------------------------------------------------- 1 | # NXOpen-CAE-python specific 2 | excluded_scripts/ 3 | 4 | # VSCode settings 5 | .vscode 6 | 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | share/python-wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | MANIFEST 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .nox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *.cover 55 | *.py,cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | cover/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | .pybuilder/ 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | # For a library or package, you might want to ignore these files since the code is 93 | # intended to run in multiple environments; otherwise, check them in: 94 | # .python-version 95 | 96 | # pipenv 97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 100 | # install all needed dependencies. 101 | #Pipfile.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/#use-with-ide 116 | .pdm.toml 117 | 118 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 119 | __pypackages__/ 120 | 121 | # Celery stuff 122 | celerybeat-schedule 123 | celerybeat.pid 124 | 125 | # SageMath parsed files 126 | *.sage.py 127 | 128 | # Environments 129 | .env 130 | .venv 131 | env/ 132 | venv/ 133 | ENV/ 134 | env.bak/ 135 | venv.bak/ 136 | 137 | # Spyder project settings 138 | .spyderproject 139 | .spyproject 140 | 141 | # Rope project settings 142 | .ropeproject 143 | 144 | # mkdocs documentation 145 | /site 146 | 147 | # mypy 148 | .mypy_cache/ 149 | .dmypy.json 150 | dmypy.json 151 | 152 | # Pyre type checker 153 | .pyre/ 154 | 155 | # pytype static type analyzer 156 | .pytype/ 157 | 158 | # Cython debug symbols 159 | cython_debug/ 160 | 161 | # PyCharm 162 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 163 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 164 | # and can be added to the global gitignore or merged into this file. For a more nuclear 165 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 166 | #.idea/ -------------------------------------------------------------------------------- /CAD/AddPartToAssembly.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # Tested in SC2212 3 | 4 | import sys 5 | import math 6 | import NXOpen 7 | import NXOpen.CAE 8 | from typing import cast 9 | 10 | theSession: NXOpen.Session = NXOpen.Session.GetSession() 11 | basePart = theSession.Parts.BaseWork 12 | theLW: NXOpen.ListingWindow = theSession.ListingWindow 13 | 14 | 15 | def main(): 16 | theLW.Open() 17 | theLW.WriteFullline("Starting Main() in " + theSession.ExecutingJournal) 18 | 19 | # full path of the part to add as a component 20 | file_name = r"D:\JdN\model1.prt" 21 | # The name of the reference set used to represent the new component 22 | referenceset_name = "Entire Part" 23 | # The name of the new component 24 | component_name = "my_component" 25 | # The layer to place the new component on: 26 | # -1 means use the original layers defined in the component. 27 | # 0 means use the work layer. 28 | # 1-256 means use the specified layer. 29 | layer: int = 1 30 | # Location of the new component 31 | base_point = NXOpen.Point3d(0.0, 0.0, 0.0) 32 | # Orientation of the new component 33 | orientation: NXOpen.Matrix3x3 = NXOpen.Matrix3x3() 34 | orientation.Xx = 1 35 | orientation.Xy = 0 36 | orientation.Xz = 0 37 | orientation.Yx = 0 38 | orientation.Yy = 1 39 | orientation.Yz = 0 40 | orientation.Zx = 0 41 | orientation.Zy = 0 42 | orientation.Zz = 1 43 | 44 | assembly: NXOpen.Part = cast(NXOpen.BasePart, basePart) # explicit casting required in Visual Studio Code 45 | component_assembly: NXOpen.Assemblies.ComponentAssembly = assembly.ComponentAssembly 46 | loadstatus, component = component_assembly.AddComponent(file_name, referenceset_name, component_name, base_point, orientation, layer) 47 | 48 | 49 | if __name__ == '__main__': 50 | main() 51 | -------------------------------------------------------------------------------- /CAD/CreateCsysFromDatum.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # Untested 3 | 4 | import sys 5 | import math 6 | import NXOpen 7 | import NXOpen.CAE 8 | 9 | theSession: NXOpen.Session = NXOpen.Session.GetSession() 10 | basePart = theSession.Parts.BaseWork 11 | theLW: NXOpen.ListingWindow = theSession.ListingWindow 12 | 13 | 14 | def create_csys_from_datum(datum_plane: NXOpen.DatumPlane) -> NXOpen.CartesianCoordinateSystem: 15 | """This function creates a Cartesion coordinates system using a datumPlane as input. 16 | The orthogonal vectors are constructed in the plane to define the coordinate system, using basic geometry. 17 | 18 | Parameters 19 | ---------- 20 | datum_plane: NXOpen.DatumPlane 21 | Instance of the datumPlane to create the coordinate system for. 22 | 23 | Returns 24 | ------- 25 | NXOpen.CartesianCoordinateSystem 26 | A coordinate system which has the same origin as the plane with x and y axis in the plane. 27 | """ 28 | origin: NXOpen.Point3d = datum_plane.Origin 29 | normal: NXOpen.Vector3d = datum_plane.Normal 30 | 31 | # we choose the global X vector to project on the plane. 32 | global_vector: NXOpen.Vector3d = NXOpen.Vector3d(1,0,0) 33 | projection: float = abs(normal.X * global_vector.X + normal.Y * global_vector.Y * normal.Z * global_vector.Z) 34 | # need to change that choice if global X is normal to the plane 35 | if (projection >= 0.999): 36 | global_vector.X = 0 37 | global_vector.Y = 1 38 | global_vector.Z = 0 39 | 40 | # we first project the global onto the plane normal 41 | # then subtract to get the component of global IN the plane which will be are local axis in the recipe definition 42 | projection_magnitude: float = global_vector.X * normal.X + global_vector.Y * normal.Y + global_vector.Z * normal.Z 43 | global_on_normal = NXOpen.Vector3d(projection_magnitude * normal.X, projection_magnitude * normal.Y, projection_magnitude * normal.Z) 44 | global_on_plane = NXOpen.Vector3d(global_vector.X - global_on_normal.X, global_vector.Y - global_on_normal.Y, global_vector.Z - global_on_normal.Z) 45 | 46 | # normalize 47 | magnitude: float = math.sqrt(global_on_plane.X ** 2 + global_on_plane.Y ** 2 + global_on_plane.Z ** 2) 48 | global_on_plane = NXOpen.Vector3d(global_on_plane.X / magnitude, global_on_plane.Y / magnitude, global_on_plane.Z / magnitude) 49 | 50 | # cross product of globalOnPlane and normal give vector in plane, otrhogonal to globalOnPlane 51 | global_on_plane_normal = NXOpen.Vector3d( 52 | normal.Y * global_on_plane.Z - normal.Z * global_on_plane.Y, 53 | -normal.X * global_on_plane.Z + normal.Z * global_on_plane.X, 54 | normal.X * global_on_plane.Y - normal.Y * global_on_plane.X) 55 | 56 | # normalize 57 | magnitude: float = math.sqrt(global_on_plane_normal.X ** 2 + global_on_plane_normal.Y ** 2 + global_on_plane_normal.Z ** 2) 58 | global_on_plane_normal = NXOpen.Vector3d(global_on_plane_normal.X / magnitude, global_on_plane_normal.Y / magnitude, global_on_plane_normal.Z / magnitude) 59 | 60 | # Create the coordinate system with these vectors 61 | xform: NXOpen.Xform = basePart.Xforms.CreateXform(origin, global_on_plane, global_on_plane_normal, NXOpen.SmartObject.UpdateOption.AfterModeling, 1.0) 62 | coordinate_system: NXOpen.CartesianCoordinateSystem = basePart.CoordinateSystems.CreateCoordinateSystem(xform, NXOpen.SmartObject.UpdateOption.AfterModeling) 63 | 64 | return coordinate_system 65 | 66 | 67 | def main(): 68 | theLW.Open() 69 | theLW.WriteFullline("Starting Main() in " + theSession.ExecutingJournal) 70 | 71 | 72 | if __name__ == '__main__': 73 | main() 74 | -------------------------------------------------------------------------------- /CAD/list_objects_on_layer.py: -------------------------------------------------------------------------------- 1 | import NXOpen 2 | from typing import List, cast 3 | 4 | 5 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 6 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 7 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 8 | 9 | 10 | def list_objects_on_layer(layer: int): 11 | if not the_lw.IsOpen: 12 | the_lw.Open() 13 | layer_manager: NXOpen.Layer.LayerManager = base_part.Layers 14 | objects_on_layer: List[NXOpen.NXObject] = layer_manager.GetAllObjectsOnLayer(layer) 15 | the_lw.WriteFullline("") 16 | the_lw.WriteFullline("There are " + str(len(objects_on_layer)) + " objects on layer " + str(layer) + ":") 17 | for item in objects_on_layer: 18 | the_lw.WriteFullline("\t" + item.JournalIdentifier + " " + str(type(item))) 19 | 20 | 21 | def main(): 22 | the_lw.Open() 23 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 24 | 25 | list_objects_on_layer(62) 26 | 27 | 28 | if __name__ == '__main__': 29 | main() -------------------------------------------------------------------------------- /CAD/print_model_history_tree.py: -------------------------------------------------------------------------------- 1 | import NXOpen 2 | from typing import List, cast 3 | 4 | 5 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 6 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 7 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 8 | 9 | 10 | def indentation(level: int) -> str: 11 | """Helper method to create indentations (eg tabs) with a given length. 12 | Can be used in print strings in a tree like structure 13 | 14 | Parameters 15 | ---------- 16 | level: int 17 | The depth of the indentations. 18 | 19 | Returns 20 | ------- 21 | str 22 | The indentation 23 | """ 24 | indentation: str = "" 25 | for i in range(level + 1): 26 | indentation += "\t" 27 | 28 | return indentation 29 | 30 | 31 | def print_history_tree(my_feature: NXOpen.Features.Feature, requested_level: int = 0) -> None: 32 | """Prints the component tree for the given component to the listing window. 33 | Recursive function 34 | 35 | Parameters 36 | ---------- 37 | component: NXOpen.Assemblies.Component 38 | The component for whch to print the component tree 39 | requested_level: int 40 | Optional parameter used for creating indentations. 41 | """ 42 | level: int = requested_level 43 | the_lw.WriteFullline(indentation(level) + "| " + my_feature.JournalIdentifier + " with name " + my_feature.GetFeatureName()) 44 | children: List[NXOpen.Features.Feature] = my_feature.GetChildren() 45 | for i in range(len(children)): 46 | print_history_tree(children[i], level + 1) 47 | 48 | 49 | def get_all_features(part: NXOpen.Part = None) -> List[NXOpen.Features.Feature]: 50 | """Gets all features in the base_part 51 | 52 | Parameters 53 | ---------- 54 | part: NXOpen.Part (optional) 55 | The part to return the features for. Takes the base_part if not given. 56 | 57 | Returns 58 | ------- 59 | List[NXOpen.Features.Feature] 60 | A list with all features. 61 | """ 62 | all_features: List[NXOpen.Features.Feature] = [] 63 | part_for_features: NXOpen.Part = cast(NXOpen.Part, base_part) 64 | if part != None: 65 | part_for_features = part 66 | for item in part_for_features.Features: 67 | all_features.append(item) 68 | return all_features 69 | 70 | 71 | def main(): 72 | the_lw.Open() 73 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 74 | 75 | all_features: List[NXOpen.Features.Feature] = get_all_features() 76 | # the first feature is the basic datum coordinate system. All the rest depends on this. 77 | print_history_tree(all_features[0]) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /CSE_Python_debugging.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theScriptingEngineer/NXOpen-CAE-python/f0746445e330747b0e49bd7e3b5a5a901bac6a48/CSE_Python_debugging.pdf -------------------------------------------------------------------------------- /Journals/journalCombineResults.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:07:38 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | simSimulation1 = workSimPart.FindObject("Simulation") 18 | simSolution1 = simSimulation1.FindObject("Solution[Transverse]") 19 | simResultReference1 = simSolution1.Find("Structural") 20 | solutionResult1 = theSession.ResultManager.CreateReferenceResult(simResultReference1) 21 | 22 | simSolution2 = simSimulation1.FindObject("Solution[Longitudinal]") 23 | simResultReference2 = simSolution2.Find("Structural") 24 | solutionResult2 = theSession.ResultManager.CreateReferenceResult(simResultReference2) 25 | 26 | # ---------------------------------------------- 27 | # Menu: Tools->Results->Combination... 28 | # ---------------------------------------------- 29 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 30 | 31 | theSession.SetUndoMarkName(markId1, "Results Combination Dialog") 32 | 33 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Results Combination") 34 | 35 | theSession.DeleteUndoMark(markId2, None) 36 | 37 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Results Combination") 38 | 39 | resultsCombinationBuilder1 = theSession.ResultManager.CreateResultsCombinationBuilder() 40 | 41 | types1 = [NXOpen.CAE.BaseResultType.Null] * 2 42 | loadcase1 = solutionResult1.Find("Loadcase[1]") 43 | iteration1 = loadcase1.Find("Iteration[1]") 44 | resultType1 = iteration1.Find("ResultType[[Stress][Element-Nodal]]") 45 | types1[0] = resultType1 46 | loadcase2 = solutionResult2.Find("Loadcase[1]") 47 | iteration2 = loadcase2.Find("Iteration[1]") 48 | resultType2 = iteration2.Find("ResultType[[Stress][Element-Nodal]]") 49 | types1[1] = resultType2 50 | names1 = [None] * 2 51 | names1[0] = "STRE" 52 | names1[1] = "STRE_1" 53 | units1 = [NXOpen.Unit.Null] * 2 54 | unit1 = workSimPart.UnitCollection.FindObject("StressMilliNewtonPerSquareMilliMeter") 55 | units1[0] = unit1 56 | units1[1] = unit1 57 | resultsCombinationBuilder1.SetResultTypes(types1, names1, units1) 58 | 59 | resultsCombinationBuilder1.SetFormula("STRE + STRE_1") 60 | 61 | resultsCombinationBuilder1.SetOutputResultType(NXOpen.CAE.ResultsManipulationBuilder.OutputResultType.Companion) 62 | 63 | resultsCombinationBuilder1.SetIncludeModel(False) 64 | 65 | resultsCombinationBuilder1.SetCompanionResultReference(simResultReference1) 66 | 67 | resultsCombinationBuilder1.SetCompanionIdentifier("companionIdentifier") 68 | 69 | resultsCombinationBuilder1.SetAppendMethod(NXOpen.CAE.ResultsManipulationBuilder.ResultAppendMethod.CreateNewLoadCases) 70 | 71 | resultsCombinationBuilder1.SetImportResult(True) 72 | 73 | resultsCombinationBuilder1.SetOutputQuantity(NXOpen.CAE.Result.Quantity.Stress) 74 | 75 | resultsCombinationBuilder1.SetOutputName("outputName") 76 | 77 | resultsCombinationBuilder1.SetLoadcaseName("loadcaseName") 78 | 79 | resultsCombinationBuilder1.SetOutputFile("C:\\Users\\Frederik\\Documents\\SC2022\\Python\\pythonCombine.unv") 80 | 81 | resultsCombinationBuilder1.SetUnitsSystem(NXOpen.CAE.ResultsManipulationBuilder.UnitsSystem.FromResult) 82 | 83 | resultsCombinationBuilder1.SetUnitsSystemResult(solutionResult1) 84 | 85 | resultsCombinationBuilder1.SetIncompatibleResultsOption(NXOpen.CAE.ResultsCombinationBuilder.IncompatibleResults.Skip) 86 | 87 | resultsCombinationBuilder1.SetNoDataOption(NXOpen.CAE.ResultsCombinationBuilder.NoData.Skip) 88 | 89 | resultsCombinationBuilder1.SetEvaluationErrorOption(NXOpen.CAE.ResultsCombinationBuilder.EvaluationError.Skip) 90 | 91 | nXObject1 = resultsCombinationBuilder1.Commit() 92 | 93 | resultsCombinationBuilder1.Destroy() 94 | 95 | theSession.DeleteUndoMark(markId3, None) 96 | 97 | theSession.SetUndoMarkName(markId1, "Results Combination") 98 | 99 | # ---------------------------------------------- 100 | # Menu: Tools->Journal->Stop Recording 101 | # ---------------------------------------------- 102 | 103 | if __name__ == '__main__': 104 | main() -------------------------------------------------------------------------------- /Journals/journalCreateBoundaryCondition.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:02:57 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.Assemblies 11 | import NXOpen.CAE 12 | import NXOpen.Fields 13 | import SafetyOpen 14 | def main() : 15 | 16 | theSession = NXOpen.Session.GetSession() 17 | workSimPart = theSession.Parts.BaseWork 18 | displaySimPart = theSession.Parts.BaseDisplay 19 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 20 | 21 | simPart1 = workSimPart 22 | simSimulation1 = simPart1.Simulation 23 | 24 | simBCBuilder1 = simSimulation1.CreateBcBuilderForConstraintDescriptor("UserDefinedDisplacementConstraint", "UserDefined(1)", 7) 25 | 26 | propertyTable1 = simBCBuilder1.PropertyTable 27 | 28 | setManager1 = simBCBuilder1.TargetSetManager 29 | 30 | fieldExpression1 = propertyTable1.GetScalarFieldPropertyValue("DOF1") 31 | 32 | fieldExpression2 = propertyTable1.GetScalarFieldPropertyValue("DOF2") 33 | 34 | fieldExpression3 = propertyTable1.GetScalarFieldPropertyValue("DOF3") 35 | 36 | fieldExpression4 = propertyTable1.GetScalarFieldPropertyValue("DOF4") 37 | 38 | fieldExpression5 = propertyTable1.GetScalarFieldPropertyValue("DOF5") 39 | 40 | fieldExpression6 = propertyTable1.GetScalarFieldPropertyValue("DOF6") 41 | 42 | theSession.SetUndoMarkName(markId1, "User Defined Constraint Dialog") 43 | 44 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "User Defined Constraint") 45 | 46 | theSession.DeleteUndoMark(markId2, None) 47 | 48 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "User Defined Constraint") 49 | 50 | objects1 = [None] * 1 51 | objects1[0] = NXOpen.CAE.SetObject() 52 | component1 = workSimPart.ComponentAssembly.RootComponent.FindObject("COMPONENT hullModelNX12_fem1 1") 53 | cAEVertex1 = component1.FindObject("PROTO#CAE_Body(82)|CAE_Vertex(1278)") 54 | objects1[0].Obj = cAEVertex1 55 | objects1[0].SubType = NXOpen.CAE.CaeSetObjectSubType.NotSet 56 | objects1[0].SubId = 0 57 | setManager1.SetTargetSetMembers(0, NXOpen.CAE.CaeSetGroupFilterType.GeomVertex, objects1) 58 | 59 | simBCBuilder1.BcName = "myConstraint" 60 | 61 | unit1 = workSimPart.UnitCollection.FindObject("MilliMeter") 62 | indepVarArray1 = [] 63 | fieldExpression1.EditFieldExpression("-777777", unit1, indepVarArray1, False) 64 | 65 | propertyTable1.SetScalarFieldPropertyValue("DOF1", fieldExpression1) 66 | 67 | indepVarArray2 = [] 68 | fieldExpression2.EditFieldExpression("0", unit1, indepVarArray2, False) 69 | 70 | propertyTable1.SetScalarFieldPropertyValue("DOF2", fieldExpression2) 71 | 72 | indepVarArray3 = [] 73 | fieldExpression3.EditFieldExpression("123", unit1, indepVarArray3, False) 74 | 75 | propertyTable1.SetScalarFieldPropertyValue("DOF3", fieldExpression3) 76 | 77 | unit2 = workSimPart.UnitCollection.FindObject("Degrees") 78 | indepVarArray4 = [] 79 | fieldExpression4.EditFieldExpression("-777777", unit2, indepVarArray4, False) 80 | 81 | propertyTable1.SetScalarFieldPropertyValue("DOF4", fieldExpression4) 82 | 83 | indepVarArray5 = [] 84 | fieldExpression5.EditFieldExpression("0", unit2, indepVarArray5, False) 85 | 86 | propertyTable1.SetScalarFieldPropertyValue("DOF5", fieldExpression5) 87 | 88 | indepVarArray6 = [] 89 | fieldExpression6.EditFieldExpression("456", unit2, indepVarArray6, False) 90 | 91 | propertyTable1.SetScalarFieldPropertyValue("DOF6", fieldExpression6) 92 | 93 | propertyValue1 = [None] * 1 94 | propertyValue1[0] = "" 95 | propertyTable1.SetTextPropertyValue("description", propertyValue1) 96 | 97 | simBCBuilder1.DestinationFolder = NXOpen.CAE.SimLbcFolder.Null 98 | 99 | simBC1 = simBCBuilder1.CommitAddBc() 100 | 101 | simBCBuilder1.Destroy() 102 | 103 | theSession.DeleteUndoMark(markId3, None) 104 | 105 | theSession.SetUndoMarkName(markId1, "User Defined Constraint") 106 | 107 | # ---------------------------------------------- 108 | # Menu: Tools->Journal->Stop Recording 109 | # ---------------------------------------------- 110 | 111 | if __name__ == '__main__': 112 | main() -------------------------------------------------------------------------------- /Journals/journalCreateGroupsFromCad.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:43:07 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.Assemblies 11 | import NXOpen.CAE 12 | import NXOpen.Features 13 | import NXOpen.MenuBar 14 | import SafetyOpen 15 | def main() : 16 | 17 | theSession = NXOpen.Session.GetSession() 18 | workFemPart = theSession.Parts.BaseWork 19 | displayFemPart = theSession.Parts.BaseDisplay 20 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Load Part") 21 | 22 | part1, partLoadStatus1 = theSession.Parts.Open("C:\\Users\\Frederik\\Documents\\SC2022\\Python\\hullModelNX12.prt") 23 | 24 | partLoadStatus1.Dispose() 25 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Change Displayed Part") 26 | 27 | baseTemplateManager1 = theSession.XYPlotManager.TemplateManager 28 | 29 | status1, partLoadStatus2 = theSession.Parts.SetActiveDisplay(part1, NXOpen.DisplayPartOption.AllowAdditional, NXOpen.PartDisplayPartWorkPartOption.UseLast) 30 | 31 | workFemPart = NXOpen.BasePart.Null 32 | workPart = theSession.Parts.Work 33 | displayFemPart = NXOpen.BasePart.Null 34 | displayPart = theSession.Parts.Display 35 | partLoadStatus2.Dispose() 36 | # ---------------------------------------------- 37 | # Menu: Application->Modeling 38 | # ---------------------------------------------- 39 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Enter Modeling") 40 | 41 | theSession.ApplicationSwitchImmediate("UG_APP_MODELING") 42 | 43 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Assign Name") 44 | 45 | datumPlaneFeature1 = workPart.Features.FindObject("DATUM_PLANE(4)") 46 | datumPlaneFeature1.SetName("Frame00") 47 | 48 | nErrs1 = theSession.UpdateManager.DoUpdate(markId4) 49 | 50 | theSession.SetUndoMarkVisibility(markId4, "Assign Name", NXOpen.Session.MarkVisibility.Visible) 51 | 52 | # ---------------------------------------------- 53 | # Menu: Window->2. hullModelNX12_fem1.fem 54 | # ---------------------------------------------- 55 | markId5 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Change Displayed Part") 56 | 57 | femPart1 = theSession.Parts.FindObject("hullModelNX12_fem1") 58 | status2, partLoadStatus3 = theSession.Parts.SetActiveDisplay(femPart1, NXOpen.DisplayPartOption.AllowAdditional, NXOpen.PartDisplayPartWorkPartOption.UseLast) 59 | 60 | workPart = NXOpen.Part.Null 61 | workFemPart = theSession.Parts.BaseWork # hullModelNX12_fem1 62 | displayPart = NXOpen.Part.Null 63 | displayFemPart = theSession.Parts.BaseDisplay # hullModelNX12_fem1 64 | partLoadStatus3.Dispose() 65 | theSession.ApplicationSwitchImmediate("UG_APP_SFEM") 66 | 67 | markId6 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Enter Pre/Post") 68 | 69 | # ---------------------------------------------- 70 | # Menu: Window->3. hullModelNX12_fem1_sim1.sim 71 | # ---------------------------------------------- 72 | markId7 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Change Displayed Part") 73 | 74 | simPart1 = theSession.Parts.FindObject("hullModelNX12_fem1_sim1") 75 | status3, partLoadStatus4 = theSession.Parts.SetActiveDisplay(simPart1, NXOpen.DisplayPartOption.AllowAdditional, NXOpen.PartDisplayPartWorkPartOption.UseLast) 76 | 77 | workSimPart = theSession.Parts.BaseWork 78 | displaySimPart = theSession.Parts.BaseDisplay 79 | partLoadStatus4.Dispose() 80 | markId8 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 81 | 82 | caePart1 = workSimPart 83 | selRecipeBuilder1 = caePart1.SelectionRecipes.CreateSelRecipeBuilder() 84 | 85 | unit1 = workSimPart.UnitCollection.FindObject("MilliMeter") 86 | expression1 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 87 | 88 | expression1.SetFormula("5.0") 89 | 90 | expression2 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 91 | 92 | expression2.SetFormula("5.0") 93 | 94 | expression3 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 95 | 96 | expression3.SetFormula("5.0") 97 | 98 | expression4 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 99 | 100 | expression4.SetFormula("5.0") 101 | 102 | expression5 = workSimPart.Expressions.CreateSystemExpressionWithUnits("0", unit1) 103 | 104 | expression6 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 105 | 106 | expression6.SetFormula("5.0") 107 | 108 | expression7 = workSimPart.Expressions.CreateSystemExpressionWithUnits("0", unit1) 109 | 110 | expression8 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 111 | 112 | expression8.SetFormula("5.0") 113 | 114 | expression9 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 115 | 116 | expression9.SetFormula("5.0") 117 | 118 | expression10 = workSimPart.Expressions.CreateSystemExpressionWithUnits("0", unit1) 119 | 120 | expression11 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 121 | 122 | expression11.SetFormula("5.0") 123 | 124 | expression12 = workSimPart.Expressions.CreateSystemExpressionWithUnits("5.0", unit1) 125 | 126 | expression12.SetFormula("5.0") 127 | 128 | unit2 = workSimPart.UnitCollection.FindObject("Degrees") 129 | expression13 = workSimPart.Expressions.CreateSystemExpressionWithUnits("0", unit2) 130 | 131 | expression14 = workSimPart.Expressions.CreateSystemExpressionWithUnits("360", unit2) 132 | 133 | expression14.SetFormula("360") 134 | 135 | theSession.SetUndoMarkName(markId8, "Create Selection Recipe Dialog") 136 | 137 | origin1 = NXOpen.Point3d(0.0, 0.0, 0.0) 138 | xDirection1 = NXOpen.Vector3d(1.0, 0.0, 0.0) 139 | yDirection1 = NXOpen.Vector3d(0.0, 1.0, 0.0) 140 | xform1 = workSimPart.Xforms.CreateXform(origin1, xDirection1, yDirection1, NXOpen.SmartObject.UpdateOption.AfterModeling, 1.0) 141 | 142 | cartesianCoordinateSystem1 = workSimPart.CoordinateSystems.CreateCoordinateSystem(xform1, NXOpen.SmartObject.UpdateOption.AfterModeling) 143 | 144 | expression1.SetFormula("100000") 145 | 146 | expression2.SetFormula("100000") 147 | 148 | expression3.SetFormula("500") 149 | 150 | scaleAboutPoint1 = NXOpen.Point3d(-7152.6268364746447, 3558.8679869288485, 0.0) 151 | viewCenter1 = NXOpen.Point3d(7152.6268364746447, -3558.8679869288485, 0.0) 152 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint1, viewCenter1) 153 | 154 | scaleAboutPoint2 = NXOpen.Point3d(-8940.7835455933018, 4448.5849836610605, 0.0) 155 | viewCenter2 = NXOpen.Point3d(8940.7835455933091, -4448.5849836610632, 0.0) 156 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint2, viewCenter2) 157 | 158 | scaleAboutPoint3 = NXOpen.Point3d(-11175.979431991631, 5560.7312295763249, 0.0) 159 | viewCenter3 = NXOpen.Point3d(11175.979431991631, -5560.7312295763286, 0.0) 160 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint3, viewCenter3) 161 | 162 | scaleAboutPoint4 = NXOpen.Point3d(-13969.974289989548, 6950.9140369704055, 0.0) 163 | viewCenter4 = NXOpen.Point3d(13969.97428998953, -6950.914036970411, 0.0) 164 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint4, viewCenter4) 165 | 166 | rotMatrix1 = NXOpen.Matrix3x3() 167 | 168 | rotMatrix1.Xx = -0.44673942119408988 169 | rotMatrix1.Xy = -0.89436719641466811 170 | rotMatrix1.Xz = -0.023047939789410013 171 | rotMatrix1.Yx = 0.39488655312465781 172 | rotMatrix1.Yy = -0.22023262709323432 173 | rotMatrix1.Yz = 0.89194293546444992 174 | rotMatrix1.Zx = -0.8028004108821174 175 | rotMatrix1.Zy = 0.38936474922748088 176 | rotMatrix1.Zz = 0.45156017577563728 177 | translation1 = NXOpen.Point3d(-7115.3336631949387, -586.98833788152479, -979.09072295236228) 178 | workSimPart.ModelingViews.WorkView.SetRotationTranslationScale(rotMatrix1, translation1, 0.0046590994835716852) 179 | 180 | origin2 = NXOpen.Point3d(0.0, 0.0, -250.0) 181 | xDirection2 = NXOpen.Vector3d(1.0, 0.0, 0.0) 182 | yDirection2 = NXOpen.Vector3d(0.0, 1.0, 0.0) 183 | xform2 = workSimPart.Xforms.CreateXform(origin2, xDirection2, yDirection2, NXOpen.SmartObject.UpdateOption.AfterModeling, 1.0) 184 | 185 | cartesianCoordinateSystem2 = workSimPart.CoordinateSystems.CreateCoordinateSystem(xform2, NXOpen.SmartObject.UpdateOption.AfterModeling) 186 | 187 | rotMatrix2 = NXOpen.Matrix3x3() 188 | 189 | rotMatrix2.Xx = -0.41730310092334594 190 | rotMatrix2.Xy = -0.90824153533018548 191 | rotMatrix2.Xz = -0.03091011906847085 192 | rotMatrix2.Yx = 0.16693753298015526 193 | rotMatrix2.Yy = -0.11004726454913918 194 | rotMatrix2.Yz = 0.97980684813270713 195 | rotMatrix2.Zx = -0.89330285012545352 196 | rotMatrix2.Zy = 0.4037163770102955 197 | rotMatrix2.Zz = 0.19754266600261691 198 | translation2 = NXOpen.Point3d(-7134.8954073411214, -570.40986093380525, 472.00170439941212) 199 | workSimPart.ModelingViews.WorkView.SetRotationTranslationScale(rotMatrix2, translation2, 0.0046590994835716852) 200 | 201 | scaleAboutPoint5 = NXOpen.Point3d(-9228.1334232654572, 1817.2324279661154, 0.0) 202 | viewCenter5 = NXOpen.Point3d(9228.1334232654335, -1817.2324279661154, 0.0) 203 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint5, viewCenter5) 204 | 205 | scaleAboutPoint6 = NXOpen.Point3d(-11535.166779081808, 2271.5405349576449, 0.0) 206 | viewCenter6 = NXOpen.Point3d(11535.166779081808, -2271.5405349576449, 0.0) 207 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint6, viewCenter6) 208 | 209 | scaleAboutPoint7 = NXOpen.Point3d(-14418.958473852261, 2839.4256686970557, 0.0) 210 | viewCenter7 = NXOpen.Point3d(14418.958473852261, -2839.4256686970557, 0.0) 211 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint7, viewCenter7) 212 | 213 | scaleAboutPoint8 = NXOpen.Point3d(-11535.166779081808, 2271.5405349576449, 0.0) 214 | viewCenter8 = NXOpen.Point3d(11535.166779081808, -2271.5405349576449, 0.0) 215 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint8, viewCenter8) 216 | 217 | scaleAboutPoint9 = NXOpen.Point3d(-9228.1334232654481, 1817.2324279661159, 0.0) 218 | viewCenter9 = NXOpen.Point3d(9228.1334232654481, -1817.2324279661159, 0.0) 219 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint9, viewCenter9) 220 | 221 | scaleAboutPoint10 = NXOpen.Point3d(-7382.5067386123583, 1453.7859423728928, 0.0) 222 | viewCenter10 = NXOpen.Point3d(7382.5067386123583, -1453.7859423728928, 0.0) 223 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint10, viewCenter10) 224 | 225 | scaleAboutPoint11 = NXOpen.Point3d(-3688.9818287712219, -2762.1932905085018, 0.0) 226 | viewCenter11 = NXOpen.Point3d(3688.9818287712219, 2762.1932905085096, 0.0) 227 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint11, viewCenter11) 228 | 229 | scaleAboutPoint12 = NXOpen.Point3d(-4611.227285964027, -3452.7416131356272, 0.0) 230 | viewCenter12 = NXOpen.Point3d(4611.227285964027, 3452.7416131356367, 0.0) 231 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint12, viewCenter12) 232 | 233 | scaleAboutPoint13 = NXOpen.Point3d(-5764.0341074550342, -4315.9270164195341, 0.0) 234 | viewCenter13 = NXOpen.Point3d(5764.0341074550342, 4315.9270164195459, 0.0) 235 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint13, viewCenter13) 236 | 237 | scaleAboutPoint14 = NXOpen.Point3d(-7205.0426343188083, -5394.9087705244174, 0.0) 238 | viewCenter14 = NXOpen.Point3d(7205.0426343187783, 5394.9087705244328, 0.0) 239 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(0.80000000000000004, scaleAboutPoint14, viewCenter14) 240 | 241 | expression5.SetFormula("0") 242 | 243 | expression7.SetFormula("0") 244 | 245 | expression10.SetFormula("0") 246 | 247 | expression13.SetFormula("0") 248 | 249 | markId9 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Create Selection Recipe") 250 | 251 | theSession.DeleteUndoMark(markId9, None) 252 | 253 | markId10 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Create Selection Recipe") 254 | 255 | entitytypes1 = [None] * 2 256 | entitytypes1[0] = NXOpen.CAE.CaeSetGroupFilterType.GeomFace 257 | entitytypes1[1] = NXOpen.CAE.CaeSetGroupFilterType.GeomBody 258 | selRecipeBoundingVolumeStrategy1 = selRecipeBuilder1.AddBoxBoundingVolumeStrategy(cartesianCoordinateSystem2, expression1, expression2, expression3, entitytypes1, NXOpen.CAE.SelRecipeBuilder.InputFilterType.EntireModel, NXOpen.TaggedObject.Null) 259 | 260 | boundingVolumePrimitive1 = selRecipeBoundingVolumeStrategy1.BoundingVolume 261 | 262 | boxBoundingVolume1 = boundingVolumePrimitive1 263 | boxBoundingVolume1.Containment = NXOpen.CAE.CaeBoundingVolumePrimitiveContainment.Inside 264 | 265 | selRecipeBuilder1.RecipeName = "SelectionRecipe" 266 | 267 | nXObject1 = selRecipeBuilder1.Commit() 268 | 269 | theSession.DeleteUndoMark(markId10, None) 270 | 271 | theSession.SetUndoMarkName(markId8, "Create Selection Recipe") 272 | 273 | selectionRecipe1 = nXObject1 274 | selectionRecipe1.Display.Update() 275 | 276 | selRecipeBuilder1.Destroy() 277 | 278 | markId11 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 279 | 280 | caePart2 = workSimPart 281 | caeGroupBuilder1 = caePart2.CaeGroups.CreateGroupBuilder(NXOpen.CAE.CaeGroup.Null) 282 | 283 | caePart3 = workSimPart 284 | selectElementsBuilder1 = caePart3.SelectElementMgr.CreateSelectElementsBuilder() 285 | 286 | theSession.SetUndoMarkName(markId11, "New Group Dialog") 287 | 288 | caeGroupBuilder1.Label = 7 289 | 290 | caeGroupBuilder1.Name = "Group(7)" 291 | 292 | # ---------------------------------------------- 293 | # Dialog Begin New Group 294 | # ---------------------------------------------- 295 | scaleAboutPoint15 = NXOpen.Point3d(-21961.182906328853, -6299.9757024216051, 0.0) 296 | viewCenter15 = NXOpen.Point3d(21961.182906328817, 6299.9757024216242, 0.0) 297 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint15, viewCenter15) 298 | 299 | scaleAboutPoint16 = NXOpen.Point3d(-17568.946325063083, -5039.9805619372846, 0.0) 300 | viewCenter16 = NXOpen.Point3d(17568.946325063054, 5039.9805619372992, 0.0) 301 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint16, viewCenter16) 302 | 303 | scaleAboutPoint17 = NXOpen.Point3d(-14055.157060050471, -4031.9844495498287, 0.0) 304 | viewCenter17 = NXOpen.Point3d(14055.15706005044, 4031.9844495498405, 0.0) 305 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint17, viewCenter17) 306 | 307 | scaleAboutPoint18 = NXOpen.Point3d(-11244.125648040384, -3225.5875596398578, 0.0) 308 | viewCenter18 = NXOpen.Point3d(11244.125648040346, 3225.5875596398719, 0.0) 309 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint18, viewCenter18) 310 | 311 | scaleAboutPoint19 = NXOpen.Point3d(-8995.3005184323065, -2580.4700477118859, 0.0) 312 | viewCenter19 = NXOpen.Point3d(8995.3005184322756, 2580.4700477119009, 0.0) 313 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint19, viewCenter19) 314 | 315 | scaleAboutPoint20 = NXOpen.Point3d(-7632.376197457711, -2674.9661339661225, 0.0) 316 | viewCenter20 = NXOpen.Point3d(7632.3761974576837, 2674.9661339661379, 0.0) 317 | workSimPart.ModelingViews.WorkView.ZoomAboutPoint(1.25, scaleAboutPoint20, viewCenter20) 318 | 319 | caePart4 = workSimPart 320 | seeds1 = [NXOpen.CAE.CAEBody.Null] * 1 321 | component1 = workSimPart.ComponentAssembly.RootComponent.FindObject("COMPONENT hullModelNX12_fem1 1") 322 | cAEBody1 = component1.FindObject("PROTO#CAE_Body(102)") 323 | seeds1[0] = cAEBody1 324 | relatedElemMethod1 = caePart4.SmartSelectionMgr.CreateRelatedElemMethod(seeds1, True) 325 | 326 | added1 = caeGroupBuilder1.Selection.Add(relatedElemMethod1) 327 | 328 | relatedElemMethod1.Dispose() 329 | markId12 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "New Group") 330 | 331 | caeGroupBuilder1.Name = "recipeGroup" 332 | 333 | theSession.DeleteUndoMark(markId12, None) 334 | 335 | markId13 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "New Group") 336 | 337 | caeGroupBuilder1.ClearDescription() 338 | 339 | nXObject2 = caeGroupBuilder1.Commit() 340 | 341 | theSession.DeleteUndoMark(markId13, None) 342 | 343 | theSession.SetUndoMarkName(markId11, "New Group") 344 | 345 | caeGroupBuilder1.Destroy() 346 | 347 | selectElementsBuilder1.Destroy() 348 | 349 | markId14 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Delete Selection Recipe(s)") 350 | 351 | caePart5 = workSimPart 352 | recipes1 = [NXOpen.CAE.SelectionRecipe.Null] * 1 353 | boundingVolumeSelectionRecipe1 = selectionRecipe1 354 | recipes1[0] = boundingVolumeSelectionRecipe1 355 | caePart5.SelectionRecipes.Delete(recipes1) 356 | 357 | # ---------------------------------------------- 358 | # Menu: Tools->Journal->Stop Recording 359 | # ---------------------------------------------- 360 | 361 | if __name__ == '__main__': 362 | main() -------------------------------------------------------------------------------- /Journals/journalCreateMeshCollector.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:12:28 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import NXOpen.PhysMat 12 | import SafetyOpen 13 | def main() : 14 | 15 | theSession = NXOpen.Session.GetSession() 16 | workFemPart = theSession.Parts.BaseWork 17 | displayFemPart = theSession.Parts.BaseDisplay 18 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 19 | 20 | fEModel1 = workFemPart.FindObject("FEModel") 21 | meshManager1 = fEModel1.Find("MeshManager") 22 | meshCollectorBuilder1 = meshManager1.CreateCollectorBuilder(NXOpen.CAE.MeshCollector.Null, "Solid") 23 | 24 | meshCollectorBuilder1.CollectorName = "Solid(1)" 25 | 26 | meshCollectorBuilder1.CollectorName = "inherited" 27 | 28 | theSession.SetUndoMarkName(markId1, "Mesh Collector Dialog") 29 | 30 | meshCollectorBuilder1.CollectorName = "Solid(1)" 31 | 32 | meshCollectorBuilder1.Destroy() 33 | 34 | theSession.UndoToMark(markId1, None) 35 | 36 | theSession.DeleteUndoMark(markId1, None) 37 | 38 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 39 | 40 | meshCollectorBuilder2 = meshManager1.CreateCollectorBuilder(NXOpen.CAE.MeshCollector.Null, "ThinShell") 41 | 42 | meshCollectorBuilder2.CollectorName = "Thin Shell(1)" 43 | 44 | theSession.SetUndoMarkName(markId2, "Mesh Collector Dialog") 45 | 46 | # ---------------------------------------------- 47 | # Dialog Begin Mesh Collector 48 | # ---------------------------------------------- 49 | caePart1 = workFemPart 50 | physicalPropertyTable1 = caePart1.PhysicalPropertyTables.CreatePhysicalPropertyTable("PSHELL", "NX NASTRAN - Structural", "NX NASTRAN", "PSHELL1", 26) 51 | 52 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 53 | 54 | propertyTable1 = physicalPropertyTable1.PropertyTable 55 | 56 | theSession.SetUndoMarkName(markId3, "PSHELL Dialog") 57 | 58 | # ---------------------------------------------- 59 | # Dialog Begin PSHELL 60 | # ---------------------------------------------- 61 | physicalMaterialListBuilder1 = workFemPart.MaterialManager.PhysicalMaterials.CreateListBlockBuilder() 62 | 63 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 64 | 65 | theSession.SetUndoMarkName(markId4, "Material List Dialog") 66 | 67 | id1 = theSession.GetNewestUndoMark(NXOpen.Session.MarkVisibility.AnyVisibility) 68 | 69 | theSession.DeleteUndoMark(id1, None) 70 | 71 | # ---------------------------------------------- 72 | # Dialog Begin Material List 73 | # ---------------------------------------------- 74 | markId5 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Material List") 75 | 76 | theSession.DeleteUndoMark(markId5, None) 77 | 78 | markId6 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Material List") 79 | 80 | physicalMaterial1 = workFemPart.MaterialManager.PhysicalMaterials.LoadFromNxmatmllibrary("Brass") 81 | 82 | theSession.DeleteUndoMark(markId6, None) 83 | 84 | theSession.DeleteUndoMark(id1, None) 85 | 86 | physicalMaterialListBuilder1.Destroy() 87 | 88 | markId7 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "PSHELL") 89 | 90 | theSession.DeleteUndoMark(markId7, None) 91 | 92 | markId8 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "PSHELL") 93 | 94 | markId9 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, None) 95 | 96 | physicalPropertyTable1.SetName("propertyName") 97 | 98 | propertyTable1.SetMaterialPropertyValue("material", False, physicalMaterial1) 99 | 100 | propertyTable1.SetTablePropertyWithoutValue("bending material") 101 | 102 | propertyTable1.SetTablePropertyWithoutValue("transverse shear material") 103 | 104 | propertyTable1.SetTablePropertyWithoutValue("membrane-bending coupling material") 105 | 106 | unit1 = workFemPart.UnitCollection.FindObject("MilliMeter") 107 | propertyTable1.SetBaseScalarWithDataPropertyValue("element thickness", "123", unit1) 108 | 109 | nErrs1 = theSession.UpdateManager.DoUpdate(markId9) 110 | 111 | theSession.DeleteUndoMark(markId9, None) 112 | 113 | theSession.DeleteUndoMark(markId8, None) 114 | 115 | theSession.SetUndoMarkName(markId3, "PSHELL") 116 | 117 | theSession.DeleteUndoMark(markId3, None) 118 | 119 | markId10 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Mesh Collector") 120 | 121 | meshCollectorBuilder2.CollectorName = "collectorName" 122 | 123 | theSession.DeleteUndoMark(markId10, None) 124 | 125 | markId11 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Mesh Collector") 126 | 127 | meshCollectorBuilder2.PropertyTable.SetNamedPropertyTablePropertyValue("Shell Property", physicalPropertyTable1) 128 | 129 | nXObject1 = meshCollectorBuilder2.Commit() 130 | 131 | theSession.DeleteUndoMark(markId11, None) 132 | 133 | theSession.SetUndoMarkName(markId2, "Mesh Collector") 134 | 135 | meshCollectorBuilder2.Destroy() 136 | 137 | # ---------------------------------------------- 138 | # Menu: Tools->Journal->Stop Recording 139 | # ---------------------------------------------- 140 | 141 | if __name__ == '__main__': 142 | main() -------------------------------------------------------------------------------- /Journals/journalCreateNodalForce.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:01:47 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import NXOpen.Fields 12 | import SafetyOpen 13 | def main() : 14 | 15 | theSession = NXOpen.Session.GetSession() 16 | workSimPart = theSession.Parts.BaseWork 17 | displaySimPart = theSession.Parts.BaseDisplay 18 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 19 | 20 | simPart1 = workSimPart 21 | simSimulation1 = simPart1.Simulation 22 | 23 | simBCBuilder1 = simSimulation1.CreateBcBuilderForLoadDescriptor("magnitudeDirectionForce", "Force(1)", 37) 24 | 25 | propertyTable1 = simBCBuilder1.PropertyTable 26 | 27 | setManager1 = simBCBuilder1.TargetSetManager 28 | 29 | setManager2 = propertyTable1.GetSetManagerPropertyValue("DirectionNode1") 30 | 31 | setManager3 = propertyTable1.GetSetManagerPropertyValue("DirectionNode2") 32 | 33 | setManager4 = propertyTable1.GetSetManagerPropertyValue("DirectionNode3") 34 | 35 | setManager5 = propertyTable1.GetSetManagerPropertyValue("DirectionNode4") 36 | 37 | theSession.SetUndoMarkName(markId1, "Force Dialog") 38 | 39 | # ---------------------------------------------- 40 | # Dialog Begin Force 41 | # ---------------------------------------------- 42 | simBCBuilder1.Destroy() 43 | 44 | theSession.UndoToMark(markId1, None) 45 | 46 | theSession.DeleteUndoMark(markId1, None) 47 | 48 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 49 | 50 | simPart2 = workSimPart 51 | simSimulation2 = simPart2.Simulation 52 | 53 | simBCBuilder2 = simSimulation2.CreateBcBuilderForLoadDescriptor("ComponentForceField", "Force(1)", 37) 54 | 55 | propertyTable2 = simBCBuilder2.PropertyTable 56 | 57 | setManager6 = simBCBuilder2.TargetSetManager 58 | 59 | theSession.SetUndoMarkName(markId2, "Force Dialog") 60 | 61 | # ---------------------------------------------- 62 | # Dialog Begin Force 63 | # ---------------------------------------------- 64 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Force") 65 | 66 | theSession.DeleteUndoMark(markId3, None) 67 | 68 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Force") 69 | 70 | objects1 = [None] * 1 71 | objects1[0] = NXOpen.CAE.SetObject() 72 | fEModelOccurrence1 = workSimPart.FindObject("FEModelOccurrence[2]") 73 | fENode1 = fEModelOccurrence1.Find("Node[1459]") 74 | objects1[0].Obj = fENode1 75 | objects1[0].SubType = NXOpen.CAE.CaeSetObjectSubType.NotSet 76 | objects1[0].SubId = 0 77 | setManager6.SetTargetSetMembers(0, NXOpen.CAE.CaeSetGroupFilterType.Node, objects1) 78 | 79 | simBCBuilder2.BcName = "ourForce" 80 | 81 | vectorFieldWrapper1 = propertyTable2.GetVectorFieldWrapperPropertyValue("CartesianMagnitude") 82 | 83 | unit1 = workSimPart.UnitCollection.FindObject("Newton") 84 | expression1 = workSimPart.Expressions.CreateSystemExpressionWithUnits("123", unit1) 85 | 86 | expression2 = workSimPart.Expressions.CreateSystemExpressionWithUnits("456", unit1) 87 | 88 | expression3 = workSimPart.Expressions.CreateSystemExpressionWithUnits("789", unit1) 89 | 90 | fieldManager1 = workSimPart.FindObject("FieldManager") 91 | expressions1 = [NXOpen.Expression.Null] * 3 92 | expressions1[0] = expression1 93 | expressions1[1] = expression2 94 | expressions1[2] = expression3 95 | vectorFieldWrapper2 = fieldManager1.CreateVectorFieldWrapperWithExpressions(expressions1) 96 | 97 | propertyTable2.SetVectorFieldWrapperPropertyValue("CartesianMagnitude", vectorFieldWrapper2) 98 | 99 | propertyTable2.SetTablePropertyWithoutValue("CylindricalMagnitude") 100 | 101 | propertyTable2.SetVectorFieldWrapperPropertyValue("CylindricalMagnitude", NXOpen.Fields.VectorFieldWrapper.Null) 102 | 103 | propertyTable2.SetTablePropertyWithoutValue("SphericalMagnitude") 104 | 105 | propertyTable2.SetVectorFieldWrapperPropertyValue("SphericalMagnitude", NXOpen.Fields.VectorFieldWrapper.Null) 106 | 107 | propertyTable2.SetTablePropertyWithoutValue("DistributionField") 108 | 109 | propertyTable2.SetScalarFieldWrapperPropertyValue("DistributionField", NXOpen.Fields.ScalarFieldWrapper.Null) 110 | 111 | propertyTable2.SetTablePropertyWithoutValue("ComponentsDistributionField") 112 | 113 | propertyTable2.SetVectorFieldWrapperPropertyValue("ComponentsDistributionField", NXOpen.Fields.VectorFieldWrapper.Null) 114 | 115 | propertyValue1 = [None] * 1 116 | propertyValue1[0] = "" 117 | propertyTable2.SetTextPropertyValue("description", propertyValue1) 118 | 119 | simBCBuilder2.DestinationFolder = NXOpen.CAE.SimLbcFolder.Null 120 | 121 | simBC1 = simBCBuilder2.CommitAddBc() 122 | 123 | simBCBuilder2.Destroy() 124 | 125 | theSession.DeleteUndoMark(markId4, None) 126 | 127 | theSession.SetUndoMarkName(markId2, "Force") 128 | 129 | # ---------------------------------------------- 130 | # Menu: Tools->Journal->Stop Recording 131 | # ---------------------------------------------- 132 | 133 | if __name__ == '__main__': 134 | main() -------------------------------------------------------------------------------- /Journals/journalCreateSolution.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:04:24 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 18 | 19 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 20 | 21 | theSession.SetUndoMarkName(markId2, "Solution Dialog") 22 | 23 | theSession.SetUndoMarkVisibility(markId2, None, NXOpen.Session.MarkVisibility.Invisible) 24 | 25 | theSession.SetUndoMarkName(markId2, "Solution") 26 | 27 | theSession.SetUndoMarkVisibility(markId2, None, NXOpen.Session.MarkVisibility.Visible) 28 | 29 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 30 | 31 | simPart1 = workSimPart 32 | simSimulation1 = simPart1.Simulation 33 | 34 | simSolution1 = simSimulation1.CreateSolution("NX NASTRAN", "Structural", "SESTATIC 101 - Single Constraint", "Solution 1", NXOpen.CAE.SimSimulation.AxisymAbstractionType.NotSet) 35 | 36 | propertyTable1 = simSolution1.PropertyTable 37 | 38 | caePart1 = workSimPart 39 | modelingObjectPropertyTable1 = caePart1.ModelingObjectPropertyTables.CreateModelingObjectPropertyTable("Bulk Data Echo Request", "NX NASTRAN - Structural", "NX NASTRAN", "Bulk Data Echo Request1", 1) 40 | 41 | caePart2 = workSimPart 42 | modelingObjectPropertyTable2 = caePart2.ModelingObjectPropertyTables.CreateModelingObjectPropertyTable("Structural Output Requests", "NX NASTRAN - Structural", "NX NASTRAN", "Structural Output Requests1", 2) 43 | 44 | theSession.SetUndoMarkName(markId3, "Solution Dialog") 45 | 46 | # ---------------------------------------------- 47 | # Dialog Begin Solution 48 | # ---------------------------------------------- 49 | # ---------------------------------------------- 50 | # Dialog Begin Solution 51 | # ---------------------------------------------- 52 | # ---------------------------------------------- 53 | # Dialog Begin Solution 54 | # ---------------------------------------------- 55 | # ---------------------------------------------- 56 | # Dialog Begin Solution 57 | # ---------------------------------------------- 58 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 59 | 60 | propertyTable2 = modelingObjectPropertyTable2.PropertyTable 61 | 62 | setManager1 = propertyTable2.GetSetManagerPropertyValue("Acceleration - Set") 63 | 64 | setManager2 = propertyTable2.GetSetManagerPropertyValue("Applied Load - Set") 65 | 66 | setManager3 = propertyTable2.GetSetManagerPropertyValue("Bolt Results - Set") 67 | 68 | setManager4 = propertyTable2.GetSetManagerPropertyValue("Gap Distance - Set") 69 | 70 | setManager5 = propertyTable2.GetSetManagerPropertyValue("Cohesive Element Results - Set") 71 | 72 | setManager6 = propertyTable2.GetSetManagerPropertyValue("Contact Result - Set") 73 | 74 | setManager7 = propertyTable2.GetSetManagerPropertyValue("Creep Strain - Set") 75 | 76 | setManager8 = propertyTable2.GetSetManagerPropertyValue("Cyclic Forces - Set") 77 | 78 | setManager9 = propertyTable2.GetSetManagerPropertyValue("Displacement - Set") 79 | 80 | setManager10 = propertyTable2.GetSetManagerPropertyValue("Elastic Strain - Set") 81 | 82 | setManager11 = propertyTable2.GetSetManagerPropertyValue("Energy Loss Per Cycle - Set") 83 | 84 | setManager12 = propertyTable2.GetSetManagerPropertyValue("Flexible Slider Result - Set") 85 | 86 | setManager13 = propertyTable2.GetSetManagerPropertyValue("Force - Set") 87 | 88 | setManager14 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Creep Strain - Set") 89 | 90 | setManager15 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Elastic Strain - Set") 91 | 92 | setManager16 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Plastic Strain - Set") 93 | 94 | setManager17 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Strain - Set") 95 | 96 | setManager18 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Stress - Set") 97 | 98 | setManager19 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Thermal Strain - Set") 99 | 100 | setManager20 = propertyTable2.GetSetManagerPropertyValue("Glue Result - Set") 101 | 102 | setManager21 = propertyTable2.GetSetManagerPropertyValue("Gpforce - Set") 103 | 104 | setManager22 = propertyTable2.GetSetManagerPropertyValue("Joint Result - Set") 105 | 106 | setManager23 = propertyTable2.GetSetManagerPropertyValue("Initial Strain - Set") 107 | 108 | setManager24 = propertyTable2.GetSetManagerPropertyValue("Kinetic Energy - Set") 109 | 110 | setManager25 = propertyTable2.GetSetManagerPropertyValue("Output Transformation Matrix Force - Set") 111 | 112 | setManager26 = propertyTable2.GetSetManagerPropertyValue("MPC Forces - Set") 113 | 114 | setManager27 = propertyTable2.GetSetManagerPropertyValue("Nonlinear Stress - Set") 115 | 116 | setManager28 = propertyTable2.GetSetManagerPropertyValue("Plastic Strain - Set") 117 | 118 | setManager29 = propertyTable2.GetSetManagerPropertyValue("Progressive Failure Results - Set") 119 | 120 | setManager30 = propertyTable2.GetSetManagerPropertyValue("SPC Forces - Set") 121 | 122 | setManager31 = propertyTable2.GetSetManagerPropertyValue("State Variable - Set") 123 | 124 | setManager32 = propertyTable2.GetSetManagerPropertyValue("Strain - Set") 125 | 126 | setManager33 = propertyTable2.GetSetManagerPropertyValue("Strain Energy - Set") 127 | 128 | setManager34 = propertyTable2.GetSetManagerPropertyValue("Stress - Set") 129 | 130 | setManager35 = propertyTable2.GetSetManagerPropertyValue("Thermal Strain - Set") 131 | 132 | setManager36 = propertyTable2.GetSetManagerPropertyValue("Temperature - Set") 133 | 134 | setManager37 = propertyTable2.GetSetManagerPropertyValue("Velocity - Set") 135 | 136 | theSession.SetUndoMarkName(markId4, "Structural Output Requests Dialog") 137 | 138 | # ---------------------------------------------- 139 | # Dialog Begin Structural Output Requests 140 | # ---------------------------------------------- 141 | # ---------------------------------------------- 142 | # Dialog Begin Structural Output Requests 143 | # ---------------------------------------------- 144 | markId5 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Structural Output Requests") 145 | 146 | theSession.DeleteUndoMark(markId5, None) 147 | 148 | markId6 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Structural Output Requests") 149 | 150 | markId7 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, None) 151 | 152 | propertyValue1 = [] 153 | propertyTable2.SetScalarArrayPropertyValue("Acceleration - Frequencies", propertyValue1) 154 | 155 | propertyTable2.SetTablePropertyWithoutValue("Acceleration - Frequencies") 156 | 157 | setManager38 = propertyTable2.GetSetManagerPropertyValue("Acceleration - Set") 158 | 159 | setManager39 = propertyTable2.GetSetManagerPropertyValue("Applied Load - Set") 160 | 161 | setManager40 = propertyTable2.GetSetManagerPropertyValue("Bolt Results - Set") 162 | 163 | setManager41 = propertyTable2.GetSetManagerPropertyValue("Gap Distance - Set") 164 | 165 | setManager42 = propertyTable2.GetSetManagerPropertyValue("Cohesive Element Results - Set") 166 | 167 | setManager43 = propertyTable2.GetSetManagerPropertyValue("Contact Result - Set") 168 | 169 | setManager44 = propertyTable2.GetSetManagerPropertyValue("Creep Strain - Set") 170 | 171 | setManager45 = propertyTable2.GetSetManagerPropertyValue("Cyclic Forces - Set") 172 | 173 | propertyValue2 = [] 174 | propertyTable2.SetScalarArrayPropertyValue("Displacement - Frequencies", propertyValue2) 175 | 176 | propertyTable2.SetTablePropertyWithoutValue("Displacement - Frequencies") 177 | 178 | setManager46 = propertyTable2.GetSetManagerPropertyValue("Displacement - Set") 179 | 180 | setManager47 = propertyTable2.GetSetManagerPropertyValue("Elastic Strain - Set") 181 | 182 | setManager48 = propertyTable2.GetSetManagerPropertyValue("Energy Loss Per Cycle - Set") 183 | 184 | propertyValue3 = [] 185 | propertyTable2.SetScalarArrayPropertyValue("Equivalent Radiated Power - Frequencies", propertyValue3) 186 | 187 | propertyTable2.SetTablePropertyWithoutValue("Equivalent Radiated Power - Frequencies") 188 | 189 | setManager49 = propertyTable2.GetSetManagerPropertyValue("Flexible Slider Result - Set") 190 | 191 | setManager50 = propertyTable2.GetSetManagerPropertyValue("Force - Set") 192 | 193 | setManager51 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Creep Strain - Set") 194 | 195 | setManager52 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Elastic Strain - Set") 196 | 197 | setManager53 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Plastic Strain - Set") 198 | 199 | setManager54 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Strain - Set") 200 | 201 | setManager55 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Stress - Set") 202 | 203 | setManager56 = propertyTable2.GetSetManagerPropertyValue("Gauss Point Thermal Strain - Set") 204 | 205 | setManager57 = propertyTable2.GetSetManagerPropertyValue("Glue Result - Set") 206 | 207 | setManager58 = propertyTable2.GetSetManagerPropertyValue("Gpforce - Set") 208 | 209 | setManager59 = propertyTable2.GetSetManagerPropertyValue("Joint Result - Set") 210 | 211 | setManager60 = propertyTable2.GetSetManagerPropertyValue("Initial Strain - Set") 212 | 213 | setManager61 = propertyTable2.GetSetManagerPropertyValue("Kinetic Energy - Set") 214 | 215 | setManager62 = propertyTable2.GetSetManagerPropertyValue("Output Transformation Matrix Force - Set") 216 | 217 | propertyValue4 = [] 218 | propertyTable2.SetScalarArrayPropertyValue("Modal Contribution - Frequencies", propertyValue4) 219 | 220 | propertyTable2.SetTablePropertyWithoutValue("Modal Contribution - Frequencies") 221 | 222 | setManager63 = propertyTable2.GetSetManagerPropertyValue("MPC Forces - Set") 223 | 224 | setManager64 = propertyTable2.GetSetManagerPropertyValue("Nonlinear Stress - Set") 225 | 226 | setManager65 = propertyTable2.GetSetManagerPropertyValue("Plastic Strain - Set") 227 | 228 | setManager66 = propertyTable2.GetSetManagerPropertyValue("Progressive Failure Results - Set") 229 | 230 | setManager67 = propertyTable2.GetSetManagerPropertyValue("SPC Forces - Set") 231 | 232 | setManager68 = propertyTable2.GetSetManagerPropertyValue("State Variable - Set") 233 | 234 | setManager69 = propertyTable2.GetSetManagerPropertyValue("Strain - Set") 235 | 236 | setManager70 = propertyTable2.GetSetManagerPropertyValue("Strain Energy - Set") 237 | 238 | propertyTable2.SetIntegerPropertyValue("Stress - Location", 1) 239 | 240 | setManager71 = propertyTable2.GetSetManagerPropertyValue("Stress - Set") 241 | 242 | setManager72 = propertyTable2.GetSetManagerPropertyValue("Thermal Strain - Set") 243 | 244 | setManager73 = propertyTable2.GetSetManagerPropertyValue("Temperature - Set") 245 | 246 | propertyValue5 = [] 247 | propertyTable2.SetScalarArrayPropertyValue("Velocity - Frequencies", propertyValue5) 248 | 249 | propertyTable2.SetTablePropertyWithoutValue("Velocity - Frequencies") 250 | 251 | setManager74 = propertyTable2.GetSetManagerPropertyValue("Velocity - Set") 252 | 253 | nErrs1 = theSession.UpdateManager.DoUpdate(markId7) 254 | 255 | theSession.DeleteUndoMark(markId7, None) 256 | 257 | theSession.DeleteUndoMark(markId6, None) 258 | 259 | theSession.SetUndoMarkName(markId4, "Structural Output Requests") 260 | 261 | theSession.DeleteUndoMark(markId4, None) 262 | 263 | markId8 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 264 | 265 | theSession.DeleteUndoMark(markId8, None) 266 | 267 | markId9 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 268 | 269 | markId10 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, None) 270 | 271 | propertyTable3 = simSolution1.PropertyTable 272 | 273 | propertyTable3.SetNamedPropertyTablePropertyValue("Bulk Data Echo Request", modelingObjectPropertyTable1) 274 | 275 | propertyTable3.SetNamedPropertyTablePropertyValue("Output Requests", modelingObjectPropertyTable2) 276 | 277 | id1 = theSession.NewestVisibleUndoMark 278 | 279 | nErrs2 = theSession.UpdateManager.DoUpdate(id1) 280 | 281 | simSolutionStep1 = simSolution1.CreateStep(0, True, "Subcase - Statics 1") 282 | 283 | nErrs3 = theSession.UpdateManager.DoUpdate(markId10) 284 | 285 | theSession.DeleteUndoMark(markId10, None) 286 | 287 | theSession.DeleteUndoMark(markId9, None) 288 | 289 | theSession.SetUndoMarkName(markId3, "Solution") 290 | 291 | theSession.DeleteUndoMark(markId3, None) 292 | 293 | theSession.DeleteUndoMark(id1, None) 294 | 295 | theSession.SetUndoMarkVisibility(markId1, None, NXOpen.Session.MarkVisibility.Visible) 296 | 297 | # ---------------------------------------------- 298 | # Menu: Tools->Journal->Stop Recording 299 | # ---------------------------------------------- 300 | 301 | if __name__ == '__main__': 302 | main() -------------------------------------------------------------------------------- /Journals/journalCreateSolutionNoSubcase.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:05:57 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 18 | 19 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 20 | 21 | theSession.SetUndoMarkName(markId2, "Solution Dialog") 22 | 23 | theSession.SetUndoMarkVisibility(markId2, None, NXOpen.Session.MarkVisibility.Invisible) 24 | 25 | theSession.SetUndoMarkName(markId2, "Solution") 26 | 27 | theSession.SetUndoMarkVisibility(markId2, None, NXOpen.Session.MarkVisibility.Visible) 28 | 29 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 30 | 31 | simPart1 = workSimPart 32 | simSimulation1 = simPart1.Simulation 33 | 34 | simSolution1 = simSimulation1.CreateSolution("NX NASTRAN", "Structural", "SESTATIC 101 - Single Constraint", "Solution 2", NXOpen.CAE.SimSimulation.AxisymAbstractionType.NotSet) 35 | 36 | propertyTable1 = simSolution1.PropertyTable 37 | 38 | theSession.SetUndoMarkName(markId3, "Solution Dialog") 39 | 40 | # ---------------------------------------------- 41 | # Dialog Begin Solution 42 | # ---------------------------------------------- 43 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 44 | 45 | theSession.DeleteUndoMark(markId4, None) 46 | 47 | markId5 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution") 48 | 49 | markId6 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, None) 50 | 51 | propertyTable2 = simSolution1.PropertyTable 52 | 53 | modelingObjectPropertyTable1 = workSimPart.ModelingObjectPropertyTables.FindObject("SsmoPropTable[Bulk Data Echo Request1]") 54 | propertyTable2.SetNamedPropertyTablePropertyValue("Bulk Data Echo Request", modelingObjectPropertyTable1) 55 | 56 | modelingObjectPropertyTable2 = workSimPart.ModelingObjectPropertyTables.FindObject("SsmoPropTable[Structural Output Requests1]") 57 | propertyTable2.SetNamedPropertyTablePropertyValue("Output Requests", modelingObjectPropertyTable2) 58 | 59 | nErrs1 = theSession.UpdateManager.DoUpdate(markId6) 60 | 61 | theSession.DeleteUndoMark(markId6, None) 62 | 63 | theSession.DeleteUndoMark(markId5, None) 64 | 65 | theSession.SetUndoMarkName(markId3, "Solution") 66 | 67 | theSession.DeleteUndoMark(markId3, None) 68 | 69 | theSession.DeleteUndoMark(markId2, None) 70 | 71 | theSession.SetUndoMarkVisibility(markId1, None, NXOpen.Session.MarkVisibility.Visible) 72 | 73 | # ---------------------------------------------- 74 | # Menu: Tools->Journal->Stop Recording 75 | # ---------------------------------------------- 76 | 77 | if __name__ == '__main__': 78 | main() -------------------------------------------------------------------------------- /Journals/journalCreateSubcase.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:05:26 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution Step") 18 | 19 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Start") 20 | 21 | simSimulation1 = workSimPart.FindObject("Simulation") 22 | simSolution1 = simSimulation1.FindObject("Solution[Solution 1]") 23 | id1 = theSession.NewestVisibleUndoMark 24 | 25 | nErrs1 = theSession.UpdateManager.DoUpdate(id1) 26 | 27 | simSolutionStep1 = simSolution1.CreateStep(0, True, "Subcase - Statics 2") 28 | 29 | propertyTable1 = simSolutionStep1.PropertyTable 30 | 31 | theSession.SetUndoMarkName(markId2, "Solution Step Dialog") 32 | 33 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution Step") 34 | 35 | theSession.DeleteUndoMark(markId3, None) 36 | 37 | markId4 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Solution Step") 38 | 39 | markId5 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, None) 40 | 41 | simSolutionStep1.SetName("mySecondSubcase") 42 | 43 | propertyTable2 = simSolutionStep1.PropertyTable 44 | 45 | nErrs2 = theSession.UpdateManager.DoUpdate(markId5) 46 | 47 | theSession.DeleteUndoMark(markId5, None) 48 | 49 | theSession.DeleteUndoMark(markId4, None) 50 | 51 | theSession.SetUndoMarkName(markId2, "Solution Step") 52 | 53 | theSession.DeleteUndoMark(markId2, None) 54 | 55 | theSession.SetUndoMarkVisibility(markId1, None, NXOpen.Session.MarkVisibility.Visible) 56 | 57 | # ---------------------------------------------- 58 | # Menu: Tools->Journal->Stop Recording 59 | # ---------------------------------------------- 60 | 61 | if __name__ == '__main__': 62 | main() -------------------------------------------------------------------------------- /Journals/journalEnvelopeResults.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:09:57 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | # ---------------------------------------------- 18 | # Menu: Tools->Results->Envelope... 19 | # ---------------------------------------------- 20 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 21 | 22 | resultsManipulationEnvelopeBuilder1 = theSession.ResultManager.CreateResultsManipulationEnvelopeBuilder() 23 | 24 | caePart1 = workSimPart 25 | selectElementsBuilder1 = caePart1.SelectElementMgr.CreateSelectElementsBuilder() 26 | 27 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.OutputName = "Default Result OutputName" 28 | 29 | resultsManipulationEnvelopeBuilder1.ApproachOption = NXOpen.CAE.ResultsManipulationEnvelopeBuilder.Approach.ThroughLoadCasesandResults 30 | 31 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.LoadCaseName = "Envelope Max Through 2 load cases" 32 | 33 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.CompanionName = "Companion" 34 | 35 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.NeedLoadImmediately = True 36 | 37 | resultsManipulationEnvelopeBuilder1.OutputFieldSettings.IndependentDomainForElementNodalResult = NXOpen.CAE.ResultsManipOutputFieldSettings.IndepDomainDefinitionOptions.ElementNodeID 38 | 39 | theSession.SetUndoMarkName(markId1, "Results Envelope Dialog") 40 | 41 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.LoadCaseName = "Envelope Max Through 0 load cases" 42 | 43 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.LoadCaseName = "Envelope Max Through 1 load cases" 44 | 45 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.LoadCaseName = "Envelope Max Through 2 load cases" 46 | 47 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.CompanionName = "CompanionIdentifier" 48 | 49 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Results Envelope") 50 | 51 | theSession.DeleteUndoMark(markId2, None) 52 | 53 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "Results Envelope") 54 | 55 | resultParameters1 = theSession.ResultManager.CreateResultParameters() 56 | 57 | resultParameters1.SetDBScaling(0) 58 | 59 | signalProcessingDBSettings1 = resultParameters1.GetDbSettings() 60 | 61 | resultManager1 = theSession.ResultManager 62 | solutionResult1 = resultManager1.FindObject("SolutionResult[hullModelNX12_fem1_sim1.sim_Transverse]") 63 | loadcase1 = solutionResult1.Find("Loadcase[1]") 64 | iteration1 = loadcase1.Find("Iteration[1]") 65 | resultType1 = iteration1.Find("ResultType[[Stress][Element-Nodal]]") 66 | resultParameters1.SetGenericResultType(resultType1) 67 | 68 | resultParameters1.SetBeamSection(NXOpen.CAE.Result.BeamSection.ValueOf(-1)) 69 | 70 | resultParameters1.SetShellSection(NXOpen.CAE.Result.ShellSection.TrueMaximum) 71 | 72 | resultParameters1.SetResultComponent(NXOpen.CAE.Result.Component.VonMises) 73 | 74 | resultParameters1.SetCoordinateSystem(NXOpen.CAE.Result.CoordinateSystem.AbsoluteRectangular) 75 | 76 | resultParameters1.SetSelectedCoordinateSystem(NXOpen.CAE.Result.CoordinateSystemSource.NotSet, -1) 77 | 78 | resultParameters1.SetRotationAxisOfAbsoluteCyndricalCSYS(NXOpen.CAE.Post.AxisymetricAxis.NotSet) 79 | 80 | resultParameters1.SetBeamResultsInLocalCoordinateSystem(True) 81 | 82 | resultParameters1.SetShellResultsInProjectedCoordinateSystem(False) 83 | 84 | resultParameters1.MakeElementResult(False) 85 | 86 | resultParameters1.SetElementValueCriterion(NXOpen.CAE.Result.ElementValueCriterion.Average) 87 | 88 | resultParameters1.SetSpectrumScaling(NXOpen.CAE.SignalProcessingPlotData.ScalingType.Unknown) 89 | 90 | resultParameters1.SetAcousticWeighting(NXOpen.CAE.SignalProcessingPlotData.AcousticalWeighting.NotSet) 91 | 92 | average1 = NXOpen.CAE.Result.Averaging() 93 | 94 | average1.DoAveraging = False 95 | average1.AverageAcrossPropertyIds = True 96 | average1.AverageAcrossMaterialIds = True 97 | average1.AverageAcrossElementTypes = False 98 | average1.AverageAcrossFeatangle = True 99 | average1.AverageAcrossAnglevalue = 45.0 100 | average1.IncludeInternalElementContributions = True 101 | resultParameters1.SetAveragingCriteria(average1) 102 | 103 | resultParameters1.SetComputationType(NXOpen.CAE.Result.ComputationType.NotSet) 104 | 105 | resultParameters1.SetComputeOnVisible(False) 106 | 107 | resultParameters1.SetComplexCriterion(NXOpen.CAE.Result.Complex.Real) 108 | 109 | resultParameters1.SetPhaseAngle(0.0) 110 | 111 | resultParameters1.SetSectionPlyLayer(0, 0, 1) 112 | 113 | resultParameters1.SetPlyID(0) 114 | 115 | resultParameters1.SetPlyLocation(NXOpen.CAE.Result.PlyLocation.Middle) 116 | 117 | resultParameters1.SetScale(1.0) 118 | 119 | unit1 = workSimPart.UnitCollection.FindObject("StressNewtonPerSquareMilliMeter") 120 | resultParameters1.SetUnit(unit1) 121 | 122 | resultParameters1.SetAbsoluteValue(False) 123 | 124 | resultParameters1.SetTensorComponentAbsoluteValue(NXOpen.CAE.Result.TensorDerivedAbsolute.DerivedComponent) 125 | 126 | resultParameters1.SetCalculateBeamStrResults(False) 127 | 128 | resultParameters1.SetBeamFillets(False) 129 | 130 | resultParameters1.SetBeamFilletRadius(0.0) 131 | 132 | resultParameters1.SetIncludeMidNode(True) 133 | 134 | resultParameters1.SetIsReferenceNode(False) 135 | 136 | resultParameters1.SetReferenceNode(None) 137 | 138 | cycparams1 = resultParameters1.GetCyclicSymmParameters() 139 | 140 | cycparams1[0].ResultOption = NXOpen.CAE.CyclicSymmetricParameters.GetResult.OnOriginalModel 141 | 142 | cycparams1[0].OriginalResultOption = NXOpen.CAE.CyclicSymmetricParameters.OriginalResult.BySector 143 | 144 | cycparams1[0].SectCriteria = NXOpen.CAE.CyclicSymmetricParameters.SectorCriteria.Index 145 | 146 | cycparams1[0].SectorValue = NXOpen.CAE.CyclicSymmetricParameters.Value.Maximum 147 | 148 | cycparams1[0].EnvValue = NXOpen.CAE.CyclicSymmetricParameters.EnvelopeValue.Average 149 | 150 | cycparams1[0].SectorIndex = 1 151 | 152 | sectors1 = [] 153 | cycparams1[0].SetSectorIndices(sectors1) 154 | 155 | cycparams2 = [NXOpen.CAE.CyclicSymmetricParameters.Null] * 1 156 | cycparams2[0] = cycparams1[0] 157 | resultParameters1.SetCyclicSymmParameters(cycparams2) 158 | 159 | axiSymmetricParameters1 = resultParameters1.GetAxiSymmetricParameters() 160 | 161 | axiSymmetricParameters1.ResultOption = NXOpen.CAE.AxiSymmetricParameters.GetResult.OnOriginalModel 162 | 163 | axiSymmetricParameters1.RotationAxis = NXOpen.CAE.AxiSymmetricParameters.AxisOfRotation.ValueOf(-1) 164 | 165 | axiSymmetricParameters1.AxiOptions = NXOpen.CAE.AxiSymmetricParameters.Options.AtRevolveAngle 166 | 167 | axiSymmetricParameters1.EnvelopeVal = NXOpen.CAE.AxiSymmetricParameters.EnvVal.Average 168 | 169 | axiSymmetricParameters1.RevolveAngle = 0.0 170 | 171 | axiSymmetricParameters1.StartRevolveAngle = 0.0 172 | 173 | axiSymmetricParameters1.EndRevolveAngle = 360.0 174 | 175 | axiSymmetricParameters1.NumberOfSections = 40 176 | 177 | resultParameters1.SetProjectOnNodeNormal(False) 178 | 179 | resultParameters2 = theSession.ResultManager.CreateResultParameters() 180 | 181 | resultParameters2.SetDBScaling(0) 182 | 183 | signalProcessingDBSettings2 = resultParameters2.GetDbSettings() 184 | 185 | solutionResult2 = resultManager1.FindObject("SolutionResult[hullModelNX12_fem1_sim1.sim_Longitudinal]") 186 | loadcase2 = solutionResult2.Find("Loadcase[1]") 187 | iteration2 = loadcase2.Find("Iteration[1]") 188 | resultType2 = iteration2.Find("ResultType[[Stress][Element-Nodal]]") 189 | resultParameters2.SetGenericResultType(resultType2) 190 | 191 | resultParameters2.SetBeamSection(NXOpen.CAE.Result.BeamSection.ValueOf(-1)) 192 | 193 | resultParameters2.SetShellSection(NXOpen.CAE.Result.ShellSection.TrueMaximum) 194 | 195 | resultParameters2.SetResultComponent(NXOpen.CAE.Result.Component.VonMises) 196 | 197 | resultParameters2.SetCoordinateSystem(NXOpen.CAE.Result.CoordinateSystem.AbsoluteRectangular) 198 | 199 | resultParameters2.SetSelectedCoordinateSystem(NXOpen.CAE.Result.CoordinateSystemSource.NotSet, -1) 200 | 201 | resultParameters2.SetRotationAxisOfAbsoluteCyndricalCSYS(NXOpen.CAE.Post.AxisymetricAxis.NotSet) 202 | 203 | resultParameters2.SetBeamResultsInLocalCoordinateSystem(True) 204 | 205 | resultParameters2.SetShellResultsInProjectedCoordinateSystem(False) 206 | 207 | resultParameters2.MakeElementResult(False) 208 | 209 | resultParameters2.SetElementValueCriterion(NXOpen.CAE.Result.ElementValueCriterion.Average) 210 | 211 | resultParameters2.SetSpectrumScaling(NXOpen.CAE.SignalProcessingPlotData.ScalingType.Unknown) 212 | 213 | resultParameters2.SetAcousticWeighting(NXOpen.CAE.SignalProcessingPlotData.AcousticalWeighting.NotSet) 214 | 215 | average2 = NXOpen.CAE.Result.Averaging() 216 | 217 | average2.DoAveraging = False 218 | average2.AverageAcrossPropertyIds = True 219 | average2.AverageAcrossMaterialIds = True 220 | average2.AverageAcrossElementTypes = False 221 | average2.AverageAcrossFeatangle = True 222 | average2.AverageAcrossAnglevalue = 45.0 223 | average2.IncludeInternalElementContributions = True 224 | resultParameters2.SetAveragingCriteria(average2) 225 | 226 | resultParameters2.SetComputationType(NXOpen.CAE.Result.ComputationType.NotSet) 227 | 228 | resultParameters2.SetComputeOnVisible(False) 229 | 230 | resultParameters2.SetComplexCriterion(NXOpen.CAE.Result.Complex.Real) 231 | 232 | resultParameters2.SetPhaseAngle(0.0) 233 | 234 | resultParameters2.SetSectionPlyLayer(0, 0, 1) 235 | 236 | resultParameters2.SetPlyID(0) 237 | 238 | resultParameters2.SetPlyLocation(NXOpen.CAE.Result.PlyLocation.Middle) 239 | 240 | resultParameters2.SetScale(1.0) 241 | 242 | resultParameters2.SetUnit(unit1) 243 | 244 | resultParameters2.SetAbsoluteValue(False) 245 | 246 | resultParameters2.SetTensorComponentAbsoluteValue(NXOpen.CAE.Result.TensorDerivedAbsolute.DerivedComponent) 247 | 248 | resultParameters2.SetCalculateBeamStrResults(False) 249 | 250 | resultParameters2.SetBeamFillets(False) 251 | 252 | resultParameters2.SetBeamFilletRadius(0.0) 253 | 254 | resultParameters2.SetIncludeMidNode(True) 255 | 256 | resultParameters2.SetIsReferenceNode(False) 257 | 258 | resultParameters2.SetReferenceNode(None) 259 | 260 | cycparams3 = resultParameters2.GetCyclicSymmParameters() 261 | 262 | cycparams3[0].ResultOption = NXOpen.CAE.CyclicSymmetricParameters.GetResult.OnOriginalModel 263 | 264 | cycparams3[0].OriginalResultOption = NXOpen.CAE.CyclicSymmetricParameters.OriginalResult.BySector 265 | 266 | cycparams3[0].SectCriteria = NXOpen.CAE.CyclicSymmetricParameters.SectorCriteria.Index 267 | 268 | cycparams3[0].SectorValue = NXOpen.CAE.CyclicSymmetricParameters.Value.Maximum 269 | 270 | cycparams3[0].EnvValue = NXOpen.CAE.CyclicSymmetricParameters.EnvelopeValue.Average 271 | 272 | cycparams3[0].SectorIndex = 1 273 | 274 | sectors2 = [] 275 | cycparams3[0].SetSectorIndices(sectors2) 276 | 277 | cycparams4 = [NXOpen.CAE.CyclicSymmetricParameters.Null] * 1 278 | cycparams4[0] = cycparams3[0] 279 | resultParameters2.SetCyclicSymmParameters(cycparams4) 280 | 281 | axiSymmetricParameters2 = resultParameters2.GetAxiSymmetricParameters() 282 | 283 | axiSymmetricParameters2.ResultOption = NXOpen.CAE.AxiSymmetricParameters.GetResult.OnOriginalModel 284 | 285 | axiSymmetricParameters2.RotationAxis = NXOpen.CAE.AxiSymmetricParameters.AxisOfRotation.ValueOf(-1) 286 | 287 | axiSymmetricParameters2.AxiOptions = NXOpen.CAE.AxiSymmetricParameters.Options.AtRevolveAngle 288 | 289 | axiSymmetricParameters2.EnvelopeVal = NXOpen.CAE.AxiSymmetricParameters.EnvVal.Average 290 | 291 | axiSymmetricParameters2.RevolveAngle = 0.0 292 | 293 | axiSymmetricParameters2.StartRevolveAngle = 0.0 294 | 295 | axiSymmetricParameters2.EndRevolveAngle = 360.0 296 | 297 | axiSymmetricParameters2.NumberOfSections = 40 298 | 299 | resultParameters2.SetProjectOnNodeNormal(False) 300 | 301 | results1 = [NXOpen.CAE.Result.Null] * 2 302 | results1[0] = solutionResult1 303 | results1[1] = solutionResult2 304 | parameters1 = [NXOpen.CAE.ResultParameters.Null] * 2 305 | parameters1[0] = resultParameters1 306 | parameters1[1] = resultParameters2 307 | resultsManipulationEnvelopeBuilder1.InputSettings.SetResultsAndParameters(results1, parameters1) 308 | 309 | resultsManipulationEnvelopeBuilder1.UnitSystem.UnitsSystemType = NXOpen.CAE.ResultsManipulationUnitsSystem.Type.FromResult 310 | 311 | resultsManipulationEnvelopeBuilder1.UnitSystem.Result = solutionResult2 312 | 313 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.OutputFile = "C:\\Users\\Frederik\\Documents\\SC2022\\Python\\CompanionIdentifier.unv" 314 | 315 | simSimulation1 = workSimPart.FindObject("Simulation") 316 | simSolution1 = simSimulation1.FindObject("Solution[Transverse]") 317 | simResultReference1 = simSolution1.Find("Structural") 318 | resultsManipulationEnvelopeBuilder1.OutputFileSettings.CompanionResultReference = simResultReference1 319 | 320 | nXObject1 = resultsManipulationEnvelopeBuilder1.Commit() 321 | 322 | resultsManipulationEnvelopeBuilder1.UnitSystem.UnitsSystemType = NXOpen.CAE.ResultsManipulationUnitsSystem.Type.FromResult 323 | 324 | resultsManipulationEnvelopeBuilder1.UnitSystem.Result = solutionResult2 325 | 326 | theSession.DeleteUndoMark(markId3, None) 327 | 328 | theSession.SetUndoMarkName(markId1, "Results Envelope") 329 | 330 | resultsManipulationEnvelopeBuilder1.Destroy() 331 | 332 | selectElementsBuilder1.Destroy() 333 | 334 | # ---------------------------------------------- 335 | # Menu: Tools->Journal->Stop Recording 336 | # ---------------------------------------------- 337 | 338 | if __name__ == '__main__': 339 | main() -------------------------------------------------------------------------------- /Journals/journalMakeSolutionInactive.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2023 2 | # Journal created by Frederik on Thu Aug 25 08:03:57 2022 W. Europe Daylight Time 3 | # 4 | import math 5 | import DSEDesignWorkflow 6 | import DSEPlatform 7 | import Join 8 | import MoldCooling 9 | import NXOpen 10 | import NXOpen.CAE 11 | import SafetyOpen 12 | def main() : 13 | 14 | theSession = NXOpen.Session.GetSession() 15 | workSimPart = theSession.Parts.BaseWork 16 | displaySimPart = theSession.Parts.BaseDisplay 17 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Deactivate Solution") 18 | 19 | simSimulation1 = workSimPart.FindObject("Simulation") 20 | simSimulation1.ActiveSolution = NXOpen.CAE.SimSolution.Null 21 | 22 | # ---------------------------------------------- 23 | # Menu: Tools->Journal->Stop Recording 24 | # ---------------------------------------------- 25 | 26 | if __name__ == '__main__': 27 | main() -------------------------------------------------------------------------------- /Journals/journal_3d_mesh.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2312 2 | # Journal created by frederik on Thu May 16 09:18:23 2024 W. Europe Daylight Time 3 | # 4 | import math 5 | import NXOpen 6 | import NXOpen.CAE 7 | def main() : 8 | 9 | theSession = NXOpen.Session.GetSession() #type: NXOpen.Session 10 | workFemPart = theSession.Parts.BaseWork 11 | displayFemPart = theSession.Parts.BaseDisplay 12 | # ---------------------------------------------- 13 | # Menu: Insert->Mesh->3D Tetrahedral Mesh... 14 | # ---------------------------------------------- 15 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Start") 16 | 17 | fEModel1: NXOpen.CAE.FEModel = workFemPart.FindObject("FEModel") 18 | meshManager1: NXOpen.CAE.MeshManager = fEModel1.Find("MeshManager") 19 | mesh3dTetBuilder1 = meshManager1.CreateMesh3dTetBuilder(NXOpen.CAE.Mesh3d.Null) 20 | mesh3dTetBuilder1.GetCommittedObjects 21 | 22 | mesh3dTetBuilder1.ElementType.DestinationCollector.ElementContainer = NXOpen.CAE.MeshCollector.Null 23 | 24 | theSession.SetUndoMarkName(markId1, "3D Tetrahedral Mesh Dialog") 25 | 26 | cAEBody1 = workFemPart.FindObject("CAE_Body(1)") 27 | added1 = mesh3dTetBuilder1.SelectionList.Add(cAEBody1) 28 | 29 | markId2 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "3D Tetrahedral Mesh") 30 | 31 | theSession.DeleteUndoMark(markId2, None) 32 | 33 | markId3 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Invisible, "3D Tetrahedral Mesh") 34 | 35 | mesh3dTetBuilder1.CheckElementSizeOption = True 36 | 37 | mesh3dTetBuilder1.AutoResetOption = False 38 | 39 | mesh3dTetBuilder1.ElementType.ElementDimension = NXOpen.CAE.ElementTypeBuilder.ElementType.FreeSolid 40 | 41 | mesh3dTetBuilder1.ElementType.ElementTypeName = "CTETRA(10)" 42 | 43 | destinationCollectorBuilder1 = mesh3dTetBuilder1.ElementType.DestinationCollector 44 | 45 | destinationCollectorBuilder1.ElementContainer = NXOpen.CAE.MeshCollector.Null 46 | 47 | destinationCollectorBuilder1.AutomaticMode = True 48 | 49 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("automatic size option bool", False) 50 | 51 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("automatic element size factor", "1", NXOpen.Unit.Null) 52 | 53 | unit1 = workFemPart.UnitCollection.FindObject("MilliMeter") 54 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("quad mesh overall edge size", "500", unit1) 55 | 56 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("maximum growth rate", "1.3", NXOpen.Unit.Null) 57 | 58 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("surface meshing method", 0) 59 | 60 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("create pyramids bool", False) 61 | 62 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("small feature percentage", "10", NXOpen.Unit.Null) 63 | 64 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("small feature size", "50", unit1) 65 | 66 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("Level of Discretization around a Circle", "25", NXOpen.Unit.Null) 67 | 68 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("Enable Distance Based Size Variation", False) 69 | 70 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("Maximum Distance to Original Mesh", "1", unit1) 71 | 72 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("Maximum Level of Discretization around a Circle", "75", NXOpen.Unit.Null) 73 | 74 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("face proximity enable", False) 75 | 76 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("face proximity search direction", 0) 77 | 78 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("face proximity points in gap", "0.5", NXOpen.Unit.Null) 79 | 80 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("edge proximity enable", False) 81 | 82 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("edge proximity faces in gap", "0.5", NXOpen.Unit.Null) 83 | 84 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("fillet num elements", 3) 85 | 86 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("num elements on cylinder circumference", 6) 87 | 88 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("element size on cylinder height", "1", unit1) 89 | 90 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("midnodes", 0) 91 | 92 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("geometry tolerance option bool", False) 93 | 94 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("geometry tolerance", "0", unit1) 95 | 96 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("max jacobian", "10", NXOpen.Unit.Null) 97 | 98 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("mapped mesh option bool", True) 99 | 100 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("multiblock cylinder option bool", False) 101 | 102 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("surface mesh size variation", "50", NXOpen.Unit.Null) 103 | 104 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("surface curvature threshold", "252.5", unit1) 105 | 106 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("volume mesh size variation", "50", NXOpen.Unit.Null) 107 | 108 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("internal mesh gradation", "1.05", NXOpen.Unit.Null) 109 | 110 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("internal max edge option bool", False) 111 | 112 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("internal max edge length value", "0", unit1) 113 | 114 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("two elements through thickness bool", False) 115 | 116 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("mesh transition bool", False) 117 | 118 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("remesh on bad quality bool", False) 119 | 120 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("maximum edge length bool", False) 121 | 122 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("maximum edge length", "1", unit1) 123 | 124 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("small feature tolerance", "10", NXOpen.Unit.Null) 125 | 126 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("small feature value", "50", NXOpen.Unit.Null) 127 | 128 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("boundary layer element type", 3) 129 | 130 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("insert blend elements", True) 131 | 132 | unit2 = workFemPart.UnitCollection.FindObject("Degrees") 133 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("blending angle", "90", unit2) 134 | 135 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("sweep angle", "45", unit2) 136 | 137 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("control aspect ratio", False) 138 | 139 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("maximum exposed aspect ratio", "1000", NXOpen.Unit.Null) 140 | 141 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("control slender", False) 142 | 143 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("minimum aspect ratio", "0.01", NXOpen.Unit.Null) 144 | 145 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("maximum imprint dihedral angle", "150", unit2) 146 | 147 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("gradation rate", "10", NXOpen.Unit.Null) 148 | 149 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("smoothing distance factor", "3", NXOpen.Unit.Null) 150 | 151 | mesh3dTetBuilder1.PropertyTable.SetBooleanPropertyValue("all-tet boundary layer", False) 152 | 153 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("dont format mesh to solver", 0) 154 | 155 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("quad mesh edge match tolerance", "0.02", NXOpen.Unit.Null) 156 | 157 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("quad mesh smoothness tolerance", "0.01", unit1) 158 | 159 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("min face angle", "20", unit2) 160 | 161 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("mesh time stamp", 0) 162 | 163 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("quad mesh node coincidence tolerance", "0.0001", unit1) 164 | 165 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("mesh edit allowed", 0) 166 | 167 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("edge angle", "15", unit2) 168 | 169 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("merDit lijkt ge edge toggle", 0) 170 | 171 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("auto constraining", 1) 172 | 173 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("curvature scaling", 1) 174 | 175 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("target angle", "45", unit2) 176 | 177 | mesh3dTetBuilder1.PropertyTable.SetIntegerPropertyValue("edge shape", 2) 178 | 179 | mesh3dTetBuilder1.PropertyTable.SetBaseScalarWithDataPropertyValue("successful element size", "0", NXOpen.Unit.Null) 180 | 181 | id1 = theSession.NewestVisibleUndoMark 182 | 183 | nErrs1 = theSession.UpdateManager.DoUpdate(id1) 184 | 185 | meshes1 = mesh3dTetBuilder1.CommitMesh() 186 | mesh3dTetBuilder1. 187 | 188 | theSession.DeleteUndoMark(markId3, None) 189 | 190 | theSession.SetUndoMarkName(id1, "3D Tetrahedral Mesh") 191 | 192 | mesh3dTetBuilder1.Destroy() 193 | 194 | theSession.CleanUpFacetedFacesAndEdges() 195 | 196 | # ---------------------------------------------- 197 | # Menu: Tools->Automation->Journal->Stop Recording 198 | # ---------------------------------------------- 199 | 200 | if __name__ == '__main__': 201 | main() -------------------------------------------------------------------------------- /Journals/journal_add_part_to_assembly.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theScriptingEngineer/NXOpen-CAE-python/f0746445e330747b0e49bd7e3b5a5a901bac6a48/Journals/journal_add_part_to_assembly.cs -------------------------------------------------------------------------------- /Journals/journal_apply_post_group_user_visibility.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2306 2 | # Journal created by HP on Mon Jul 22 17:20:15 2024 W. Europe Daylight Time 3 | # 4 | import math 5 | import NXOpen 6 | import NXOpen.CAE 7 | def main() : 8 | 9 | theSession = NXOpen.Session.GetSession() 10 | workSimPart = theSession.Parts.BaseWork 11 | displaySimPart = theSession.Parts.BaseDisplay 12 | markId1 = theSession.SetUndoMark(NXOpen.Session.MarkVisibility.Visible, "Show Only Group(s)") 13 | 14 | fEModelOccurrence1 = workSimPart.FindObject("FEModelOccurrence[8]") 15 | caeGroup1 = fEModelOccurrence1.FindObject("CaeGroup[MainBoomBottom]") 16 | caeGroup1.ShowOnlyGroup() 17 | 18 | rotMatrix1 = NXOpen.Matrix3x3() 19 | 20 | rotMatrix1.Xx = 0.81868981892792381 21 | rotMatrix1.Xy = 0.57332503243447586 22 | rotMatrix1.Xz = -0.032332453785181028 23 | rotMatrix1.Yx = -0.039084264791366577 24 | rotMatrix1.Yy = 0.11180874101363869 25 | rotMatrix1.Yz = 0.99296083793806467 26 | rotMatrix1.Zx = 0.5729043555686073 27 | rotMatrix1.Zy = -0.81166323842893884 28 | rotMatrix1.Zz = 0.11394466531420301 29 | translation1 = NXOpen.Point3d(-7554.342606962492, 2034.2802574848361, -15739.214069367838) 30 | workSimPart.ModelingViews.WorkView.SetRotationTranslationScale(rotMatrix1, translation1, 0.01213137740467715) 31 | 32 | results1 = [NXOpen.CAE.Result.Null] * 1 33 | resultManager1 = theSession.ResultManager 34 | solutionResult1 = resultManager1.FindObject("SolutionResult[Full_crane_assyfem_sim.sim_Position0][Structural]") 35 | results1[0] = solutionResult1 36 | usergroupIds1 = [None] * 1 37 | usergroupIds1[0] = 36 38 | theSession.Post.PostviewApplyUserGroupVisibility(6, results1, usergroupIds1, NXOpen.CAE.Post.GroupVisibility.ShowOnly) 39 | 40 | # ---------------------------------------------- 41 | # Menu: Tools->Automation->Journal->Stop Recording 42 | # ---------------------------------------------- 43 | 44 | if __name__ == '__main__': 45 | main() -------------------------------------------------------------------------------- /Journals/journal_body_from_copy_feature.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theScriptingEngineer/NXOpen-CAE-python/f0746445e330747b0e49bd7e3b5a5a901bac6a48/Journals/journal_body_from_copy_feature.cs -------------------------------------------------------------------------------- /Journals/journal_selection_recipe.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theScriptingEngineer/NXOpen-CAE-python/f0746445e330747b0e49bd7e3b5a5a901bac6a48/Journals/journal_selection_recipe.cs -------------------------------------------------------------------------------- /Journals/journal_show_group_post_first_last.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2306 2 | # Journal created by HP on Tue Jul 23 09:07:15 2024 W. Europe Daylight Time 3 | # 4 | import math 5 | import NXOpen 6 | import NXOpen.CAE 7 | def main() : 8 | 9 | theSession = NXOpen.Session.GetSession() 10 | workSimPart = theSession.Parts.BaseWork 11 | displaySimPart = theSession.Parts.BaseDisplay 12 | results1 = [NXOpen.CAE.Result.Null] * 1 13 | resultManager1 = theSession.ResultManager 14 | solutionResult1 = resultManager1.FindObject("SolutionResult[Full_crane_assyfem_sim.sim_Position0][Structural]") 15 | results1[0] = solutionResult1 16 | usergroupIds1 = [None] * 1 17 | usergroupIds1[0] = 1 18 | theSession.Post.PostviewApplyUserGroupVisibility(1, results1, usergroupIds1, NXOpen.CAE.Post.GroupVisibility.ShowOnly) 19 | 20 | results2 = [NXOpen.CAE.Result.Null] * 1 21 | results2[0] = solutionResult1 22 | usergroupIds2 = [None] * 1 23 | usergroupIds2[0] = 107 24 | theSession.Post.PostviewApplyUserGroupVisibility(1, results2, usergroupIds2, NXOpen.CAE.Post.GroupVisibility.ShowOnly) 25 | 26 | # ---------------------------------------------- 27 | # Menu: Tools->Automation->Journal->Stop Recording 28 | # ---------------------------------------------- 29 | 30 | if __name__ == '__main__': 31 | main() -------------------------------------------------------------------------------- /Journals/journal_show_group_post_first_last_second_time.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2306 2 | # Journal created by HP on Tue Jul 23 09:09:53 2024 W. Europe Daylight Time 3 | # 4 | import math 5 | import NXOpen 6 | import NXOpen.CAE 7 | def main() : 8 | 9 | theSession = NXOpen.Session.GetSession() 10 | workSimPart = theSession.Parts.BaseWork 11 | displaySimPart = theSession.Parts.BaseDisplay 12 | results1 = [NXOpen.CAE.Result.Null] * 1 13 | resultManager1 = theSession.ResultManager 14 | solutionResult1 = resultManager1.FindObject("SolutionResult[Full_crane_assyfem_sim.sim_Position0][Structural]") 15 | results1[0] = solutionResult1 16 | usergroupIds1 = [None] * 1 17 | usergroupIds1[0] = 1 18 | theSession.Post.PostviewApplyUserGroupVisibility(2, results1, usergroupIds1, NXOpen.CAE.Post.GroupVisibility.ShowOnly) 19 | 20 | results2 = [NXOpen.CAE.Result.Null] * 1 21 | results2[0] = solutionResult1 22 | usergroupIds2 = [None] * 1 23 | usergroupIds2[0] = 107 24 | theSession.Post.PostviewApplyUserGroupVisibility(2, results2, usergroupIds2, NXOpen.CAE.Post.GroupVisibility.ShowOnly) 25 | 26 | # ---------------------------------------------- 27 | # Menu: Tools->Automation->Journal->Stop Recording 28 | # ---------------------------------------------- 29 | 30 | if __name__ == '__main__': 31 | main() -------------------------------------------------------------------------------- /Journals/journal_show_group_post_temp.py: -------------------------------------------------------------------------------- 1 | # Simcenter 3D 2306 2 | # Journal created by HP on Tue Jul 23 10:22:48 2024 W. Europe Daylight Time 3 | # 4 | import math 5 | import NXOpen 6 | import NXOpen.CAE 7 | def main() : 8 | 9 | theSession = NXOpen.Session.GetSession() 10 | workSimPart = theSession.Parts.BaseWork 11 | displaySimPart = theSession.Parts.BaseDisplay 12 | results1 = [NXOpen.CAE.Result.Null] * 1 13 | resultManager1 = theSession.ResultManager 14 | solutionResult1 = resultManager1.FindObject("SolutionResult[Full_crane_assyfem_sim.sim_Position0][Structural]") 15 | results1[0] = solutionResult1 16 | usergroupIds1 = [None] * 1 17 | usergroupIds1[0] = 1500 18 | # Potential journal callback detected. Pausing journal. 19 | 20 | if __name__ == '__main__': 21 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NXOpen-CAE-python 2 | 3 | This repository is no longer maintained, but the code is kept for reference. 4 | 5 | Instead of the journal approach in this repository, we created a dedicated python package called **nxopentse**. 6 | 7 | With this package, you can immediately use the functions within your own journals, without the need to have the function code itself in your journal. Not only is this a much better approach for version control and traceability, but you also get the power of the comminity behind **nxopentse**. 8 | 9 | [nxopentse on github](https://github.com/theScriptingEngineer/nxopentse) 10 | -------------------------------------------------------------------------------- /Tools/Excel/Sample1.xlsx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/theScriptingEngineer/NXOpen-CAE-python/f0746445e330747b0e49bd7e3b5a5a901bac6a48/Tools/Excel/Sample1.xlsx -------------------------------------------------------------------------------- /Tools/Excel/read_excel.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # untested 3 | # If you only need to READ data from Excel or WRITE data to Excel, you can use openpyxl. 4 | # This does not require that you have Excel installed on the machine that you are running the journal on 5 | 6 | # In case you need to calculate the formulas, but don't have excel installed you can try pycel (limited functionality!) 7 | 8 | import sys 9 | import math 10 | import NXOpen 11 | import NXOpen.CAE 12 | from typing import List, cast, Optional, Union 13 | import openpyxl # pip install openpyxl 14 | 15 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 16 | base_part = the_session.Parts.BaseWork 17 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 18 | 19 | 20 | def main(): 21 | the_lw.Open() 22 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 23 | 24 | file_name = sys.argv[1] # "C:\\temp\\Sample1.xlsx" 25 | # opening with the data_only=True option gives the values in case the cell contains a formula. 26 | wb_object: openpyxl.Workbook = openpyxl.load_workbook(file_name, data_only=True) 27 | sheet_object = wb_object["Sheet1"] 28 | value_a5 = sheet_object.cell(row=5, column=1).value 29 | print(value_a5) # 15 30 | 31 | if __name__ == '__main__': 32 | main() 33 | -------------------------------------------------------------------------------- /Tools/Excel/read_excel_xlwings.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # untested 3 | # If you need your Excel file to recalculate during your journal (eg. you are changing values and want to formulas to update) 4 | # Then yo can use xlwings. 5 | # This requires you to have Excel installed on the machine that you are running the journal on. 6 | 7 | # Note that xlwings will needs Excel running with the file and thus will start Excel and open that file. 8 | 9 | import sys 10 | import math 11 | import NXOpen 12 | import NXOpen.CAE 13 | from typing import List, cast, Optional, Union 14 | import xlwings as xw # pip install xlwings 15 | 16 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 17 | base_part = the_session.Parts.BaseWork 18 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 19 | 20 | 21 | def main(): 22 | the_lw.Open() 23 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 24 | 25 | file_name = sys.argv[1] # "C:\\temp\\Sample1.xlsx" 26 | with xw.Book(file_name) as wb: 27 | sheet = wb.sheets['Sheet1'] 28 | print(sheet['A5'].value) # 15 29 | sheet['B18'].value = '=sum(B1:B17)' 30 | print(sheet['A18'].value) # 493 31 | 32 | if __name__ == '__main__': 33 | main() 34 | -------------------------------------------------------------------------------- /Tools/create_groups_from_cad.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # untested 6 | 7 | import NXOpen 8 | import NXOpen.UF 9 | import NXOpen.CAE 10 | from typing import List, cast, Optional, Union 11 | 12 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 13 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 14 | base_part = the_session.Parts.BaseWork 15 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 16 | 17 | 18 | def cross_product_vector3d(vector1: NXOpen.Vector3d, vector2: NXOpen.Vector3d) -> NXOpen.Vector3d: 19 | """ 20 | Calculate the cross product of two vectors. 21 | 22 | Parameters: 23 | vector1 (NXOpen.Vector3d): The first vector. 24 | vector2 (NXOpen.Vector3d): The second vector. 25 | 26 | Returns: 27 | NXOpen.Vector3d: The cross product of the two vectors. 28 | """ 29 | x = vector1.Y * vector2.Z - vector2.Y * vector1.Z 30 | y = vector1.Z * vector2.X - vector2.Z * vector1.X 31 | z = vector1.X * vector2.Y - vector2.X * vector1.Y 32 | return NXOpen.Vector3d(x, y, z) 33 | 34 | 35 | def dot_product_vector3d(vector1: NXOpen.Vector3d, vector2: NXOpen.Vector3d) -> float: 36 | """ 37 | Calculate the dot product of two vectors. 38 | 39 | Parameters: 40 | vector1 (NXOpen.Vector3d): The first vector. 41 | vector2 (NXOpen.Vector3d): The second vector. 42 | 43 | Returns: 44 | float: The dot product of the two vectors. 45 | """ 46 | return vector1.X * vector2.X + vector1.Y * vector2.Y + vector1.Z * vector2.Z 47 | 48 | 49 | def get_associated_cad_part(fem_part: NXOpen.CAE.FemPart) -> NXOpen.Part: 50 | """Gets the associated cad part for a given FemPart. 51 | Will load the part if not loaded. 52 | It assumes that the FemPart has an associated cad part (is not an orphan mesh) 53 | 54 | Parameters 55 | ---------- 56 | fem_part: NXOpen.CAE.FemPart 57 | The FemPart for which to return the associated cad part. 58 | 59 | Returns 60 | ------- 61 | NXOpen.Part 62 | The associated cad part. 63 | """ 64 | associated_cad_part: NXOpen.Part = fem_part.AssociatedCadPart 65 | if associated_cad_part == None: 66 | # "load" the part (right-click load under fem) 67 | # error will occur if FemPart has no associated cad part: 68 | # fem_part.FullPathForAssociatedCadPart will be None and the open will fail. 69 | associated_cad_part = cast(NXOpen.Part, the_session.Parts.Open(fem_part.FullPathForAssociatedCadPart)) 70 | 71 | return associated_cad_part 72 | 73 | 74 | def get_named_datum_planes(cad_part: NXOpen.Part) -> List[NXOpen.DatumPlane]: 75 | """Searches the part for all datum planes with a name and returns them. 76 | Naming a datum plane is done by right-clicking on the plane in the GUI and selecting rename. 77 | 78 | Parameters 79 | ---------- 80 | cad_part: NXOpen.Part 81 | The part for which to return the named datum planes. 82 | 83 | Returns 84 | ------- 85 | List[NXOpen.DatumPlane] 86 | A list with the named datum planes. 87 | """ 88 | named_datum_planes: List[NXOpen.DatumPlane] = [] 89 | for item in cad_part.Datums: # type: ignore 90 | # cad_part.Datums.ToArray() will also contain datum axis (if present) 91 | if type(item) is NXOpen.DatumPlane: 92 | # item is a datum plane. Now check if it has a name. 93 | # Note Feature.Name and not Name 94 | if cast(NXOpen.DatumPlane, item).Feature.Name != "": 95 | named_datum_planes.append(cast(NXOpen.DatumPlane, item)) 96 | 97 | return named_datum_planes 98 | 99 | 100 | def create_selection_recipe(fem_part: NXOpen.CAE.FemPart, datum_plane: NXOpen.DatumPlane, entity_types: List[NXOpen.CAE.CaeSetGroupFilterType]) -> NXOpen.CAE.SelectionRecipe: 101 | """This function creates a selection recipe around a given datum plane. 102 | Since a selection recipe is not infinite, the dimensions are hard coded, but can be easily adjusted. 103 | 104 | Parameters 105 | ---------- 106 | fem_part: NXOpen.CAE.FemPart 107 | The part in whcih to create a selection recipe. 108 | datum_plane: NXOpen.DatumPlane 109 | A datum plane, which is used to define the selection recipe. 110 | entity_types: List[NXOpen.CAE.CaeSetGroupFilterType] 111 | A list of filters for the type of objects to add to the selection recipe. 112 | 113 | Returns 114 | ------- 115 | NXOpen.CAE.SelectionRecipe 116 | The created selection recipe. 117 | """ 118 | recipe_thickness: float = 1 119 | recipe_size: float = 100000 120 | 121 | # unfortunately NXOpen.VectorArithmetic.Vector3 does not exist in Python. 122 | # Not using general python libraries for this a this would require additional importing of libraries 123 | origin: NXOpen.Vector3d = NXOpen.Vector3d(datum_plane.Origin.X, datum_plane.Origin.Y, datum_plane.Origin.Z) 124 | normal: NXOpen.Vector3d = NXOpen.Vector3d(datum_plane.Normal.X, datum_plane.Normal.Y, datum_plane.Normal.Z) 125 | 126 | global_vector: NXOpen.Vector3d = NXOpen.Vector3d(1.0, 0.0, 0.0) 127 | projection: float = abs(dot_product_vector3d(normal, global_vector)) # absolute value so only need to check larger than 0.999 128 | if projection >= 0.999: 129 | # use global y if plane normal paralell to global x vector 130 | global_vector = NXOpen.Vector3d(0, 1, 0) 131 | 132 | # we first project the global onto the plane normal 133 | # then subtract to get the component of global IN the plane which will be are local axis in the recipe definition 134 | projection_magnitude: float = dot_product_vector3d(normal, global_vector) 135 | global_on_normal: NXOpen.Vector3d = NXOpen.Vector3d(normal.X * projection_magnitude, normal.Y * projection_magnitude, normal.Z * projection_magnitude) 136 | global_on_plane = NXOpen.Vector3d(global_vector.X - global_on_normal.X, global_vector.Y - global_on_normal.Y, global_vector.Z - global_on_normal.Z) 137 | 138 | # normalize 139 | global_on_plane_magnitude = global_on_plane.X **2 + global_on_plane.Y **2 + global_on_plane.Z **2 140 | global_on_plane = NXOpen.Vector3d(global_on_plane.X / global_on_plane_magnitude, global_on_plane.Y / global_on_plane_magnitude, global_on_plane.Z / global_on_plane_magnitude) 141 | 142 | # cross product of globalOnPlane and normal give vector in plane, otrhogonal to globalOnPlane 143 | global_on_plane_normal: NXOpen.Vector3d = cross_product_vector3d(normal, global_on_plane) 144 | # normalize 145 | global_on_plane_normal_magnitude = global_on_plane_normal.X **2 + global_on_plane_normal.Y **2 + global_on_plane_normal.Z **2 146 | global_on_plane_normal = NXOpen.Vector3d(global_on_plane_normal.X / global_on_plane_normal_magnitude, global_on_plane_normal.Y / global_on_plane_normal_magnitude, global_on_plane_normal.Z / global_on_plane_normal_magnitude) 147 | 148 | # offset origin so the recipe is centered around the origin 149 | # translate half recipeWidth in negative direction of globalOnPlane 150 | origin = NXOpen.Vector3d(origin.X - global_on_plane.X * recipe_size / 2, origin.Y - global_on_plane.Y * recipe_size / 2, origin.Z - global_on_plane.Z * recipe_size / 2) 151 | 152 | # translate half recipeWidth in negative direction of globalOnPlaneNormal 153 | origin = NXOpen.Vector3d(origin.X - global_on_plane_normal.X * recipe_size / 2, origin.Y - global_on_plane_normal.Y * recipe_size / 2, origin.Z - global_on_plane_normal.Z * recipe_size / 2) 154 | 155 | # Translate half the thickness in negative normal direction 156 | origin = NXOpen.Vector3d(origin.X - normal.X * recipe_thickness / 2, origin.Y - normal.Y * recipe_thickness / 2, origin.Z - normal.Z * recipe_thickness / 2) 157 | 158 | # prepare objects to create selection recipe 159 | recipe_origin: NXOpen.Point3d = NXOpen.Point3d(origin.X, origin.Y, origin.Z) 160 | x_direction: NXOpen.Vector3d = NXOpen.Vector3d(global_on_plane.X, global_on_plane.Y, global_on_plane.Z) 161 | y_direction: NXOpen.Vector3d = NXOpen.Vector3d(global_on_plane_normal.X, global_on_plane_normal.Y, global_on_plane_normal.Z) 162 | 163 | recipe_xform: NXOpen.Xform = fem_part.Xforms.CreateXform(recipe_origin, x_direction, y_direction, NXOpen.SmartObject.UpdateOption.AfterModeling, 1.0) 164 | recipe_coordinate_system: NXOpen.CartesianCoordinateSystem = fem_part.CoordinateSystems.CreateCoordinateSystem(recipe_xform, NXOpen.SmartObject.UpdateOption.AfterModeling) 165 | 166 | unit_millimeter: NXOpen.Unit = cast(NXOpen.UnitCollection, fem_part.UnitCollection).FindObject("MilliMeter") 167 | expression_length: NXOpen.Expression = fem_part.Expressions.CreateSystemExpressionWithUnits(str(recipe_size), unit_millimeter) 168 | expression_width: NXOpen.Expression = fem_part.Expressions.CreateSystemExpressionWithUnits(str(recipe_size), unit_millimeter) 169 | expression_height: NXOpen.Expression = fem_part.Expressions.CreateSystemExpressionWithUnits(str(recipe_thickness), unit_millimeter) 170 | 171 | # selection_recipe: NXOpen.CAE.SelectionRecipe = fem_part.SelectionRecipes.CreateBoxBoundingVolumeRecipe(datum_plane.Feature.Name, recipe_coordinate_system, expression_length, expression_width, expression_height, entity_types) 172 | selection_recipe_builder = fem_part.SelectionRecipes.CreateSelRecipeBuilder() 173 | selection_recipe_builder.AddBoxBoundingVolumeStrategy(recipe_coordinate_system, expression_length, expression_width, expression_height, entity_types, NXOpen.CAE.SelRecipeBuilder.InputFilterType.EntireModel, None) 174 | selection_recipe_builder.RecipeName = datum_plane.Feature.Name 175 | 176 | selection_recipe = selection_recipe_builder.Commit() 177 | selection_recipe_builder.Destroy() 178 | 179 | return selection_recipe 180 | 181 | 182 | def create_groups_from_named_planes(fem_part: NXOpen.CAE.FemPart) -> None: 183 | """This function creates a group with faces and bodies for each named datum plane in the associated cad part. 184 | All named datum planes are collected from the associated cad part. 185 | Then for each datum plane a selection recipe is created, "centered around" the datum plane, with the faces and bodies. 186 | For each selection recipe a group is created and the selection recipe deleted. 187 | Groups are created instead of selection recipes because older versions of Simcenter cannot use selection recipes in post-processing. 188 | Function is idempotent. 189 | 190 | Parameters 191 | ---------- 192 | fem_part: NXOpen.CAE.FemPart 193 | The part in which to create the groups. 194 | """ 195 | # Get the associated cad part 196 | associated_cad_part: NXOpen.Part = get_associated_cad_part(fem_part) 197 | 198 | # Get an array of all named datum planes 199 | named_datum_planes: List[NXOpen.DatumPlane] = get_named_datum_planes(associated_cad_part) 200 | if len(named_datum_planes) == 0: 201 | the_lw.WriteFullline("No named datum planes found in " + associated_cad_part.Name) 202 | return 203 | 204 | the_lw.WriteFullline("Found the following named datum planes in " + associated_cad_part.Name + ":") 205 | for item in named_datum_planes: 206 | the_lw.WriteFullline(item.Feature.Name) 207 | 208 | # Create selection recipe for each named datum plane 209 | selection_recipes: List[NXOpen.CAE.SelectionRecipe] = [] 210 | entity_types: List[NXOpen.CAE.CaeSetGroupFilterType] = [] 211 | entity_types.append(NXOpen.CAE.CaeSetGroupFilterType.GeomFace) 212 | entity_types.append(NXOpen.CAE.CaeSetGroupFilterType.GeomBody) 213 | for item in named_datum_planes: 214 | selection_recipes.append(create_selection_recipe(fem_part, item, entity_types)) 215 | 216 | # Create a group for each recipe 217 | cae_groups: List[NXOpen.CAE.CaeGroup] = fem_part.CaeGroups 218 | for i in range(len(named_datum_planes)): 219 | tagged_objects: List[NXOpen.TaggedObject] = selection_recipes[i].GetEntities() 220 | if len(tagged_objects) == 0: 221 | the_lw.WriteFullline("Recipe with name " + selection_recipes[i].Name + " contains no items to put into a group") 222 | continue # continue to the next datum plane 223 | 224 | cae_group: List[NXOpen.CAE.CaeGroup] = [item for item in cae_groups if item.Name.lower() == named_datum_planes[i].Feature.Name.lower()] 225 | if len(cae_group) == 0: 226 | # no group found with the feaure name, thus creating 227 | fem_part.CaeGroups.CreateGroup(named_datum_planes[i].Feature.Name, tagged_objects) 228 | else: 229 | cae_group[0].SetEntities(tagged_objects) 230 | 231 | # delete temporary selection recipes 232 | fem_part.SelectionRecipes.Delete(selection_recipes) 233 | 234 | 235 | def add_related_nodes_and_elements(cae_part: NXOpen.CAE.CaePart): 236 | """This function cycles through all cae groups in a CaePart. 237 | For each group it adds the related nodes and elements for the bodies and faces in the group. 238 | Practical for repopulating groups after a (partial) remesh. 239 | Function is idempotent. 240 | 241 | Parameters 242 | ---------- 243 | fem_part: NXOpen.CAE.FemPart 244 | The CaePart to perform this operation on. 245 | """ 246 | cae_groups: List[NXOpen.CAE.CaeGroup] = cae_part.CaeGroups 247 | for group in cae_groups: # type: ignore 248 | the_lw.WriteFullline("Processing group " + group.Name) 249 | seeds_body: List[NXOpen.CAE.CAEBody] = [] 250 | seeds_face: List[NXOpen.CAE.CAEFace] = [] 251 | 252 | for tagged_object in group.GetEntities(): 253 | if type(tagged_object) is NXOpen.CAE.CAEBody: 254 | seeds_body.append(cast(NXOpen.CAE.CAEBody, tagged_object)) 255 | 256 | elif type(tagged_object) is NXOpen.CAE.CAEFace: 257 | seeds_face.append(cast(NXOpen.CAE.CAEFace, tagged_object)) 258 | 259 | smart_selection_manager: NXOpen.CAE.SmartSelectionManager = cae_part.SmartSelectionMgr 260 | 261 | related_element_method_body: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedElemMethod(seeds_body, False) 262 | # related_node_method_body: NXOpen.CAE.RelatedNodeMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromBody(seeds_body, False) 263 | # comment previous line and uncomment next line for NX version 2007 (release 2022.1) and later 264 | related_node_method_body: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromBodies(seeds_body, False, False) 265 | 266 | group.AddEntities(related_element_method_body.GetElements()) 267 | group.AddEntities(related_node_method_body.GetNodes()) 268 | 269 | related_element_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedElemMethod(seeds_face, False) 270 | # related_node_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedNodeMethod(seeds_face, False) 271 | # comment previous line and uncomment next line for NX version 2007 (release 2022.1) and later 272 | related_node_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromFaces(seeds_face, False, False) 273 | 274 | group.AddEntities(related_element_method_face.GetElements()) 275 | group.AddEntities(related_node_method_face.GetNodes()) 276 | 277 | 278 | def main(): 279 | the_lw.Open() 280 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 281 | 282 | fem_part: NXOpen.CAE.FemPart = None 283 | if type(base_part) is NXOpen.CAE.SimPart: 284 | # started from a sim file. 285 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 286 | # switch to the fem or afem 287 | cae_part: NXOpen.CAE.CaePart = sim_part.FemPart 288 | if type(base_part) is NXOpen.CAE.AssyFemPart: 289 | the_lw.WriteFullline("Create groups from CAD does not support .afem files yet.") 290 | return 291 | 292 | fem_part = cast(NXOpen.CAE.FemPart, cae_part) 293 | 294 | elif type(base_part) is NXOpen.CAE.AssyFemPart: 295 | # started from an .afem file 296 | the_lw.WriteFullline("Create groups from CAD does not support .afem files yet.") 297 | return 298 | 299 | elif type(base_part) is NXOpen.CAE.FemPart: 300 | # started from a .fem file 301 | fem_part = cast(NXOpen.CAE.FemPart, base_part) 302 | 303 | else: 304 | # not started from a base fem part 305 | the_lw.WriteFullline("Create groups does not work on non-cae parts") 306 | return 307 | 308 | create_groups_from_named_planes(fem_part) 309 | add_related_nodes_and_elements(fem_part) 310 | 311 | if __name__ == '__main__': 312 | main() 313 | -------------------------------------------------------------------------------- /Tools/points_to_csv.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # untested 6 | 7 | import os 8 | import math 9 | import NXOpen 10 | import NXOpen.CAE 11 | from typing import List, cast, Optional, Union 12 | 13 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 14 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 15 | base_part = the_session.Parts.BaseWork 16 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 17 | 18 | 19 | def get_all_points(base_part: NXOpen.BasePart) -> List[NXOpen.Point]: 20 | """This function returns all points in a part. 21 | 22 | Parameters 23 | ---------- 24 | base_part: NXOpen.BasePart 25 | The part for which to to return the points 26 | 27 | Returns 28 | ------- 29 | List[NXOpen.Point] 30 | A list containing all points in the base part. 31 | """ 32 | return base_part.Points.ToArray() 33 | 34 | 35 | def list_csv(points: List[NXOpen.Point]) -> None: 36 | """This function lists the coordinates of all points to the listing window. 37 | 38 | Parameters 39 | ---------- 40 | points: List[NXOpen.Point] 41 | The list of points to list the coordinates for in the listing window. 42 | """ 43 | for item in points: 44 | the_lw.WriteFullline(str(item.Coordinates.X).replace(",",".") + "," + str(item.Coordinates.Y).replace(",",".") + "," + str(item.Coordinates.Z).replace(",",".")) 45 | 46 | 47 | def create_full_path(file_name: str, extension: str = ".unv") -> str: 48 | """This function takes a filename and adds the .unv extension and path of the part if not provided by the user. 49 | If the fileName contains an extension, this function leaves it untouched, othwerwise adds .unv as extension. 50 | If the fileName contains a path, this function leaves it untouched, otherwise adds the path of the BasePart as the path. 51 | Undefined behaviour if basePart has not yet been saved (eg FullPath not available) 52 | 53 | Parameters 54 | ---------- 55 | file_name: str 56 | The filename with or without path and .unv extension. 57 | 58 | Returns 59 | ------- 60 | str 61 | A string with .unv extension and path of the basePart if the fileName parameter did not include a path. 62 | """ 63 | # check if an extension is included 64 | if os.path.splitext(file_name)[1] == "": 65 | file_name = file_name + extension 66 | 67 | # check if path is included in fileName, if not add path of the .sim file 68 | unv_file_path: str = os.path.dirname(file_name) 69 | if unv_file_path == "": 70 | # if the .sim file has never been saved, the next will give an error 71 | file_name = os.path.join(os.path.dirname(base_part.FullPath), file_name) 72 | 73 | return file_name 74 | 75 | 76 | def write_csv(file_name: str, points: List[NXOpen.Point]): 77 | """This function writes the coordinates of all points to a .csv file. 78 | 79 | Parameters 80 | ---------- 81 | file_name: str 82 | The file name and path for the csv file. If no path provided, it is written to the location of the part. 83 | points: List[NXOpen.Point] 84 | The list of points to write the coordinates to file. 85 | """ 86 | 87 | full_path: str = create_full_path(file_name, ".csv") 88 | file_content: str = "" 89 | for item in points: 90 | file_content = file_content + str(item.Coordinates.X).replace(",",".") + "," + str(item.Coordinates.Y).replace(",",".") + "," + str(item.Coordinates.Z).replace(",",".") + "\n" 91 | 92 | with open(full_path, 'w') as file: 93 | file.write(file_content) 94 | 95 | 96 | def main(): 97 | the_lw.Open() 98 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 99 | 100 | all_points: List[NXOpen.Point] = get_all_points(base_part) 101 | # List all points in the listing window 102 | list_csv(all_points) 103 | # Write points to csv file 104 | write_csv(f"C:\\myPoints.csv", all_points) 105 | 106 | 107 | if __name__ == '__main__': 108 | main() 109 | -------------------------------------------------------------------------------- /Tools/print_assembly_structure.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # untested 6 | 7 | import NXOpen 8 | import NXOpen.CAE 9 | from typing import List, cast, Optional, Union 10 | 11 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 12 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 13 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 14 | 15 | 16 | def indentation(level: int) -> str: 17 | """Helper method to create indentations (eg tabs) with a given length. 18 | Can be used in print strings in a tree like structure 19 | 20 | Parameters 21 | ---------- 22 | level: int 23 | The depth of the indentations. 24 | 25 | Returns 26 | ------- 27 | str 28 | The indentation 29 | """ 30 | indentation: str = "" 31 | for i in range(level + 1): 32 | indentation += "\t" 33 | 34 | return indentation 35 | 36 | 37 | def print_component_tree(component: NXOpen.Assemblies.Component, requested_level: int = 0) -> None: 38 | """Prints the component tree for the given component to the listing window. 39 | Recursive function 40 | 41 | Parameters 42 | ---------- 43 | component: NXOpen.Assemblies.Component 44 | The component for whch to print the component tree 45 | requested_level: int 46 | Optional parameter used for creating indentations. 47 | """ 48 | level: int = requested_level 49 | the_lw.WriteFullline(indentation(level) + "| " + component.JournalIdentifier + " is a compont(instance) of " + component.Prototype.OwningPart.Name + " located in " + component.OwningPart.Name) 50 | children: List[NXOpen.Assemblies.Component] = component.GetChildren() 51 | for i in range(len(children) -1, -1, -1): 52 | print_component_tree(children[i], level + 1) 53 | 54 | 55 | def print_part_tree(base_part: NXOpen.BasePart, requested_level: int = 0) -> None: 56 | """Prints the part tree for the given BasePart to the listing window. 57 | Recursive function 58 | 59 | Parameters 60 | ---------- 61 | base_part: NXOpen.BasePart 62 | The BasePart to print the tree for. 63 | requested_level: int 64 | Optional parameter used for creating indentations. 65 | """ 66 | level: int = requested_level 67 | if isinstance(NXOpen.CAE.SimPart, base_part): 68 | # it's a .sim part 69 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 70 | the_lw.WriteFullline(sim_part.Name) 71 | 72 | # both are equal: 73 | # print_part_tree(sim_part.ComponentAssembly.RootComponent.GetChildren()[0].Prototype.OwningPart) 74 | print_part_tree(sim_part.FemPart) 75 | 76 | elif isinstance(NXOpen.CAE.AssyFemPart, base_part): 77 | # it's a .afem part 78 | assy_fem_part: NXOpen.CAE.AssyFemPart = cast(NXOpen.CAE.AssyFemPart, base_part) 79 | the_lw.WriteFullline(indentation(level) + "| " + assy_fem_part.Name + " located in " + assy_fem_part.FullPath + " linked to part " + assy_fem_part.FullPathForAssociatedCadPart) 80 | children: List[NXOpen.Assemblies.Component] = cast(NXOpen.Assemblies.ComponentAssembly, assy_fem_part.ComponentAssembly).RootComponent.GetChildren() 81 | for i in range(len(children) - 1): 82 | print_part_tree(children[i].Prototype.OwningPart, level + 1) 83 | 84 | elif isinstance(NXOpen.CAE.FemPart, base_part): 85 | # it's a .fem part 86 | fem_part: NXOpen.CAE.FemPart = cast(NXOpen.CAE.FemPart, base_part) 87 | # try except since calling femPart.FullPathForAssociatedCadPart on a part which has no cad part results in an error 88 | try: 89 | # femPart.MasterCadPart returns the actual part, but is null if the part is not loaded. 90 | the_lw.WriteFullline(indentation(level) + "| " + fem_part.Name + " which is linked to part " + fem_part.FullPathForAssociatedCadPart) 91 | except: 92 | # femPart has no associated cad part 93 | the_lw.WriteFullline(indentation(level) + "| " + fem_part.Name + " not linked to a part.") 94 | 95 | else: 96 | # it's a .prt part, but can still contain components 97 | the_lw.WriteFullline(indentation(level) + "| " + base_part.Name + " located in " + base_part.FullPath) 98 | children: List[NXOpen.Assemblies.Component] = cast(NXOpen.Assemblies.ComponentAssembly, base_part.ComponentAssembly).RootComponent.GetChildren() 99 | for i in range(len(children) - 1): 100 | print_part_tree(children[i].Prototype.OwningPart, level + 1) 101 | 102 | 103 | def main(): 104 | the_lw.Open() 105 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 106 | 107 | all_parts_in_session: List[NXOpen.BasePart] = the_session.Parts.ToArray() 108 | the_lw.WriteFullline("The following parts are loaded in the session: ") 109 | for part in all_parts_in_session: 110 | the_lw.WriteFullline("{:<50}{:<128}".format(part.Name, part.FullPath)) 111 | the_lw.WriteFullline("") 112 | 113 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 114 | base_display_part: NXOpen.BasePart = the_session.Parts.BaseDisplay 115 | the_lw.WriteFullline("The current workpart is: " + base_part.Name + " located in " + base_part.FullPath) 116 | the_lw.WriteFullline("The current displaypart is: " + base_display_part.Name + " located in " + base_display_part.FullPath) 117 | the_lw.WriteFullline("") 118 | 119 | 120 | if __name__ == '__main__': 121 | main() 122 | -------------------------------------------------------------------------------- /Tools/read_simcenter_log_file.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # This file is used to demonstrate a working intellisense (code completion) for 6 | # writing NXOpen journals using Python 7 | 8 | import sys 9 | import math 10 | import re 11 | import NXOpen 12 | import NXOpen.CAE 13 | from typing import List, cast, Optional, Union 14 | 15 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 16 | base_part = the_session.Parts.BaseWork 17 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 18 | 19 | def main(): 20 | the_lw.Open() 21 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 22 | 23 | log_file_name: str = the_session.LogFile.FileName 24 | with open(log_file_name, 'r') as file: 25 | lines = file.readlines() 26 | for line in lines: 27 | # define the regex pattern to look for lines starting with a whitespace followed by "License File Sold To" followed by any number of characters 28 | regex_pattern = r"\s*License File Sold To.*" 29 | # if line matches the regex pattern, print the line 30 | if re.match(regex_pattern, line): 31 | sold_to: str = line.split(":")[1].strip() 32 | the_lw.WriteFullline(sold_to) 33 | 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /hello_world.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | import NXOpen 6 | 7 | 8 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 9 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 10 | work_part: NXOpen.Part = the_session.Parts.Work 11 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 12 | 13 | 14 | def main(): 15 | the_lw.Open() 16 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 17 | 18 | the_lw.WriteFullline("Hello, World!") 19 | 20 | 21 | if __name__ == '__main__': 22 | main() 23 | -------------------------------------------------------------------------------- /intellisense.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # This file is used to demonstrate a working intellisense (code completion) for 6 | # writing NXOpen journals using Python 7 | 8 | import sys 9 | import math 10 | import NXOpen 11 | import NXOpen.CAE 12 | from typing import List, cast, Optional, Union 13 | 14 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 15 | base_part = the_session.Parts.BaseWork 16 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 17 | 18 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 19 | assem = the_uf_session.Assem 20 | 21 | def get_solution(solution_name: str) -> Union[NXOpen.CAE.SimSolution, None]: 22 | """This function returns the SimSolution object with the given name. 23 | Returns None if not found, so the user can check and act accordingly 24 | 25 | Parameters 26 | ---------- 27 | solution_name: int 28 | The name of the solution to return, case insensitive 29 | 30 | Returns 31 | ------- 32 | NXOpen.CAE.SimSolution or None 33 | The FIRST solution object with the given name if found, None otherwise 34 | """ 35 | # The next commented block is an extended example where each object is typed. 36 | # sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, basePart) # explicit casting makes it clear 37 | # sim_simulation: NXOpen.CAE.SimSimulation = sim_part.Simulation 38 | # sim_solution_collection: NXOpen.CAE.SimSolutionCollection = sim_simulation.Solutions 39 | # sim_solutions: List[NXOpen.CAE.SimSolution] = sim_solution_collection.ToArray() 40 | # sim_solution: List[NXOpen.CAE.SimSolution] = [item for item in sim_solutions if item.Name.lower == solution_name.lower()] 41 | 42 | # # minimal working example PyCharm 43 | # sim_part: NXOpen.CAE.SimPart = basePart # simply typing the sim_part provides intellisense. 44 | # sim_solutions: List[NXOpen.CAE.SimSolution] = sim_part.Simulation.Solutions.ToArray() 45 | 46 | # # minimal working example Visual Studio Code 47 | sim_part = cast(NXOpen.CAE.SimPart, base_part) # explicit casting required in Visual Studio Code 48 | sim_solutions = sim_part.Simulation.Solutions.ToArray() 49 | 50 | sim_solution = [item for item in sim_solutions if item.Name.lower() == solution_name.lower()] 51 | if len(sim_solution) == 0: 52 | # solution with given name not found 53 | return None 54 | 55 | # return the first solution with the requested name 56 | return sim_solution[0] 57 | 58 | 59 | def main(): 60 | the_lw.Open() 61 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 62 | 63 | my_solution: NXOpen.CAE.SimSolution = get_solution("my_solution_name") 64 | if my_solution is not None: 65 | print(my_solution.JournalIdentifier) 66 | 67 | 68 | if __name__ == '__main__': 69 | main() 70 | -------------------------------------------------------------------------------- /post_processing/export_all_solutions.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer 2 | # untested 3 | 4 | # The code for EnvelopeResults is only available in NX version 1980, release 2021.2 onwards. For earlier NX versions, use PostProcessing.py 5 | 6 | import math 7 | import sys 8 | import os 9 | import NXOpen 10 | import NXOpen.CAE 11 | import NXOpen.Fields 12 | from typing import List, cast, Tuple, Dict 13 | 14 | the_session = NXOpen.Session.GetSession() 15 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 16 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 17 | 18 | class PostInput: 19 | """A class for declaring inputs used in CombineResults""" 20 | _solution: str 21 | _subcase: int 22 | _iteration: int 23 | _resultType: str 24 | _identifier: str 25 | 26 | def __init__(self) -> None: 27 | """Parameterless constructor. Strings initialized to empty strings and integers to -1""" 28 | self._solution = "" 29 | self._subcase = -1 30 | self._iteration = -1 31 | self._resultType = "" 32 | self._identifier = "" 33 | 34 | def __init__(self, solution: str, subcase: int, iteration: int, resultType: str, identifier: str = ""): 35 | """Constructor""" 36 | self._solution = solution 37 | self._subcase = subcase 38 | self._iteration = iteration 39 | self._resultType = resultType 40 | self._identifier = identifier 41 | 42 | def __repr__(self) -> str: 43 | """String representation of a PostInput""" 44 | return "Solution: " + self._solution + " Subcase: " + str(self._subcase) + " Iteration: " + str(self._iteration) + " ResultType: " + self._resultType + " Identifier: " + self._identifier 45 | 46 | 47 | def get_solution(solution_name: str) -> NXOpen.CAE.SimSolution: 48 | """This function returns the SimSolution object with the given name. 49 | 50 | Parameters 51 | ---------- 52 | solution_name: str 53 | The name of the solution to return. Case insensitive. 54 | 55 | Returns 56 | ------- 57 | NXOpen.CAE.SimSolution 58 | Returns a list of SolutionResult. 59 | """ 60 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) # explicit casting makes it clear 61 | sim_simulation: NXOpen.CAE.SimSimulation = sim_part.Simulation 62 | 63 | sim_solutions: List[NXOpen.CAE.SimSolution] = [item for item in sim_simulation.Solutions if item.Name.lower() == solution_name.lower()] 64 | if len(sim_solutions) == 0: 65 | return None 66 | 67 | return sim_solutions[0] 68 | 69 | 70 | def load_results(post_inputs: List[PostInput], reference_type: str = "Structural") -> List[NXOpen.CAE.SolutionResult]: 71 | """Loads the results for the given list of PostInput and returns a list of SolutionResult. 72 | An exception is raised if the result does not exist (-> to check if CreateReferenceResult raises error or returns None) 73 | 74 | Parameters 75 | ---------- 76 | post_inputs: List[PostInput] 77 | The result of each of the provided solutions is loaded. 78 | reference_type: str 79 | The type of SimResultReference eg. Structural. Defaults to structral 80 | 81 | Returns 82 | ------- 83 | NXOpen.CAE.SolutionResult 84 | Returns a list of SolutionResult. 85 | """ 86 | solution_results: List[NXOpen.CAE.SolutionResult] = [NXOpen.CAE.SolutionResult] * len(post_inputs) 87 | simPart: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 88 | 89 | for i in range(len(post_inputs)): 90 | sim_solution: NXOpen.CAE.SimSolution = get_solution(post_inputs[i]._solution) 91 | sim_result_reference: NXOpen.CAE.SimResultReference = cast(NXOpen.CAE.SimResultReference, sim_solution.Find(reference_type)) 92 | 93 | try: 94 | # SolutionResult[filename_solutionname] 95 | solution_results[i] = cast(NXOpen.CAE.SolutionResult, the_session.ResultManager.FindObject("SolutionResult[" + sys.Path.GetFileName(simPart.FullPath) + "_" + sim_solution.Name + "]")) 96 | except: 97 | solution_results[i] = the_session.ResultManager.CreateReferenceResult(sim_result_reference) 98 | 99 | return solution_results 100 | 101 | 102 | def get_results_units(base_result_types: List[NXOpen.CAE.BaseResultType]) -> List[NXOpen.Unit]: 103 | """This funciton returns the unit of the first component in each resulttype. 104 | Note that the unit is taken from the SolutionResult and not the SimSolution! 105 | 106 | Parameters 107 | ---------- 108 | base_result_types: List[NXOpen.CAE.BaseResultType] 109 | The list of baseresulttypes defining the result 110 | 111 | Returns 112 | ------- 113 | NXOpen.Unit 114 | A list of unit for each resulttype 115 | """ 116 | result_component_mapping = get_result_component_names() 117 | 118 | result_units: List[NXOpen.Unit] = [NXOpen.Unit] * len(base_result_types) 119 | for i in range(len(base_result_types)): 120 | components: List[NXOpen.CAE.Result.Component] = base_result_types[i].AskComponents() 121 | result_units[i] = base_result_types[i].AskDefaultUnitForComponent(components[1][0]) 122 | 123 | return result_units 124 | 125 | 126 | def get_result_types(post_inputs: List[PostInput], solution_results: List[NXOpen.CAE.SolutionResult]) -> List[NXOpen.CAE.BaseResultType]: 127 | """Helper function for CombineResults and GetResultParameters. 128 | Returns the ResultTypes specified in PostInputs 129 | 130 | Parameters 131 | ---------- 132 | postInputs: List[PostInput] 133 | The input as an array of PostInput. 134 | solutionResults: List[NXOpen.CAE.SolutionResult] 135 | The already loaded results to search through for the results. 136 | 137 | Returns 138 | ------- 139 | List[NXOpen.CAE.BaseResultType] 140 | Returns the result objects 141 | """ 142 | result_types: List[NXOpen.CAE.BaseResultType] = [NXOpen.CAE.BaseResultType] * len(post_inputs) 143 | for i in range(len(post_inputs)): 144 | base_load_cases: List[NXOpen.CAE.BaseLoadcase] = solution_results[i].GetLoadcases() 145 | loadCase: NXOpen.CAE.Loadcase = cast(NXOpen.CAE.Loadcase, base_load_cases[post_inputs[i]._subcase - 1]) # user starts counting at 1 146 | base_iterations: List[NXOpen.CAE.BaseIteration] = loadCase.GetIterations() 147 | iteration: NXOpen.CAE.Iteration = cast(NXOpen.CAE.Iteration, base_iterations[post_inputs[i]._iteration - 1]) # user starts counting at 1 148 | base_result_types: List[NXOpen.CAE.BaseResultType] = iteration.GetResultTypes() 149 | base_result_type: List[NXOpen.CAE.ResultType] = [item for item in base_result_types if item.Name.lower().strip() == post_inputs[i]._resultType.lower().strip()][0] 150 | result_types[i] = cast(NXOpen.CAE.ResultType, base_result_type) 151 | 152 | return result_types 153 | 154 | 155 | def get_sim_result_reference(solution_name: str, reference_type: str = "Structural") -> NXOpen.CAE.SimResultReference: 156 | """Helper function for CombineResults and EnvelopeResults. 157 | Returns the SimResultReferece for the given solution 158 | 159 | Parameters 160 | ---------- 161 | solution_name: str 162 | The solution for which to get the "structural" SimResultReference. 163 | reference_type: str 164 | The type of SimResultReference eg. Structural. Defaults to structral 165 | 166 | Returns 167 | ------- 168 | NXOpen.CAE.SimResultReference 169 | Returns the "Structural" simresultreference. 170 | """ 171 | simSolution: NXOpen.CAE.SimSolution = get_solution(solution_name) 172 | if simSolution == None: 173 | # solution with given name not found 174 | the_lw.WriteFullline("GetSimResultReference: Solution with name " + solution_name + " not found.") 175 | return None 176 | simResultReference: NXOpen.CAE.SimResultReference = cast(NXOpen.CAE.SimResultReference, simSolution.Find(reference_type)) 177 | return simResultReference 178 | 179 | 180 | def create_full_path(file_name: str, extension: str = ".unv") -> str: 181 | """This function takes a filename and adds the .unv extension and path of the part if not provided by the user. 182 | If the fileName contains an extension, this function leaves it untouched, othwerwise adds .unv as extension. 183 | If the fileName contains a path, this function leaves it untouched, otherwise adds the path of the BasePart as the path. 184 | Undefined behaviour if basePart has not yet been saved (eg FullPath not available) 185 | 186 | Parameters 187 | ---------- 188 | file_name: str 189 | The filename with or without path and .unv extension. 190 | 191 | Returns 192 | ------- 193 | str 194 | A string with .unv extension and path of the basePart if the fileName parameter did not include a path. 195 | """ 196 | # check if an extension is included 197 | if os.path.splitext(file_name)[1] == "": 198 | file_name = file_name + extension 199 | 200 | # check if path is included in fileName, if not add path of the .sim file 201 | unv_file_path: str = os.path.dirname(file_name) 202 | if unv_file_path == "": 203 | # if the .sim file has never been saved, the next will give an error 204 | file_name = os.path.join(os.path.dirname(base_part.FullPath), file_name) 205 | 206 | return file_name 207 | 208 | 209 | def check_post_input(post_inputs: List[PostInput]) -> None: 210 | """Check if the provided list of PostInput will not return an error when used in CombineResults. 211 | Identifiers are checked with separate function check_post_input_identifiers 212 | Raises exceptions which can be caught by the user. 213 | 214 | Parameters 215 | ---------- 216 | post_inputs: List[PostInput] 217 | The array of PostInput to check. 218 | """ 219 | for i in range(len(post_inputs)): 220 | # Does the solution exist? 221 | sim_solution: NXOpen.CAE.SimSolution = get_solution(post_inputs[i]._solution) 222 | if sim_solution == None: 223 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 224 | the_lw.WriteFullline("Solution with name " + post_inputs[i]._solution + " not found.") 225 | raise ValueError("Solution with name " + post_inputs[i]._solution + " not found") 226 | 227 | # Does the result exist? 228 | solution_result: List[NXOpen.CAE.SolutionResult] = [] 229 | try: 230 | solution_result = load_results([post_inputs[i]]) 231 | except: 232 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 233 | the_lw.WriteFullline("No result for Solution with name " + post_inputs[i]._solution) 234 | raise 235 | 236 | # Does the subcase exist? 237 | base_load_cases: List[NXOpen.CAE.BaseLoadcase] = solution_result[0].GetLoadcases() 238 | loadCase: NXOpen.CAE.Loadcase = None 239 | try: 240 | loadCase = cast(NXOpen.CAE.Loadcase, base_load_cases[post_inputs[i]._subcase - 1]) # user starts counting at 1 241 | except: 242 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 243 | the_lw.WriteFullline("SubCase with number " + str(post_inputs[i]._subcase) + " not found in solution with name " + post_inputs[i]._solution) 244 | raise 245 | 246 | # Does the iteration exist? 247 | base_iterations: List[NXOpen.CAE.BaseIteration] = loadCase.GetIterations() 248 | iteration: NXOpen.CAE.Iteration = None 249 | try: 250 | iteration = cast(NXOpen.CAE.Iteration, base_iterations[post_inputs[i]._iteration - 1]) # user starts counting at 1 251 | except: 252 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 253 | the_lw.WriteFullline("Iteration number " + str(post_inputs[i]._iteration) + "not found in SubCase with number " + str(post_inputs[i]._subcase) + " in solution with name " + post_inputs[i]._solution) 254 | raise 255 | 256 | # Does the ResultType exist? 257 | base_result_types: List[NXOpen.CAE.BaseResultType] = iteration.GetResultTypes() 258 | base_result_type: List[NXOpen.CAE.BaseResultType] = [item for item in base_result_types if item.Name.lower().strip() == post_inputs[i]._resultType.lower().strip()] 259 | if len(base_result_type) == 0: 260 | # resulttype does not exist 261 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 262 | the_lw.WriteFullline("ResultType " + post_inputs[i]._resultType + "not found in iteration number " + str(post_inputs[i]._iteration) + " in SubCase with number " + str(post_inputs[i]._subcase) + " in solution with name " + post_inputs[i]._solution) 263 | for result_type in base_result_types: 264 | the_lw.WriteFullline(result_type.UserName) 265 | raise ValueError("ResultType " + post_inputs[i]._resultType + "not found in iteration number " + str(post_inputs[i]._iteration) + " in SubCase with number " + str(post_inputs[i]._subcase) + " in solution with name " + post_inputs[i]._solution) 266 | 267 | 268 | def check_post_input_identifiers(post_inputs: List[PostInput]) -> None: 269 | """This function verifies the identifiers in all post_inputs: 270 | Null or empty string. 271 | Reserved expression name. 272 | Use of an expression which already exists. 273 | 274 | Parameters 275 | ---------- 276 | post_inputs: List[PostInput] 277 | The array of PostInput to check. 278 | """ 279 | for i in range(len(post_inputs)): 280 | # is the identifier not null 281 | if post_inputs[i]._identifier == "": 282 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 283 | the_lw.WriteFullline("No identifier provided for solution " + post_inputs[i]._solution + " SubCase " + str(post_inputs[i]._subcase) + " iteration " + str(post_inputs[i]._iteration) + " ResultType " + post_inputs[i]._resultType) 284 | raise ValueError("No identifier provided for solution " + post_inputs[i]._solution + " SubCase " + str(post_inputs[i]._subcase) + " iteration " + str(post_inputs[i]._iteration) + " ResultType " + post_inputs[i]._resultType) 285 | 286 | # check for reserved expressions 287 | nx_reserved_expressions: List[str] = ["angle", "angular velocity", "axial", "contact pressure", "Corner ID", "depth", "dynamic viscosity", "edge_id", "element_id", "face_id", "fluid", "fluid temperature", "frequency", "gap distance", "heat flow rate", "iter_val", "length", "mass density", "mass flow rate", "node_id", "nx", "ny", "nz", "phi", "pressure", "radius", "result", "rotational speed", "solid", "solution", "specific heat", "step", "temperature", "temperature difference", "thermal capacitance", "thermal conductivity", "theta", "thickness", "time", "u", "v", "velocity", "volume flow rate", "w", "x", "y", "z"] 288 | check: List[str] = [item for item in nx_reserved_expressions if item.lower() == post_inputs[i]._identifier.lower()] 289 | if len(check) != 0: 290 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 291 | the_lw.WriteFullline("Expression with name " + post_inputs[i]._identifier + " is a reserved expression in nx and cannot be used as an identifier."); 292 | raise ValueError("Expression with name " + post_inputs[i]._identifier + " is a reserved expression in nx and cannot be used as an identifier.") 293 | 294 | # check if identifier is not already in use as an expression 295 | expressions: List[NXOpen.Expression] = [item for item in base_part.Expressions if item.Name.lower() == post_inputs[i]._identifier.lower()] 296 | if len(expressions) != 0: 297 | the_lw.WriteFullline("Error in input " + str(post_inputs[i])) 298 | the_lw.WriteFullline("Expression with name " + post_inputs[i]._identifier + " already exist in this part and cannot be used as an identifier.") 299 | raise ValueError("Expression with name " + post_inputs[i]._identifier + " already exist in this part and cannot be used as an identifier.") 300 | 301 | 302 | def check_unv_file_name(unv_file_name: str) -> None: 303 | """This method loops through all solutions and all companion results in these solutions. 304 | It checks if the file name is not already in use by another companion result. 305 | And throws an error if so. 306 | 307 | Parameters 308 | ---------- 309 | unv_file_name: str 310 | The file name to look for. 311 | """ 312 | 313 | # Don't perform checks on the file itself in the file system! 314 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 315 | # loop through all solutions 316 | solutions: List[NXOpen.CAE.SimSolution] = sim_part.Simulation.Solutions.ToArray() 317 | for i in range(len(solutions)): 318 | sim_result_reference: NXOpen.CAE.SimResultReference = get_sim_result_reference(solutions[i].Name) 319 | # loop through each companion result 320 | companion_results: List[NXOpen.CAE.CompanionResult] = sim_result_reference.CompanionResults.ToArray() 321 | for j in range(len(companion_results)): 322 | # create the builder with the companion result, so can access the CompanionResultsFile 323 | companion_result_builder: NXOpen.CAE.CompanionResultBuilder = sim_result_reference.CompanionResults.CreateCompanionResultBuilder(companion_results[j]) 324 | if (companion_result_builder.CompanionResultsFile.lower() == unv_file_name.lower()): 325 | # the file is the same, so throw exception 326 | raise ValueError("Companion results file name " + unv_file_name + " is already used by companion result " + companion_results[j].Name) 327 | 328 | 329 | def get_full_result_names(post_inputs: List[PostInput], solution_results: List[NXOpen.CAE.SolutionResult]) -> List[str]: 330 | """This function returns a representation of the Results used in PostInputs. 331 | Note that the representation is taken from the SolutionResult and not the SimSolution! 332 | 333 | Parameters 334 | ---------- 335 | post_inputs: List[PostInput] 336 | The list of PostInput defining the results. 337 | solution_results: List[NXOpen.CAE.SolutionResult] 338 | The solution results from which the representation is obtained. 339 | 340 | Returns 341 | ------- 342 | List[str] 343 | List of string with each representation. 344 | """ 345 | full_result_names: List[str] = [""] * len(post_inputs) 346 | for i in range(len(post_inputs)): 347 | full_result_names[i] = full_result_names[i] + solution_results[i].Name 348 | base_load_cases: List[NXOpen.CAE.BaseLoadcase] = solution_results[i].GetLoadcases() 349 | loadCase: NXOpen.CAE.Loadcase = cast(NXOpen.CAE.Loadcase, base_load_cases[post_inputs[i]._subcase - 1]) # user starts counting at 1 350 | full_result_names[i] = full_result_names[i] + "::" + loadCase.Name 351 | 352 | base_iterations: List[NXOpen.CAE.BaseIteration] = loadCase.GetIterations() 353 | iteration: NXOpen.CAE.Iteration = cast(NXOpen.CAE.Iteration, base_iterations[post_inputs[i]._iteration - 1]) # user starts counting at 1 354 | full_result_names[i] = full_result_names[i] + "::" + iteration.Name 355 | 356 | base_result_types: List[NXOpen.CAE.BaseResultType] = iteration.GetResultTypes() 357 | base_result_type: List[NXOpen.CAE.BaseResultType] = [item for item in base_result_types if item.Name.lower().strip() == post_inputs[i]._resultType.lower().strip()][0] 358 | resultType: NXOpen.CAE.ResultType = cast(NXOpen.CAE.ResultType, base_result_type) 359 | full_result_names[i] = full_result_names[i] + "::" + resultType.Name 360 | 361 | return full_result_names 362 | 363 | 364 | def export_result(post_input: PostInput, unv_file_name: str, si_units: bool = False) -> None: 365 | """Export a single result to universal file.""" 366 | if not isinstance(base_part, NXOpen.CAE.SimPart): 367 | the_lw.WriteFullline("ExportResult needs to start from a .sim file. Exiting") 368 | return 369 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 370 | 371 | post_input_list: List[PostInput] = [post_input] 372 | # check input and catch errors so that the user doesn't get a error pop-up in SC 373 | try: 374 | check_post_input(post_input_list) 375 | 376 | except ValueError as e: 377 | # internal raised exceptions are raised as valueError 378 | the_lw.WriteFullline("Did not execute ExportResult due to input error. Please check the previous messages.") 379 | # we still return the tehcnical message as an additional log 380 | the_lw.WriteFullline(str(e)) 381 | return 382 | except: 383 | the_lw.WriteFullline("Did not execute ExportResult due to general error. Please check the previous messages.") 384 | # we still return the tehcnical message as an additional log 385 | the_lw.WriteFullline(str(e)) 386 | return 387 | 388 | # Make sure the file is complete with path and extension 389 | unv_full_name: str = create_full_path(unv_file_name) 390 | 391 | # Load the results and store them in a list 392 | solution_results: List[NXOpen.CAE.SolutionResult] = load_results(post_input_list) 393 | 394 | # get all ResultType objects as defined in postInputs and store them in a list 395 | result_types: List[NXOpen.CAE.BaseResultType] = get_result_types(post_input_list, solution_results) 396 | 397 | # get all identifiers in postInputs and store them in a list, using list comprehension 398 | identifiers: List[str] = ["nxopenexportresult"] 399 | 400 | # get the full result names for user feedback. Do this before the try except block, otherwise the variable is no longer available 401 | full_result_names: List[str] = get_full_result_names(post_input_list, solution_results) 402 | 403 | # get the unit for each resultType from the result itself 404 | resultUnits: List[NXOpen.Unit] = get_results_units(result_types) 405 | 406 | results_combination_builder = the_session.ResultManager.CreateResultsCombinationBuilder() 407 | results_combination_builder.SetResultTypes(result_types, identifiers, resultUnits) 408 | results_combination_builder.SetFormula("nxopenexportresult") 409 | results_combination_builder.SetOutputResultType(NXOpen.CAE.ResultsManipulationBuilder.OutputResultType.Full) 410 | results_combination_builder.SetIncludeModel(False) 411 | results_combination_builder.SetOutputQuantity(result_types[0].Quantity) 412 | results_combination_builder.SetOutputName(full_result_names[0]) 413 | results_combination_builder.SetLoadcaseName(full_result_names[0]) 414 | results_combination_builder.SetOutputFile(unv_full_name) 415 | results_combination_builder.SetIncompatibleResultsOption(NXOpen.CAE.ResultsCombinationBuilder.IncompatibleResults.Skip) 416 | results_combination_builder.SetNoDataOption(NXOpen.CAE.ResultsCombinationBuilder.NoData.Skip) 417 | results_combination_builder.SetEvaluationErrorOption(NXOpen.CAE.ResultsCombinationBuilder.EvaluationError.Skip) 418 | 419 | # The following 2 lines have no effect if SetIncludeModel is set to false 420 | # If SetIncludeModel is true these 2 lines adds dataset 164 to the .unv file 421 | # resultsCombinationBuilder.SetUnitsSystem(NXOpen.CAE.ResultsManipulationBuilder.UnitsSystem.FromResult) 422 | # resultsCombinationBuilder.SetUnitsSystemResult(solutionResults[0]) 423 | 424 | if si_units: 425 | # in case you want to set a userdefined units system 426 | user_defined_unit_system: NXOpen.CAE.Result.ResultBasicUnit = NXOpen.CAE.Result.ResultBasicUnit() 427 | units: List[NXOpen.Unit] = sim_part.UnitCollection 428 | # # Prints a list of all available units 429 | # for item in units: 430 | # the_lw.WriteFullline(item.TypeName) 431 | 432 | user_defined_unit_system.AngleUnit = [item for item in units if item.TypeName == "Radian"][0] 433 | user_defined_unit_system.LengthUnit = [item for item in units if item.TypeName == "Meter"][0] 434 | user_defined_unit_system.MassUnit = [item for item in units if item.TypeName == "Kilogram"][0] 435 | user_defined_unit_system.TemperatureUnit = [item for item in units if item.TypeName == "Celsius"][0] 436 | user_defined_unit_system.ThermalenergyUnit = [item for item in units if item.TypeName == "ThermalEnergy_Metric1"][0] 437 | user_defined_unit_system.TimeUnit = [item for item in units if item.TypeName == "Second"][0] 438 | results_combination_builder.SetUnitsSystem(NXOpen.CAE.ResultsManipulationBuilder.UnitsSystem.UserDefined) 439 | results_combination_builder.SetUserDefinedUnitsSystem(user_defined_unit_system) 440 | # if set to false, dataset 164 is not added and the results are ambiguos for external use 441 | results_combination_builder.SetIncludeModel(True) 442 | 443 | try: 444 | results_combination_builder.Commit() 445 | the_lw.WriteFullline("Exported result:") 446 | the_lw.WriteFullline(full_result_names[0]) 447 | 448 | except Exception as e: 449 | the_lw.WriteFullline("Error in ExportResult:") 450 | the_lw.WriteFullline(str(e)) 451 | raise 452 | 453 | finally: 454 | results_combination_builder.Destroy() 455 | 456 | expressions: List[NXOpen.Expression] = sim_part.Expressions 457 | for i in range(len(identifiers)): 458 | check: NXOpen.Expression = [item for item in expressions if item.Name.lower() == identifiers[i].lower()] 459 | if len(check) != 0: 460 | # expression found, thus deleting 461 | sim_part.Expressions.Delete(check[0]) 462 | 463 | 464 | def get_result_paramaters(result_types: List[NXOpen.CAE.BaseResultType], result_shell_section: NXOpen.CAE.Result.ShellSection, result_component: NXOpen.CAE.Result.Component, absolute: bool) -> List[NXOpen.CAE.ResultParameters]: 465 | result_parameter_list: List[NXOpen.CAE.ResultParameters] = [NXOpen.CAE.ResultParameters] * len(result_types) 466 | 467 | for i in range(len(result_parameter_list)): 468 | result_parameters: NXOpen.CAE.ResultParameters = the_session.ResultManager.CreateResultParameters() 469 | result_parameters.SetGenericResultType(result_types[i]) 470 | result_parameters.SetShellSection(result_shell_section) 471 | result_parameters.SetResultComponent(result_component) 472 | result_parameters.SetSelectedResultCoordinateSystem(-1) 473 | result_parameters.MakeElementResult(False) 474 | 475 | # components: List[NXOpen.CAE.Result.Component] = resultTypes[i].AskComponents() 476 | result: Tuple[List[NXOpen.CAE.Result.Component], List[str]] = result_types[i].AskComponents() 477 | unit: NXOpen.Unit = result_types[i].AskDefaultUnitForComponent(result[0][0]) # [0] for the list of componentns and another [0] for the first componentn 478 | result_parameters.SetUnit(unit) 479 | 480 | result_parameters.SetAbsoluteValue(absolute) 481 | result_parameters.SetTensorComponentAbsoluteValue(NXOpen.CAE.Result.TensorDerivedAbsolute.DerivedComponent) 482 | 483 | result_parameter_list[i] = result_parameters 484 | 485 | return result_parameter_list 486 | 487 | 488 | def get_result_component_names() -> Dict[int, str]: 489 | """ 490 | Get the names of the available result components in order to give meaningful feedback 491 | 492 | Returns 493 | ------- 494 | Dict[int, str] 495 | A dictionary with the int value and the string value of the result component 496 | 497 | Notes 498 | ----- 499 | Warning: this assumes that the enum is ordered according the values by the NXOpen developers!! 500 | Tested in SC2212 501 | 502 | """ 503 | values = list(NXOpen.CAE.Result.Component.__dict__) 504 | mapping = {} 505 | for i in range(0, len(values)): 506 | # the_lw.WriteFullline(values[i] + ': ' + str(NXOpen.CAE.ResultsManipulationEnvelopeBuilder.Operation.ValueOf(i))) 507 | mapping[i] = values[i] 508 | 509 | # for key, value in mapping.items(): 510 | # the_lw.WriteFullline(str(key) + ': ' + value) 511 | return mapping 512 | 513 | 514 | def main() : 515 | the_lw.Open() 516 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 517 | 518 | if not type(base_part) is NXOpen.CAE.SimPart: 519 | the_lw.WriteFullline("This script needs to start from a .sim file. Exiting") 520 | return 521 | 522 | sim_solutions: List[NXOpen.CAE.SimSolution] = cast(NXOpen.CAE.SimPart, base_part).Simulation.Solutions 523 | 524 | 525 | for solution in sim_solutions: 526 | export_inputs: List[PostInput] = [PostInput("", -1, -1, "")] * solution.StepCount # declare the list with the correct length 527 | for i in range(len(export_inputs)): 528 | export_inputs[i] = PostInput(solution.Name, i + 1, 1, "Stress - Element-Nodal") 529 | 530 | for item in export_inputs: 531 | export_result(item, item._solution + "_" + str(item._subcase), True) 532 | 533 | 534 | if __name__ == '__main__': 535 | main() 536 | -------------------------------------------------------------------------------- /post_processing/export_shell_thickness_as_unv.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | 3 | # SimCenter support for universal file: 4 | # NX12 https://docs.sw.siemens.com/en-US/product/289054037/doc/PL20190719090640300.advanced/html/xid1404617 5 | # Release SC2019.1 https://docs.sw.siemens.com/en-US/product/289054037/doc/PL20190702084816205.advanced/html/xid1404617 6 | # Release SC2020.1 https://docs.sw.siemens.com/en-US/product/289054037/doc/PL20191009145841552.advanced/html/xid1404617 7 | # Release SC2021.1 https://docs.sw.siemens.com/en-US/product/289054037/doc/PL20200601120302950.advanced/html/xid1404617 8 | # Release SC2022.1 https://docs.sw.siemens.com/en-US/product/289054037/doc/PL20201105151514625.advanced/html/xid1404617 9 | 10 | # Fortran format codes 11 | # https://www.l3harrisgeospatial.com/docs/format_codes_fortran.html 12 | # https://help.perforce.com/pv-wave/2017.1/PVWAVE_Online_Help/pvwave.html#page/Foundation/ap.a.format.066.09.html 13 | 14 | import os 15 | import datetime 16 | import NXOpen 17 | import NXOpen.CAE 18 | from typing import List, cast, Dict 19 | 20 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 21 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 22 | base_part = the_session.Parts.BaseWork 23 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 24 | 25 | def create_thickness_header(dataset_label: int, dataset_name: str, type: str) -> str: 26 | """Creates a universal file dataset header 27 | 28 | Parameters 29 | ---------- 30 | dataset_label: int 31 | The label for the dataset 32 | dataset_name: str 33 | The name for the dataset 34 | type: str 35 | The type of result for the dataset: "Elemental" or "Element-Nodal" 36 | 37 | Returns 38 | ------- 39 | str 40 | The header as a string 41 | """ 42 | the_uf_session.Ui.SetStatus("Creating thickness header") 43 | header: str = "" 44 | header = header + "{: ^6}".format("-1") + "\n" # every dataset starts with -1 45 | header = header + "{: ^6}".format("2414") + "\n" # this is the header for dataset 2414 46 | header = header + "{: ^10}".format(dataset_label) + "\n" # record 1 47 | header = header + "LOADCASE_NAME_KEY " + dataset_name + "\n" # record 2 - analysis dataset name 40A2: using this syntax, SimCenter will set the load case name to "datasetName" 48 | 49 | # record 3 50 | if type.strip().lower() == "elemental": 51 | header = header + "{: ^10}".format("2") + "\n" # Record 3 - dataset location - data on elements 52 | 53 | elif type.strip().lower() == "element-nodal" or type.strip().lower() == "elementnodal" or type.strip().lower() == "element nodal": 54 | header = header + "{: ^10}".format("3") + "\n" # Record 3 - dataset location - data at nodes on element 55 | 56 | else: 57 | the_lw.WriteFullline("Unsupported type " + type + " in CreateThicknessHeader. Should be \"elemental\" or \"element-nodal\"") 58 | raise ValueError("Unsupported type " + type + " in CreateThicknessHeader. Should be \"elemental\" or \"element-nodal\"") 59 | 60 | header = header + "RESULT_NAME_KEY " + dataset_name + "\n" # record 4 - analysis dataset name 40A2: using this syntax, will set the resulttype to dataset_name 61 | header = header + "NONE" + "\n" # record 5 - analysis dataset name 40A2: using this syntax, Simcenter will parse it and show in the GUI. 62 | header = header + "EXPRESSION_NAME_KEY " + dataset_name + "\n" # record 6 - analysis dataset name 40A2: using this syntax, Simcenter will parse it and show in the GUI. 63 | # by using utc, the time is clear. 64 | header = header + "Creation time: " + str(datetime.datetime.utcnow()) + "\n" # record 7 - analysis dataset name 40A2: using this syntax, Simcenter will parse it and show in the GUI. 65 | header = header + "NONE" + "\n" # record 8 - analysis dataset name 40A2: using this syntax, Simcenter will parse it and show in the GUI. 66 | header = header + "{: ^10}".format("1") + "{: ^10}".format("1") + "{: ^10}".format("1") + "{: ^10}".format("94") + "{: ^10}".format("2") + "{: ^10}".format("1") + "\n" # record 9 67 | header = header + "{: ^10}".format("1") + "{: ^10}".format("0") + "{: ^10}".format(dataset_label) + "{: ^10}".format("0") + "{: ^10}".format("1") + "{: ^10}".format("0") + "{: ^10}".format("0") + "{: ^10}".format("0") + "\n" # record 10 68 | header = header + "{: ^10}".format("0") + "{: ^10}".format("0") + "\n" # record 11: using this syntax for Simcenter to parse it properly 69 | header = header + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "\n" # record 12: using this syntax for Simcenter to parse it properly 70 | header = header + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "{: ^10}".format("0.00000E+00") + "\n" # record 13: using this syntax for Simcenter to parse it properly 71 | 72 | return header 73 | 74 | 75 | def get_all_fe_elements(base_fem_part: NXOpen.CAE.BaseFemPart) -> Dict[int, NXOpen.CAE.FEElement]: 76 | """Get all elements from the model. 77 | Note that this is the most performant way to do so. 78 | 79 | Parameters 80 | ---------- 81 | base_fem_part: NXOpen.CAE.BaseFemPart 82 | The BaseFemPart to get the elements from. 83 | 84 | Returns 85 | ------- 86 | List[NXOpen.CAE.FEElement] 87 | A list of all FEElements in the base_fem_part 88 | """ 89 | 90 | all_elements: Dict[int, NXOpen.CAE.FEElement] = {} 91 | fe_element_label_map = base_fem_part.BaseFEModel.FeelementLabelMap 92 | element_label: int = fe_element_label_map.AskNextElementLabel(0) 93 | while (element_label > 0): 94 | all_elements[element_label] = fe_element_label_map.GetElement(element_label) 95 | element_label = fe_element_label_map.AskNextElementLabel(element_label) 96 | 97 | # sort the dict (valid for python 3.7+) even thought the items should be in order from the element label map 98 | all_elements = dict(sorted(all_elements.items())) 99 | return all_elements 100 | 101 | 102 | def create_thickness_records(base_fem_part: NXOpen.CAE.BaseFemPart, fe_element: NXOpen.CAE.FEElement) -> List[str]: 103 | """This function returns a representation of the Results used in PostInputs. 104 | Note that the representation is taken from the SolutionResult and not the SimSolution! 105 | 106 | Parameters 107 | ---------- 108 | base_fem_part: NXOpen.CAE.BaseFemPart 109 | The BaseFemPart to generate the thickness datasets for. 110 | fe_element: NXOpen.CAE.FEElement 111 | The FEElement for which to generate to thickness records for 112 | 113 | Returns 114 | ------- 115 | List[str] 116 | A list with the elemental and element-nodal record for the given FEElement. 117 | """ 118 | 119 | # user feedback, but not for all, othwerwise some performance hit 120 | if (fe_element.Label % 1000 == 0): 121 | the_uf_session.Ui.SetStatus("Generating records for element " + str(fe_element.Label)) 122 | 123 | # from the manual it looks like this is the correct code, but it unchecked 124 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/a09128.html#aa053492346c7911e6691696cb41fcb56 125 | thickness: float = -1 126 | thickness_unit: NXOpen.Unit 127 | thickness, thickness_unit = fe_element.Mesh.MeshCollector.ElementPropertyTable.GetNamedPropertyTablePropertyValue("Shell Property").PropertyTable.GetScalarWithDataPropertyValue("element thickness") 128 | 129 | record14_elemental: str = "{: ^10}".format(fe_element.Label) + "{: ^10}".format("1") + "\n" 130 | record15_elemental: str = "{: ^13}".format(thickness) + "\n" 131 | 132 | # even though the second record is 1 (data present for all nodes) SimCenter will not read it properly use the first value for all nodes!! 133 | # some versions of (NX12) will even give a "result file in wrong format" error. In this case, simply change the value to 2 134 | record14_element_nodal: str = "{: ^10}".format(fe_element.Label) + "{: ^10}".format("2") + "{: ^10}".format(len(fe_element.GetNodes())) + "{: ^10}".format("1") + "\n" 135 | 136 | # Get the element nodal thickness form the element associated data (if defined) - NOT IMPLEMENTED 137 | # for the python documentation it seems like it is not possible to get the thickness 138 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/a03583.html#a35f17731a5527236c5a8731fce37a741 139 | # compare to .net: 140 | # https://docs.sw.siemens.com/documentation/external/PL20200522120320484/en-US/nx_api_sc/nx/1980/nx_api_sc/en-US/nxopen_net/a35347.html#a7a1d17eb44c21e11636df16ecfa16fc4 141 | # however, should test how many items are returned from the method: all out elements could be returned as a tuple, which is typical for pyton. 142 | # element_associated_data_utils = base_fem_part.BaseFEModel.NodeElementMgr.ElemAssociatedDataUtils 143 | # element_associated_data_utils.AskShellData() 144 | 145 | record15_element_nodal: str = "{: ^10}".format("{:.5E}".format(thickness)) 146 | result: List[str] = [record14_elemental + record15_elemental, record14_element_nodal + record15_element_nodal] 147 | return result 148 | 149 | 150 | def create_thickness_datasets(base_fem_part: NXOpen.CAE.BaseFemPart) -> List[str]: 151 | """This function creates an elemental and element-nodal thickness dataset 152 | for all shell elements in the base_fem_part. 153 | 154 | Parameters 155 | ---------- 156 | base_fem_part: NXOpen.CAE.BaseFemPart 157 | The BaseFemPart to generate the thickness datasets for. 158 | 159 | Returns 160 | ------- 161 | List[str] 162 | Each dataset as a string. 163 | """ 164 | the_lw.WriteFullline("---------- WARNING ----------") 165 | the_lw.WriteFullline("The Element-Nodal result Record 14 field 2 is set to 2: ") 166 | the_lw.WriteFullline("'Data present for only first node, all other nodes the same'") 167 | the_lw.WriteFullline("While all nodes are listed individually in Record 15, which is contradictory.") 168 | the_lw.WriteFullline("When using externally, update Record 14 field 2 to 1!") 169 | the_lw.WriteFullline("-------- END WARNING ---------") 170 | 171 | thickness_dataset_elemental = create_thickness_header(1, "Thickness", "Elemental") 172 | thickness_dataset_element_nodal = create_thickness_header(1, "Thickness", "Elemental-Nodal") # by providing the same label, both results will get grouped under the loadcase thickness 173 | 174 | all_elements: Dict[int, NXOpen.CAE.FEElement] = get_all_fe_elements(base_fem_part) 175 | for key, value in all_elements.items(): 176 | if str(value.Shape) == "Quad" or str(value.Shape) == "Tri": 177 | thickness_dataset_elemental = thickness_dataset_elemental + create_thickness_records(base_fem_part, value)[0] 178 | thickness_dataset_elemental = thickness_dataset_elemental + create_thickness_records(base_fem_part, value)[1] 179 | 180 | thickness_dataset_elemental = thickness_dataset_elemental + "{: ^6}".format("-1") 181 | thickness_dataset_element_nodal = thickness_dataset_element_nodal + "{: ^6}".format("-1") 182 | 183 | thickness_datasets: List[str] = [thickness_dataset_elemental, thickness_dataset_element_nodal] 184 | return thickness_datasets 185 | 186 | 187 | def create_full_path(file_name: str, extension: str = ".unv") -> str: 188 | """This function takes a filename and adds the .unv extension and path of the part if not provided by the user. 189 | If the fileName contains an extension, this function leaves it untouched, othwerwise adds .unv as extension. 190 | If the fileName contains a path, this function leaves it untouched, otherwise adds the path of the BasePart as the path. 191 | Undefined behaviour if basePart has not yet been saved (eg FullPath not available) 192 | 193 | Parameters 194 | ---------- 195 | file_name: str 196 | The filename with or without path and .unv extension. 197 | extension (optional): str 198 | The extension to add if not provided. Defaults to .unv 199 | 200 | Returns 201 | ------- 202 | str 203 | A string with .unv extension and path of the basePart if the fileName parameter did not include a path. 204 | """ 205 | # check if .unv is included in fileName 206 | if os.path.splitext(file_name)[1] != ".unv": 207 | file_name = file_name + ".unv" 208 | 209 | # check if path is included in fileName, if not add path of the .sim file 210 | unv_file_path: str = os.path.dirname(file_name) 211 | if unv_file_path == "": 212 | # if the .sim file has never been saved, the next will give an error 213 | file_name = os.path.join(os.path.dirname(base_part.FullPath), file_name) 214 | 215 | return file_name 216 | 217 | 218 | def write_thickness_results(base_fem_part: NXOpen.CAE.BaseFemPart, file_name: str): 219 | """This function writes an elemental and element-nodal result to a universal file. 220 | The content of the result is the shell thickness of all shell elements in the model. 221 | 222 | Parameters 223 | ---------- 224 | base_fem_part: NXOpen.CAE.BaseFemPart 225 | The BaseFemPart to generate the thickness result for. 226 | file_name: str 227 | The name of the universal file to write the results to 228 | """ 229 | datasets: List[str] = create_thickness_datasets(base_fem_part) 230 | file_name = create_full_path(file_name) 231 | 232 | # concatenate all datasets 233 | unv_file: str = datasets[0] + "\n" + datasets[1] 234 | with open(file_name, 'w') as file: 235 | file.write(unv_file) 236 | 237 | 238 | def main(): 239 | the_lw.Open() 240 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 241 | 242 | base_fem_part: NXOpen.CAE.BaseFemPart 243 | if isinstance(base_part, NXOpen.CAE.SimPart): 244 | the_lw.WriteFullline("Starting from sim file.") 245 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 246 | base_fem_part = cast(NXOpen.CAE.BaseFemPart, sim_part.FemPart) 247 | 248 | # if the baseFemPart is an AssyFemPart then need to make it work for the code to run. 249 | the_session.Parts.SetWork(base_fem_part) 250 | 251 | elif isinstance(base_part, NXOpen.CAE.BaseFemPart): 252 | the_lw.WriteFullline("Starting from a fem or afem file.") 253 | base_fem_part = cast(NXOpen.CAE.BaseFemPart, base_part) 254 | 255 | else: 256 | the_lw.WriteFullline("This function needs to start from a .sim, .afem or .fem.") 257 | return 258 | 259 | write_thickness_results(base_fem_part, "Thickness.unv") 260 | 261 | # return to original work part. 262 | the_session.Parts.SetWork(base_part) 263 | 264 | 265 | if __name__ == '__main__': 266 | main() 267 | -------------------------------------------------------------------------------- /post_processing/list_nodal_results.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import math 4 | import NXOpen 5 | import NXOpen.UF 6 | import NXOpen.CAE 7 | from typing import List, cast, Tuple 8 | 9 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 10 | base_part = the_session.Parts.BaseWork 11 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 12 | 13 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 14 | 15 | 16 | class PostInput: 17 | """A class for declaring inputs used in CombineResults""" 18 | _solution: str 19 | _subcase: int 20 | _iteration: int 21 | _resultType: str 22 | _identifier: str 23 | 24 | def __init__(self) -> None: # type: ignore 25 | """Parameterless constructor. Strings initialized to empty strings and integers to -1""" 26 | self._solution = "" 27 | self._subcase = -1 28 | self._iteration = -1 29 | self._resultType = "" 30 | self._identifier = "" 31 | 32 | def __init__(self, solution: str, subcase: int, iteration: int, resultType: str, identifier: str = ""): 33 | """Constructor""" 34 | self._solution = solution 35 | self._subcase = subcase 36 | self._iteration = iteration 37 | self._resultType = resultType 38 | self._identifier = identifier 39 | 40 | def __repr__(self) -> str: 41 | """String representation of a PostInput""" 42 | return "Solution: " + self._solution + " Subcase: " + str(self._subcase) + " Iteration: " + str(self._iteration) + " ResultType: " + self._resultType + " Identifier: " + self._identifier 43 | 44 | 45 | def get_solution(solution_name: str) -> NXOpen.CAE.SimSolution: 46 | """This function returns the SimSolution object with the given name. 47 | 48 | Parameters 49 | ---------- 50 | solution_name: str 51 | The name of the solution to return. Case insensitive. 52 | 53 | Returns 54 | ------- 55 | NXOpen.CAE.SimSolution 56 | Returns a list of SolutionResult. 57 | """ 58 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) # explicit casting makes it clear 59 | sim_simulation: NXOpen.CAE.SimSimulation = sim_part.Simulation 60 | 61 | sim_solutions: List[NXOpen.CAE.SimSolution] = [item for item in sim_simulation.Solutions if item.Name.lower() == solution_name.lower()] 62 | if len(sim_solutions) == 0: 63 | return None # type: ignore 64 | 65 | return sim_solutions[0] 66 | 67 | 68 | def load_results(post_inputs: List[PostInput], reference_type: str = "Structural") -> List[NXOpen.CAE.SolutionResult]: 69 | """Loads the results for the given list of PostInput and returns a list of SolutionResult. 70 | An exception is raised if the result does not exist (-> to check if CreateReferenceResult raises error or returns None) 71 | 72 | Parameters 73 | ---------- 74 | post_inputs: List[PostInput] 75 | The result of each of the provided solutions is loaded. 76 | reference_type: str 77 | The type of SimResultReference eg. Structural. Defaults to structral 78 | 79 | Returns 80 | ------- 81 | NXOpen.CAE.SolutionResult 82 | Returns a list of SolutionResult. 83 | """ 84 | solution_results: List[NXOpen.CAE.SolutionResult] = [NXOpen.CAE.SolutionResult] * len(post_inputs) 85 | simPart: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 86 | 87 | for i in range(len(post_inputs)): 88 | sim_solution: NXOpen.CAE.SimSolution = get_solution(post_inputs[i]._solution) 89 | sim_result_reference: NXOpen.CAE.SimResultReference = cast(NXOpen.CAE.SimResultReference, sim_solution.Find(reference_type)) 90 | 91 | try: 92 | # SolutionResult[filename_solutionname] 93 | solution_results[i] = cast(NXOpen.CAE.SolutionResult, the_session.ResultManager.FindObject("SolutionResult[" + (os.path.basename(simPart.FullPath) + "_" + sim_solution.Name + "]"))) 94 | except: 95 | solution_results[i] = the_session.ResultManager.CreateReferenceResult(sim_result_reference) 96 | 97 | return solution_results 98 | 99 | 100 | def get_result_types(post_inputs: List[PostInput], solution_results: List[NXOpen.CAE.SolutionResult]) -> List[NXOpen.CAE.BaseResultType]: 101 | """Helper function for CombineResults and GetResultParameters. 102 | Returns the ResultTypes specified in PostInputs 103 | 104 | Parameters 105 | ---------- 106 | postInputs: List[PostInput] 107 | The input as an array of PostInput. 108 | solutionResults: List[NXOpen.CAE.SolutionResult] 109 | The already loaded results to search through for the results. 110 | 111 | Returns 112 | ------- 113 | List[NXOpen.CAE.BaseResultType] 114 | Returns the result objects 115 | """ 116 | result_types: List[NXOpen.CAE.BaseResultType] = [NXOpen.CAE.BaseResultType] * len(post_inputs) 117 | for i in range(len(post_inputs)): 118 | base_load_cases: List[NXOpen.CAE.BaseLoadcase] = solution_results[i].GetLoadcases() 119 | loadCase: NXOpen.CAE.Loadcase = cast(NXOpen.CAE.Loadcase, base_load_cases[post_inputs[i]._subcase - 1]) # user starts counting at 1 120 | base_iterations: List[NXOpen.CAE.BaseIteration] = loadCase.GetIterations() 121 | iteration: NXOpen.CAE.Iteration = cast(NXOpen.CAE.Iteration, base_iterations[post_inputs[i]._iteration - 1]) # user starts counting at 1 122 | base_result_types: List[NXOpen.CAE.BaseResultType] = iteration.GetResultTypes() 123 | base_result_type: List[NXOpen.CAE.ResultType] = [item for item in base_result_types if item.Name.lower().strip() == post_inputs[i]._resultType.lower().strip()][0] 124 | result_types[i] = cast(NXOpen.CAE.ResultType, base_result_type) 125 | 126 | return result_types 127 | 128 | 129 | def get_result_paramaters(result_types: List[NXOpen.CAE.BaseResultType], result_shell_section: NXOpen.CAE.Result.ShellSection, result_component: NXOpen.CAE.Result.Component, absolute: bool) -> List[NXOpen.CAE.ResultParameters]: 130 | result_parameter_list: List[NXOpen.CAE.ResultParameters] = [NXOpen.CAE.ResultParameters] * len(result_types) 131 | 132 | for i in range(len(result_parameter_list)): 133 | result_parameters: NXOpen.CAE.ResultParameters = the_session.ResultManager.CreateResultParameters() 134 | result_parameters.SetGenericResultType(result_types[i]) 135 | result_parameters.SetShellSection(result_shell_section) 136 | result_parameters.SetResultComponent(result_component) 137 | # result_parameters.SetSelectedCoordinateSystem(NXOpen.CAE.Result.CoordinateSystem.None, -1) 138 | result_parameters.MakeElementResult(False) 139 | 140 | # components: List[NXOpen.CAE.Result.Component] = resultTypes[i].AskComponents() 141 | result: Tuple[List[NXOpen.CAE.Result.Component], List[str]] = result_types[i].AskComponents() # type: ignore 142 | unit: NXOpen.Unit = result_types[i].AskDefaultUnitForComponent(result_component) 143 | result_parameters.SetUnit(unit) 144 | 145 | result_parameters.SetAbsoluteValue(absolute) 146 | result_parameters.SetTensorComponentAbsoluteValue(NXOpen.CAE.Result.TensorDerivedAbsolute.DerivedComponent) 147 | 148 | result_parameter_list[i] = result_parameters 149 | 150 | return result_parameter_list 151 | 152 | 153 | def list_nodal_values(solution_name: str, subcase: int, iteration: int, result_type: str, node_label: int) -> None: 154 | """Lists nodal values for a given 155 | 156 | Parameters 157 | ---------- 158 | solution_name: string 159 | The name of the solution 160 | subcase: int 161 | The subcase number. User starts counting at 1 162 | iteration: int 163 | The iteration number. User starts counting at 1 164 | result_type: str 165 | The name of the result type to ask results (eg. "Reaction Force - Nodal") 166 | node_label: int 167 | The label of the node to get the result for. 168 | """ 169 | post_input = PostInput(solution_name, subcase, iteration, result_type) # Assuming PostInput is available in Python 170 | post_input_array = [post_input] 171 | solution_results = load_results(post_input_array) 172 | result = solution_results[0] 173 | result_types = get_result_types(post_input_array, solution_results) 174 | result_parameters = get_result_paramaters(result_types, NXOpen.CAE.Result.ShellSection.Maximum, NXOpen.CAE.Result.Component.Magnitude, False) 175 | result_access = the_session.ResultManager.CreateResultAccess(result, result_parameters[0]) 176 | node_index = solution_results[0].AskNodeIndex(node_label) 177 | nodal_data = result_access.AskNodalResultAllComponents(node_index) 178 | 179 | # Printing is hard coded as X Y Z Magnitude 180 | the_lw.WriteFullline(f"X:\t{nodal_data[0]}\tY:\t{nodal_data[1]}\tZ:\t{nodal_data[2]}\tMagnitude:\t{nodal_data[3]}") 181 | 182 | 183 | def list_element_nodal_values(solution_name, subcase, iteration, result_type, element_label): 184 | # still needs implementing 185 | pass 186 | # post_input = PostInput(solution_name, subcase, iteration, result_type) # Assuming PostInput is available in Python 187 | # post_input_array = [post_input] 188 | # solution_results = load_results(post_input_array) 189 | # result = solution_results[0] 190 | # result_types = get_result_types(post_input_array, solution_results) 191 | # result_parameters = get_result_paramaters(result_types, NXOpen.CAE.Result.ShellSection.Maximum, NXOpen.CAE.Result.Component.Axial, False) 192 | # result_access = the_session.ResultManager.CreateResultAccess(result, result_parameters[0]) 193 | # element_index = solution_results[0].AskElementIndex(element_label) 194 | 195 | # element_nodal_data: List[float] = result_access.AskElementNodalResultAllComponents(element_index) 196 | 197 | # # Get the number of nodes and from that the number of components 198 | # # All values will be returned as a single dimensional array. 199 | # # The array can be addressed as index = node_index*numComponents + component_index 200 | # num_components = 6 201 | # node_indexes = int(len(element_nodal_data) / num_components) 202 | 203 | # header = "{0:13}{1:13}{2:13}{3:13}{4:13}{5:13}{6:13}".format("ID:", "Nxx:", "Myy:", "Mzz:", "Mxx:", "Qxy:", "Qxz:") 204 | 205 | # the_lw.WriteFullline(header) 206 | 207 | # for i in range(node_indexes): 208 | # node_label = i # solution_results[0].AskNodeLabel(node_indexes[i]) 209 | # values = ["{0:#.#####E+00}".format(element_nodal_data[i * num_components + j]) for j in range(num_components)] 210 | # line = "{0:13}{1:13}{2:13}{3:13}{4:13}{5:13}{6:13}".format(node_label, *values) 211 | # the_lw.WriteFullline(line) 212 | 213 | 214 | def main() : 215 | the_lw.Open() 216 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 217 | 218 | node_label = 16885 219 | list_nodal_values("PinnedPinned", 1, 1, "Reaction Force - Nodal", node_label) 220 | list_nodal_values("FixedPinned", 1, 1, "Reaction Moment - Nodal", node_label) 221 | 222 | if __name__ == '__main__': 223 | main() 224 | -------------------------------------------------------------------------------- /pre_processing/add_related_nodes_and_elements.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # This file is used to demonstrate a working intellisense (code completion) for 6 | # writing NXOpen journals using Python 7 | 8 | import sys 9 | import math 10 | import NXOpen 11 | import NXOpen.CAE 12 | import NXOpen.UF 13 | from typing import List, cast, Optional, Union 14 | 15 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 16 | base_part = the_session.Parts.BaseWork 17 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 18 | 19 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 20 | 21 | 22 | def add_related_nodes_and_elements(cae_part: NXOpen.CAE.CaePart): 23 | """This function cycles through all cae groups in a CaePart. 24 | For each group it adds the related nodes and elements for the bodies and faces in the group. 25 | Practical for repopulating groups after a (partial) remesh. 26 | Function is idempotent. 27 | 28 | Parameters 29 | ---------- 30 | fem_part: NXOpen.CAE.FemPart 31 | The CaePart to perform this operation on. 32 | 33 | Notes 34 | ----- 35 | Tested in SC2306 36 | """ 37 | cae_groups: List[NXOpen.CAE.CaeGroup] = cae_part.CaeGroups 38 | for group in cae_groups: # type: ignore 39 | the_lw.WriteFullline("Processing group " + group.Name) 40 | seeds_body: List[NXOpen.CAE.CAEBody] = [] 41 | seeds_face: List[NXOpen.CAE.CAEFace] = [] 42 | 43 | for tagged_object in group.GetEntities(): 44 | if type(tagged_object) is NXOpen.CAE.CAEBody: 45 | seeds_body.append(cast(NXOpen.CAE.CAEBody, tagged_object)) 46 | 47 | elif type(tagged_object) is NXOpen.CAE.CAEFace: 48 | seeds_face.append(cast(NXOpen.CAE.CAEFace, tagged_object)) 49 | 50 | smart_selection_manager: NXOpen.CAE.SmartSelectionManager = cae_part.SmartSelectionMgr 51 | 52 | related_element_method_body: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedElemMethod(seeds_body, False) 53 | # related_node_method_body: NXOpen.CAE.RelatedNodeMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromBody(seeds_body, False) 54 | # For NX version 2007 (release 2022.1) and later 55 | related_node_method_body: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromBodies(seeds_body, False, False) 56 | 57 | group.AddEntities(related_element_method_body.GetElements()) 58 | group.AddEntities(related_node_method_body.GetNodes()) 59 | 60 | related_element_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedElemMethod(seeds_face, False) 61 | # related_node_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateRelatedNodeMethod(seeds_face, False) 62 | # For NX version 2007 (release 2022.1) and later 63 | related_node_method_face: NXOpen.CAE.RelatedElemMethod = smart_selection_manager.CreateNewRelatedNodeMethodFromFaces(seeds_face, False, False) 64 | 65 | group.AddEntities(related_element_method_face.GetElements()) 66 | group.AddEntities(related_node_method_face.GetNodes()) 67 | 68 | 69 | def main(): 70 | the_lw.Open() 71 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 72 | 73 | add_related_nodes_and_elements(cast(NXOpen.CAE.CaePart, base_part)) 74 | 75 | 76 | if __name__ == '__main__': 77 | main() -------------------------------------------------------------------------------- /pre_processing/create_mesh_collector.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | import sys 6 | import math 7 | import NXOpen 8 | import NXOpen.CAE 9 | from typing import List, cast, Optional, Union 10 | 11 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 12 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 13 | base_part = the_session.Parts.BaseWork 14 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 15 | 16 | 17 | def create_2dmesh_collector(thickness: float, physical_property_label: int) -> Optional[NXOpen.CAE.MeshCollector]: 18 | """This function creates a 2d mesh collector with the given thickness and label. 19 | the color of the mesh collector is set as 10 times the label 20 | 21 | Parameters 22 | ---------- 23 | thickness: float 24 | The thickness to set in the mesh collector 25 | physical_property_label: int 26 | The label of the physical property. Needs to be unique and thus cannot already be used in the part. 27 | 28 | 29 | Returns 30 | ------- 31 | NXOpen.CAE.MeshCollector 32 | Returns the created 2d mesh collector. 33 | """ 34 | 35 | if not isinstance(NXOpen.CAE.FemPart, base_part): 36 | the_lw.WriteFullline("create_node needs to start from a .fem file. Exiting") 37 | return 38 | 39 | fem_part: NXOpen.CAE.FemPart = cast(NXOpen.CAE.FemPart, base_part) 40 | fe_model: NXOpen.CAE.FEModel = fem_part.BaseFEModel 41 | 42 | mesh_manager: NXOpen.CAE.MeshManager = cast(NXOpen.CAE.MeshManager, fe_model.MeshManager) 43 | null_mesh_collector: NXOpen.CAE.MeshCollector = None 44 | mesh_collector_builder: NXOpen.CAE.MeshCollectorBuilder = mesh_manager.CreateCollectorBuilder(null_mesh_collector, "ThinShell") 45 | 46 | physical_property_table: NXOpen.CAE.PhysicalPropertyTable = fem_part.PhysicalPropertyTables.CreatePhysicalPropertyTable("PSHELL", "NX NASTRAN - Structural", "NX NASTRAN", "PSHELL2", physical_property_label) 47 | physical_property_table.SetName(str(thickness) + "mm") 48 | 49 | material_manager: NXOpen.CAE.MaterialManager = cast(NXOpen.CAE.MaterialManager, fem_part.MaterialManager) # cast only required because of intellisensse 50 | physical_materials: List[NXOpen.CAE.PhysicalMaterial] = material_manager.PhysicalMaterials.GetUsedMaterials() 51 | steel: List[NXOpen.CAE.PhysicalMaterial] = [item for item in physical_materials if item.Name == "Steel"] 52 | if steel == None: 53 | steel = material_manager.PhysicalMaterials.LoadFromNxlibrary("Steel") 54 | else: 55 | steel = steel[0] 56 | 57 | property_table: NXOpen.CAE.PropertyTable = physical_property_table.PropertyTable 58 | property_table.SetMaterialPropertyValue("material", False, steel) 59 | property_table.SetTablePropertyWithoutValue("bending material") 60 | property_table.SetTablePropertyWithoutValue("transverse shear material") 61 | property_table.SetTablePropertyWithoutValue("membrane-bending coupling material") 62 | 63 | unit_millimeter: NXOpen.Unit = cast(NXOpen.UnitCollection, fem_part.UnitCollection).FindObject("MilliMeter") 64 | property_table.SetBaseScalarWithDataPropertyValue("element thickness", str(thickness), unit_millimeter) 65 | 66 | mesh_collector_builder.CollectorName = str(thickness) + "mm" 67 | mesh_collector_builder.PropertyTable.SetNamedPropertyTablePropertyValue("Shell Property", physical_property_table) 68 | 69 | nx_object: NXOpen.NXObject = mesh_collector_builder.Commit() 70 | 71 | mesh_collector_builder.Destroy() 72 | 73 | # Setting the color of the MeshCollector we just created 74 | mesh_collector: NXOpen.CAE.MeshCollector = cast(NXOpen.CAE.MeshCollector, nx_object) 75 | mesh_collector_display_defaults = mesh_collector.GetMeshDisplayDefaults() 76 | 77 | # we set the color as label * 10 to make a distinction between the colors. The maximum color number is 216, therefore we take the modulus to not exceed this numer (eg. 15%4 -> 3) 78 | mesh_collector_display_defaults.Color = NXOpen.NXColor.NXColor._Get((label * 10) % 216) 79 | 80 | mesh_collector_display_defaults.Dispose() 81 | 82 | 83 | def main(): 84 | the_lw.Open() 85 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 86 | 87 | thicknesses: List[float] = [6, 8, 10, 12, 14, 15, 16, 18, 20, 22, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100] 88 | for i in range(len(thicknesses)): 89 | create_2dmesh_collector(thicknesses[i], i + 1) 90 | 91 | 92 | if __name__ == '__main__': 93 | main() 94 | -------------------------------------------------------------------------------- /pre_processing/create_nodes.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # This file is used to demonstrate a working intellisense (code completion) for 6 | # writing NXOpen journals using Python 7 | 8 | import sys 9 | import math 10 | import NXOpen 11 | import NXOpen.CAE 12 | from typing import List, cast, Optional, Union 13 | 14 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 15 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 16 | base_part = the_session.Parts.BaseWork 17 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 18 | 19 | 20 | def create_node(label: int, x_coordinate: float, y_coordinate: float, z_coordinate: float) -> Optional[NXOpen.CAE.FENode]: 21 | """This function creates a node with given label and coordinates. 22 | It is the user responsibility to make sure the label does not already exists in the model! 23 | 24 | Parameters 25 | ---------- 26 | label: int 27 | The node label 28 | x_coordinate: float 29 | The global x-coordinate of the node to be created 30 | y_coordinate: float 31 | The global y-coordinate of the node to be created 32 | z_coordinate: float 33 | The global z-coordinate of the node to be created 34 | 35 | Returns 36 | ------- 37 | NXOpen.CAE.FENode 38 | Returns the created node. 39 | """ 40 | 41 | if not isinstance(NXOpen.CAE.BaseFemPart, base_part): 42 | the_lw.WriteFullline("create_node needs to start from a .fem or .afem file. Exiting") 43 | return 44 | 45 | base_fem_part: NXOpen.CAE.BaseFemPart = cast(NXOpen.CAE.BaseFemPart, base_part) 46 | base_fe_model: NXOpen.CAE.FEModel = base_fem_part.BaseFEModel 47 | node_create_builder: NXOpen.CAE.NodeCreateBuilder = base_fe_model.NodeElementMgr.CreateNodeCreateBuilder() 48 | 49 | node_create_builder.Label = label 50 | null_nxopen_coordinate_system: NXOpen.CoordinateSystem = None 51 | node_create_builder.Csys = null_nxopen_coordinate_system 52 | node_create_builder.SingleOption = True 53 | 54 | node_create_builder.X.Value = x_coordinate 55 | node_create_builder.Y.Value = y_coordinate 56 | node_create_builder.Z.Value = z_coordinate 57 | 58 | coordinates: NXOpen.Point3d = NXOpen.Point3d(x_coordinate, y_coordinate, z_coordinate) 59 | point: NXOpen.Point = base_fem_part.Points.CreatePoint(coordinates) 60 | node_create_builder.Point = point 61 | 62 | node: NXOpen.NXObject = node_create_builder.Commit() 63 | 64 | node_create_builder.Csys = null_nxopen_coordinate_system 65 | node_create_builder.DispCsys = null_nxopen_coordinate_system 66 | 67 | node_create_builder.Destroy() 68 | 69 | return cast(NXOpen.CAE.FENode, node) 70 | 71 | 72 | def main(): 73 | the_lw.Open() 74 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 75 | 76 | for i in range(1000): 77 | create_node(10000 + i, 0, 0, i) 78 | 79 | 80 | if __name__ == '__main__': 81 | main() 82 | -------------------------------------------------------------------------------- /pre_processing/force_bc.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer 2 | import NXOpen 3 | import NXOpen.CAE 4 | import NXOpen.Fields 5 | from typing import List, cast 6 | 7 | the_session = NXOpen.Session.GetSession() 8 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 9 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 10 | 11 | def create_nodal_constraint(node_label: int, dx: float, dy : float, dz: float, rx: float, ry: float, rz: float, constraint_name: str) -> NXOpen.CAE.SimBC: 12 | """This function creates a constraint on a node. For free, set the value to -777777 13 | THis is minus 7, six times. Which equals 42 ;) You got to love the NX developers humor. 14 | 15 | Parameters 16 | ---------- 17 | node_label: int 18 | The node label to appy the constraint to. 19 | dx: float 20 | the displacement in global x-direction. 21 | dy: float 22 | the displacement in global y-direction. 23 | dz: float 24 | the displacement in global z-direction. 25 | rx: float 26 | the rotation in global x-direction. 27 | ry: float 28 | the rotation in global y-direction. 29 | rz: float 30 | the rotation in global z-direction. 31 | constraint_name: str 32 | The name of the constraint for the GUI. 33 | 34 | Returns 35 | ------- 36 | NXOpen.CAE.SimBC 37 | Returns the created constraint. 38 | 39 | Notes 40 | ----- 41 | Tested in SC2212 42 | 43 | """ 44 | # check if started from a SimPart, returning othwerwise 45 | base_part: NXOpen.BasePart = the_session.Parts.BaseWork 46 | if not isinstance(base_part, NXOpen.CAE.SimPart): 47 | the_lw.WriteFullline("CreateConstraint needs to start from a .sim file. Exiting") 48 | return 49 | # we are now sure that basePart is a SimPart 50 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) # explicit casting makes it clear 51 | 52 | sim_simulation: NXOpen.CAE.SimSimulation = sim_part.Simulation 53 | # make the active solution inactive, so bondary condition is not automatically added to active subcase 54 | sim_simulation.ActiveSolution = NXOpen.CAE.SimSolution.Null 55 | 56 | # check if constaint already exists 57 | sim_constraints: List[NXOpen.CAE.SimConstraint] = [item for item in sim_simulation.Constraints] 58 | sim_constraint: List[NXOpen.CAE.SimConstraint] = [item for item in sim_constraints if item.Name.lower() == constraint_name.lower()] 59 | sim_bc_builder: NXOpen.CAE.SimBCBuilder 60 | if len(sim_constraint) == 0: 61 | # no constraint with the given name, thus creating the constrain 62 | sim_bc_builder = sim_simulation.CreateBcBuilderForConstraintDescriptor("UserDefinedDisplacementConstraint", constraint_name, 0) 63 | elif len(sim_constraint) == 1: 64 | the_lw.WriteFullline(f'A constraint with the name {constraint_name} already exists therefore editing the constraint.') 65 | sim_bc_builder = sim_simulation.CreateBcBuilderForBc(sim_constraint[0]) 66 | else: 67 | the_lw.WriteFullline(f'Multiple constraints with the name {constraint_name} exist. This function requires unique names and is not case sensitive.') 68 | raise ValueError(f'Multiple constraints with the name {constraint_name} exist.') 69 | 70 | property_table: NXOpen.CAE.PropertyTable = sim_bc_builder.PropertyTable 71 | field_expression1: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF1") 72 | field_expression2: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF2") 73 | field_expression3: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF3") 74 | field_expression4: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF4") 75 | field_expression5: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF5") 76 | field_expression6: NXOpen.Fields.FieldExpression = property_table.GetScalarFieldPropertyValue("DOF6") 77 | 78 | unit_millimeter: NXOpen.Unit = cast(NXOpen.Unit, sim_part.UnitCollection.FindObject("MilliMeter")) 79 | indep_var_array1: List[NXOpen.Fields.FieldVariable] = [] 80 | field_expression1.EditFieldExpression(str(dx), unit_millimeter, indep_var_array1, False) 81 | property_table.SetScalarFieldPropertyValue("DOF1", field_expression1) 82 | 83 | indep_var_array2: List[NXOpen.Fields.FieldVariable] = [] 84 | field_expression2.EditFieldExpression(str(dy), unit_millimeter, indep_var_array2, False) 85 | property_table.SetScalarFieldPropertyValue("DOF2", field_expression2) 86 | 87 | indep_var_array3: List[NXOpen.Fields.FieldVariable] = [] 88 | field_expression3.EditFieldExpression(str(dz), unit_millimeter, indep_var_array3, False) 89 | property_table.SetScalarFieldPropertyValue("DOF3", field_expression3) 90 | 91 | unit_degrees: NXOpen.Unit = cast(NXOpen.Unit, sim_part.UnitCollection.FindObject("Degrees")) 92 | indep_var_array4: List[NXOpen.Fields.FieldVariable] = [] 93 | field_expression4.EditFieldExpression(str(rx), unit_degrees, indep_var_array4, False) 94 | property_table.SetScalarFieldPropertyValue("DOF4", field_expression4) 95 | 96 | indep_var_array5: List[NXOpen.Fields.FieldVariable] = [] 97 | field_expression5.EditFieldExpression(str(ry), unit_degrees, indep_var_array5, False) 98 | property_table.SetScalarFieldPropertyValue("DOF5", field_expression5) 99 | 100 | indep_var_array6: List[NXOpen.Fields.FieldVariable] = [] 101 | field_expression6.EditFieldExpression(str(rz), unit_degrees, indep_var_array6, False) 102 | property_table.SetScalarFieldPropertyValue("DOF6", field_expression6) 103 | 104 | # select the node via the label to assign the constraint to 105 | set_manager: NXOpen.CAE.SetManager = sim_bc_builder.TargetSetManager 106 | 107 | objects: List[NXOpen.CAE.SetObject] = [NXOpen.CAE.SetObject.Obj] * 1 108 | objects[0] = NXOpen.CAE.SetObject() 109 | fe_model_ccurrence: NXOpen.CAE.FEModelOccurrence = sim_part.Simulation.Femodel 110 | fe_node: NXOpen.CAE.FENode = fe_model_ccurrence.FenodeLabelMap.GetNode(node_label) 111 | if fe_node is None: 112 | the_lw.WriteFullline("CreateConstraint: node with label " + str(node_label) + " not found in the model. Constaint not created.") 113 | return 114 | 115 | objects[0].Obj = fe_node 116 | objects[0].SubType = NXOpen.CAE.CaeSetObjectSubType.NotSet 117 | objects[0].SubId = 0 118 | set_manager.SetTargetSetMembers(0, NXOpen.CAE.CaeSetGroupFilterType.Node, objects) 119 | 120 | sim_bc: NXOpen.CAE.SimBC = sim_bc_builder.CommitAddBc() 121 | sim_bc_builder.Destroy() 122 | 123 | return sim_bc 124 | def create_nodal_force_default_name(node_label: int, fx: float, fy : float, fz: float): 125 | defaultName: str = "Nodalforce_" + str(node_label) 126 | create_nodal_force(node_label, fx, fy, fz, defaultName) 127 | 128 | 129 | def create_nodal_force(node_label: int, fx: float, fy: float, fz: float, force_name: str): 130 | # check if started from a SimPart, returning othwerwise 131 | if not isinstance(base_part, NXOpen.CAE.SimPart): 132 | the_lw.WriteFullline("CreateNodalForce needs to start from a .sim file. Exiting") 133 | return 134 | # we are now sure that basePart is a SimPart 135 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) # explicit casting makes it clear 136 | 137 | sim_simulation: NXOpen.CAE.SimSimulation = sim_part.Simulation 138 | # make the active solution inactive, so load is not automatically added to active subcase 139 | sim_simulation.ActiveSolution = NXOpen.CAE.SimSolution.Null 140 | 141 | # check if a nodal force with that name already exists. If it does, update, if not create it 142 | sim_loads: List[NXOpen.CAE.SimLoad] = sim_part.Simulation.Loads 143 | sim_load: NXOpen.CAE.SimLoad = [item for item in sim_loads if item.Name.lower() == force_name.lower()] 144 | if len(sim_load) == 0: 145 | # load not found 146 | sim_bc_builder: NXOpen.CAE.SimBCBuilder = sim_simulation.CreateBcBuilderForLoadDescriptor("ComponentForceField", force_name, 0) # overloaded function is unknow to intellisense 147 | else: 148 | sim_bc_builder: NXOpen.CAE.SimBCBuilder = sim_simulation.CreateBcBuilderForBc(sim_load[0]) 149 | 150 | # define the force 151 | property_table: NXOpen.CAE.PropertyTable = sim_bc_builder.PropertyTable 152 | set_manager: NXOpen.CAE.SetManager = sim_bc_builder.TargetSetManager 153 | 154 | objects: List[NXOpen.CAE.SetObject] = [NXOpen.CAE.SetObject.Obj] * 1 155 | objects[0] = NXOpen.CAE.SetObject() 156 | fe_node: NXOpen.CAE.FENode = sim_part.Simulation.Femodel.FenodeLabelMap.GetNode(node_label) 157 | if fe_node is None: 158 | the_lw.WriteFullline("CreateNodalForce: node with label " + str(node_label) + " not found in the model. Force not created.") 159 | return 160 | 161 | objects[0].Obj = fe_node 162 | objects[0].SubType = NXOpen.CAE.CaeSetObjectSubType.NotSet 163 | objects[0].SubId = 0 164 | set_manager.SetTargetSetMembers(0, NXOpen.CAE.CaeSetGroupFilterType.Node, objects) 165 | 166 | unit1: NXOpen.Unit = sim_part.UnitCollection.FindObject("Newton") 167 | expression1: NXOpen.Expression = sim_part.Expressions.CreateSystemExpressionWithUnits(str(fx), unit1) 168 | expression2: NXOpen.Expression = sim_part.Expressions.CreateSystemExpressionWithUnits(str(fy), unit1) 169 | expression3: NXOpen.Expression = sim_part.Expressions.CreateSystemExpressionWithUnits(str(fz), unit1) 170 | 171 | field_manager: NXOpen.Fields.FieldManager = cast(NXOpen.Fields.FieldManager, sim_part.FindObject("FieldManager")) 172 | expressions: List[NXOpen.Expression] = [NXOpen.Expression.Null] * 3 173 | expressions[0] = expression1 174 | expressions[1] = expression2 175 | expressions[2] = expression3 176 | vector_field_wrapper: NXOpen.Fields.VectorFieldWrapper = field_manager.CreateVectorFieldWrapperWithExpressions(expressions) 177 | 178 | property_table.SetVectorFieldWrapperPropertyValue("CartesianMagnitude", vector_field_wrapper) 179 | property_table.SetTablePropertyWithoutValue("CylindricalMagnitude") 180 | property_table.SetVectorFieldWrapperPropertyValue("CylindricalMagnitude", NXOpen.Fields.VectorFieldWrapper.Null) 181 | property_table.SetTablePropertyWithoutValue("SphericalMagnitude") 182 | property_table.SetVectorFieldWrapperPropertyValue("SphericalMagnitude", NXOpen.Fields.VectorFieldWrapper.Null) 183 | property_table.SetTablePropertyWithoutValue("DistributionField") 184 | property_table.SetScalarFieldWrapperPropertyValue("DistributionField", NXOpen.Fields.ScalarFieldWrapper.Null) 185 | property_table.SetTablePropertyWithoutValue("ComponentsDistributionField") 186 | property_table.SetVectorFieldWrapperPropertyValue("ComponentsDistributionField", NXOpen.Fields.VectorFieldWrapper.Null) 187 | 188 | sim_bc: NXOpen.CAE.SimBC = sim_bc_builder.CommitAddBc() 189 | 190 | sim_bc_builder.Destroy() 191 | 192 | def main() : 193 | the_lw.Open() 194 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 195 | 196 | # create_nodal_force(1871, 0, 0, -9810, "DeckLoadPS1") 197 | # create_nodal_force(1948, 0, 0, -9810, "DeckLoadPS2") 198 | # create_nodal_force(1908, 0, 0, -9810, "DeckLoadPS3") 199 | 200 | # create_nodal_force(1870, 0, 0, -9810, "DeckLoadSB1") 201 | # create_nodal_force(1938, 0, 0, -9810, "DeckLoadSB2") 202 | # create_nodal_force(1907, 0, 0, -9810, "DeckLoadSB3") 203 | 204 | # create_nodal_force(1882, 0, 0, -9810, "DeckLoadCenter1") 205 | # create_nodal_force(1927, 0, 0, -9810, "DeckLoadCenter2") 206 | # create_nodal_force(1918, 0, 0, -9810, "DeckLoadCenter3") 207 | 208 | # create_nodal_force(3810, 0, 0, 9810, "BottomLoadPS1") 209 | # create_nodal_force(3692, 0, 0, 9810, "BottomLoadPS2") 210 | # create_nodal_force(3739, 0, 0, 9810, "BottomLoadPS3") 211 | 212 | # create_nodal_force(3649, 0, 0, 9810, "BottomLoadSB1") 213 | # create_nodal_force(3684, 0, 0, 9810, "BottomLoadSB2") 214 | # create_nodal_force(3710, 0, 0, 9810, "BottomLoadSB3") 215 | 216 | # create_nodal_force(3773, 0, 0, 9810, "BottomLoadCenter1") 217 | # create_nodal_force(3668, 0, 0, 9810, "BottomLoadCenter2") 218 | # create_nodal_force(3705, 0, 0, 9810, "BottomLoadCenter3") 219 | 220 | # create_nodal_constraint(1969, 0, 0, 0, -777777, -777777, -777777, "XYZ_Fixed") 221 | # create_nodal_constraint(2010, -777777, 0, 0, -777777, -777777, -777777, "YZ_Fixed") 222 | # create_nodal_constraint(2012, -777777, -777777, 0, -777777, -777777, -777777, "Z_Fixed") 223 | 224 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadPS1") 225 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadPS2") 226 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadPS3") 227 | 228 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadSB1") 229 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadSB2") 230 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadSB3") 231 | 232 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadCenter1") 233 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadCenter2") 234 | create_nodal_force(20232, 0, 0, -9810, "DeckLoadCenter3") 235 | 236 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadPS1") 237 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadPS2") 238 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadPS3") 239 | 240 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadSB1") 241 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadSB2") 242 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadSB3") 243 | 244 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadCenter1") 245 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadCenter2") 246 | create_nodal_force(20232, 0, 0, 9810, "BottomLoadCenter3") 247 | 248 | create_nodal_constraint(30203, 0, 0, 0, -777777, -777777, -777777, "XYZ_Fixed") 249 | create_nodal_constraint(32963, -777777, 0, 0, -777777, -777777, -777777, "YZ_Fixed") 250 | create_nodal_constraint(32964, -777777, -777777, 0, -777777, -777777, -777777, "Z_Fixed") 251 | 252 | if __name__ == '__main__': 253 | main() 254 | -------------------------------------------------------------------------------- /pre_processing/solve_solution.py: -------------------------------------------------------------------------------- 1 | # intellisense by theScriptingEngineer (www.theScriptingEngineer.com) 2 | # NXOpen Python Reference Guide: 3 | # https://docs.plm.automation.siemens.com/data_services/resources/nx/1899/nx_api/custom/en_US/nxopen_python_ref/index.html 4 | 5 | # untested 6 | 7 | import sys 8 | import os 9 | import subprocess 10 | import NXOpen 11 | import NXOpen.UF 12 | import NXOpen.CAE 13 | from typing import List, cast, Optional, Union 14 | 15 | the_session: NXOpen.Session = NXOpen.Session.GetSession() 16 | the_uf_session: NXOpen.UF.UFSession = NXOpen.UF.UFSession.GetUFSession() 17 | the_lw: NXOpen.ListingWindow = the_session.ListingWindow 18 | 19 | 20 | def solve_solution(solution_name: str, sim_part: NXOpen.CAE.SimPart = None): 21 | """This function solves a solution with the given name, in the active sim file 22 | 23 | Parameters 24 | ---------- 25 | solution_name: str 26 | Name of the solution to solve 27 | """ 28 | the_lw.WriteFullline("Solving " + solution_name) 29 | if sim_part == None: 30 | # get the active part 31 | sim_part = cast(NXOpen.CAE.SimPart, the_session.Parts.BaseWork) 32 | 33 | # get the requested solution 34 | sim_solutions: List[NXOpen.CAE.SimSolution] = sim_part.Simulation.Solutions 35 | sim_solution: List[NXOpen.CAE.SimSolution] = [item for item in sim_solutions if item.Name.lower() == solution_name.lower()] 36 | if sim_solution == None: 37 | the_lw.WriteFullline("Solution with name " + solution_name + " could not be found in " + sim_part.FullPath) 38 | return 39 | else: 40 | sim_solution = sim_solution[0] 41 | 42 | # solve the solution 43 | chain: List[NXOpen.CAE.SimSolution] = [sim_solution] 44 | sim_solve_manager: NXOpen.CAE.SimSolveManager = NXOpen.CAE.SimSolveManager.GetSimSolveManager(the_session) 45 | # Not sure if the following returns a tuple in Python. In C#, additional parameters are returned through pass by reference using the out keyword 46 | sim_solve_manager.SolveChainOfSolutions(chain, NXOpen.CAE.SimSolution.SolveOption.Solve, NXOpen.CAE.SimSolution.SetupCheckOption.DoNotCheck, NXOpen.CAE.SimSolution.SolveMode.Foreground) 47 | 48 | # user feedback 49 | the_lw.WriteFullline("Solved solution " + solution_name) 50 | 51 | 52 | def solve_all_solutions(): 53 | """This function solves all solutions in the active sim file 54 | """ 55 | # Note: don't loop over the solutions and solve. This will give a memory access violation error, but will still solve. 56 | the_lw.WriteFullline("Solving all solutions:") 57 | sim_solve_manager: NXOpen.CAE.SimSolveManager = NXOpen.CAE.SimSolveManager.GetSimSolveManager(the_session) 58 | sim_solve_manager.SolveAllSolutions(NXOpen.CAE.SimSolution.SolveOption.Solve, NXOpen.CAE.SimSolution.SetupCheckOption.DoNotCheck, NXOpen.CAE.SimSolution.SolveMode.Foreground, False) 59 | 60 | 61 | def solve_dat_file(dat_file: str): 62 | """This function solves a .dat file by directly calling the nastran.exe executable. 63 | It takes the location of the nastran.exe executable form the environmental variable UGII_NX_NASTRAN. 64 | By directly calling the nastran executable, a standalone license for the executable is required! 65 | Running this with a desktop license wil result in an error: 66 | "Could not check out license for module: Simcenter Nastran Basic" 67 | 68 | Parameters 69 | ---------- 70 | dat_file: str 71 | The full path of the .dat file to be solved. 72 | If no extension is provided, .dat is assumed. 73 | If no directory is provided, assumed same as the sim file 74 | """ 75 | # get the location nastran.exe via the environmental variable 76 | UGII_NX_NASTRAN: str = the_session.GetEnvironmentVariableValue("UGII_NX_NASTRAN") 77 | the_lw.WriteFullline(UGII_NX_NASTRAN) 78 | 79 | # process dat file for path and execution 80 | full_dat_file: str = create_full_path(dat_file, ".dat") 81 | 82 | # change working directory to the location of the .dat file. 83 | # So that this is where the solve happens. 84 | cwd = os.getcwd() 85 | os.chdir(os.path.dirname(full_dat_file)) 86 | 87 | # solve the .dat file. 88 | result = subprocess.run([UGII_NX_NASTRAN, full_dat_file]) 89 | print(result) 90 | 91 | # return to original cwd 92 | os.chdir(cwd) 93 | 94 | 95 | def create_full_path(file_name: str, extension: str = ".unv") -> str: 96 | """This function takes a filename and adds the .unv extension and path of the part if not provided by the user. 97 | If the fileName contains an extension, this function leaves it untouched, othwerwise adds .unv as extension. 98 | If the fileName contains a path, this function leaves it untouched, otherwise adds the path of the BasePart as the path. 99 | Undefined behaviour if basePart has not yet been saved (eg FullPath not available) 100 | 101 | Parameters 102 | ---------- 103 | file_name: str 104 | The filename with or without path and .unv extension. 105 | 106 | Returns 107 | ------- 108 | str 109 | A string with .unv extension and path of the basePart if the fileName parameter did not include a path. 110 | """ 111 | # check if an extension is included 112 | if os.path.splitext(file_name)[1] == "": 113 | file_name = file_name + extension 114 | 115 | # check if path is included in fileName, if not add path of the .sim file 116 | unv_file_path: str = os.path.dirname(file_name) 117 | if unv_file_path == "": 118 | # if the .sim file has never been saved, the next will give an error 119 | file_name = os.path.join(os.path.dirname(base_part.FullPath), file_name) 120 | 121 | return file_name 122 | 123 | 124 | def main(): 125 | the_lw.Open() 126 | the_lw.WriteFullline("Starting Main() in " + the_session.ExecutingJournal) 127 | 128 | if the_session.IsBatch: 129 | the_lw.WriteFullline("This journal gives a memory access violation error when running in batch mode.") 130 | the_lw.WriteFullline("It is not clear why this happens, so the journal will exit.") 131 | the_lw.WriteFullline("Please run this journal in interactive mode, or use the C# version.") 132 | return 133 | 134 | if len(sys.argv) == 1: 135 | # no arguments passed 136 | # write some sort of a help 137 | the_lw.WriteFullline("Need to pass the full path of the .sim file as a first argument.") 138 | the_lw.WriteFullline("All additional parameters should be solutions to solve.") 139 | the_lw.WriteFullline("If no additional parameters are passed, all solutions in the sim file are solved.") 140 | return 141 | 142 | # designed to run in batch, so need to open the file. 143 | if the_session.IsBatch: 144 | # open file using the first argument 145 | file_name: str = sys.argv[1] # index 0 is the name of the python file itself 146 | the_lw.WriteFullline("Opening file " + file_name) 147 | try: 148 | 149 | base_part, load_status = the_session.Parts.Open(file_name) # in python, open returns a tuple with the part and the status 150 | except Exception as e: 151 | the_lw.WriteFullline("The file " + file_name + " could not be opened!") 152 | the_lw.WriteFullline(str(e)) 153 | return 154 | else: 155 | base_part = the_session.Parts.BaseWork 156 | 157 | # check if running from a sim part 158 | if not isinstance(base_part, NXOpen.CAE.SimPart): 159 | the_lw.WriteFullline("SolveSolution needs to start from a .sim file") 160 | return 161 | 162 | sim_part: NXOpen.CAE.SimPart = cast(NXOpen.CAE.SimPart, base_part) 163 | 164 | if the_session.IsBatch: 165 | if len(sys.argv) == 2: 166 | # only one argument (file to open) so solve all solutions 167 | solve_all_solutions() 168 | else: 169 | for i in range(2, len(sys.argv)): 170 | # 2 or more arguments. Solve the solution for each argument. (skip arg[1] becasue that's the sim file) 171 | solve_solution(sys.argv[i], sim_part) 172 | else: 173 | if len(sys.argv) == 2: 174 | # only one argument (file to open) so solve all solutions 175 | solve_all_solutions() 176 | else: 177 | for i in range(2, len(sys.argv)): 178 | # 2 or more arguments. Solve the solution for each argument. (skip arg[1] becasue that's the sim file) 179 | solve_solution(sys.argv[i], sim_part) 180 | 181 | 182 | if __name__ == '__main__': 183 | main() 184 | --------------------------------------------------------------------------------