def __enter__(self): # TODO: Add exception handling for lock file conflict if isinstance(self.launch_options, dict): if "run_location" in self.launch_options: Path(self.launch_options["run_location"]).mkdir(parents=True, exist_ok=True) self.ansys = launch_mapdl(**self.launch_options) else: self.ansys = launch_mapdl() setattr(self.ansys, "pymapdl_version", ansys.mapdl.core.__version__) print(self.ansys) return self.ansys
def main(): mapdl = launch_mapdl() examples.vmfiles print(mapdl) mapdl.units("SI") # only for documentation - no influence on FEA # clear any potential data from previous FEA, and set element type and material data reset_mapdl(mapdl) # create geometry for beam create_geometry_v1(mapdl, segments=77) # crash for segments > 77 #plot_geometry(mapdl) # set E and Poisson ratio set_material(mapdl) # set bounding conditions set_boundary_conditions_v1(mapdl) mapdl.slashsolu() mapdl.antype("static") mapdl.solve() plot_results(mapdl) mapdl.exit() return
def mapdl_console(request): if os.name != "posix": raise RuntimeError('"--console" testing option unavailable. ' "Only Linux is supported.") ansys_base_paths = _get_available_base_ansys() # find a valid version of corba console_path = None for version in ansys_base_paths: if version < 211: console_path = get_ansys_bin(str(version)) if console_path is None: raise RuntimeError( '"--console" testing option unavailable.' "No local console compatible MAPDL installation found. " "Valid versions are up to 2020R2.") mapdl = launch_mapdl(console_path) from ansys.mapdl.core.mapdl_console import MapdlConsole assert isinstance(mapdl, MapdlConsole) mapdl._show_matplotlib_figures = False # CI: don't show matplotlib figures # using yield rather than return here to be able to test exit yield mapdl # verify mapdl exits mapdl.exit() assert mapdl._exited assert "MAPDL exited" in str(mapdl) with pytest.raises(MapdlExitedError): mapdl.prep7()
def mapdl_corba(request): ansys_base_paths = _get_available_base_ansys() # find a valid version of corba corba_path = None for version in ansys_base_paths: if version >= 170 and version < 202: corba_path = get_ansys_bin(str(version)) if corba_path is None: raise RuntimeError( '"-corba" testing option unavailable.' "No local CORBA compatible MAPDL installation found. " "Valid versions are ANSYS 17.0 up to 2020R2.") mapdl = launch_mapdl(corba_path) from ansys.mapdl.core.mapdl_corba import MapdlCorba assert isinstance(mapdl, MapdlCorba) mapdl._show_matplotlib_figures = False # CI: don't show matplotlib figures # using yield rather than return here to be able to test exit yield mapdl # verify mapdl exits mapdl.exit() assert mapdl._exited assert "MAPDL exited" in str(mapdl) with pytest.raises(MapdlExitedError): mapdl.prep7()
def ansys(tmp_path_factory): path = tmp_path_factory.getbasetemp() mapdl = launch_mapdl(override=True, interactive_plotting=True, run_location=path, loglevel='ERROR') yield mapdl # ansys.open_gui() mapdl.exit()
def test_launch_corba(version): mapdl = pymapdl.launch_mapdl(get_ansys_bin(version), mode="corba") assert mapdl.version == int(version) / 10 # mapdl.exit() # exit is already tested for in test_mapdl.py. # Instead, test collection mapdl_ref = weakref.ref(mapdl) del mapdl assert mapdl_ref() is None
def mapdl(request, tmpdir_factory): # don't use the default run location as tests run multiple unit testings run_path = str(tmpdir_factory.mktemp("ansys")) # don't allow mapdl to exit upon collection unless mapdl is local cleanup = START_INSTANCE if request.param: # usage of a just closed channel on same port causes connectivity issues port = MAPDL_DEFAULT_PORT + 10 else: port = MAPDL_DEFAULT_PORT mapdl = launch_mapdl(EXEC_FILE, override=True, run_location=run_path, cleanup_on_exit=cleanup) mapdl._show_matplotlib_figures = False # CI: don't show matplotlib figures if HAS_GRPC: mapdl._local = request.param # CI: override for testing if mapdl._local: assert Path(mapdl.directory) == Path(run_path) assert mapdl._distributed # using yield rather than return here to be able to test exit yield mapdl ########################################################################### # test exit: only when allowed to start PYMAPDL ########################################################################### if START_INSTANCE: mapdl._local = True mapdl.exit() assert mapdl._exited assert "MAPDL exited" in str(mapdl) if mapdl._local: assert not os.path.isfile(mapdl._lockfile) # should test if _exited protects from execution with pytest.raises(MapdlExitedError): mapdl.prep7() # actually test if server is shutdown if HAS_GRPC: with pytest.raises(MapdlExitedError): mapdl._send_command("/PREP7") with pytest.raises(MapdlExitedError): mapdl._send_command_stream("/PREP7") # verify PIDs are closed time.sleep(1) # takes a second for the processes to shutdown for pid in mapdl._pids: assert not check_pid(pid)
def _spawn_mapdl(self, index, port=None, pbar=None): """Spawn a mapdl instance at an index""" # create a new temporary directory for each instance run_location = create_temp_dir(self._root_dir) self._instances[index] = launch_mapdl(run_location=run_location, port=port, **self._spawn_kwargs) LOG.debug('Spawned instance: %d', index) if pbar is not None: pbar.update(1)
def test_check_license_file(tmpdir): timeout = 15 checker = licensing.LicenseChecker(verbose=True, timeout=timeout) # start the license check in the background checker.start(checkout_license=False) try: mapdl = launch_mapdl(license_server_check=False, start_timeout=timeout) assert mapdl._local mapdl.exit() except IOError: # MAPDL never started assert not checker._license_file_success else: assert checker._license_file_success
def CombineRSTResults(wdir, jobname, numFiles): ''' Combines distributed RST files to one huge RST file This works when the solution is terminated due to error or other reasons. ''' mapdl = launch_mapdl(nproc=numFiles, jobname=jobname, run_location=wdir, override=True) mapdl.aux2() mapdl.combine('rst') mapdl.exit() pass
def mapdl(request): """This fixture will only be called if ``ansys.mapdl.core`` is installed.""" from ansys.mapdl.core import launch_mapdl from ansys.mapdl.core.misc import get_ansys_bin from ansys.mapdl.core.launcher import get_start_instance # check if the user wants to permit pytest to start MAPDL # and don't allow mapdl to exit upon collection unless mapdl is local cleanup = get_start_instance() # check for a valid MAPDL install with gRPC valid_rver = ['211'] # checks in this order EXEC_FILE = None for rver in valid_rver: if os.path.isfile(get_ansys_bin(rver)): EXEC_FILE = get_ansys_bin(rver) break return launch_mapdl(EXEC_FILE, override=True, cleanup_on_exit=cleanup)
# import pyansys # pyansys.convert_script('../APDL/apdl_disp_pump_bytime.txt', 'pump.py') from ansys.mapdl.core import launch_mapdl exec_loc = r'C:\Program Files\ANSYS Inc\v211\ansys\bin\winx64\ANSYS211.exe' mapdl = launch_mapdl(exec_loc) print(mapdl)
def test_old_version(): exec_file = get_ansys_bin("150") with pytest.raises(ValueError): pymapdl.launch_mapdl(exec_file, mode="corba")
def test_invalid_mode(): with pytest.raises(ValueError): exec_file = get_ansys_bin(valid_versions[0]) pymapdl.launch_mapdl(exec_file, mode="notamode")
def compare_apdl_barfem(nodes_pos, edges_indices, edges_thickness, input_nodes, input_vectors, frozen_nodes, tmax=100000, eps=1.0e-11, mode="force"): # C言語を用いたbarfem displacement = barfem(nodes_pos, edges_indices, edges_thickness, input_nodes, input_vectors, frozen_nodes, mode=mode, tmax=tmax, eps=eps) # APDLの設定 mapdl = launch_mapdl() mapdl.finish() mapdl.clear() mapdl.prep7() # 材料物性値の設定 mapdl.et(1, 3) mapdl.mp("ex", 1, 1) # ヤング率 mapdl.mp("prxy", 1, 0.3) # ポアソン比 mapdl.mat(1) # 節点部分の設定 for i, node_pos in enumerate(nodes_pos): mapdl.n(i + 1, node_pos[0], node_pos[1], 0) # エッジ部分の設定 for i, edges_indice in enumerate(edges_indices): b = 0.2 # 奥行 h = edges_thickness[i] mapdl.r(i + 1, b * h, b * (h * h**2) / 12, h, 0) # A,I,height=y方向の長さ,SHEARZ mapdl.real(i + 1) mapdl.e(edges_indice[0] + 1, edges_indice[1] + 1) mapdl.finish() mapdl.run('/solu') mapdl.antype('static') # 解析条件設定 # 固定ノード設定 for i in frozen_nodes: mapdl.d(i + 1, "all", 0) # 外力設定 for i, input_vector in enumerate(input_vectors): if mode == "displacement": mapdl.d(input_nodes[i] + 1, "UX", input_vector[0]) mapdl.d(input_nodes[i] + 1, "UY", input_vector[1]) else: mapdl.f(input_nodes[i] + 1, "FX", input_vector[0]) mapdl.f(input_nodes[i] + 1, "FY", input_vector[1]) # 解析開始 mapdl.solve() mapdl.finish() # 結果出力 x_disp = mapdl.post_processing.nodal_displacement('X') y_disp = mapdl.post_processing.nodal_displacement('Y') z_rot = mapdl.post_processing.nodal_rotation('Z') ansys_disp = np.stack([x_disp, y_disp, z_rot]).T.flatten() #result = mapdl.result #nnum, principal_nodal_stress = result.principal_nodal_stress(0) # von_mises = principal_nodal_stress[:, -1] # von-Mises stress is the right most column # print(von_mises) # print(np.max(von_mises)) mapdl.exit() # ポート番号などをリセットするために必要 # 厳密には少し小さい値の部分が異なる為,allclose構文を利用 return np.allclose(ansys_disp, displacement)
def test_launch_console(version): exec_file = get_ansys_bin(version) mapdl = pymapdl.launch_mapdl(exec_file, mode="console") assert mapdl.version == int(version) / 10
def test_failed_console(): exec_file = get_ansys_bin(valid_versions[0]) with pytest.raises(ValueError): pymapdl.launch_mapdl(exec_file, mode="console")
import os import numpy as np from ansys.mapdl.core import launch_mapdl if __name__ == '__main__': tmp_dir = os.path.join(os.getcwd(), 'tmp') if not os.path.exists(tmp_dir): os.mkdir(tmp_dir) mapdl = launch_mapdl(run_location=tmp_dir, override=True) print(mapdl) # Geometry and Material Properties mapdl.prep7() mapdl.mp('kxx', 1, 45) mapdl.et(1, 90) mapdl.block(-0.3, 0.3, -0.46, 1.34, -0.2, -0.2 + 0.02) mapdl.vsweep(1) # mapdl.eplot() # Boundary Conditions mapdl.asel('S', vmin=3) mapdl.nsla() mapdl.d('all', 'temp', 5) mapdl.asel('S', vmin=4) mapdl.nsla() mapdl.d('all', 'temp', 100) out = mapdl.allsel() # Solve
""" .. _ref_contact_example: Contact Element Example ~~~~~~~~~~~~~~~~~~~~~~~ This example demonstrates how to create contact elements for general contact. Begin by launching MAPDL. """ from ansys.mapdl import core as pymapdl mapdl = pymapdl.launch_mapdl() ############################################################################### # Enter the pre-processor, create a block and mesh it with tetrahedral # elements. # mapdl.prep7() vnum0 = mapdl.block(0, 1, 0, 1, 0, 0.5) mapdl.et(1, 187) mapdl.esize(0.1) mapdl.vmesh(vnum0) mapdl.eplot() ###############################################################################
---------------------------------------- This tutorial shows how you can use pyansys and MAPDL to interpolate along a path for stress. This shows some advanced features of the `pyvista` module to perform the interpolation. First, start MAPDL as a service and disable all but error messages. """ # sphinx_gallery_thumbnail_number = 3 import numpy as np import pyvista as pv import matplotlib.pyplot as plt from ansys.mapdl.core import launch_mapdl mapdl = launch_mapdl(loglevel='ERROR') ############################################################################### # MAPDL: Solve a Beam with a Non-Uniform Load # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Create a beam, apply a load, and solve for the static solution. # beam dimensions _width = 0.5 _height = 2 _length = 10 # simple 3D beam mapdl.clear() mapdl.prep7() mapdl.mp("EX", 1, 70000)
"""Import the CDB database, setup modal analysis and run it.""" from ansys.mapdl.core import launch_mapdl mapdl = launch_mapdl(override=True, additional_switches="-smp") filename = "archive.cdb" mapdl.cdread("db", filename) mapdl.save() # verify cells are valid mapdl.prep7() mapdl.shpp("SUMM") # specify material properties # using aprox values for AISI 5000 Series Steel mapdl.units("SI") mapdl.mp("EX", 1, 200e9) # Elastic moduli in Pa (kg/(m*s**2)) mapdl.mp("DENS", 1, 7700) # Density in kg/m3 mapdl.mp("NUXY", 1, 0.3) # Poissons Ratio mapdl.et(1, 181) # ! ET,1,SHELL181 ! SHELL181 mapdl.keyopt( 1, 3, 2 ) # ! Option for the shell. Integration option: 'Full integration with incompatible modes' mapdl.sectype(1, "SHELL") mapdl.secdata(1, 1, 0, 3) # ! which means: SECDATA,TK, MAT, THETA, NUMPT, LayerName mapdl.emodif("ALL", "MAT", 1) # ! Setting material id mapdl.emodif("ALL", "REAL", 1) # ! Setting real constant # By setting the section type (`SECTYPE`) the model will run and solve.
nodalFile = 'nodalData.inp' wdir = 'D:\\Basil\\Deformation_Comp\\Hao\\CD4\\' nodalFileIt = '' rstFile = '' # Backup Original Nodal Information nodalNameOnly = os.path.splitext(nodalFile)[0] nodalExtOnly = os.path.splitext(nodalFile)[1] backupFile = nodalNameOnly + "_ORIG" + nodalExtOnly backupNodalInfo = shutil.copyfile(wdir + nodalFile, wdir + backupFile) # STORE ORIGINAL GEOMETRY CONFIGURATION AS TARGET targetNodes = GetNodalData( wdir + backupFile) # Load the solver's server mapdl = launch_mapdl(run_location=wdir,jobname='file', nproc=2) # rstFile = FullPath('file.rst', wdir) # Run Iteration, # Iterate(mapdl, target, errTol = 1e-5, maxItn=10, wdir='', mainFile ='') Iterate(mapdl, targetNodes,1e-5,5,wdir, mainFile) mapdl.exit() # Close the APDL ## EXPORT DEFORMED GEOMETRY ## COMPARE SOLUTION ## CONVERGED SOLUTION ### EXPORT PRE-DEFORMED GEOMETRY
------------------------------------- Use APDLMath to solve eigenproblems. This example uses a verification manual input file, but you can use your own sparse or dense matrices and solve those. """ import matplotlib.pylab as plt import time import numpy as np from ansys.mapdl.core.examples import vmfiles from ansys.mapdl.core import launch_mapdl # Start MAPDL as a service and create an APDLMath object mapdl = launch_mapdl(loglevel="ERROR") mm = mapdl.math ############################################################################### # First we get the `STIFF` and `MASS` matrices from the full file # after running the input file from Verification Manual 153 # out = mapdl.input(vmfiles["vm153"]) k = mm.stiff(fname="PRSMEMB.full") m = mm.mass(fname="PRSMEMB.full") ############################################################################### # Display size of the M and K matrices print(m.shape) print(k.shape)
""" # 単体実行用 max_free_node_num = 1 free_nodes_num = np.arange(max_free_node_num, max_free_node_num + 1) fix_nodes_num = np.ones(free_nodes_num.shape, dtype=np.int) * 8 experient_num = 1 if __name__ == "__main__": # define the problem definition save_dir = "GA/result" generation = 1 save_interval = 1 parent_mult_value = 10 # 遺伝子個数に対する親の個数の比率 mapdl = launch_mapdl() # PATH = os.path.join(save_dir, "parent_{}_gen_{}".format(parent, generation)) # os.makedirs(PATH, exist_ok=False) for t in range(experient_num): PATH = os.path.join(save_dir, "test_{}".format(t)) os.makedirs(PATH, exist_ok=True) start = time.time() # instantiate the optimization algorithm to run in parallel for index, (free_node_num, fix_node_num) in enumerate( zip(free_nodes_num, fix_nodes_num)): problem = Ansys_GA(mapdl, free_node_num, fix_node_num) parent = problem.nvars * parent_mult_value #parent = 1 print(parent)
def test_grpc_custom_ip(): ip = '127.0.0.2' mapdl = launch_mapdl(ip=ip) assert mapdl._ip == ip