diff --git a/examples/00_tips/readme.txt b/examples/00_tips/readme.txt deleted file mode 100644 index 2439d4a8..00000000 --- a/examples/00_tips/readme.txt +++ /dev/null @@ -1,5 +0,0 @@ -Tips -==== - -This section showcases some of the useful functions that can be used -in PyMechanical embedding workflow. diff --git a/examples/00_tips/tips_01.py b/examples/00_tips/tips_01.py deleted file mode 100644 index a839fcb3..00000000 --- a/examples/00_tips/tips_01.py +++ /dev/null @@ -1,53 +0,0 @@ -""".. _ref_tips_01: - -3D visualization ----------------- - -Visualize 3D imported geometry -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - - -# %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download geometry - -geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") - -# %% -# Import geometry - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import.Import(geometry_path) - -# %% -# Visualize in 3D -# ~~~~~~~~~~~~~~~ - -app.plot() - -# %% -# .. note:: -# This visualization is currently available only for geometry and on version 24R2 or later - -# %% -# Cleanup -# ~~~~~~~ - -delete_downloads() -app.new() diff --git a/examples/00_tips/tips_02.py b/examples/00_tips/tips_02.py deleted file mode 100644 index 8bc4ec54..00000000 --- a/examples/00_tips/tips_02.py +++ /dev/null @@ -1,100 +0,0 @@ -""".. _ref_tips_02: - -Export image ------------- - -Export image and display -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file - -# %% -# Embed Mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - - -# %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download geometry - -geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") - -# %% -# Import geometry - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import.Import(geometry_path) - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -# Orientation -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) - -# Export format -image_export_format = GraphicsImageExportFormat.PNG - -# Resolution and background -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - -# Rotate the geometry if needed -ExtAPI.Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) - - -# %% -# Custom function for displaying the image -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -from matplotlib import image as mpimg -from matplotlib import pyplot as plt - -# Temporary directory to save the image -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Export and display the image -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -# Fits the geometry in the viewing area -Graphics.Camera.SetFit() - -Graphics.ExportImage( - os.path.join(cwd, "geometry.png"), image_export_format, settings_720p -) - -# Display the image using matplotlib -display_image("geometry.png") - -# %% -# Cleanup -# ~~~~~~~ - -delete_downloads() -app.new() diff --git a/examples/00_tips/tips_03.py b/examples/00_tips/tips_03.py deleted file mode 100644 index e6f16eb4..00000000 --- a/examples/00_tips/tips_03.py +++ /dev/null @@ -1,54 +0,0 @@ -""".. _ref_tips_03: - -Project tree --------------------- - -Display the heirarchial Mechanical project structure. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file - -# %% -# Embed Mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - - -# %% -# Download the mechdb file -# ~~~~~~~~~~~~~~~~~~~~~~~~ - -mechdb_path = download_file("graphics_test.mechdb", "pymechanical", "test_files") - -# %% -# Load the mechdb file inside Mechanical - -app.open(mechdb_path) - -# %% -# Display the project tree -# ~~~~~~~~~~~~~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Display the tree only under the first analysis -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -app.print_tree(Model.Analyses[0]) - - -# %% -# Cleanup -# ~~~~~~~ - -delete_downloads() -app.new() diff --git a/examples/01_basic/bolt_pretension.py b/examples/01_basic/bolt_pretension.py deleted file mode 100644 index 44450a3a..00000000 --- a/examples/01_basic/bolt_pretension.py +++ /dev/null @@ -1,515 +0,0 @@ -""".. _ref_bolt_pretension: - -Bolt Pretension ---------------- - -This example demonstrates how to insert a Static Structural analysis -into a new Mechanical session and execute a sequence of Python scripting -commands that define and solve a bolt-pretension analysis. -Scripts then evaluate the following results: deformation, -equivalent stresses, contact, and bolt -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -Graphics.Camera.SetFit() -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False -Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) - -# %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download the geometry file - -geometry_path = download_file( - "example_06_bolt_pret_geom.agdb", "pymechanical", "00_basic" -) - -# %% -# Import geometry - -geometry_import_group = Model.GeometryImportGroup -geometry_import = geometry_import_group.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -# sphinx_gallery_start_ignore -assert str(geometry_import.ObjectState) == "Solved", "Geometry Import unsuccessful" -# sphinx_gallery_end_ignore - -app.plot() - - -# %% -# Download and import material -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download materials - -mat_Copper_file_path = download_file( - "example_06_Mat_Copper.xml", "pymechanical", "00_basic" -) -mat_Steel_file_path = download_file( - "example_06_Mat_Steel.xml", "pymechanical", "00_basic" -) - -# %% -# Import materials - -MAT = Model.Materials -MAT.Import(mat_Copper_file_path) -MAT.Import(mat_Steel_file_path) - -# sphinx_gallery_start_ignore -assert str(MAT.ObjectState) == "FullyDefined", "Materials are not defined" -# sphinx_gallery_end_ignore - -# %% -# Define Analysis and unit system -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Add Structural analysis - -Model.AddStaticStructuralAnalysis() -STAT_STRUC = Model.Analyses[0] -STAT_STRUC_SOLN = STAT_STRUC.Solution -STAT_STRUC_ANA_SETTING = STAT_STRUC.Children[0] - -# %% -# Set up the unit system. - -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardNMM - -# %% -# Store all main tree nodes as variables - -MODEL = Model -GEOM = Model.Geometry -CONN_GRP = Model.Connections -CS_GRP = Model.CoordinateSystems -MSH = Model.Mesh -NS_GRP = Model.NamedSelections - -# %% -# Store named selections - -block3_block2_cont_NS = [x for x in Tree.AllObjects if x.Name == "block3_block2_cont"][ - 0 -] -block3_block2_targ_NS = [x for x in Tree.AllObjects if x.Name == "block3_block2_targ"][ - 0 -] -shank_block3_targ_NS = [x for x in Tree.AllObjects if x.Name == "shank_block3_targ"][0] -shank_block3_cont_NS = [x for x in Tree.AllObjects if x.Name == "shank_block3_cont"][0] -block1_washer_cont_NS = [x for x in Tree.AllObjects if x.Name == "block1_washer_cont"][ - 0 -] -block1_washer_targ_NS = [x for x in Tree.AllObjects if x.Name == "block1_washer_targ"][ - 0 -] -washer_bolt_cont_NS = [x for x in Tree.AllObjects if x.Name == "washer_bolt_cont"][0] -washer_bolt_targ_NS = [x for x in Tree.AllObjects if x.Name == "washer_bolt_targ"][0] -shank_bolt_targ_NS = [x for x in Tree.AllObjects if x.Name == "shank_bolt_targ"][0] -shank_bolt_cont_NS = [x for x in Tree.AllObjects if x.Name == "shank_bolt_cont"][0] -block2_block1_cont_NS = [x for x in Tree.AllObjects if x.Name == "block2_block1_cont"][ - 0 -] -block2_block1_targ_NS = [x for x in Tree.AllObjects if x.Name == "block2_block1_targ"][ - 0 -] -all_bodies = [x for x in Tree.AllObjects if x.Name == "all_bodies"][0] -bodies_5 = [x for x in Tree.AllObjects if x.Name == "bodies_5"][0] -shank = [x for x in Tree.AllObjects if x.Name == "shank"][0] -shank_face = [x for x in Tree.AllObjects if x.Name == "shank_face"][0] -shank_face2 = [x for x in Tree.AllObjects if x.Name == "shank_face2"][0] -bottom_surface = [x for x in Tree.AllObjects if x.Name == "bottom_surface"][0] -block2_surface = [x for x in Tree.AllObjects if x.Name == "block2_surface"][0] -shank_surface = [x for x in Tree.AllObjects if x.Name == "shank_surface"][0] - -# %% -# Assign material to bodies - -SURFACE1 = GEOM.Children[0].Children[0] -SURFACE1.Material = "Steel" - -SURFACE2 = GEOM.Children[1].Children[0] -SURFACE2.Material = "Copper" - -SURFACE3 = GEOM.Children[2].Children[0] -SURFACE3.Material = "Copper" - -SURFACE4 = GEOM.Children[3].Children[0] -SURFACE4.Material = "Steel" - -SURFACE5 = GEOM.Children[4].Children[0] -SURFACE5.Material = "Steel" - -SURFACE6 = GEOM.Children[5].Children[0] -SURFACE6.Material = "Steel" - -# %% -# Define coordinate system -# ~~~~~~~~~~~~~~~~~~~~~~~~~ - -coordinate_system = CS_GRP.AddCoordinateSystem() -coordinate_system.OriginDefineBy = CoordinateSystemAlignmentType.Fixed -coordinate_system.OriginX = Quantity(-195, "mm") -coordinate_system.OriginY = Quantity(100, "mm") -coordinate_system.OriginZ = Quantity(50, "mm") -coordinate_system.PrimaryAxis = CoordinateSystemAxisType.PositiveZAxis - -# %% -# Define Contacts -# ~~~~~~~~~~~~~~~ -# Change contact settings - -# %% -# Delete existing contacts - -for connection in CONN_GRP.Children: - if connection.DataModelObjectCategory == DataModelObjectCategory.ConnectionGroup: - connection.Delete() - -CONT_REG1 = CONN_GRP.AddContactRegion() -CONT_REG1.SourceLocation = NS_GRP.Children[0] -CONT_REG1.TargetLocation = NS_GRP.Children[1] -CONT_REG1.ContactType = ContactType.Frictional -CONT_REG1.FrictionCoefficient = 0.2 -CONT_REG1.SmallSliding = ContactSmallSlidingType.Off -CONT_REG1.UpdateStiffness = UpdateContactStiffness.Never -CMD1 = CONT_REG1.AddCommandSnippet() - -# %% -# Add missing contact keyopt and Archard Wear Model using a command snippet - -AWM = """keyopt,cid,9,5 -rmodif,cid,10,0.00 -rmodif,cid,23,0.001""" -CMD1.AppendText(AWM) - -CONTS = CONN_GRP.Children[0] -CONT_REG2 = CONTS.AddContactRegion() -CONT_REG2.SourceLocation = NS_GRP.Children[3] -CONT_REG2.TargetLocation = NS_GRP.Children[2] -CONT_REG2.ContactType = ContactType.Bonded -CONT_REG2.ContactFormulation = ContactFormulation.MPC - -CONT_REG3 = CONTS.AddContactRegion() -CONT_REG3.SourceLocation = NS_GRP.Children[4] -CONT_REG3.TargetLocation = NS_GRP.Children[5] -CONT_REG3.ContactType = ContactType.Frictional -CONT_REG3.FrictionCoefficient = 0.2 -CONT_REG3.SmallSliding = ContactSmallSlidingType.Off -CONT_REG3.UpdateStiffness = UpdateContactStiffness.Never -CMD3 = CONT_REG3.AddCommandSnippet() - -# Add missing contact keyopt and Archard Wear Model using a command snippet - -AWM3 = """keyopt,cid,9,5 -rmodif,cid,10,0.00 -rmodif,cid,23,0.001""" -CMD3.AppendText(AWM3) - -CONT_REG4 = CONTS.AddContactRegion() -CONT_REG4.SourceLocation = NS_GRP.Children[6] -CONT_REG4.TargetLocation = NS_GRP.Children[7] -CONT_REG4.ContactType = ContactType.Bonded -CONT_REG4.ContactFormulation = ContactFormulation.MPC - -CONT_REG5 = CONTS.AddContactRegion() -CONT_REG5.SourceLocation = NS_GRP.Children[9] -CONT_REG5.TargetLocation = NS_GRP.Children[8] -CONT_REG5.ContactType = ContactType.Bonded -CONT_REG5.ContactFormulation = ContactFormulation.MPC - -CONT_REG6 = CONTS.AddContactRegion() -CONT_REG6.SourceLocation = NS_GRP.Children[10] -CONT_REG6.TargetLocation = NS_GRP.Children[11] -CONT_REG6.ContactType = ContactType.Frictional -CONT_REG6.FrictionCoefficient = 0.2 -CONT_REG6.SmallSliding = ContactSmallSlidingType.Off -CONT_REG6.UpdateStiffness = UpdateContactStiffness.Never -CMD6 = CONT_REG6.AddCommandSnippet() - -# Add missing contact keyopt and Archard Wear Model using a command snippet - -AWM6 = """keyopt,cid,9,5 -rmodif,cid,10,0.00 -rmodif,cid,23,0.001""" -CMD6.AppendText(AWM6) - -# %% -# Mesh -# ~~~~ - -Hex_Method = MSH.AddAutomaticMethod() -Hex_Method.Location = all_bodies -Hex_Method.Method = MethodType.Automatic - -BODY_SIZING1 = MSH.AddSizing() -BODY_SIZING1.Location = bodies_5 -BODY_SIZING1.ElementSize = Quantity(15, "mm") - -BODY_SIZING2 = MSH.AddSizing() -BODY_SIZING2.Location = shank -BODY_SIZING2.ElementSize = Quantity(7, "mm") - -Face_Meshing = MSH.AddFaceMeshing() -Face_Meshing.Location = shank_face -Face_Meshing.MappedMesh = False - -Sweep_Method = MSH.AddAutomaticMethod() -Sweep_Method.Location = shank -Sweep_Method.Method = MethodType.Sweep -Sweep_Method.SourceTargetSelection = 2 -Sweep_Method.SourceLocation = shank_face -Sweep_Method.TargetLocation = shank_face2 - -MSH.Activate() -MSH.GenerateMesh() - -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Analysis settings -# ~~~~~~~~~~~~~~~~~ - -STAT_STRUC_ANA_SETTING.NumberOfSteps = 4 -step_index_list = [1] - -with Transaction(): - for step_index in step_index_list: - STAT_STRUC_ANA_SETTING.SetAutomaticTimeStepping( - step_index, AutomaticTimeStepping.Off - ) - -STAT_STRUC_ANA_SETTING.Activate() -step_index_list = [1] - -with Transaction(): - for step_index in step_index_list: - STAT_STRUC_ANA_SETTING.SetNumberOfSubSteps(step_index, 2) - -STAT_STRUC_ANA_SETTING.Activate() -STAT_STRUC_ANA_SETTING.SolverType = SolverType.Direct -STAT_STRUC_ANA_SETTING.SolverPivotChecking = SolverPivotChecking.Off - -# %% -# Define loads and boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -FIX_SUP = STAT_STRUC.AddFixedSupport() -FIX_SUP.Location = block2_surface - -Tabular_Force = STAT_STRUC.AddForce() -Tabular_Force.Location = bottom_surface -Tabular_Force.DefineBy = LoadDefineBy.Components -Tabular_Force.XComponent.Inputs[0].DiscreteValues = [ - Quantity("0[s]"), - Quantity("1[s]"), - Quantity("2[s]"), - Quantity("3[s]"), - Quantity("4[s]"), -] -Tabular_Force.XComponent.Output.DiscreteValues = [ - Quantity("0[N]"), - Quantity("0[N]"), - Quantity("5.e+005[N]"), - Quantity("0[N]"), - Quantity("-5.e+005[N]"), -] - -Bolt_Pretension = STAT_STRUC.AddBoltPretension() -Bolt_Pretension.Location = shank_surface -Bolt_Pretension.Preload.Inputs[0].DiscreteValues = [ - Quantity("1[s]"), - Quantity("2[s]"), - Quantity("3[s]"), - Quantity("4[s]"), -] -Bolt_Pretension.Preload.Output.DiscreteValues = [ - Quantity("6.1363e+005[N]"), - Quantity("0 [N]"), - Quantity("0 [N]"), - Quantity("0[N]"), -] -Bolt_Pretension.SetDefineBy(2, BoltLoadDefineBy.Lock) -Bolt_Pretension.SetDefineBy(3, BoltLoadDefineBy.Lock) -Bolt_Pretension.SetDefineBy(4, BoltLoadDefineBy.Lock) - -Tree.Activate([Bolt_Pretension]) -Graphics.ExportImage( - os.path.join(cwd, "loads_and_boundaryconditions.png"), - image_export_format, - settings_720p, -) -display_image("loads_and_boundaryconditions.png") - -# %% -# Insert results -# ~~~~~~~~~~~~~~ - -Post_Contact_Tool = STAT_STRUC_SOLN.AddContactTool() -Post_Contact_Tool.ScopingMethod = GeometryDefineByType.Worksheet -Bolt_Tool = STAT_STRUC_SOLN.AddBoltTool() -Bolt_Working_Load = Bolt_Tool.AddWorkingLoad() -Total_Deformation = STAT_STRUC_SOLN.AddTotalDeformation() -Equivalent_stress_1 = STAT_STRUC_SOLN.AddEquivalentStress() -Equivalent_stress_2 = STAT_STRUC_SOLN.AddEquivalentStress() -Equivalent_stress_2.Location = shank -Force_Reaction_1 = STAT_STRUC_SOLN.AddForceReaction() -Force_Reaction_1.BoundaryConditionSelection = FIX_SUP -Moment_Reaction_2 = STAT_STRUC_SOLN.AddMomentReaction() -Moment_Reaction_2.BoundaryConditionSelection = FIX_SUP - -# %% -# Solve -# ~~~~~ - -STAT_STRUC_SOLN.Solve(True) -STAT_STRUC_SS = STAT_STRUC_SOLN.Status -# sphinx_gallery_start_ignore -assert str(STAT_STRUC_SS) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - -# %% -# Results -# ~~~~~~~ -# Total deformation - -Tree.Activate([Total_Deformation]) -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "total_deformation.png"), image_export_format, settings_720p -) -display_image("total_deformation.png") - -# %% -# Equivalent stress on all bodies - -Tree.Activate([Equivalent_stress_1]) -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "equivalent_stress_total.png"), image_export_format, settings_720p -) -display_image("equivalent_stress_total.png") - -# %% -# Equivalent stress on shank - -Tree.Activate([Equivalent_stress_2]) -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "equivalent_stress_shank.png"), image_export_format, settings_720p -) -display_image("equivalent_stress_shank.png") - -# %% -# Export contact status animation - -Post_Contact_Tool_status = Post_Contact_Tool.Children[0] -Tree.Activate([Post_Contact_Tool_status]) -Graphics.Camera.SetFit() -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -Post_Contact_Tool_status.ExportAnimation( - os.path.join(cwd, "contact_status.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "contact_status.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=200, repeat=True, blit=True -) -plt.show() - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "bolt_pretension.mechdat")) -app.new() - -# %% -# Delete the example file - -delete_downloads() diff --git a/examples/01_basic/fracture_analysis_contact_debonding.py b/examples/01_basic/fracture_analysis_contact_debonding.py deleted file mode 100644 index 17b4bf08..00000000 --- a/examples/01_basic/fracture_analysis_contact_debonding.py +++ /dev/null @@ -1,435 +0,0 @@ -""".. _ref_contact: - -Fracture Analysis - Contact debonding -------------------------------------- - -The following example demonstrates the use of the Contact Debonding -featuring in Mechanical using the Cohesive Zone Material (CZM) method. -This example displaces two two-dimensional parts on a -double cantilever beam. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Front) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - -# %% -# Download geometry and materials files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -geometry_path = download_file( - "Contact_Debonding_Example.agdb", "pymechanical", "embedding" -) -mat1_path = download_file( - "Contact_Debonding_Example_Mat1.xml", "pymechanical", "embedding" -) -mat2_path = download_file( - "Contact_Debonding_Example_Mat2.xml", "pymechanical", "embedding" -) - - -# %% -# Import the geometry -# ~~~~~~~~~~~~~~~~~~~ - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import_preferences.AnalysisType = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.AnalysisType.Type2D -) -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -app.plot() - -# %% -# Material import, named selections, and connections -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Import materials - -MODEL = Model -GEOMETRY = Model.Geometry -MAT_GRP = MODEL.Materials -MAT_GRP.Import(mat1_path) -MAT_GRP.Import(mat2_path) - -PART = [x for x in Tree.AllObjects if x.Name == "Part 2"][0] -MAT_BODY = [ - i - for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) - if i.Name == "Interface Body Material" -][0] -MAT_CZM = [ - i - for i in MAT_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.Material](True) - if i.Name == "CZM Crack Material" -][0] - -# %% -# Connections - -connections = MODEL.AddConnections() -CONNECTIONS_GRP = connections.AddConnectionGroup() -MODEL.Connections.CreateAutomaticConnections() -CONNECTIONS_GRP = Model.Connections -CONTACTS = [ - i - for i in CONNECTIONS_GRP.GetChildren[ - Ansys.ACT.Automation.Mechanical.Connections.ConnectionGroup - ](True) - if i.Name == "Contacts" -][0] -CONTACT_REGION = [ - i - for i in CONTACTS.GetChildren[ - Ansys.ACT.Automation.Mechanical.Connections.ContactRegion - ](True) - if i.Name == "Contact Region" -][0] - -# %% -# Named selections - -NAMED_SELECTIONS = Model.NamedSelections -NS_EDGE_HIGH = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "High_Edge" -][0] -NS_EDGE_LOW = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Low_Edge" -][0] -NS_EDGES_SHORT = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Short_Edges" -][0] -NS_EDGES_LONG = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Long_Edges" -][0] -NS_EDGES_FIXED = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Fixed_Edges" -][0] -NS_VERTEX_DISP1 = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Disp1_Vertex" -][0] -NS_VERTEX_DISP2 = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Disp2_Vertex" -][0] -NS_FACES_BOTH = [ - i - for i in NAMED_SELECTIONS.GetChildren[ - Ansys.ACT.Automation.Mechanical.NamedSelection - ](True) - if i.Name == "Both_Faces" -][0] - -# %% -# Define static structural analysis and settings -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MODEL.AddStaticStructuralAnalysis() -STATIC_STRUCTURAL = DataModel.AnalysisByName("Static Structural") -ANALYSIS_SETTINGS = STATIC_STRUCTURAL.AnalysisSettings -SOLUTION = STATIC_STRUCTURAL.Solution -MESH = Model.Mesh - -# Set unit system - -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardNMM - -# Set 2D behavior - -GEOMETRY.Activate() -GEOMETRY.Model2DBehavior = Model2DBehavior.PlaneStrain - -# Assign material - -PART.Activate() -PART.Material = MAT_BODY.Name - -# Define contact Region - -CONTACT_REGION.Activate() -CONTACT_REGION.SourceLocation = NS_EDGE_HIGH -CONTACT_REGION.TargetLocation = NS_EDGE_LOW -CONTACT_REGION.ContactType = ContactType.Bonded -CONTACT_REGION.ContactFormulation = ContactFormulation.PurePenalty - -# %% -# Define mesh controls and generate mesh -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MESH.Activate() -MESH.ElementOrder = ElementOrder.Quadratic -MESH.UseAdaptiveSizing = False -MESH.ElementSize = Quantity("0.75 [mm]") - -SIZING_MESH = MESH.AddSizing() -SIZING_MESH.Location = NS_EDGES_SHORT -SIZING_MESH.ElementSize = Quantity("0.75 [mm]") -SIZING_MESH.Behavior = SizingBehavior.Hard - -SIZING_MESH2 = MESH.AddSizing() -SIZING_MESH2.Location = NS_EDGES_LONG -SIZING_MESH2.ElementSize = Quantity("0.5 [mm]") -SIZING_MESH2.Behavior = SizingBehavior.Hard - -FACE_MESHING = MESH.AddFaceMeshing() -FACE_MESHING.Location = NS_FACES_BOTH -FACE_MESHING.Method = FaceMeshingMethod.Quadrilaterals - -MESH.Activate() -MESH.GenerateMesh() - -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Add contact debonding object -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MODEL.Activate() -FRACTURE = MODEL.AddFracture() - -CONTACT_DEBONDING = FRACTURE.AddContactDebonding() -CONTACT_DEBONDING.Material = MAT_CZM.Name -CONTACT_DEBONDING.ContactRegion = CONTACT_REGION - -# %% -# Define analysis settings -# ~~~~~~~~~~~~~~~~~~~~~~~~ - -ANALYSIS_SETTINGS.Activate() -ANALYSIS_SETTINGS.AutomaticTimeStepping = AutomaticTimeStepping.On -ANALYSIS_SETTINGS.DefineBy = TimeStepDefineByType.Substeps -ANALYSIS_SETTINGS.MaximumSubsteps = 100 -ANALYSIS_SETTINGS.InitialSubsteps = 100 -ANALYSIS_SETTINGS.MinimumSubsteps = 100 -ANALYSIS_SETTINGS.LargeDeflection = True - -# %% -# Define boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Add fixed support - -STATIC_STRUCTURAL.Activate() -FIXED_SUPPORT = STATIC_STRUCTURAL.AddFixedSupport() -FIXED_SUPPORT.Location = NS_EDGES_FIXED - -# %% -# Add displacement - -STATIC_STRUCTURAL.Activate() -DISPLACEMENT = STATIC_STRUCTURAL.AddDisplacement() -DISPLACEMENT.Location = NS_VERTEX_DISP1 -DISPLACEMENT.DefineBy = LoadDefineBy.Components -DISPLACEMENT.YComponent.Output.DiscreteValues = [Quantity("10 [mm]")] - -STATIC_STRUCTURAL.Activate() -DISPLACEMENT2 = STATIC_STRUCTURAL.AddDisplacement() -DISPLACEMENT2.Location = NS_VERTEX_DISP2 -DISPLACEMENT2.DefineBy = LoadDefineBy.Components -DISPLACEMENT2.YComponent.Output.DiscreteValues = [Quantity("-10 [mm]")] - -STATIC_STRUCTURAL.Activate() - -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "boundary_conditions.png"), image_export_format, settings_720p -) -display_image("boundary_conditions.png") - -# %% -# Add results -# ~~~~~~~~~~~ - -SOLUTION.Activate() -DIRECTIONAL_DEFORMATION = SOLUTION.AddDirectionalDeformation() -DIRECTIONAL_DEFORMATION.NormalOrientation = NormalOrientationType.YAxis - -FORCE_REACTION = SOLUTION.AddForceReaction() -FORCE_REACTION.BoundaryConditionSelection = DISPLACEMENT - -# %% -# Solve -# ~~~~~ - -STATIC_STRUCTURAL.Activate() -SOLUTION.Solve(True) - -# sphinx_gallery_start_ignore -assert str(SOLUTION.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - -# %% -# Display results -# ~~~~~~~~~~~~~~~ -# Directional deformation - -DIRECTIONAL_DEFORMATION.Activate() - -Graphics.ExportImage( - os.path.join(cwd, "directional_deformation.png"), image_export_format, settings_720p -) -display_image("directional_deformation.png") - -# %% -# Force reaction - -FORCE_REACTION.Activate() - -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "force_reaction.png"), image_export_format, settings_720p -) -display_image("force_reaction.png") - -# %% -# Export animation -# ~~~~~~~~~~~~~~~~ - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -FORCE_REACTION.ExportAnimation( - os.path.join(cwd, "force_reaction.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "force_reaction.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=100, repeat=True, blit=True -) -plt.show() - -# %% -# Display output file from solve -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -def write_file_contents_to_console(path): - """Write file contents to console.""" - with open(path, "rt") as file: - for line in file: - print(line, end="") - - -solve_path = STATIC_STRUCTURAL.WorkingDir -solve_out_path = os.path.join(solve_path, "solve.out") -if solve_out_path: - write_file_contents_to_console(solve_out_path) - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "contact_debonding.mechdat")) -app.new() - -# %% -# Delete example files - -delete_downloads() diff --git a/examples/01_basic/harmonic_acoustics.py b/examples/01_basic/harmonic_acoustics.py deleted file mode 100644 index cf343d3a..00000000 --- a/examples/01_basic/harmonic_acoustics.py +++ /dev/null @@ -1,506 +0,0 @@ -""".. _ref_harmonic_acoustics: - -Harmonic acoustic analysis --------------------------- - -This example examines a harmonic acoustic analysis that uses -surface velocity to determine the steady-state response of a -structure and the surrounding fluid medium to loads and excitations -that vary sinusoidally with time. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False -Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) - -# %% -# Download geometry and materials files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -geometry_path = download_file("C_GEOMETRY.agdb", "pymechanical", "embedding") -mat_path = download_file("Air-material.xml", "pymechanical", "embedding") - -# %% -# Import the geometry -# ~~~~~~~~~~~~~~~~~~~ - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - - -GEOM = Model.Geometry - -solid1 = GEOM.Children[0] -solid2 = GEOM.Children[1] -solid3 = GEOM.Children[2] -solid4 = GEOM.Children[3] -solid5 = GEOM.Children[4] -solid6 = GEOM.Children[5] -solid7 = GEOM.Children[6] -solid8 = GEOM.Children[7] -solid9 = GEOM.Children[8] -solid10 = GEOM.Children[9] -solid11 = GEOM.Children[10] - -solid1.Suppressed = True -solid2.Suppressed = True -solid3.Suppressed = True -solid4.Suppressed = True -solid5.Suppressed = True -solid7.Suppressed = True -solid10.Suppressed = True -solid11.Suppressed = True - - -app.plot() - -# %% -# Store all Variables necessary for analysis -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -MESH = Model.Mesh -NS = Model.NamedSelections -CONN = Model.Connections -CS = Model.CoordinateSystems -MAT = Model.Materials - -# %% -# Setup the Analysis -# ~~~~~~~~~~~~~~~~~~ -# Add harmonic acoustics and unit system - -Model.AddHarmonicAcousticAnalysis() -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS - -# %% -# Import and assign materials - -MAT.Import(mat_path) -solid6.Material = "Air" -solid8.Material = "Air" -solid9.Material = "Air" - -# %% -# Create coordinate system -LCS1 = CS.AddCoordinateSystem() -LCS1.OriginX = Quantity("0 [mm]") -LCS1.OriginY = Quantity("0 [mm]") -LCS1.OriginZ = Quantity("0 [mm]") -LCS1.PrimaryAxisDefineBy = CoordinateSystemAlignmentType.GlobalZ - -# %% -# Generate mesh - -MESH.ElementSize = Quantity("200 [mm]") -MESH.GenerateMesh() - - -# %% -# Create named selections -# ~~~~~~~~~~~~~~~~~~~~~~~~ - -SF_Velo = Model.AddNamedSelection() -SF_Velo.ScopingMethod = GeometryDefineByType.Worksheet -SF_Velo.Name = "SF_Velo" -GEN_CRT1 = SF_Velo.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.Size -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("3e6 [mm^2]") -GEN_CRT1.Add(CRT1) -CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT2.Active = True -CRT2.Action = SelectionActionType.Filter -CRT2.EntityType = SelectionType.GeoFace -CRT2.Criterion = SelectionCriterionType.LocationZ -CRT2.Operator = SelectionOperatorType.Equal -CRT2.Value = Quantity("15000 [mm]") -GEN_CRT1.Add(CRT2) -SF_Velo.Activate() -SF_Velo.Generate() - -ABS_Face = Model.AddNamedSelection() -ABS_Face.ScopingMethod = GeometryDefineByType.Worksheet -ABS_Face.Name = "ABS_Face" -GEN_CRT2 = ABS_Face.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.Size -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("1.5e6 [mm^2]") -GEN_CRT2.Add(CRT1) -CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT2.Active = True -CRT2.Action = SelectionActionType.Filter -CRT2.EntityType = SelectionType.GeoFace -CRT2.Criterion = SelectionCriterionType.LocationY -CRT2.Operator = SelectionOperatorType.Equal -CRT2.Value = Quantity("500 [mm]") -GEN_CRT2.Add(CRT2) -ABS_Face.Activate() -ABS_Face.Generate() - -PRES_Face = Model.AddNamedSelection() -PRES_Face.ScopingMethod = GeometryDefineByType.Worksheet -PRES_Face.Name = "PRES_Face" -GEN_CRT3 = PRES_Face.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.Size -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("1.5e6 [mm^2]") -GEN_CRT3.Add(CRT1) -CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT2.Active = True -CRT2.Action = SelectionActionType.Filter -CRT2.EntityType = SelectionType.GeoFace -CRT2.Criterion = SelectionCriterionType.LocationY -CRT2.Operator = SelectionOperatorType.Equal -CRT2.Value = Quantity("4500 [mm]") -GEN_CRT3.Add(CRT2) -PRES_Face.Activate() -PRES_Face.Generate() - -ACOUSTIC_Region = Model.AddNamedSelection() -ACOUSTIC_Region.ScopingMethod = GeometryDefineByType.Worksheet -ACOUSTIC_Region.Name = "ACOUSTIC_Region" -GEN_CRT4 = ACOUSTIC_Region.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoBody -CRT1.Criterion = SelectionCriterionType.Type -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = 8 -GEN_CRT4.Add(CRT1) -ACOUSTIC_Region.Activate() -ACOUSTIC_Region.Generate() - -# %% -# Analysis settings -# ~~~~~~~~~~~~~~~~~ - -ANALYSIS_SETTINGS = Model.Analyses[0].AnalysisSettings -ANALYSIS_SETTINGS.RangeMaximum = Quantity("100 [Hz]") -ANALYSIS_SETTINGS.SolutionIntervals = 50 -ANALYSIS_SETTINGS.CalculateVelocity = True -ANALYSIS_SETTINGS.CalculateEnergy = True -ANALYSIS_SETTINGS.CalculateVolumeEnergy = True - -# %% -# Boundary conditions and load -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -HARM_ACOUST = Model.Analyses[0] - -# %% -# Acoustic region - -Acoustic_region = [x for x in HARM_ACOUST.Children if x.Name == "Acoustics Region"][0] -Acoustic_region.Location = ACOUSTIC_Region - -# %% -# Surface velocity - -SURF_VEL = HARM_ACOUST.AddAcousticSurfaceVelocity() -SURF_VEL.Location = SF_Velo -SURF_VEL.Magnitude.Output.DiscreteValues = [Quantity("5000 [mm s-1]")] - -# %% -# Acoustic pressure - -ACOUST_PRES = HARM_ACOUST.AddAcousticPressure() -ACOUST_PRES.Location = PRES_Face -ACOUST_PRES.Magnitude = Quantity("1.5e-7 [MPa]") - -# %% -# Acoustic absoption surface - -ABSORP_SURF = HARM_ACOUST.AddAcousticAbsorptionSurface() -ABSORP_SURF.Location = ABS_Face -ABSORP_SURF.AbsorptionCoefficient.Output.DiscreteValues = [Quantity("0.02")] - -HARM_ACOUST.Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "bounday_conditions.png"), image_export_format, settings_720p -) -display_image("bounday_conditions.png") - -# %% -# Add results -# ~~~~~~~~~~~ - -SOLN = Model.Analyses[0].Solution - -# %% -# Acoustic pressure - -ACOUST_PRES_RES1 = SOLN.AddAcousticPressureResult() -ACOUST_PRES_RES1.By = SetDriverStyle.ResultSet -ACOUST_PRES_RES1.SetNumber = 25 - -# %% -# Acoustic velocity - total and directional - -ACOUST_TOT_VEL1 = SOLN.AddAcousticTotalVelocityResult() -ACOUST_TOT_VEL1.Frequency = Quantity("50 [Hz]") - -ACOUST_DIR_VEL1 = SOLN.AddAcousticDirectionalVelocityResult() -ACOUST_DIR_VEL1.Frequency = Quantity("50 [Hz]") -ACOUST_DIR_VEL1.CoordinateSystem = LCS1 - -ACOUST_DIR_VEL2 = SOLN.AddAcousticDirectionalVelocityResult() -ACOUST_DIR_VEL2.NormalOrientation = NormalOrientationType.ZAxis -ACOUST_DIR_VEL2.By = SetDriverStyle.ResultSet -ACOUST_DIR_VEL2.SetNumber = 25 - -# %% -# Acoustic sound pressure and frequency bands - -ACOUST_SPL = SOLN.AddAcousticSoundPressureLevel() -ACOUST_SPL.Frequency = Quantity("50 [Hz]") - -ACOUST_A_SPL = SOLN.AddAcousticAWeightedSoundPressureLevel() -ACOUST_A_SPL.Frequency = Quantity("50 [Hz]") - -ACOUST_FRQ_BAND_SPL = SOLN.AddAcousticFrequencyBandSPL() - -A_FREQ_BAND_SPL = SOLN.AddAcousticFrequencyBandAWeightedSPL() - -Z_VELO_RESP = SOLN.AddAcousticVelocityFrequencyResponse() -Z_VELO_RESP.NormalOrientation = NormalOrientationType.ZAxis -Z_VELO_RESP.Location = PRES_Face -Z_VELO_RESP.NormalOrientation = NormalOrientationType.ZAxis - -# %% -# Acoustic kinetic and potentional energy frequency response - -KE_RESP = SOLN.AddAcousticKineticEnergyFrequencyResponse() -KE_RESP.Location = ABS_Face -KE_display = KE_RESP.TimeHistoryDisplay - -PE_RESP = SOLN.AddAcousticPotentialEnergyFrequencyResponse() -PE_RESP.Location = ABS_Face -PE_display = PE_RESP.TimeHistoryDisplay - -# %% -# Acoustic total and directional velocity - -ACOUST_TOT_VEL2 = SOLN.AddAcousticTotalVelocityResult() -ACOUST_TOT_VEL2.Location = PRES_Face -ACOUST_TOT_VEL2.Frequency = Quantity("30 [Hz]") -ACOUST_TOT_VEL2.Amplitude = True - -ACOUST_DIR_VEL3 = SOLN.AddAcousticDirectionalVelocityResult() -ACOUST_DIR_VEL3.NormalOrientation = NormalOrientationType.ZAxis -ACOUST_DIR_VEL3.Location = PRES_Face -ACOUST_DIR_VEL3.Frequency = Quantity("10 [Hz]") -ACOUST_DIR_VEL3.Amplitude = True - -ACOUST_KE = SOLN.AddAcousticKineticEnergy() -ACOUST_KE.Location = ABS_Face -ACOUST_KE.Frequency = Quantity("68 [Hz]") -ACOUST_KE.Amplitude = True - -ACOUST_PE = SOLN.AddAcousticPotentialEnergy() -ACOUST_PE.Location = ABS_Face -ACOUST_PE.Frequency = Quantity("10 [Hz]") -ACOUST_PE.Amplitude = True - -# %% -# Solve -# ~~~~~ - -SOLN.Solve(True) - -# sphinx_gallery_start_ignore -assert str(SOLN.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - - -# %% -# Postprocessing -# ~~~~~~~~~~~~~~ - -# %% -# Total acoustic pressure -# ^^^^^^^^^^^^^^^^^^^^^^^ - -Tree.Activate([ACOUST_PRES_RES1]) -Graphics.ExportImage( - os.path.join(cwd, "acou_pressure.png"), image_export_format, settings_720p -) -display_image("acou_pressure.png") - -# %% -# Total acoustic velocity -# ^^^^^^^^^^^^^^^^^^^^^^^ - -Tree.Activate([ACOUST_PRES_RES1]) -Graphics.ExportImage( - os.path.join(cwd, "totalvelocity.png"), image_export_format, settings_720p -) -display_image("totalvelocity.png") - -# %% -# Sound pressure level -# ^^^^^^^^^^^^^^^^^^^^ - -Tree.Activate([ACOUST_SPL]) -Graphics.ExportImage( - os.path.join(cwd, "sound_pressure.png"), image_export_format, settings_720p -) -display_image("sound_pressure.png") - -# %% -# Total velocity on pressure surface -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Tree.Activate([ACOUST_TOT_VEL2]) -Graphics.ExportImage( - os.path.join(cwd, "totalvelocity_pressure.png"), image_export_format, settings_720p -) -display_image("totalvelocity_pressure.png") - -# %% -# Kinetic energy on absorption face -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -Tree.Activate([ACOUST_KE]) -Graphics.ExportImage( - os.path.join(cwd, "kineticenergy.png"), image_export_format, settings_720p -) -display_image("kineticenergy.png") - -# %% -# Total acoustic pressure animation -# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -ACOUST_PRES_RES1.ExportAnimation( - os.path.join(cwd, "press.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "press.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=200, repeat=True, blit=True -) -plt.show() - -# %% -# Display output file from solve -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -def write_file_contents_to_console(path): - """Write file contents to console.""" - with open(path, "rt") as file: - for line in file: - print(line, end="") - - -solve_path = HARM_ACOUST.WorkingDir -solve_out_path = os.path.join(solve_path, "solve.out") -if solve_out_path: - write_file_contents_to_console(solve_out_path) - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "harmnonic_acoustics.mechdat")) -app.new() - -# delete example file -delete_downloads() diff --git a/examples/01_basic/modal_acoustics_analysis.py b/examples/01_basic/modal_acoustics_analysis.py deleted file mode 100644 index 398a5410..00000000 --- a/examples/01_basic/modal_acoustics_analysis.py +++ /dev/null @@ -1,538 +0,0 @@ -""".. _ref_modal_acoustics_analysis: - -Modal acoustics analysis ------------------------- - -This example demonstrate modal acoustic analysis that involves -modeling both a structure and the surrounding -fluid to analyze frequencies and standing wave patterns within the structure. -This type of analysis is essential for applications such as Sonar, concert hall design, -noise reduction in various settings, audio speaker design, and geophysical exploration. - -Mechanical enables you to model pure acoustic problems and fluid-structure -interaction (FSI) problems.A coupled acoustic analysis accounts for FSI. -An uncoupled acoustic analysis simulates -the fluid only and ignores any fluid-structure interaction. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - -# %% -# Download geometry and materials files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -geometry_path = download_file("sloshing_geometry.agdb", "pymechanical", "embedding") -mat_path = download_file("Water_material_explicit.xml", "pymechanical", "embedding") - - -# %% -# Import the geometry -# ~~~~~~~~~~~~~~~~~~~ - -geometry_import_group = Model.GeometryImportGroup -geometry_import = geometry_import_group.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "geometry.png"), image_export_format, settings_720p -) -display_image("geometry.png") - -# %% -# Store all variables necessary for analysis -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -GEOM = Model.Geometry -MESH = Model.Mesh -NS = Model.NamedSelections -CONN = Model.Connections -MAT = Model.Materials - -# %% -# Import material setup analysis -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Model.AddModalAcousticAnalysis() -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS -MAT.Import(mat_path) -print("Material Import Done !") - -# %% -# Get all required named selections and assign materials -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -acst_bodies = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Acoustic_bodies" -][0] -struct_bodies = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Structural_bodies" -][0] -top_bodies = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "top_bodies" -][0] -cont_bodies = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "container_bodies" -][0] -cont_V1 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_V1" -][0] -cont_V2 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_V2" -][0] -cont_V3 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_V3" -][0] -cont_face1 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_face1" -][0] -cont_face2 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_face2" -][0] -cont_face3 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_face3" -][0] -cont_face4 = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cont_face4" -][0] -free_faces = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Free_faces" -][0] -fsi_faces = [ - i - for i in NS.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "FSI_faces" -][0] - -solid1 = [ - i - for i in GEOM.GetChildren[Ansys.ACT.Automation.Mechanical.Body](True) - if i.Name == "Solid1" -][0] -solid2 = [ - i - for i in GEOM.GetChildren[Ansys.ACT.Automation.Mechanical.Body](True) - if i.Name == "Solid2" -][0] -solid3 = [ - i - for i in GEOM.GetChildren[Ansys.ACT.Automation.Mechanical.Body](True) - if i.Name == "Solid3" -][0] -solid4 = [ - i - for i in GEOM.GetChildren[Ansys.ACT.Automation.Mechanical.Body](True) - if i.Name == "Solid4" -][0] - - -# %% -# Assign material water to acoustic parts - -solid1.Material = "WATER" -solid2.Material = "WATER" -solid3.Material = "WATER" -solid4.Material = "WATER" - -# %% -# Mesh -# ~~~~ - -MESH.ElementOrder = ElementOrder.Quadratic - -method1 = MESH.AddAutomaticMethod() -method1.Location = acst_bodies -method1.Method = MethodType.AllTriAllTet - -method2 = MESH.AddAutomaticMethod() -method2.Location = top_bodies -method2.Method = MethodType.Automatic - -# Add mesh sizing - -sizing1 = MESH.AddSizing() -sizing1.Location = top_bodies -sizing1.ElementSize = Quantity("0.2 [m]") -sizing1.Behavior = SizingBehavior.Hard - -# Add mesh sizing - -sizing2 = MESH.AddSizing() -sizing2.Location = acst_bodies -sizing2.ElementSize = Quantity("0.2 [m]") -sizing2.Behavior = SizingBehavior.Hard - -# Add mesh method - -method3 = MESH.AddAutomaticMethod() -method3.Location = cont_bodies -method3.Method = MethodType.Sweep -method3.SourceTargetSelection = 4 - -MESH.GenerateMesh() - -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Insert contacts -# ~~~~~~~~~~~~~~~ -# Contact 1 -CONN_GROUP = CONN.AddConnectionGroup() -CONT1 = CONN_GROUP.AddContactRegion() -CONT1.SourceLocation = cont_V1 -CONT1.TargetLocation = cont_face1 -CONT1.ContactFormulation = ContactFormulation.MPC -CONT1.Behavior = ContactBehavior.Asymmetric -CONT1.PinballRegion = ContactPinballType.Radius -CONT1.PinballRadius = Quantity("0.25 [m]") - -# %% -# Contact 2 - -CONT2 = CONN_GROUP.AddContactRegion() -CONT2.SourceLocation = cont_V2 -CONT2.TargetLocation = cont_face2 -CONT2.ContactFormulation = ContactFormulation.MPC -CONT2.Behavior = ContactBehavior.Asymmetric -CONT2.PinballRegion = ContactPinballType.Radius -CONT2.PinballRadius = Quantity("0.25 [m]") - -# %% -# Contact 3 - -CONT3 = CONN_GROUP.AddContactRegion() -CONT3.SourceLocation = cont_V3 -CONT3.TargetLocation = cont_face3 -CONT3.ContactFormulation = ContactFormulation.MPC -CONT3.Behavior = ContactBehavior.Asymmetric -CONT3.PinballRegion = ContactPinballType.Radius -CONT3.PinballRadius = Quantity("0.25 [m]") - -# %% -# Contact 3 - -sel_manager = ExtAPI.SelectionManager -cnv4 = DataModel.GeoData.Assemblies[0].Parts[1].Bodies[0].Vertices[3] -cont_V4 = sel_manager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) -cont_V4.Entities = [cnv4] - -# %% -# Contact 4 - -CONT4 = CONN_GROUP.AddContactRegion() -CONT4.TargetLocation = cont_face4 -CONT4.SourceLocation = cont_V4 -CONT4.ContactFormulation = ContactFormulation.MPC -CONT4.Behavior = ContactBehavior.Asymmetric -CONT4.PinballRegion = ContactPinballType.Radius -CONT4.PinballRadius = Quantity("0.25 [m]") - -# %% -# Fully define Modal Multiphysics region with two physics regions - -MODAL_ACST = DataModel.Project.Model.Analyses[0] -ACOUST_REG = MODAL_ACST.Children[2] -ACOUST_REG.Location = acst_bodies - - -STRUCT_REG = MODAL_ACST.AddPhysicsRegion() -STRUCT_REG.Structural = True -STRUCT_REG.RenameBasedOnDefinition() -STRUCT_REG.Location = struct_bodies - - -# %% -# Analysis settings -# ~~~~~~~~~~~~~~~~~ - -ANALYSIS_SETTINGS = MODAL_ACST.Children[1] -ANALYSIS_SETTINGS.MaximumModesToFind = 12 -ANALYSIS_SETTINGS.SearchRangeMinimum = Quantity("0.1 [Hz]") -ANALYSIS_SETTINGS.SolverType = SolverType.Unsymmetric -ANALYSIS_SETTINGS.GeneralMiscellaneous = True -ANALYSIS_SETTINGS.CalculateReactions = True - -# %% -# Boundary conditions and load -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Free surface - -FREE_SF = MODAL_ACST.AddAcousticFreeSurface() -FREE_SF.Location = free_faces - -# %% -# Solid fluid interface - -FSI_OBJ = MODAL_ACST.AddFluidSolidInterface() -FSI_OBJ.Location = fsi_faces - -# %% -# Gravity - -ACCELERATION = MODAL_ACST.AddAcceleration() -ACCELERATION.DefineBy = LoadDefineBy.Components -ACCELERATION.YComponent.Output.DiscreteValues = [Quantity("9.81 [m sec^-1 sec^-1]")] - -# %% -# Fixed Support - -fv1 = DataModel.GeoData.Assemblies[0].Parts[1].Bodies[0].Vertices[0] -fv2 = DataModel.GeoData.Assemblies[0].Parts[1].Bodies[1].Vertices[0] -fv3 = DataModel.GeoData.Assemblies[0].Parts[1].Bodies[2].Vertices[0] -fv4 = DataModel.GeoData.Assemblies[0].Parts[1].Bodies[3].Vertices[0] - -fvert = sel_manager.CreateSelectionInfo(SelectionTypeEnum.GeometryEntities) -fvert.Entities = [fv1, fv2, fv3, fv4] -FIXED_SUPPORT = MODAL_ACST.AddFixedSupport() -FIXED_SUPPORT.Location = fvert - -MODAL_ACST.Activate() -Graphics.ExportImage( - os.path.join(cwd, "geometry.png"), image_export_format, settings_720p -) -display_image("geometry.png") - -# %% -# Add results -# ~~~~~~~~~~~ -# Add 10 modes - -soln = Model.Analyses[0].Solution -TOT_DEF1 = soln.AddTotalDeformation() -TOT_DEF2 = soln.AddTotalDeformation() -TOT_DEF2.Mode = 2 -TOT_DEF3 = soln.AddTotalDeformation() -TOT_DEF3.Mode = 3 -TOT_DEF4 = soln.AddTotalDeformation() -TOT_DEF4.Mode = 4 -TOT_DEF5 = soln.AddTotalDeformation() -TOT_DEF5.Mode = 5 -TOT_DEF6 = soln.AddTotalDeformation() -TOT_DEF6.Mode = 6 -TOT_DEF7 = soln.AddTotalDeformation() -TOT_DEF7.Mode = 7 -TOT_DEF8 = soln.AddTotalDeformation() -TOT_DEF8.Mode = 8 -TOT_DEF9 = soln.AddTotalDeformation() -TOT_DEF9.Mode = 9 -TOT_DEF10 = soln.AddTotalDeformation() -TOT_DEF10.Mode = 10 - -# %% -# Add acoustic pressure - -ACOUST_PRES_RES = soln.AddAcousticPressureResult() - -# %% -# Add force reaction scoped to fixed Support - -FORCE_REACT1 = soln.AddForceReaction() -FORCE_REACT1.BoundaryConditionSelection = FIXED_SUPPORT - -# %% -# Solve -# ~~~~~ - -soln.Solve(True) - -# sphinx_gallery_start_ignore -assert str(soln.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - - -# %% -# Results -# ~~~~~~~ -# Total deformation - mode 1 - -Tree.Activate([TOT_DEF1]) -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "totaldeformation1.png"), image_export_format, settings_720p -) -display_image("totaldeformation1.png") - - -# %% -# Acoustic pressure - -Tree.Activate([ACOUST_PRES_RES]) -Graphics.ExportImage( - os.path.join(cwd, "acoustic_pressure.png"), image_export_format, settings_720p -) -display_image("acoustic_pressure.png") - - -# %% -# Display all modal frequency, force reaction -# and acoustic pressure values - -FREQ1 = TOT_DEF1.ReportedFrequency.Value -FREQ2 = TOT_DEF2.ReportedFrequency.Value -FREQ3 = TOT_DEF3.ReportedFrequency.Value -FREQ4 = TOT_DEF4.ReportedFrequency.Value -FREQ5 = TOT_DEF5.ReportedFrequency.Value -FREQ6 = TOT_DEF6.ReportedFrequency.Value -FREQ7 = TOT_DEF7.ReportedFrequency.Value -FREQ8 = TOT_DEF8.ReportedFrequency.Value -FREQ9 = TOT_DEF9.ReportedFrequency.Value -FREQ10 = TOT_DEF10.ReportedFrequency.Value - -PRMAX = ACOUST_PRES_RES.Maximum.Value -PRMIN = ACOUST_PRES_RES.Minimum.Value - -FRC1_X = FORCE_REACT1.XAxis.Value -FRC1_Z = FORCE_REACT1.ZAxis.Value - -print("Modal Acoustic Results") -print("----------------------") -print("Frequency for mode 1 : ", FREQ1) -print("Frequency for mode 2 : ", FREQ2) -print("Frequency for mode 3 : ", FREQ3) -print("Frequency for mode 4 : ", FREQ4) -print("Frequency for mode 5 : ", FREQ5) -print("Frequency for mode 6 : ", FREQ6) -print("Frequency for mode 7 : ", FREQ7) -print("Frequency for mode 8 : ", FREQ8) -print("Frequency for mode 9 : ", FREQ9) -print("Frequency for mode 10 : ", FREQ10) -print("Acoustic pressure minimum : ", PRMIN) -print("Acoustic pressure Maximum : ", PRMAX) -print("Force reaction x-axis : ", FRC1_X) -print("Force reaction z-axis : ", FRC1_Z) - -# %% -# Total deformation animation for mode 10 - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -TOT_DEF10.ExportAnimation( - os.path.join(cwd, "deformation_10.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "deformation_10.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=100, repeat=True, blit=True -) -plt.show() - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "modal_acoustics.mechdat")) -app.new() - -# %% -# Delete example file - -delete_downloads() diff --git a/examples/01_basic/readme.txt b/examples/01_basic/readme.txt deleted file mode 100644 index 9aa25cde..00000000 --- a/examples/01_basic/readme.txt +++ /dev/null @@ -1,4 +0,0 @@ -Basic -====== - -This section demonstrates the basic capabilities of PyMechanical diff --git a/examples/01_basic/steady_state_thermal_analysis.py b/examples/01_basic/steady_state_thermal_analysis.py deleted file mode 100644 index 51cf3c88..00000000 --- a/examples/01_basic/steady_state_thermal_analysis.py +++ /dev/null @@ -1,467 +0,0 @@ -""".. _ref_steady_state_thermal: - -Steady state thermal analysis ------------------------------ - -This example problem demonstrates the use of a -simple steady-state thermal analysis to determine the temperatures, -thermal gradients, heat flow rates, and heat fluxes that are caused -by thermal loads that do not vary over time. A steady-state thermal -analysis calculates the effects of steady thermal loads on a system -or component, in this example, a long bar model. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -Graphics.Camera.SetFit() -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - - -# %% -# Download and import geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download the geometry file. - -geometry_path = download_file("LONGBAR.x_t", "pymechanical", "embedding") - -# %% -# Import the geometry - -geometry_import_group = Model.GeometryImportGroup -geometry_import = geometry_import_group.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -app.plot() - - -# %% -# Add steady state thermal analysis -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Model.AddSteadyStateThermalAnalysis() -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS -STAT_THERM = Model.Analyses[0] -MODEL = Model -CS = MODEL.CoordinateSystems -LCS1 = CS.AddCoordinateSystem() -LCS1.OriginX = Quantity("0 [m]") - -LCS2 = CS.AddCoordinateSystem() -LCS2.OriginX = Quantity("0 [m]") -LCS2.PrimaryAxisDefineBy = CoordinateSystemAlignmentType.GlobalY - -# %% -# Create named selections and construction geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Create named selections - -FACE1 = Model.AddNamedSelection() -FACE1.ScopingMethod = GeometryDefineByType.Worksheet -FACE1.Name = "Face1" -GEN_CRT1 = FACE1.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.LocationZ -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("20 [m]") -GEN_CRT1.Add(CRT1) -FACE1.Activate() -FACE1.Generate() - -FACE2 = Model.AddNamedSelection() -FACE2.ScopingMethod = GeometryDefineByType.Worksheet -FACE2.Name = "Face2" -GEN_CRT2 = FACE2.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.LocationZ -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("0 [m]") -GEN_CRT2.Add(CRT1) -FACE2.Activate() -FACE2.Generate() - -FACE3 = Model.AddNamedSelection() -FACE3.ScopingMethod = GeometryDefineByType.Worksheet -FACE3.Name = "Face3" -GEN_CRT3 = FACE3.GenerationCriteria -CRT1 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT1.Active = True -CRT1.Action = SelectionActionType.Add -CRT1.EntityType = SelectionType.GeoFace -CRT1.Criterion = SelectionCriterionType.LocationX -CRT1.Operator = SelectionOperatorType.Equal -CRT1.Value = Quantity("1 [m]") -GEN_CRT3.Add(CRT1) -CRT2 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT2.Active = True -CRT2.Action = SelectionActionType.Filter -CRT2.EntityType = SelectionType.GeoFace -CRT2.Criterion = SelectionCriterionType.LocationY -CRT2.Operator = SelectionOperatorType.Equal -CRT2.Value = Quantity("2 [m]") -GEN_CRT3.Add(CRT2) -CRT3 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT3.Active = True -CRT3.Action = SelectionActionType.Filter -CRT3.EntityType = SelectionType.GeoFace -CRT3.Criterion = SelectionCriterionType.LocationZ -CRT3.Operator = SelectionOperatorType.Equal -CRT3.Value = Quantity("12 [m]") -GEN_CRT3.Add(CRT3) -CRT4 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT4.Active = True -CRT4.Action = SelectionActionType.Add -CRT4.EntityType = SelectionType.GeoFace -CRT4.Criterion = SelectionCriterionType.LocationZ -CRT4.Operator = SelectionOperatorType.Equal -CRT4.Value = Quantity("4.5 [m]") -GEN_CRT3.Add(CRT4) -CRT5 = Ansys.ACT.Automation.Mechanical.NamedSelectionCriterion() -CRT5.Active = True -CRT5.Action = SelectionActionType.Filter -CRT5.EntityType = SelectionType.GeoFace -CRT5.Criterion = SelectionCriterionType.LocationY -CRT5.Operator = SelectionOperatorType.Equal -CRT5.Value = Quantity("2 [m]") -GEN_CRT3.Add(CRT5) -FACE3.Activate() -FACE3.Generate() - -BODY1 = Model.AddNamedSelection() -BODY1.ScopingMethod = GeometryDefineByType.Worksheet -BODY1.Name = "Body1" -BODY1.GenerationCriteria.Add(None) -BODY1.GenerationCriteria[0].EntityType = SelectionType.GeoFace -BODY1.GenerationCriteria[0].Criterion = SelectionCriterionType.LocationZ -BODY1.GenerationCriteria[0].Operator = SelectionOperatorType.Equal -BODY1.GenerationCriteria[0].Value = Quantity("1 [m]") -BODY1.GenerationCriteria.Add(None) -BODY1.GenerationCriteria[1].EntityType = SelectionType.GeoFace -BODY1.GenerationCriteria[1].Criterion = SelectionCriterionType.LocationZ -BODY1.GenerationCriteria[1].Operator = SelectionOperatorType.Equal -BODY1.GenerationCriteria[1].Value = Quantity("1 [m]") -BODY1.Generate() - -# %% -# Create construction geometry - -CONST_GEOM = MODEL.AddConstructionGeometry() -Path = CONST_GEOM.AddPath() -Path.StartYCoordinate = Quantity(2, "m") -Path.StartZCoordinate = Quantity(20, "m") -Path.StartZCoordinate = Quantity(20, "m") -Path.EndXCoordinate = Quantity(2, "m") -SURF = CONST_GEOM.AddSurface() -SURF.CoordinateSystem = LCS2 -CONST_GEOM.UpdateAllSolids() - -# %% -# Define boundary condition and add results -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Add temperature boundary conditions - -TEMP = STAT_THERM.AddTemperature() -TEMP.Location = FACE1 -TEMP.Magnitude.Output.DiscreteValues = [Quantity("22[C]"), Quantity("30[C]")] - -TEMP2 = STAT_THERM.AddTemperature() -TEMP2.Location = FACE2 -TEMP2.Magnitude.Output.DiscreteValues = [Quantity("22[C]"), Quantity("60[C]")] - -TEMP.Magnitude.Inputs[0].DiscreteValues = [ - Quantity("0 [sec]"), - Quantity("1 [sec]"), - Quantity("2 [sec]"), -] -TEMP.Magnitude.Output.DiscreteValues = [ - Quantity("22[C]"), - Quantity("30[C]"), - Quantity("40[C]"), -] - -TEMP2.Magnitude.Inputs[0].DiscreteValues = [ - Quantity("0 [sec]"), - Quantity("1 [sec]"), - Quantity("2 [sec]"), -] -TEMP2.Magnitude.Output.DiscreteValues = [ - Quantity("22[C]"), - Quantity("50[C]"), - Quantity("80[C]"), -] - -# %% -# Add radiation - -RAD = STAT_THERM.AddRadiation() -RAD.Location = FACE3 -RAD.AmbientTemperature.Inputs[0].DiscreteValues = [ - Quantity("0 [sec]"), - Quantity("1 [sec]"), - Quantity("2 [sec]"), -] -RAD.AmbientTemperature.Output.DiscreteValues = [ - Quantity("22[C]"), - Quantity("30[C]"), - Quantity("40[C]"), -] -RAD.Correlation = RadiationType.SurfaceToSurface - -# %% -# Analysis settings - -ANLYS_SET = STAT_THERM.AnalysisSettings -ANLYS_SET.NumberOfSteps = 2 -ANLYS_SET.CalculateVolumeEnergy = True - -STAT_THERM.Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "BC_steadystate.png"), image_export_format, settings_720p -) -display_image("BC_steadystate.png") - -# %% -# Add results -# ~~~~~~~~~~~ -# Temperature - -STAT_THERM_SOLN = Model.Analyses[0].Solution -TEMP_RST = STAT_THERM_SOLN.AddTemperature() -TEMP_RST.By = SetDriverStyle.MaximumOverTime - - -TEMP_RST2 = STAT_THERM_SOLN.AddTemperature() -TEMP_RST2.Location = BODY1 - -TEMP_RST3 = STAT_THERM_SOLN.AddTemperature() -TEMP_RST3.Location = Path - -TEMP_RST4 = STAT_THERM_SOLN.AddTemperature() -TEMP_RST4.Location = SURF - -# %% -# Total and directional heat flux - -TOT_HFLUX = STAT_THERM_SOLN.AddTotalHeatFlux() -DIR_HFLUX = STAT_THERM_SOLN.AddTotalHeatFlux() -DIR_HFLUX.ThermalResultType = TotalOrDirectional.Directional -DIR_HFLUX.NormalOrientation = NormalOrientationType.ZAxis - -LCS2.PrimaryAxisDefineBy = CoordinateSystemAlignmentType.GlobalZ -DIR_HFLUX.CoordinateSystem = LCS2 -DIR_HFLUX.DisplayOption = ResultAveragingType.Averaged - -# %% -# Thermal error - -THERM_ERROR = STAT_THERM_SOLN.AddThermalError() - -# %% -# Temperature probe - -TEMP_PROBE = STAT_THERM_SOLN.AddTemperatureProbe() -TEMP_PROBE.GeometryLocation = FACE1 -TEMP_PROBE.LocationMethod = LocationDefinitionMethod.CoordinateSystem -TEMP_PROBE.CoordinateSystemSelection = LCS2 - -# %% -# Heat flux probe - -HFLUX_PROBE = STAT_THERM_SOLN.AddHeatFluxProbe() -HFLUX_PROBE.LocationMethod = LocationDefinitionMethod.CoordinateSystem -HFLUX_PROBE.CoordinateSystemSelection = LCS2 -HFLUX_PROBE.ResultSelection = ProbeDisplayFilter.ZAxis - -# %% -# Reaction probe - -ANLYS_SET.NodalForces = OutputControlsNodalForcesType.Yes -REAC_PROBE = STAT_THERM_SOLN.AddReactionProbe() -REAC_PROBE.LocationMethod = LocationDefinitionMethod.GeometrySelection -REAC_PROBE.GeometryLocation = FACE1 - -# %% -# Radiation probe - -Rad_Probe = STAT_THERM_SOLN.AddRadiationProbe() -Rad_Probe.BoundaryConditionSelection = RAD -Rad_Probe.ResultSelection = ProbeDisplayFilter.All - - -# %% -# Solve -# ~~~~~ - -STAT_THERM_SOLN.Solve(True) - -# sphinx_gallery_start_ignore -assert str(STAT_THERM_SOLN.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - -# Display results -# ~~~~~~~~~~~~~~~ -# Total body temperature - -Tree.Activate([TEMP_RST]) -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "temp.png"), image_export_format, settings_720p) -display_image("temp.png") - -# %% -# Temperature on part of the body - -Tree.Activate([TEMP_RST2]) -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "temp2.png"), image_export_format, settings_720p) -display_image("temp2.png") - -# %% -# Temperature distribution along the specific path - -Tree.Activate([TEMP_RST3]) -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "temp3.png"), image_export_format, settings_720p) -display_image("temp3.png") - -# %% -# Temperature of bottom surface - -Tree.Activate([TEMP_RST4]) -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "temp4.png"), image_export_format, settings_720p) -display_image("temp4.png") - -# %% -# Export directional heat flux animation -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Directional heat flux - -Tree.Activate([DIR_HFLUX]) -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -DIR_HFLUX.ExportAnimation( - os.path.join(cwd, "DirectionalHeatFlux.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "DirectionalHeatFlux.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=100, repeat=True, blit=True -) -plt.show() - -# %% -# Display output file from solve -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -def write_file_contents_to_console(path): - """Write file contents to console.""" - with open(path, "rt") as file: - for line in file: - print(line, end="") - - -solve_path = STAT_THERM.WorkingDir -solve_out_path = os.path.join(solve_path, "solve.out") -if solve_out_path: - write_file_contents_to_console(solve_out_path) - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "steady_state_thermal.mechdat")) -app.new() - -# %% -# Delete example files - -delete_downloads() diff --git a/examples/01_basic/topology_optimization_cantilever_beam.py b/examples/01_basic/topology_optimization_cantilever_beam.py deleted file mode 100644 index 8d3cf6d4..00000000 --- a/examples/01_basic/topology_optimization_cantilever_beam.py +++ /dev/null @@ -1,230 +0,0 @@ -""".. _ref_topology_optimization: - -Topology optimization of a simple cantilever beam -------------------------------------------------- - -This example demonstrates the structural topology optimization of a simple -cantilever beam. The structural analysis is performed with basic constraints and -load, which is then transferred to the topology optimization. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt - -# %% -# Embed Mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -cwd = os.path.join(os.getcwd(), "out") - -# %% -# Configure graphics for image export - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Front) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - -# %% -# Import structural analsys -# ~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download ``.mechdat`` file - -structural_mechdat_file = download_file( - "cantilever.mechdat", "pymechanical", "embedding" -) -app.open(structural_mechdat_file) -STRUCT = Model.Analyses[0] - -# sphinx_gallery_start_ignore -assert str(STRUCT.ObjectState) == "Solved" -# sphinx_gallery_end_ignore -STRUCT_SLN = STRUCT.Solution -STRUCT_SLN.Solve(True) -# sphinx_gallery_start_ignore -assert str(STRUCT_SLN.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Display structural analsys results -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Total deformation - -STRUCT_SLN.Children[1].Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "total_deformation.png"), image_export_format, settings_720p -) -display_image("total_deformation.png") - -# %% -# Equivalent stress - -STRUCT_SLN.Children[2].Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "equivalent_stress.png"), image_export_format, settings_720p -) -display_image("equivalent_stress.png") - -# %% -# Topology optimization -# ~~~~~~~~~~~~~~~~~~~~~ - -# Set MKS unit system - -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardMKS - -# Get structural analysis and link to topology optimization - -TOPO_OPT = Model.AddTopologyOptimizationAnalysis() -TOPO_OPT.TransferDataFrom(STRUCT) - -OPT_REG = DataModel.GetObjectsByType(DataModelObjectCategory.OptimizationRegion)[0] -OPT_REG.BoundaryCondition = BoundaryConditionType.AllLoadsAndSupports -OPT_REG.OptimizationType = OptimizationType.TopologyDensity - -# sphinx_gallery_start_ignore -assert str(TOPO_OPT.ObjectState) == "NotSolved" -# sphinx_gallery_end_ignore - -# Insert volume response constraint object for topology optimization -# Delete mass response constraint - -MASS_CONSTRN = TOPO_OPT.Children[3] -MASS_CONSTRN.Delete() - -# Add volume response constraint - -VOL_CONSTRN = TOPO_OPT.AddVolumeConstraint() - -# Insert member size manufacturing constraint - -MEM_SIZE_MFG_CONSTRN = TOPO_OPT.AddMemberSizeManufacturingConstraint() -MEM_SIZE_MFG_CONSTRN.Minimum = ManuMemberSizeControlledType.Manual -MEM_SIZE_MFG_CONSTRN.MinSize = Quantity("2.4 [m]") - - -TOPO_OPT.Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "boundary_conditions.png"), image_export_format, settings_720p -) -display_image("boundary_conditions.png") - -# %% -# Solve -# ~~~~~ - -TOPO_OPT_SLN = TOPO_OPT.Solution -TOPO_OPT_SLN.Solve(True) -# sphinx_gallery_start_ignore -assert str(TOPO_OPT_SLN.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - -# %% -# Display results -# ~~~~~~~~~~~~~~~ - -TOPO_OPT_SLN.Children[1].Activate() -TOPO_DENS = TOPO_OPT_SLN.Children[1] - -# %% -# Add smoothing to the STL - -TOPO_DENS.AddSmoothing() -TOPO_OPT.Solution.EvaluateAllResults() -TOPO_DENS.Children[0].Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "topo_opitimized_smooth.png"), image_export_format, settings_720p -) -display_image("topo_opitimized_smooth.png") - -# %% -# Export animation - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -TOPO_DENS.ExportAnimation( - os.path.join(cwd, "Topo_opitimized.gif"), animation_export_format, settings_720p -) - -# %% -# .. image:: /_static/basic/Topo_opitimized.gif - -# %% -# Review the results - -# Print topology density results -print("Topology Density Results") -print("Minimum Density: ", TOPO_DENS.Minimum) -print("Maximum Density: ", TOPO_DENS.Maximum) -print("Iteration Number: ", TOPO_DENS.IterationNumber) -print("Original Volume: ", TOPO_DENS.OriginalVolume.Value) -print("Final Volume: ", TOPO_DENS.FinalVolume.Value) -print("Percent Volume of Original: ", TOPO_DENS.PercentVolumeOfOriginal) -print("Original Mass: ", TOPO_DENS.OriginalMass.Value) -print("Final Mass: ", TOPO_DENS.FinalMass.Value) -print("Percent Mass of Original: ", TOPO_DENS.PercentMassOfOriginal) - - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "cantilever_beam_topology_optimization.mechdat")) -app.new() - -# %% -# Delete the example files - -delete_downloads() diff --git a/examples/01_basic/valve.py b/examples/01_basic/valve.py deleted file mode 100644 index 6778723f..00000000 --- a/examples/01_basic/valve.py +++ /dev/null @@ -1,244 +0,0 @@ -""".. _ref_basic_valve: - -Basic Valve Implementation --------------------------- - -This example demonstrates a basic implementation of a valve in Python. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - - -# %% -# Download geometry and import -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Download geometry - -geometry_path = download_file("Valve.pmdb", "pymechanical", "embedding") - -# %% -# Import geometry - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -app.plot() - -# %% -# Assign materials and mesh the geometry -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -material_assignment = Model.Materials.AddMaterialAssignment() -material_assignment.Material = "Structural Steel" -sel = ExtAPI.SelectionManager.CreateSelectionInfo( - Ansys.ACT.Interfaces.Common.SelectionTypeEnum.GeometryEntities -) -sel.Ids = [ - body.GetGeoBody().Id - for body in Model.Geometry.GetChildren( - Ansys.Mechanical.DataModel.Enums.DataModelObjectCategory.Body, True - ) -] -material_assignment.Location = sel - -# %% -# Define mesh settings, generate mesh - -mesh = Model.Mesh -mesh.ElementSize = Quantity(25, "mm") -mesh.GenerateMesh() -Tree.Activate([mesh]) -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Define analysis and boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -analysis = Model.AddStaticStructuralAnalysis() - -fixed_support = analysis.AddFixedSupport() -fixed_support.Location = ExtAPI.DataModel.GetObjectsByName("NSFixedSupportFaces")[0] - -frictionless_support = analysis.AddFrictionlessSupport() -frictionless_support.Location = ExtAPI.DataModel.GetObjectsByName( - "NSFrictionlessSupportFaces" -)[0] - -pressure = analysis.AddPressure() -pressure.Location = ExtAPI.DataModel.GetObjectsByName("NSInsideFaces")[0] - -pressure.Magnitude.Inputs[0].DiscreteValues = [Quantity("0 [s]"), Quantity("1 [s]")] -pressure.Magnitude.Output.DiscreteValues = [Quantity("0 [Pa]"), Quantity("15 [MPa]")] - -analysis.Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage( - os.path.join(cwd, "boundary_conditions.png"), image_export_format, settings_720p -) -display_image("boundary_conditions.png") - - -# %% -# Add results - -solution = analysis.Solution -deformation = solution.AddTotalDeformation() -stress = solution.AddEquivalentStress() - -# %% -# Solve - -solution.Solve(True) - -# sphinx_gallery_start_ignore -assert str(solution.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Messages -# ~~~~~~~~ - -Messages = ExtAPI.Application.Messages -if Messages: - for message in Messages: - print(f"[{message.Severity}] {message.DisplayString}") -else: - print("No [Info]/[Warning]/[Error] Messages") - -# %% -# Results -# ~~~~~~~ - -# %% -# Total deformation - -Tree.Activate([deformation]) -Graphics.ExportImage( - os.path.join(cwd, "totaldeformation_valve.png"), image_export_format, settings_720p -) -display_image("totaldeformation_valve.png") - -# %% -# Stress - -Tree.Activate([stress]) -Graphics.ExportImage( - os.path.join(cwd, "stress_valve.png"), image_export_format, settings_720p -) -display_image("stress_valve.png") - -# %% -# Export stress animation - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -stress.ExportAnimation( - os.path.join(cwd, "Valve.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "Valve.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=100, repeat=True, blit=True -) -plt.show() - -# %% -# Display output file from solve -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - -def write_file_contents_to_console(path): - """Write file contents to console.""" - with open(path, "rt") as file: - for line in file: - print(line, end="") - - -solve_path = analysis.WorkingDir -solve_out_path = os.path.join(solve_path, "solve.out") -if solve_out_path: - write_file_contents_to_console(solve_out_path) - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "Valve.mechdat")) -app.new() - -# %% -# delete example files - -delete_downloads() diff --git a/examples/02_technology_showcase/Rotor_Blade_Inverse_solve.py b/examples/02_technology_showcase/Rotor_Blade_Inverse_solve.py index 7eeb72af..ba35dccd 100644 --- a/examples/02_technology_showcase/Rotor_Blade_Inverse_solve.py +++ b/examples/02_technology_showcase/Rotor_Blade_Inverse_solve.py @@ -399,6 +399,8 @@ def display_image(image_name): Imported_Pressure.Location = selection Imported_Pressure.AppliedBy = LoadAppliedBy.Direct Imported_Pressure.ImportLoad() +Imported_Pressure.Properties[4].InternalValue = 1 +Imported_Pressure.ExternalLoadScopingType = ExternalLoadScopingType.Nodal Tree.Activate([Imported_Pressure]) Graphics.Camera.SetFit() diff --git a/examples/02_technology_showcase/conact_wear_simulation.py b/examples/02_technology_showcase/conact_wear_simulation.py deleted file mode 100644 index 9455af21..00000000 --- a/examples/02_technology_showcase/conact_wear_simulation.py +++ /dev/null @@ -1,385 +0,0 @@ -""".. _ref_contact_wear_simulation: - -Contact Surface Wear Simulation -------------------------------- - -Using a Archard wear model, this example demonstrates contact sliding -of a hemispherical ring on a flat ring to produce wear. - -The model includes: - -- Hemispherical ring with a radius of 30 mm made of copper. -- Flat ring with an inner radius of 50 mm and an outer radius of 150 mm made of steel. - -The hemispherical ring is in contact with the flat ring at the center -from the axis of rotation at 100 mm and is subjected to a -1) pressure of 4000 N/mm2 and 2) a rotation with a frequency -of 100,000 revolutions/sec. - -The application evaluates total deformation and normal stress results, -in loading direction, prior to and following wear. In addition, -contact pressure prior to wear is evaluated. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Front) -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False -Graphics.Camera.Rotate(180, CameraAxisType.ScreenY) - -# %% -# Download geometry and materials files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -geometry_path = download_file("example_07_td43_wear.agdb", "pymechanical", "00_basic") -mat1_path = download_file("example_07_Mat_Copper.xml", "pymechanical", "00_basic") -mat2_path = download_file("example_07_Mat_Steel.xml", "pymechanical", "00_basic") - -# %% -# Import geometry -# ~~~~~~~~~~~~~~~ - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import_preferences.ProcessCoordinateSystems = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -app.plot() - -# %% -# Import materials -# ~~~~~~~~~~~~~~~~ - -MAT = Model.Materials -MAT.Import(mat1_path) -MAT.Import(mat2_path) - -print("Material import done !") - -# %% -# Setup the Analysis -# ~~~~~~~~~~~~~~~~~~ -# Set up the unit system - -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardNMM - -# %% -# Store all main tree nodes as variables - -MODEL = Model -GEOM = Model.Geometry -CS_GRP = Model.CoordinateSystems -CONN_GRP = Model.Connections -MSH = Model.Mesh -NS_GRP = Model.NamedSelections - -# %% -# Add static structural analysis - -Model.AddStaticStructuralAnalysis() -STAT_STRUC = Model.Analyses[0] -STAT_STRUC_SOLN = STAT_STRUC.Solution -STAT_STRUC_ANA_SETTING = STAT_STRUC.Children[0] - -# %% -# Store name selection - -CURVE_NS = [x for x in Tree.AllObjects if x.Name == "curve"][0] -DIA_NS = [x for x in Tree.AllObjects if x.Name == "dia"][0] -VER_EDGE1 = [x for x in Tree.AllObjects if x.Name == "v1"][0] -VER_EDGE2 = [x for x in Tree.AllObjects if x.Name == "v2"][0] -HOR_EDGE1 = [x for x in Tree.AllObjects if x.Name == "h1"][0] -HOR_EDGE2 = [x for x in Tree.AllObjects if x.Name == "h2"][0] -ALL_BODIES_NS = [x for x in Tree.AllObjects if x.Name == "all_bodies"][0] - -# %% -# Assign material to bodies and change behavior to axisymmetric - -GEOM.Model2DBehavior = Model2DBehavior.AxiSymmetric - -SURFACE1 = GEOM.Children[0].Children[0] -SURFACE1.Material = "Steel" -SURFACE1.Dimension = ShellBodyDimension.Two_D - -SURFACE2 = GEOM.Children[1].Children[0] -SURFACE2.Material = "Copper" -SURFACE2.Dimension = ShellBodyDimension.Two_D - -# %% -# Change contact settings - -CONT_REG = CONN_GRP.AddContactRegion() -CONT_REG.SourceLocation = NS_GRP.Children[6] -CONT_REG.TargetLocation = NS_GRP.Children[3] -# CONT_REG.FlipContactTarget() -CONT_REG.ContactType = ContactType.Frictionless -CONT_REG.Behavior = ContactBehavior.Asymmetric -CONT_REG.ContactFormulation = ContactFormulation.AugmentedLagrange -CONT_REG.DetectionMethod = ContactDetectionPoint.NodalNormalToTarget - -# %% -# Add a command snippet to use Archard Wear Model - -AWM = """keyo,cid,5,1 -keyo,cid,10,2 -pi=acos(-1) -slide_velocity=1e5 -Uring_offset=100 -kcopper=10e-13*slide_velocity*2*pi*Uring_offset -TB,WEAR,cid,,,ARCD -TBFIELD,TIME,0 -TBDATA,1,0,1,1,0,0 -TBFIELD,TIME,1 -TBDATA,1,0,1,1,0,0 -TBFIELD,TIME,1.01 -TBDATA,1,kcopper,1,1,0,0 -TBFIELD,TIME,4 -TBDATA,1,kcopper,1,1,0,0""" -CMD1 = CONT_REG.AddCommandSnippet() -CMD1.AppendText(AWM) - -# %% -# Insert remote point - -REM_PT = MODEL.AddRemotePoint() -REM_PT.Location = DIA_NS -REM_PT.Behavior = LoadBehavior.Rigid - -# %% -# Mesh -# ~~~~ - -MSH.ElementOrder = ElementOrder.Linear -MSH.ElementSize = Quantity("1 [mm]") - -EDGE_SIZING1 = MSH.AddSizing() -EDGE_SIZING1.Location = HOR_EDGE1 -EDGE_SIZING1.Type = SizingType.NumberOfDivisions -EDGE_SIZING1.NumberOfDivisions = 70 - -EDGE_SIZING2 = MSH.AddSizing() -EDGE_SIZING2.Location = HOR_EDGE2 -EDGE_SIZING2.Type = SizingType.NumberOfDivisions -EDGE_SIZING2.NumberOfDivisions = 70 - -EDGE_SIZING3 = MSH.AddSizing() -EDGE_SIZING3.Location = VER_EDGE1 -EDGE_SIZING3.Type = SizingType.NumberOfDivisions -EDGE_SIZING3.NumberOfDivisions = 35 - -EDGE_SIZING4 = MSH.AddSizing() -EDGE_SIZING4.Location = VER_EDGE2 -EDGE_SIZING4.Type = SizingType.NumberOfDivisions -EDGE_SIZING4.NumberOfDivisions = 35 - -EDGE_SIZING5 = MSH.AddSizing() -EDGE_SIZING5.Location = DIA_NS -EDGE_SIZING5.Type = SizingType.NumberOfDivisions -EDGE_SIZING5.NumberOfDivisions = 40 - -EDGE_SIZING6 = MSH.AddSizing() -EDGE_SIZING6.Location = CURVE_NS -EDGE_SIZING6.Type = SizingType.NumberOfDivisions -EDGE_SIZING6.NumberOfDivisions = 60 - -MSH.GenerateMesh() - -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Analysis settings -# ~~~~~~~~~~~~~~~~~ - -STAT_STRUC_ANA_SETTING.NumberOfSteps = 2 -STAT_STRUC_ANA_SETTING.CurrentStepNumber = 1 -STAT_STRUC_ANA_SETTING.AutomaticTimeStepping = AutomaticTimeStepping.On -STAT_STRUC_ANA_SETTING.DefineBy = TimeStepDefineByType.Time -STAT_STRUC_ANA_SETTING.InitialTimeStep = Quantity("0.1 [s]") -STAT_STRUC_ANA_SETTING.MinimumTimeStep = Quantity("0.0001 [s]") -STAT_STRUC_ANA_SETTING.MaximumTimeStep = Quantity("1 [s]") -STAT_STRUC_ANA_SETTING.CurrentStepNumber = 2 -STAT_STRUC_ANA_SETTING.Activate() -STAT_STRUC_ANA_SETTING.StepEndTime = Quantity("4 [s]") -STAT_STRUC_ANA_SETTING.AutomaticTimeStepping = AutomaticTimeStepping.On -STAT_STRUC_ANA_SETTING.DefineBy = TimeStepDefineByType.Time -STAT_STRUC_ANA_SETTING.InitialTimeStep = Quantity("0.01 [s]") -STAT_STRUC_ANA_SETTING.MinimumTimeStep = Quantity("0.000001 [s]") -STAT_STRUC_ANA_SETTING.MaximumTimeStep = Quantity("0.02 [s]") - -STAT_STRUC_ANA_SETTING.LargeDeflection = True - -# %% -# Insert loading and boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -FIX_SUP = STAT_STRUC.AddFixedSupport() -FIX_SUP.Location = HOR_EDGE1 - -REM_DISP = STAT_STRUC.AddRemoteDisplacement() -REM_DISP.Location = REM_PT -REM_DISP.XComponent.Output.DiscreteValues = [Quantity("0[mm]")] -REM_DISP.RotationZ.Output.DiscreteValues = [Quantity("0[deg]")] - -REM_FRC = STAT_STRUC.AddRemoteForce() -REM_FRC.Location = REM_PT -REM_FRC.DefineBy = LoadDefineBy.Components -REM_FRC.YComponent.Output.DiscreteValues = [Quantity("-150796320 [N]")] - -# Nonlinear Adaptivity does not support contact criterion yet hence command snippet used - -NLAD = """NLADAPTIVE,all,add,contact,wear,0.50 -NLADAPTIVE,all,on,all,all,1,,4 -NLADAPTIVE,all,list,all,all""" -CMD2 = STAT_STRUC.AddCommandSnippet() -CMD2.AppendText(NLAD) -CMD2.StepSelectionMode = SequenceSelectionType.All - -STAT_STRUC.Activate() -Graphics.Camera.SetFit() -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Insert results -# ~~~~~~~~~~~~~~ - -TOT_DEF = STAT_STRUC_SOLN.AddTotalDeformation() - -NORM_STRS1 = STAT_STRUC_SOLN.AddNormalStress() -NORM_STRS1.NormalOrientation = NormalOrientationType.YAxis -NORM_STRS1.DisplayTime = Quantity("1 [s]") -NORM_STRS1.DisplayOption = ResultAveragingType.Unaveraged - -NORM_STRS2 = STAT_STRUC_SOLN.AddNormalStress() -NORM_STRS2.NormalOrientation = NormalOrientationType.YAxis -NORM_STRS2.DisplayTime = Quantity("4 [s]") -NORM_STRS2.DisplayOption = ResultAveragingType.Unaveraged - -CONT_TOOL = STAT_STRUC_SOLN.AddContactTool() -CONT_TOOL.ScopingMethod = GeometryDefineByType.Geometry -SEL1 = ExtAPI.SelectionManager.AddSelection(ALL_BODIES_NS) -SEL2 = ExtAPI.SelectionManager.CurrentSelection -CONT_TOOL.Location = SEL2 -ExtAPI.SelectionManager.ClearSelection() -CONT_PRES1 = CONT_TOOL.AddPressure() -CONT_PRES1.DisplayTime = Quantity("1 [s]") - -CONT_PRES2 = CONT_TOOL.AddPressure() -CONT_PRES2.DisplayTime = Quantity("4 [s]") - -# %% -# Solve -# ~~~~~ - -STAT_STRUC_SOLN.Solve(True) -STAT_STRUC_SS = STAT_STRUC_SOLN.Status -# sphinx_gallery_start_ignore -assert str(STAT_STRUC_SS) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Postprocessing -# ~~~~~~~~~~~~~~ -# Normal stress - -Tree.Activate([NORM_STRS1]) -Graphics.ExportImage( - os.path.join(cwd, "normal_stresss.png"), image_export_format, settings_720p -) -display_image("normal_stresss.png") - -# %% -# Total deformation animation - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -TOT_DEF.ExportAnimation( - os.path.join(cwd, "totaldeformation.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "totaldeformation.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=200, repeat=True, blit=True -) -plt.show() - - -# %% -# Project tree -# ~~~~~~~~~~~~ - -app.print_tree() - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "contact_wear.mechdat")) -app.new() - -# delete example file -delete_downloads() diff --git a/examples/02_technology_showcase/non_linear_analsis_rubber_boot_seal.py b/examples/02_technology_showcase/non_linear_analsis_rubber_boot_seal.py deleted file mode 100644 index 815cc621..00000000 --- a/examples/02_technology_showcase/non_linear_analsis_rubber_boot_seal.py +++ /dev/null @@ -1,473 +0,0 @@ -""".. _ref_non_linear_analysis_rubber_boot_seal: - -Nonlinear Analysis of a Rubber Boot Seal Model ----------------------------------------------- - -This example demonstrates a nonlinear 3D analysis of a rubber boot seal to: - -- Create a rigid-flexible contact pair between a rigid shaft and a - rubber boot part. -- Specify ramped effects using the On Gauss Point Detection Method - to update contact stiffness at each iteration. -- Specify contact pairs at the inner and outer surfaces of the rubber boot. -- Specify non-ramped effects using the Nodal-Projected Normal From Contact - Detection Method to update contact stiffness at each iteration. -""" - -# %% -# Import necessary libraries -# ~~~~~~~~~~~~~~~~~~~~~~~~~~ - -import os - -from PIL import Image -from ansys.mechanical.core import App -from ansys.mechanical.core.examples import delete_downloads, download_file -from matplotlib import image as mpimg -from matplotlib import pyplot as plt -from matplotlib.animation import FuncAnimation - -# %% -# Embed mechanical and set global variables - -app = App() -app.update_globals(globals()) -print(app) - -cwd = os.path.join(os.getcwd(), "out") - - -def display_image(image_name): - plt.figure(figsize=(16, 9)) - plt.imshow(mpimg.imread(os.path.join(cwd, image_name))) - plt.xticks([]) - plt.yticks([]) - plt.axis("off") - plt.show() - - -# %% -# Configure graphics for image export -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Graphics.Camera.SetSpecificViewOrientation(ViewOrientationType.Iso) -Graphics.Camera.SetFit() -image_export_format = GraphicsImageExportFormat.PNG -settings_720p = Ansys.Mechanical.Graphics.GraphicsImageExportSettings() -settings_720p.Resolution = GraphicsResolutionType.EnhancedResolution -settings_720p.Background = GraphicsBackgroundType.White -settings_720p.Width = 1280 -settings_720p.Height = 720 -settings_720p.CurrentGraphicsDisplay = False - -# %% -# Download geometry and materials files -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -geometry_path = download_file( - "example_05_td26_Rubber_Boot_Seal.agdb", "pymechanical", "00_basic" -) -mat_path = download_file("example_05_Boot_Mat.xml", "pymechanical", "00_basic") - -# %% -# Import geometry and material -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -# Import material - -materials = Model.Materials -materials.Import(mat_path) -print("Material import done !") -# %% -# Import geometry - -geometry_import = Model.GeometryImportGroup.AddGeometryImport() -geometry_import_format = ( - Ansys.Mechanical.DataModel.Enums.GeometryImportPreference.Format.Automatic -) -geometry_import_preferences = Ansys.ACT.Mechanical.Utilities.GeometryImportPreferences() -geometry_import_preferences.ProcessNamedSelections = True -geometry_import_preferences.ProcessCoordinateSystems = True -geometry_import.Import( - geometry_path, geometry_import_format, geometry_import_preferences -) - -app.plot() - -# %% -# Setup the Analysis -# ~~~~~~~~~~~~~~~~~~ -# Set up the unit system - -ExtAPI.Application.ActiveUnitSystem = MechanicalUnitSystem.StandardNMM -ExtAPI.Application.ActiveAngleUnit = AngleUnitType.Radian - -# %% -# Store all main tree nodes as variables - -GEOM = Model.Geometry -PRT1 = [x for x in Tree.AllObjects if x.Name == "Part"][0] -PRT2 = [x for x in Tree.AllObjects if x.Name == "Solid"][1] -CS_GRP = Model.CoordinateSystems -GCS = CS_GRP.Children[0] - -# %% -# Add static structural analysis - -Model.AddStaticStructuralAnalysis() -STAT_STRUC = Model.Analyses[0] -ANA_SETTING = STAT_STRUC.Children[0] -STAT_STRUC_SOLN = STAT_STRUC.Solution -SOLN_INFO = STAT_STRUC_SOLN.SolutionInformation - -# %% -# Define named selection and coordinate system - -NS_GRP = ExtAPI.DataModel.Project.Model.NamedSelections -TOP_FACE = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Top_Face" -][0] -BOTTOM_FACE = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Bottom_Face" -][0] -SYMM_FACES30 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Symm_Faces30" -][0] -FACES2 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Faces2" -][0] -CYL_FACES2 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Cyl_Faces2" -][0] -RUBBER_BODIES30 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Rubber_Bodies30" -][0] -INNER_FACES30 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Inner_Faces30" -][0] -OUTER_FACES30 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Outer_Faces30" -][0] -SHAFT_FACE = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Shaft_Face" -][0] -SYMM_FACES15 = [ - i - for i in NS_GRP.GetChildren[Ansys.ACT.Automation.Mechanical.NamedSelection](True) - if i.Name == "Symm_Faces15" -][0] - -LCS1 = CS_GRP.AddCoordinateSystem() -LCS1.OriginY = Quantity("97[mm]") - -# %% -# Assign material - -PRT1.Material = "Boot" -PRT2.StiffnessBehavior = StiffnessBehavior.Rigid - -# %% -# Define connections - -CONN_GRP = Model.Connections -CONT_REG1 = CONN_GRP.AddContactRegion() -CONT_REG1.TargetLocation = SHAFT_FACE -CONT_REG1.SourceLocation = INNER_FACES30 -CONT_REG1.ContactType = ContactType.Frictional -CONT_REG1.FrictionCoefficient = 0.2 -CONT_REG1.Behavior = ContactBehavior.Asymmetric -CONT_REG1.SmallSliding = ContactSmallSlidingType.Off -CONT_REG1.DetectionMethod = ContactDetectionPoint.OnGaussPoint -CONT_REG1.UpdateStiffness = UpdateContactStiffness.EachIteration -CONT_REG1.InterfaceTreatment = ContactInitialEffect.AddOffsetRampedEffects -CONT_REG1.TargetGeometryCorrection = TargetCorrection.Smoothing -CONT_REG1.TargetOrientation = TargetOrientation.Cylinder -CONT_REG1.TargetStartingPoint = GCS -CONT_REG1.TargetEndingPoint = LCS1 - -CONTS = CONN_GRP.Children[0] -CONT_REG2 = CONTS.AddContactRegion() -CONT_REG2.SourceLocation = INNER_FACES30 -CONT_REG2.TargetLocation = INNER_FACES30 -CONT_REG2.ContactType = ContactType.Frictional -CONT_REG2.FrictionCoefficient = 0.2 -CONT_REG2.Behavior = ContactBehavior.Asymmetric -CONT_REG2.SmallSliding = ContactSmallSlidingType.Off -CONT_REG2.DetectionMethod = ContactDetectionPoint.NodalProjectedNormalFromContact -CONT_REG2.UpdateStiffness = UpdateContactStiffness.EachIteration -CONT_REG2.NormalStiffnessValueType = ElementControlsNormalStiffnessType.Factor -CONT_REG2.NormalStiffnessFactor = 1 - -CONT_REG3 = CONTS.AddContactRegion() -CONT_REG3.SourceLocation = OUTER_FACES30 -CONT_REG3.TargetLocation = OUTER_FACES30 -CONT_REG3.ContactType = ContactType.Frictional -CONT_REG3.FrictionCoefficient = 0.2 -CONT_REG3.Behavior = ContactBehavior.Asymmetric -CONT_REG3.SmallSliding = ContactSmallSlidingType.Off -CONT_REG3.DetectionMethod = ContactDetectionPoint.NodalProjectedNormalFromContact -CONT_REG3.UpdateStiffness = UpdateContactStiffness.EachIteration -CONT_REG3.NormalStiffnessValueType = ElementControlsNormalStiffnessType.Factor -CONT_REG3.NormalStiffnessFactor = 1 - -# %% -# Mesh -# ~~~~ - -MSH = Model.Mesh -FACE_MSH = MSH.AddFaceMeshing() -FACE_MSH.Location = SHAFT_FACE -FACE_MSH.InternalNumberOfDivisions = 1 - -MSH_SIZE = MSH.AddSizing() -MSH_SIZE.Location = SYMM_FACES15 -MSH_SIZE.ElementSize = Quantity("2 [mm]") - -MSH.ElementOrder = ElementOrder.Linear -MSH.Resolution = 2 - -MSH.GenerateMesh() - -Graphics.ExportImage(os.path.join(cwd, "mesh.png"), image_export_format, settings_720p) -display_image("mesh.png") - -# %% -# Define remote points -# ~~~~~~~~~~~~~~~~~~~~ -# scope them to the top and bottom faces of rigid shaft - -RMPT01 = Model.AddRemotePoint() -RMPT01.Location = BOTTOM_FACE -RMPT01.Behavior = LoadBehavior.Rigid - -RMPT02 = Model.AddRemotePoint() -RMPT02.Location = TOP_FACE -RMPT02.Behavior = LoadBehavior.Rigid - -# %% -# Analysis settings -# ~~~~~~~~~~~~~~~~~ - -ANA_SETTING.Activate() -ANA_SETTING.LargeDeflection = True -ANA_SETTING.Stabilization = StabilizationType.Off - -ANA_SETTING.NumberOfSteps = 2 -ANA_SETTING.CurrentStepNumber = 1 -ANA_SETTING.AutomaticTimeStepping = AutomaticTimeStepping.On -ANA_SETTING.DefineBy = TimeStepDefineByType.Substeps -ANA_SETTING.InitialSubsteps = 5 -ANA_SETTING.MinimumSubsteps = 5 -ANA_SETTING.MaximumSubsteps = 1000 -ANA_SETTING.StoreResultsAt = TimePointsOptions.EquallySpacedPoints -ANA_SETTING.StoreResulsAtValue = 5 - -ANA_SETTING.CurrentStepNumber = 2 -ANA_SETTING.AutomaticTimeStepping = AutomaticTimeStepping.On -ANA_SETTING.DefineBy = TimeStepDefineByType.Substeps -ANA_SETTING.InitialSubsteps = 10 -ANA_SETTING.MinimumSubsteps = 10 -ANA_SETTING.MaximumSubsteps = 1000 -ANA_SETTING.StoreResultsAt = TimePointsOptions.EquallySpacedPoints -ANA_SETTING.StoreResulsAtValue = 10 - -ANA_SETTING.CurrentStepNumber = 3 -ANA_SETTING.AutomaticTimeStepping = AutomaticTimeStepping.On -ANA_SETTING.DefineBy = TimeStepDefineByType.Substeps -ANA_SETTING.InitialSubsteps = 30 -ANA_SETTING.MinimumSubsteps = 30 -ANA_SETTING.MaximumSubsteps = 1000 -ANA_SETTING.StoreResultsAt = TimePointsOptions.EquallySpacedPoints -ANA_SETTING.StoreResulsAtValue = 20 - -SOLN_INFO.NewtonRaphsonResiduals = 4 - -# %% -# Loads and boundary conditions -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -REM_DISP = STAT_STRUC.AddRemoteDisplacement() -REM_DISP.Location = RMPT01 -REM_DISP.XComponent.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.XComponent.Output.DiscreteValues = [ - Quantity("0 [mm]"), - Quantity("0 [mm]"), - Quantity("0 [mm]"), - Quantity("0 [mm]"), -] -REM_DISP.YComponent.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.YComponent.Output.DiscreteValues = [ - Quantity("0 [mm]"), - Quantity("0 [mm]"), - Quantity("-10 [mm]"), - Quantity("-10 [mm]"), -] -REM_DISP.ZComponent.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.ZComponent.Output.DiscreteValues = [ - Quantity("0 [mm]"), - Quantity("0 [mm]"), - Quantity("0 [mm]"), - Quantity("0 [mm]"), -] - -REM_DISP.RotationX.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.RotationX.Output.DiscreteValues = [ - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0 [rad]"), -] -REM_DISP.RotationY.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.RotationY.Output.DiscreteValues = [ - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0 [rad]"), -] -REM_DISP.RotationZ.Inputs[0].DiscreteValues = [ - Quantity("0 [s]"), - Quantity("1 [s]"), - Quantity("2 [s]"), - Quantity("3 [s]"), -] -REM_DISP.RotationZ.Output.DiscreteValues = [ - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0 [rad]"), - Quantity("0.55 [rad]"), -] - -FRIC_SUP01 = STAT_STRUC.AddFrictionlessSupport() -FRIC_SUP01.Location = SYMM_FACES30 -FRIC_SUP01.Name = "Symmetry_BC" -FRIC_SUP02 = STAT_STRUC.AddFrictionlessSupport() -FRIC_SUP02.Location = FACES2 -FRIC_SUP02.Name = "Boot_Bottom_BC" -FRIC_SUP03 = STAT_STRUC.AddFrictionlessSupport() -FRIC_SUP03.Location = CYL_FACES2 -FRIC_SUP03.Name = "Boot_Radial_BC" - -# %% -# Add results -# ~~~~~~~~~~~ - -TOT_DEF = STAT_STRUC.Solution.AddTotalDeformation() -TOT_DEF.Location = RUBBER_BODIES30 - -EQV_STRS = STAT_STRUC.Solution.AddEquivalentStress() -EQV_STRS.Location = RUBBER_BODIES30 - -# %% -# Solve -# ~~~~~ - -STAT_STRUC.Solution.Solve(True) - -# sphinx_gallery_start_ignore -assert str(STAT_STRUC_SOLN.Status) == "Done", "Solution status is not 'Done'" -# sphinx_gallery_end_ignore - -# %% -# Postprocessing -# ~~~~~~~~~~~~~~ -# Total deformation - - -Tree.Activate([TOT_DEF]) -Graphics.ExportImage( - os.path.join(cwd, "totaldeformation.png"), image_export_format, settings_720p -) -display_image("totaldeformation.png") - -# %% -# Equivalent stress - -Tree.Activate([EQV_STRS]) -Graphics.ExportImage( - os.path.join(cwd, "equivalent_stress.png"), image_export_format, settings_720p -) -display_image("equivalent_stress.png") - -# %% -# Total deformation animation - -animation_export_format = ( - Ansys.Mechanical.DataModel.Enums.GraphicsAnimationExportFormat.GIF -) -settings_720p = Ansys.Mechanical.Graphics.AnimationExportSettings() -settings_720p.Width = 1280 -settings_720p.Height = 720 - -TOT_DEF.ExportAnimation( - os.path.join(cwd, "totaldeformation.gif"), animation_export_format, settings_720p -) -gif = Image.open(os.path.join(cwd, "totaldeformation.gif")) -fig, ax = plt.subplots(figsize=(16, 9)) -ax.axis("off") -img = ax.imshow(gif.convert("RGBA")) - - -def update(frame): - gif.seek(frame) - img.set_array(gif.convert("RGBA")) - return [img] - - -ani = FuncAnimation( - fig, update, frames=range(gif.n_frames), interval=200, repeat=True, blit=True -) -plt.show() - - -# %% -# Cleanup -# ~~~~~~~ -# Save project - -app.save(os.path.join(cwd, "non-linear-rubber-boot-seal.mechdat")) -app.new() - -# delete example file -delete_downloads()