/
mapdl_core.py
2902 lines (2362 loc) · 97.3 KB
/
mapdl_core.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright (C) 2024 ANSYS, Inc. and/or its affiliates.
# SPDX-License-Identifier: MIT
#
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Module to control interaction with MAPDL through Python"""
import atexit
from functools import wraps
import glob
import logging
import os
import pathlib
import re
from shutil import copyfile, rmtree
from subprocess import DEVNULL, call
import tempfile
import time
from typing import TYPE_CHECKING, Any, Dict, List, Literal, Optional, Tuple, Union
from warnings import warn
import weakref
import numpy as np
from ansys.mapdl import core as pymapdl
from ansys.mapdl.core import LOG as logger
from ansys.mapdl.core import _HAS_PYVISTA
from ansys.mapdl.core.commands import (
CMD_BC_LISTING,
CMD_LISTING,
CMD_XSEL,
XSEL_DOCSTRING_INJECTION,
BoundaryConditionsListingOutput,
CommandListingOutput,
Commands,
StringWithLiteralRepr,
inject_docs,
)
from ansys.mapdl.core.errors import (
ComponentNoData,
MapdlCommandIgnoredError,
MapdlFileNotFoundError,
MapdlInvalidRoutineError,
MapdlRuntimeError,
)
from ansys.mapdl.core.inline_functions import Query
from ansys.mapdl.core.mapdl_types import MapdlFloat
from ansys.mapdl.core.misc import (
Information,
check_valid_routine,
last_created,
random_string,
requires_package,
run_as_prep7,
supress_logging,
)
if TYPE_CHECKING: # pragma: no cover
from ansys.mapdl.reader import Archive
from ansys.mapdl.core.component import ComponentManager
from ansys.mapdl.core.mapdl import MapdlBase
from ansys.mapdl.core.mapdl_geometry import Geometry, LegacyGeometry
from ansys.mapdl.core.parameters import Parameters
from ansys.mapdl.core.solution import Solution
from ansys.mapdl.core.xpl import ansXpl
if _HAS_PYVISTA:
from ansys.mapdl.core.plotting import get_meshes_from_plotter
from ansys.mapdl.core.post import PostProcessing
DEBUG_LEVELS = Literal["DEBUG", "INFO", "WARNING", "ERROR"]
VALID_DEVICES = ["PNG", "TIFF", "VRML", "TERM", "CLOSE"]
VALID_DEVICES_LITERAL = Literal[tuple(["PNG", "TIFF", "VRML", "TERM", "CLOSE"])]
VALID_FILE_TYPE_FOR_PLOT = VALID_DEVICES.copy()
VALID_FILE_TYPE_FOR_PLOT.remove("CLOSE")
VALID_FILE_TYPE_FOR_PLOT_LITERAL = Literal[tuple(VALID_FILE_TYPE_FOR_PLOT)]
_PERMITTED_ERRORS = [
r"(\*\*\* ERROR \*\*\*).*(?:[\r\n]+.*)+highly distorted.",
r"(\*\*\* ERROR \*\*\*).*[\r\n]+.*is turning inside out.",
r"(\*\*\* ERROR \*\*\*).*[\r\n]+.*The distributed memory parallel solution does not support KRYLOV method",
]
# test for png file
PNG_IS_WRITTEN_TO_FILE = re.compile(
"WRITTEN TO FILE"
) # getting the file name is buggy.
VWRITE_REPLACEMENT = """
Cannot use *VWRITE directly as a command in MAPDL
service mode. Instead, run it as ``non_interactive``.
For example:
with self.non_interactive:
self.vwrite('%s(1)' % parm_name)
self.run('(F20.12)')
"""
## Invalid commands in interactive mode.
INVAL_COMMANDS = {
"*VWR": VWRITE_REPLACEMENT,
"*CFO": "Run CFOPEN as ``non_interactive``",
"*CRE": "Create a function within python or run as non_interactive",
"*END": "Create a function within python or run as non_interactive",
"/EOF": "Unsupported command. Use ``exit`` to stop the server.",
"*ASK": "Unsupported command. Use python ``input`` instead.",
"*IF": "Use a python ``if`` or run as non_interactive",
"CMAT": "Run `CMAT` as ``non_interactive``.",
"*REP": "Run '*REPEAT' in ``non_interactive``.",
"LSRE": "Run 'LSREAD' in ``non_interactive``.",
}
## Soft-invalid commands
# Invalid commands in interactive mode but their execution is just ignored.
# The correspondent command is replaced by a comment using the command '\COM'
# and a warning is recorded in the logger
#
# This commands can still be executed in ``non_interactive`` mode or using
# ``Mapdl._run`` method.
#
# Format of the message:
# f"{CMD} is ignored: {INVAL_COMMANDS_SILENT[CMD]}.
#
# NOTE
# Obtain the command from the string supplied using
#
# string.split(',')[0].upper()
#
# This way to get the command is different from the one used in ``INVAL_COMMANDS``.
#
INVAL_COMMANDS_SILENT = {
"/NOPR": "Suppressing console output is not recommended, use ``Mute`` parameter instead. This command is disabled in interactive mode."
}
PLOT_COMMANDS = ["NPLO", "EPLO", "KPLO", "LPLO", "APLO", "VPLO", "PLNS", "PLES"]
MAX_COMMAND_LENGTH = 600 # actual is 640, but seems to fail above 620
VALID_SELECTION_TYPE_TP = Literal["S", "R", "A", "U"]
VALID_SELECTION_ENTITY_TP = Literal["VOLU", "AREA", "LINE", "KP", "ELEM", "NODE"]
GUI_FONT_SIZE = 15
def parse_to_short_cmd(command):
"""Takes any MAPDL command and returns the first 4 characters of
the command
Examples
--------
>>> parse_to_short_cmd('K,,1,0,0,')
'K'
>>> parse_to_short_cmd('VPLOT, ALL')
'VPLO'
"""
try:
short_cmd = command.split(",")[0]
return short_cmd[:4].upper()
except Exception: # pragma: no cover
return
def setup_logger(loglevel="INFO", log_file=True, mapdl_instance=None):
"""Setup logger"""
# return existing log if this function has already been called
if hasattr(setup_logger, "log"):
return setup_logger.log
else:
setup_logger.log = logger.add_instance_logger("MAPDL", mapdl_instance)
return setup_logger.log
_ALLOWED_START_PARM = [
"additional_switches",
"exec_file",
"ip",
"jobname",
"local",
"nproc",
"override",
"port",
"print_com",
"process",
"ram",
"run_location",
"start_timeout",
"timeout",
"check_parameter_names",
]
def _sanitize_start_parm(start_parm):
for each_key in start_parm:
if each_key not in _ALLOWED_START_PARM:
raise ValueError(f"The argument '{each_key}' is not recognaised.")
class _MapdlCore(Commands):
"""Contains methods in common between all Mapdl subclasses"""
def __init__(
self,
loglevel: DEBUG_LEVELS = "DEBUG",
use_vtk: Optional[bool] = None,
log_apdl: Optional[str] = None,
log_file: Union[bool, str] = False,
local: bool = True,
print_com: bool = False,
file_type_for_plots: VALID_FILE_TYPE_FOR_PLOT_LITERAL = "PNG",
**start_parm,
):
"""Initialize connection with MAPDL."""
atexit.register(self.__del__) # registering to exit properly
self._name = None # For naming the instance.
self._show_matplotlib_figures = True # for testing
self._query = None
self._exited: bool = False
self._ignore_errors: bool = False
self._apdl_log = None
self._store_commands: bool = False
self._stored_commands = []
self._response = None
self._mode = None
self._mapdl_process = None
self._launched: bool = False
self._stderr = None
self._stdout = None
self._file_type_for_plots = file_type_for_plots
self._default_file_type_for_plots = file_type_for_plots
self._version = None # cached version
if _HAS_PYVISTA:
if use_vtk is not None: # pragma: no cover
self._use_vtk = use_vtk
else:
self._use_vtk = True
else: # pragma: no cover
if use_vtk:
raise ModuleNotFoundError(
"Using the keyword argument 'use_vtk' requires having Pyvista installed."
)
else:
self._use_vtk = False
self._log_filehandler = None
self._local: bool = local
self._cleanup: bool = True
self._vget_arr_counter = 0
self._cached_routine = None
self._geometry = None
self.legacy_geometry: bool = False
self._math = None
self._krylov = None
self._on_docker = None
self._platform = None
_sanitize_start_parm(start_parm)
self._start_parm: Dict[str, Any] = start_parm
self._jobname: str = start_parm.get("jobname", "file")
self._path: Union[str, pathlib.Path] = start_parm.get("run_location", None)
self._print_com: bool = print_com # print the command /COM input.
self.check_parameter_names = start_parm.get("check_parameter_names", True)
# Setting up loggers
self._log: logging.Logger = logger.add_instance_logger(
self.name, self, level=loglevel
) # instance logger
# adding a file handler to the logger
if log_file:
if not isinstance(log_file, str):
log_file = "instance.log"
self._log.log_to_file(filename=log_file, level=loglevel)
self._log.debug("Logging set to %s", loglevel)
# Modules
from ansys.mapdl.core.parameters import Parameters
self._parameters: Parameters = Parameters(self)
from ansys.mapdl.core.solution import Solution
self._solution: Solution = Solution(self)
self._xpl: Optional[ansXpl] = None # Initialized in mapdl_grpc
from ansys.mapdl.core.component import ComponentManager
self._componentmanager: ComponentManager = ComponentManager(self)
if log_apdl:
self.open_apdl_log(log_apdl, mode="w")
self._post = PostProcessing(self)
# Wrapping listing functions for "to_array" methods
self._wrap_listing_functions()
# Wrapping XSEL commands to return ids.
self._xsel_mapdl_output = False
self._wrap_xsel_commands()
self._info = Information(self)
@property
def allow_ignore(self):
"""Invalid commands will be ignored rather than exceptions
A command executed in the wrong processor will raise an
exception when ``allow_ignore=False``. This is the default
behavior.
Examples
--------
>>> mapdl.post1()
>>> mapdl.k(1, 0, 0, 0)
Exception: K is not a recognized POST1 command, abbreviation, or macro.
Ignore these messages by setting allow_ignore=True
>>> mapdl.allow_ignore = True
2020-06-08 21:39:58,094 [INFO] : K is not a
recognized POST1 command, abbreviation, or macro. This
command will be ignored.
*** WARNING *** CP = 0.372 TIME= 21:39:58
K is not a recognized POST1 command, abbreviation, or macro.
This command will be ignored.
"""
warn(
"'allow_ignore' is being deprecated and will be removed in a future release. "
"Use ``mapdl.ignore_errors`` instead.",
DeprecationWarning,
)
return self._ignore_errors
@allow_ignore.setter
def allow_ignore(self, value):
"""Set allow ignore"""
warn(
"'allow_ignore' is being deprecated and will be removed in a future release. "
"Use ``mapdl.ignore_errors`` instead.",
DeprecationWarning,
)
self._ignore_errors = bool(value)
@property
def chain_commands(self):
"""Chain several mapdl commands.
Commands can be separated with ``"$"`` in MAPDL rather than
with a line break, so you could send multiple commands to
MAPDL with:
``mapdl.run("/PREP7$K,1,1,2,3")``
This method is merely a convenience context manager to allow
for easy chaining of PyMAPDL commands to speed up sending
commands to MAPDL.
View the response from MAPDL with :attr:`Mapdl.last_response`.
Notes
-----
Distributed Ansys cannot properly handle condensed data input
and chained commands are not permitted in distributed ansys.
Examples
--------
>>> with mapdl.chain_commands:
mapdl.prep7()
mapdl.k(1, 1, 2, 3)
"""
if self._distributed:
raise MapdlRuntimeError(
"Chained commands are not permitted in distributed ansys."
)
return self._chain_commands(self)
@property
def check_status(self):
"""Return MAPDL status.
* 'exited' if MAPDL is exited
* 'exiting' if MAPDL is exiting
* Otherwise returns 'OK'.
"""
if self.exited:
return "exited"
elif self.exiting:
return "exiting"
else:
return "OK"
@property
def components(self) -> "ComponentManager":
"""MAPDL Component manager.
Returns
-------
:class:`ansys.mapdl.core.component.ComponentManager`
Examples
--------
Check if a solution has converged.
>>> mapdl.solution.converged
"""
if self._exited: # pragma: no cover
raise MapdlRuntimeError("MAPDL exited.")
return self._componentmanager
@property
def connection(self):
"""Return the type of connection to the instance, namely: grpc, corba or console."""
return self._mode
@property
def default_file_type_for_plots(self):
"""Default file type for plots.
Use when device is not properly set, for instance when the device is closed."""
return self._default_file_type_for_plots
@default_file_type_for_plots.setter
def default_file_type_for_plots(self, value: VALID_FILE_TYPE_FOR_PLOT_LITERAL):
"""Set default file type for plots.
Used when device is not properly set, for instance when the device is closed."""
if not isinstance(value, str) or value.upper() not in VALID_FILE_TYPE_FOR_PLOT:
raise ValueError(f"'{value}' is not allowed as file output for plots.")
return self._default_file_type_for_plots
@property
@supress_logging
def directory(self) -> str:
"""
Current MAPDL directory.
Examples
--------
Directory on Linux
>>> mapdl.directory
'/tmp/ansys'
Directory on Windows
>>> mapdl.directory
'C:/temp_directory/'
Setting the directory
>>> mapdl.directory = 'C:/temp_directory/'
None
In case the directory does not exist or it is not
accessible, ``cwd`` (:func:`MapdlBase.cwd`) will raise
a warning.
"""
# always attempt to cache the path
i = 0
while (not self._path and i > 5) or i == 0:
try:
self._path = self.inquire("", "DIRECTORY")
except Exception: # pragma: no cover
pass
i += 1
if not self._path: # pragma: no cover
time.sleep(0.1)
# os independent path format
if self._path: # self.inquire might return ''.
self._path = self._path.replace("\\", "/")
# new line to fix path issue, see #416
self._path = repr(self._path)[1:-1]
else: # pragma: no cover
raise IOError(
f"The directory returned by /INQUIRE is not valid ('{self._path}')."
)
return self._path
@directory.setter
@supress_logging
def directory(self, path: Union[str, pathlib.Path]) -> None:
"""Change the directory using ``Mapdl.cwd``"""
self.cwd(path)
@property
def exited(self):
"""Return true if the MAPDL session exited"""
return self._exited
@property
def file_type_for_plots(self):
"""Returns the current file type for plotting."""
if not self._file_type_for_plots:
self._run("/show, PNG")
self._file_type_for_plots = "PNG"
return self._file_type_for_plots
@file_type_for_plots.setter
def file_type_for_plots(self, value: VALID_DEVICES_LITERAL):
"""Modify the current file type for plotting."""
if isinstance(value, str) and value.upper() in VALID_DEVICES:
self._run(
f"/show, {value.upper()}"
) # To avoid recursion we need to use _run.
self._file_type_for_plots = value.upper()
else:
raise ValueError(f"'{value}' is not allowed as file output for plots.")
@property
def force_output(self):
"""Force text output globally by turning the ``Mapdl.mute`` attribute to False
and activating text output (``/GOPR``)
You can still do changes to those inside this context.
"""
return self._force_output(self)
@property
def geometry(self) -> "Geometry":
"""Geometry information.
See :class:`ansys.mapdl.core.mapdl_geometry.Geometry`
Examples
--------
Print the current status of the geometry.
>>> print(mapdl.geometry)
MAPDL Selected Geometry
Keypoints: 8
Lines: 12
Areas: 6
Volumes: 1
Return the number of lines.
>>> mapdl.geometry.n_line
12
Return the number of areas.
>>> mapdl.geometry.n_area
6
Select a list of keypoints.
>>> mapdl.geometry.keypoint_select([1, 5, 10])
Append to an existing selection of lines.
>>> mapdl.geometry.line_select([1, 2, 3], sel_type='A')
Reselect from the existing selection of lines.
>>> mapdl.geometry.line_select([3, 4, 5], sel_type='R')
"""
if self._geometry is None:
self._geometry = self._create_geometry()
return self._geometry
@property
def ignore_errors(self) -> bool:
"""Invalid commands will be ignored rather than exceptions
Normally, any string containing "*** ERROR ***" from MAPDL
will trigger a ``MapdlRuntimeError``. Set this to ``True`` to
ignore these errors.
For example, a command executed in the wrong processor will
raise an exception when ``ignore_errors=False``.
This is the default behavior.
Examples
--------
>>> mapdl.post1()
>>> mapdl.k(1, 0, 0, 0)
Exception: K is not a recognized POST1 command, abbreviation, or macro.
Ignore these messages by setting ignore_errors=True
>>> mapdl.ignore_errors = True
2020-06-08 21:39:58,094 [INFO] : K is not a
recognized POST1 command, abbreviation, or macro. This
command will be ignored.
*** WARNING *** CP = 0.372 TIME= 21:39:58
K is not a recognized POST1 command, abbreviation, or macro.
This command will be ignored.
"""
return self._ignore_errors
@ignore_errors.setter
def ignore_errors(self, value):
self._ignore_errors = bool(value)
@property
def info(self):
"""General information"""
return self._info
@property
def is_console(self):
"""Return true if using console to connect to the MAPDL instance."""
return self._mode == "console"
@property
def is_corba(self):
"""Return true if using corba to connect to the MAPDL instance."""
return self._mode == "corba"
@property
def is_grpc(self):
"""Return true if using grpc to connect to the MAPDL instance."""
return self._mode == "grpc"
@property
def is_local(self):
"""Check if the instance is running locally or remotely."""
return self._local
@property
def jobname(self) -> str:
"""
MAPDL job name.
This is requested from the active mapdl instance.
"""
try:
self._jobname = self.inquire("", "JOBNAME")
except Exception:
pass
return self._jobname
@jobname.setter
def jobname(self, new_jobname: str):
"""Set the jobname"""
self.finish(mute=True)
self.filname(new_jobname)
self._jobname = new_jobname
@property
def on_docker(self):
"""Check if MAPDL is running on docker."""
if self._on_docker is None:
self._on_docker = self._check_on_docker()
return self._on_docker
@property
def last_response(self):
"""Returns the last response from MAPDL.
Examples
--------
>>> mapdl.last_response
'KEYPOINT 1 X,Y,Z= 1.00000 1.00000 1.00000'
"""
return self._response
@property
def launched(self):
"""Check if the MAPDL instance has been launched by PyMAPDL."""
return self._launched
@property
def logger(self) -> logging.Logger:
return self._log
@property
def mesh(self):
"""Mesh information.
Returns
-------
:class:`Mapdl.Mesh <ansys.mapdl.core.mesh_grpc.Mesh>`
Examples
--------
Return an array of the active nodes
>>> mapdl.mesh.nodes
array([[ 1., 0., 0.],
[ 2., 0., 0.],
[ 3., 0., 0.],
[ 4., 0., 0.],
[ 5., 0., 0.],
[ 6., 0., 0.],
[ 7., 0., 0.],
[ 8., 0., 0.],
[ 9., 0., 0.],
[10., 0., 0.]])
Return an array of the node numbers of the active nodes
>>> mapdl.mesh.nnum
array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=int32)
Simply query and print the geometry
>>> print(mapdl.mesh)
ANSYS Mapdl Mesh
Number of Nodes: 321
Number of Elements: 40
Number of Element Types: 1
Number of Node Components: 2
Number of Element Components: 2
Access the geometry as a VTK object
>>> mapdl.mesh.grid
"""
return self._mesh
@property
def name(self) -> str:
raise NotImplementedError("Implemented by child classes.")
@name.setter
def name(self, name) -> None:
raise AttributeError("The name of an instance cannot be changed.")
@property
def non_interactive(self):
"""Non-interactive context manager.
Allow to execute code without user interaction or waiting
between PyMAPDL responses.
It can also be used to execute some commands which are not
supported in interactive mode. For a complete list of commands
visit :ref:`ref_unsupported_interactive_commands`.
View the last response with :attr:`Mapdl.last_response` method.
Notes
-----
All the commands executed inside this context manager are not
executed until the context manager exits which then execute them
all at once in the MAPDL instance.
This command uses :func:`Mapdl.input() <ansys.mapdl.core.Mapdl.input>`
method.
Examples
--------
Use the non-interactive context manager for the VWRITE (
:func:`Mapdl.vwrite() <ansys.mapdl.core.Mapdl.vwrite>`)
command.
>>> with mapdl.non_interactive:
... mapdl.run("*VWRITE,LABEL(1),VALUE(1,1),VALUE(1,2),VALUE(1,3)")
... mapdl.run("(1X,A8,' ',F10.1,' ',F10.1,' ',1F5.3)")
>>> mapdl.last_response
"""
return self._non_interactive(self)
@property
def parameters(self) -> "Parameters":
"""Collection of MAPDL parameters.
Notes
-----
See :ref:`ref_special_named_param` for additional notes regarding parameter naming in MAPDL.
Examples
--------
Simply list all parameters except for MAPDL MATH parameters.
>>> mapdl.parameters
ARR : ARRAY DIM (3, 1, 1)
PARM_FLOAT : 20.0
PARM_INT : 10.0
PARM_LONG_STR : "stringstringstringstringstringst"
PARM_STR : "string"
PORT : 50052.0
Get a parameter
>>> mapdl.parameters['PARM_FLOAT']
20.0
Get an array parameter
>>> mapdl.parameters['ARR']
array([1., 2., 3.])
"""
return self._parameters
@property
def platform(self):
"""Return the platform where MAPDL is running."""
if self._platform is None:
self._check_mapdl_os()
return self._platform
@property
def post_processing(self) -> "PostProcessing":
"""Post-process an active MAPDL session.
Examples
--------
Get the nodal displacement in the X direction for the first
result set.
>>> mapdl.set(1, 1)
>>> disp_x = mapdl.post_processing.nodal_displacement('X')
array([1.07512979e-04, 8.59137773e-05, 5.70690047e-05, ...,
5.70333124e-05, 8.58600402e-05, 1.07445726e-04])
"""
if self._exited:
raise MapdlRuntimeError(
"MAPDL exited.\n\nCan only postprocess a live " "MAPDL instance."
)
return self._post
@property
def print_com(self):
return self._print_com
@print_com.setter
def print_com(self, value):
if isinstance(value, bool):
status = "activated" if value else "deactivated"
self._log.debug(f"The print of '/COM' commands has been {status}.")
self._print_com = value
else:
raise ValueError(
f"The property ``print_com`` only allows booleans, but type {type(value)} was supplied."
)
@property
def queries(self):
"""Get instance of Query class containing inline functions of APDL.
Most of the results of these methods are shortcuts for specific
combinations of arguments supplied to :func:`ansys.mapdl.core.Mapdl.get`.
Currently implemented functions:
- ``centrx(e)`` - get the centroid x-coordinate of element `e`
- ``centry(e)`` - get the centroid y-coordinate of element `e`
- ``centrz(e)`` - get the centroid z-coordinate of element `e`
- ``nx(n)`` - get the x-coordinate of node `n`
- ``ny(n)`` - get the y-coordinate of node `n`
- ``nz(n)`` - get the z-coordinate of node `n`
- ``kx(k)`` - get the x-coordinate of keypoint `k`
- ``ky(k)`` - get the y-coordinate of keypoint `k`
- ``kz(k)`` - get the z-coordinate of keypoint `k`
- ``lx(n, lfrac)`` - X-coordinate of line ``n`` at length fraction ``lfrac``
- ``ly(n, lfrac)`` - Y-coordinate of line ``n`` at length fraction ``lfrac``
- ``lz(n, lfrac)`` - Z-coordinate of line ``n`` at length fraction ``lfrac``
- ``lsx(n, lfrac)`` - X-slope of line ``n`` at length fraction ``lfrac``
- ``lsy(n, lfrac)`` - Y-slope of line ``n`` at length fraction ``lfrac``
- ``lsz(n, lfrac)`` - Z-slope of line ``n`` at length fraction ``lfrac``
- ``ux(n)`` - get the structural displacement at node `n` in x
- ``uy(n)`` - get the structural displacement at node `n` in y
- ``uz(n)`` - get the structural displacement at node `n` in z
- ``rotx(n)`` - get the rotational displacement at node `n` in x
- ``roty(n)`` - get the rotational displacement at node `n` in y
- ``rotz(n)`` - get the rotational displacement at node `n` in z
- ``nsel(n)`` - get the selection status of node `n`
- ``ksel(k)`` - get the selection status of keypoint `k`
- ``lsel(n)`` - get the selection status of line `n`
- ``asel(a)`` - get the selection status of area `a`
- ``esel(n)`` - get the selection status of element `e`
- ``vsel(v)`` - get the selection status of volume `v`
- ``ndnext(n)`` - get the next selected node with a number greater than `n`.
- ``kpnext(k)`` - get the next selected keypoint with a number greater than `k`.
- ``lsnext(n)`` - get the next selected line with a number greater than `n`.
- ``arnext(a)`` - get the next selected area with a number greater than `a`.
- ``elnext(e)`` - get the next selected element with a number greater than `e`.
- ``vlnext(v)`` - get the next selected volume with a number greater than `v`.
- ``node(x, y, z)`` - get the node closest to coordinate (x, y, z)
- ``kp(x, y, z)`` - get the keypoint closest to coordinate (x, y, z)
Returns
-------
:class:`ansys.mapdl.core.inline_functions.Query`
Instance of the Query class
Examples
--------
In this example we construct a solid box and mesh it. Then we use
the ``Query`` methods ``nx``, ``ny``, and ``nz`` to find the
cartesian coordinates of the first node.
>>> from ansys.mapdl.core import launch_mapdl
>>> mapdl = launch_mapdl()
>>> mapdl.prep7()
>>> mapdl.et(1, 'SOLID5')
>>> mapdl.block(0, 10, 0, 20, 0, 30)
>>> mapdl.esize(2)
>>> mapdl.vmesh('ALL')
>>> q = mapdl.queries
>>> q.nx(1), q.ny(1), q.nz(1)
0.0 20.0 0.0
"""
if self._query is None:
self._query = Query(self)
return self._query
@property
def save_selection(self):
"""Save selection
Save the current selection (nodes, elements, keypoints, lines, areas,
volumes and components) before entering in the context manager, and
when exit returns to that selection.
"""
return self._save_selection(self)
@property
def solution(self) -> "Solution":
"""Solution parameters of MAPDL.
Returns
-------
:class:`ansys.mapdl.core.solution.Solution`
Examples
--------
Check if a solution has converged.
>>> mapdl.solution.converged
"""
if self._exited:
raise MapdlRuntimeError("MAPDL exited.")
return self._solution
@property
def use_vtk(self):
"""Returns if using VTK by default or not."""
return self._use_vtk
@use_vtk.setter
def use_vtk(self, value: bool):
"""Set VTK to be used by default or not."""
self._use_vtk = value
@property
@requires_package("ansys.mapdl.reader", softerror=True)
def result(self):
"""Binary interface to the result file using :class:`ansys.mapdl.reader.rst.Result`.
Returns
-------
:class:`ansys.mapdl.reader.rst.Result`.
Result reader class. See `Legacy PyMAPDL Reader <https://readerdocs.pyansys.com/>`.
Examples
--------
>>> mapdl.solve()
>>> mapdl.finish()
>>> result = mapdl.result
>>> print(result)
PyMAPDL-Reader Result file object
Units : User Defined
Version : 18.2
Cyclic : False
Result Sets : 1
Nodes : 3083
Elements : 977
...