-
Notifications
You must be signed in to change notification settings - Fork 127
/
Copy pathmapdl.py
2658 lines (2163 loc) · 88 KB
/
mapdl.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
"""Module to control interaction with MAPDL through Python"""
import time
import glob
import re
import os
import logging
import tempfile
from shutil import rmtree, copyfile
import weakref
import warnings
import pathlib
from warnings import warn
from functools import wraps
import numpy as np
from ansys.mapdl import core as pymapdl
from ansys.mapdl.core.misc import (
random_string,
supress_logging,
run_as_prep7,
last_created,
)
from ansys.mapdl.core.errors import MapdlRuntimeError, MapdlInvalidRoutineError
from ansys.mapdl.core.plotting import general_plotter
from ansys.mapdl.core.post import PostProcessing
from ansys.mapdl.core.commands import Commands
from ansys.mapdl.core.inline_functions import Query
from ansys.mapdl.core import LOG as logger
from ansys.mapdl.reader.rst import Result
_PERMITTED_ERRORS = [
r"(\*\*\* ERROR \*\*\*).*(?:[\r\n]+.*)+highly distorted.",
r"(\*\*\* ERROR \*\*\*).*[\r\n]+.*is turning inside out.",
]
# test for png file
PNG_TEST = re.compile("WRITTEN TO FILE(.*).png")
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``."
}
## 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
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
class _MapdlCore(Commands):
"""Contains methods in common between all Mapdl subclasses"""
def __init__(self, loglevel='DEBUG', use_vtk=True, log_apdl=None,
log_file=False, local=True, **start_parm):
"""Initialize connection with MAPDL."""
self._show_matplotlib_figures = True # for testing
self._query = None
self._exited = False
self._allow_ignore = False
self._apdl_log = None
self._store_commands = False
self._stored_commands = []
self._response = None
self._use_vtk = use_vtk
self._log_filehandler = None
self._version = None # cached version
self._local = local
self._jobname = start_parm.get("jobname", "file")
self._cleanup = True
self._vget_arr_counter = 0
self._start_parm = start_parm
self._path = start_parm.get("run_location", None)
self._ignore_errors = False
# Setting up loggers
self._log = 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)
from ansys.mapdl.core.parameters import Parameters
self._parameters = Parameters(self)
from ansys.mapdl.core.solution import Solution
self._solution = Solution(self)
if log_apdl:
self.open_apdl_log(log_apdl, mode='w')
self._post = PostProcessing(self)
@property
def _name(self): # pragma: no cover
"""Implemented by child class"""
raise NotImplementedError("Implemented by child class")
@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 non_interactive(self):
"""Non-interactive context manager.
Use this when using commands that require user
interaction within MAPDL (e.g. :func:`Mapdl.vwrite`).
Examples
--------
Use the non-interactive context manager for the VWRITE
command. View the last response with :attr:`Mapdl.last_response`.
>>> 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 solution(self):
"""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 RuntimeError("MAPDL exited.")
return self._solution
@property
def _distributed(self):
"""MAPDL is running in distributed mode."""
return "-smp" not in self._start_parm.get("additional_switches", "")
@property
def post_processing(self):
"""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 RuntimeError(
"MAPDL exited.\n\nCan only postprocess a live " "MAPDL instance."
)
return self._post
@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 RuntimeError(
"chained commands are not permitted in distributed ansys."
)
return self._chain_commands(self)
def _chain_stored(self):
"""Send a series of commands to MAPDL"""
# there's to be an limit to 640 characters per command, so
# when chaining commands they must be shorter than 640 (minus
# some overhead).
c = 0
chained_commands = []
chunk = []
for command in self._stored_commands:
len_command = len(command) + 1 # include sep var
if len_command + c > MAX_COMMAND_LENGTH:
chained_commands.append("$".join(chunk))
chunk = [command]
c = 0
else:
chunk.append(command)
c += len_command
# join the last
chained_commands.append("$".join(chunk))
self._stored_commands = []
responses = [self._run(command) for command in chained_commands]
self._response = "\n".join(responses)
@property
def parameters(self):
"""Collection of MAPDL parameters obtainable from the ``*GET`` command or ``GET`` command.
Returns
-------
:class:`ansys.mapdl.core.parameters.Parameters`
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.])
Get the current routine
>>> mapdl.parameters.routine
'PREP7'
>>> mapdl.parameters.units
'SI'
>>> mapdl.parameters.csys
0
"""
return self._parameters
class _non_interactive:
"""Allows user to enter commands that need to run non-interactively."""
def __init__(self, parent):
self._parent = weakref.ref(parent)
def __enter__(self):
self._parent()._log.debug("Entering non-interactive mode")
self._parent()._store_commands = True
def __exit__(self, *args):
self._parent()._log.debug("Entering non-interactive mode")
self._parent()._flush_stored()
class _chain_commands:
"""Store MAPDL commands and send one chained command."""
def __init__(self, parent):
self._parent = weakref.ref(parent)
def __enter__(self):
self._parent()._log.debug("Entering chained command mode")
self._parent()._store_commands = True
def __exit__(self, *args):
self._parent()._log.debug("Entering chained command mode")
self._parent()._chain_stored()
self._parent()._store_commands = False
@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
def clear(self, *args, **kwargs):
"""Clear the database.
APDL Command: ``/CLEAR``
Resets the ANSYS database to the conditions at the beginning
of the problem. Sets the import and Boolean options back to
the ANSYS default. All items are deleted from the database and
memory values are set to zero for items derived from database
information. All files are left intact. This command is
useful between multiple analyses in the same run, or between
passes of a multi-pass analysis (such as between the
substructure generation, use, and expansion passes). Should
not be used in a do-loop since loop counters will be reset.
on the same line as the ``/CLEAR`` command.
``/CLEAR`` resets the jobname to match the currently open
session .LOG and .ERR files. This will return the jobname to
its original value, or to the most recent value specified on
``/FILNAME`` with KEY = 1.
This command is valid only at the Begin level.
Examples
--------
>>> mapdl.clear()
"""
self.run("/CLE,NOSTART", mute=True)
@supress_logging
def __str__(self):
try:
if self._exited:
return "MAPDL exited"
stats = self.slashstatus("PROD")
except Exception: # pragma: no cover
return "MAPDL exited"
st = stats.find("*** Products ***")
en = stats.find("*** PrePro")
product = "\n".join(stats[st:en].splitlines()[1:]).strip()
# get product version
stats = self.slashstatus("TITLE")
st = stats.find("RELEASE")
en = stats.find("INITIAL", st)
mapdl_version = stats[st:en].split("CUSTOMER")[0].strip()
info = [f"Product: {product}"]
info.append(f"MAPDL Version: {mapdl_version}")
info.append(f"PyMAPDL Version: {pymapdl.__version__}\n")
return "\n".join(info)
@property
def geometry(self):
"""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')
"""
return self._geometry
@property
def _geometry(self): # pragma: no cover
"""Return geometry cache"""
from ansys.mapdl.core.mapdl_geometry import Geometry
return Geometry(self)
@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
@supress_logging
def _mesh(self):
"""Write entire archive to ASCII and read it in as an
``ansys.mapdl.core.Archive``"""
# lazy import here to avoid loading pyvista and vtk
from ansys.mapdl.reader import Archive
if self._archive_cache is None:
# write database to an archive file
arch_filename = os.path.join(self.directory, "_tmp.cdb")
nblock_filename = os.path.join(self.directory, "nblock.cdb")
# must have all nodes elements are using selected
if hasattr(self, "mute"):
old_mute = self.mute
self.mute = True
self.cm("__NODE__", "NODE", mute=True)
self.nsle("S", mute=True)
self.cdwrite("db", arch_filename, mute=True)
self.cmsel("S", "__NODE__", "NODE", mute=True)
self.cm("__ELEM__", "ELEM", mute=True)
self.esel("NONE", mute=True)
self.cdwrite("db", nblock_filename, mute=True)
self.cmsel("S", "__ELEM__", "ELEM", mute=True)
if hasattr(self, "mute"):
self.mute = old_mute
self._archive_cache = Archive(arch_filename, parse_vtk=False, name="Mesh")
grid = self._archive_cache._parse_vtk(additional_checking=True)
self._archive_cache._grid = grid
# rare bug
if grid is not None:
if grid.n_points != self._archive_cache.n_node:
self._archive_cache = Archive(
arch_filename, parse_vtk=True, name="Mesh"
)
# overwrite nodes in archive
nblock = Archive(nblock_filename, parse_vtk=False)
self._archive_cache._nodes = nblock._nodes
self._archive_cache._nnum = nblock._nnum
self._archive_cache._node_coord = None
return self._archive_cache
def _reset_cache(self):
"""Reset cached items"""
self._archive_cache = None
@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.
"""
return self._allow_ignore
@allow_ignore.setter
def allow_ignore(self, value):
"""Set allow ignore"""
self._allow_ignore = bool(value)
def open_apdl_log(self, filename, mode="w"):
"""Start writing all APDL commands to an MAPDL input file.
Parameters
----------
filename : str
Filename of the log.
mode : str, optional
Python file modes (for example, ``'a'``, ``'w'``). Should
be either write or append.
Examples
--------
Begin writing APDL commands to ``"log.inp"``.
>>> mapdl.open_apdl_log("log.inp")
"""
if self._apdl_log is not None:
raise RuntimeError("APDL command logging already enabled")
self._log.debug("Opening ANSYS log file at %s", filename)
if mode not in ["w", "a", "x"]:
raise ValueError("File mode should either be write, append, or exclusive"
" creation ('w', 'a', or 'x').")
self._apdl_log = open(filename, mode=mode, buffering=1) # line buffered
self._apdl_log.write(
"! APDL script generated using ansys.mapdl.core {pymapdl.__version__}\n"
)
@supress_logging
@run_as_prep7
def _generate_iges(self):
"""Save IGES geometry representation to disk"""
filename = os.path.join(self.directory, "_tmp.iges")
self.igesout(filename, att=1, mute=True)
return filename
def open_gui(self, include_result=True): # pragma: no cover
"""Saves existing database and opens up the APDL GUI.
Parameters
----------
include_result : bool, optional
Allow the result file to be post processed in the GUI.
Examples
--------
>>> from ansys.mapdl.core import launch_mapdl
>>> mapdl = launch_mapdl()
Create a square area using keypoints
>>> mapdl.prep7()
>>> mapdl.k(1, 0, 0, 0)
>>> mapdl.k(2, 1, 0, 0)
>>> mapdl.k(3, 1, 1, 0)
>>> mapdl.k(4, 0, 1, 0)
>>> mapdl.l(1, 2)
>>> mapdl.l(2, 3)
>>> mapdl.l(3, 4)
>>> mapdl.l(4, 1)
>>> mapdl.al(1, 2, 3, 4)
Open up the gui
>>> mapdl.open_gui()
Resume where you left off
>>> mapdl.et(1, 'MESH200', 6)
>>> mapdl.amesh('all')
>>> mapdl.eplot()
"""
# lazy load here to avoid circular import
from ansys.mapdl.core.launcher import get_ansys_path
if not self._local:
raise RuntimeError(
"``open_gui`` can only be called from a local " "MAPDL instance"
)
# specify a path for the temporary database
temp_dir = tempfile.gettempdir()
save_path = os.path.join(temp_dir, f"ansys_{random_string(10)}")
if os.path.isdir(save_path):
rmtree(save_path)
os.mkdir(save_path)
name = "tmp"
tmp_database = os.path.join(save_path, "%s.db" % name)
if os.path.isfile(tmp_database):
os.remove(tmp_database)
# cache result file, version, and routine before closing
resultfile = self._result_file
version = self.version
prior_processor = self.parameters.routine
# finish, save and exit the server
self.finish(mute=True)
self.save(tmp_database, mute=True)
self.exit()
# copy result file to temp directory
if include_result and self._result_file is not None:
if os.path.isfile(resultfile):
tmp_resultfile = os.path.join(save_path, "%s.rst" % name)
copyfile(resultfile, tmp_resultfile)
# write temporary input file
start_file = os.path.join(save_path, "start%s.ans" % version)
with open(start_file, "w") as f:
f.write("RESUME\n")
# some versions of ANSYS just look for "start.ans" when starting
other_start_file = os.path.join(save_path, "start.ans")
with open(other_start_file, "w") as f:
f.write("RESUME\n")
# issue system command to run ansys in GUI mode
cwd = os.getcwd()
os.chdir(save_path)
exec_file = self._start_parm.get("exec_file", get_ansys_path(allow_input=False))
nproc = self._start_parm.get("nproc", 2)
add_sw = self._start_parm.get("additional_switches", "")
os.system(
f'cd "{save_path}" && "{exec_file}" -g -j {name} -np {nproc} {add_sw}'
)
os.chdir(cwd)
# Consider removing this temporary directory
# reattach to a new session and reload database
self._launch(self._start_parm)
self.resume(tmp_database, mute=True)
if prior_processor is not None:
if "BEGIN" not in prior_processor.upper():
self.run(f"/{prior_processor}", mute=True)
def _launch(self, *args, **kwargs): # pragma: no cover
raise NotImplementedError("Implemented by child class")
def _close_apdl_log(self):
"""Closes the APDL log"""
if self._apdl_log is not None:
self._apdl_log.close()
self._apdl_log = None
def nplot(self, nnum="", vtk=None, **kwargs):
"""APDL Command: NPLOT
Displays nodes.
.. note::
PyMAPDL plotting commands with ``vtk=True`` ignore any
values set with the ``PNUM`` command.
Parameters
----------
nnum : bool, int, optional
Node number key:
- ``False`` : No node numbers on display (default).
- ``True`` : Include node numbers on display.
.. note::
This parameter is only valid when ``vtk==True``
vtk : bool, optional
Plot the currently selected nodes using ``pyvista``.
Defaults to current ``use_vtk`` setting as set on the
initialization of MAPDL.
Examples
--------
Plot using VTK while showing labels and changing the background
>>> mapdl.prep7()
>>> mapdl.n(1, 0, 0, 0)
>>> mapdl.n(11, 10, 0, 0)
>>> mapdl.fill(1, 11, 9)
>>> mapdl.nplot(nnum=True, vtk=True, background='w', color='k',
show_bounds=True)
Plot without using VTK
>>> mapdl.prep7()
>>> mapdl.n(1, 0, 0, 0)
>>> mapdl.n(11, 10, 0, 0)
>>> mapdl.fill(1, 11, 9)
>>> mapdl.nplot(vtk=False)
"""
# lazy import here to avoid top level import
import pyvista as pv
if vtk is None:
vtk = self._use_vtk
if "knum" in kwargs:
raise ValueError("`knum` keyword deprecated. Please use `nnum` instead.")
if vtk:
kwargs.setdefault("title", "MAPDL Node Plot")
if not self.mesh.n_node:
warnings.warn("There are no nodes to plot.")
return general_plotter([], [], [], **kwargs)
labels = []
if nnum:
# must eliminate duplicate points or labeling fails miserably.
pcloud = pv.PolyData(self.mesh.nodes)
pcloud["labels"] = self.mesh.nnum
pcloud.clean(inplace=True)
labels = [{"points": pcloud.points, "labels": pcloud["labels"]}]
points = [{"points": self.mesh.nodes}]
return general_plotter([], points, labels, **kwargs)
# otherwise, use the built-in nplot
if isinstance(nnum, bool):
nnum = int(nnum)
self._enable_interactive_plotting()
return super().nplot(nnum, **kwargs)
def vplot(
self,
nv1="",
nv2="",
ninc="",
degen="",
scale="",
vtk=None,
quality=4,
show_area_numbering=False,
show_line_numbering=False,
color_areas=False,
show_lines=True,
**kwargs,
):
"""Plot the selected volumes.
APDL Command: VPLOT
.. note::
PyMAPDL plotting commands with ``vtk=True`` ignore any
values set with the ``PNUM`` command.
Parameters
----------
nv1, nv2, ninc
Display volumes from NV1 to NV2 (defaults to NV1) in steps
of NINC (defaults to 1). If NV1 = ALL (default), NV2 and
NINC are ignored and all selected volumes [VSEL] are
displayed. Ignored when ``vtk=True``.
degen
Degeneracy marker. ``"blank"`` No degeneracy marker is
used (default), or ``"DEGE"``. A red star is placed on
keypoints at degeneracies (see the Modeling and Meshing
Guide). Not available if /FACET,WIRE is set. Ignored
when ``vtk=True``.
scale
Scale factor for the size of the degeneracy-marker star. The scale
is the size in window space (-1 to 1 in both directions) (defaults
to .075). Ignored when ``vtk=True``.
vtk : bool, optional
Plot the currently selected volumes using ``pyvista``. As
this creates a temporary surface mesh, this may have a
long execution time for large meshes.
quality : int, optional
quality of the mesh to display. Varies between 1 (worst)
to 10 (best). Applicable when ``vtk=True``.
show_numbering : bool, optional
Display line and keypoint numbers when ``vtk=True``.
Examples
--------
Plot while displaying area numbers.
>>> mapdl.vplot(show_area_numbering=True)
"""
if vtk is None:
vtk = self._use_vtk
if vtk:
kwargs.setdefault("title", "MAPDL Volume Plot")
cm_name = "__tmp_area2__"
self.cm(cm_name, "AREA", mute=True)
self.aslv("S", mute=True) # select areas attached to active volumes
out = self.aplot(
vtk=vtk,
color_areas=color_areas,
quality=quality,
show_area_numbering=show_area_numbering,
show_line_numbering=show_line_numbering,
show_lines=show_lines,
**kwargs,
)
self.cmsel("S", cm_name, "AREA", mute=True)
return out
else:
self._enable_interactive_plotting()
return super().vplot(
nv1=nv1, nv2=nv2, ninc=ninc, degen=degen, scale=scale, **kwargs
)
def aplot(