Examples#
Example 01 - Contour Model and Export#
1from hw import *
2from hw.hv import *
3import os
4
5scriptDir = os.path.abspath(os.path.dirname(__file__))
6modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
7resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
8h3dFile = os.path.join(scriptDir,'demo_model_export.h3d')
9jpgFile = os.path.join(scriptDir,'demo_image_export.jpeg')
10
11ses = Session()
12ses.new()
13win=ses.get(Window)
14win.type = 'animation'
15
16win.addModelAndResult(modelFile, result=resultFile)
17res = ses.get(Result)
18resScalar = ResultDefinitionScalar(dataType='Composite Stress',dataComponent='vonMises',layer='Max')
19res.plot(resScalar)
20
21exportH3D = ExportModelH3D(animation=True,
22 previewImage=False,
23 compressOutput=True,
24 compressionLoss=0.05,
25 file=h3dFile)
26
27captureImage = CaptureImageTool(type = 'jpg',
28 width = 3000,
29 height = 2000,
30 file=jpgFile)
31
32animTool=AnimationTool()
33animTool.currentFrame=1
34
35evalHWC('view orientation iso')
36exportH3D.export()
37captureImage.capture()
Figure 1. Output of ‘Contour Model and Export’
Example 02 - Part lists with Collections and evalTcl()#
1from hw import *
2from hw.hv import *
3import os
4
5scriptDir = os.path.abspath(os.path.dirname(__file__))
6modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
7resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
8
9ses = Session()
10ses.new()
11page=ses.get(Page)
12win=ses.get(Window)
13win.type = 'animation'
14win.addModelAndResult(modelFile, result=resultFile)
15animTool=AnimationTool()
16animTool.currentFrame=1
17evalHWC('view orientation iso')
18
19print()
20print('Part lists by evalTcl() with postquery package')
21evalTcl('package require postquery')
22partList=[int(x) for x in evalTcl('::hwp::getComponentList').split()]
23print('Part ID List = ',partList)
24partNameList=evalTcl('::hwp::getComponentList -byname 1').split()
25print('Part Name List = ',partNameList)
26
27print()
28print('Part lists by Collections')
29partCol=Collection(Part)
30partList = [p.id for p in partCol.getEntities()]
31print('Part ID List = ',partList)
32partNameList = [p.name for p in partCol.getEntities()]
33print('Part Name List = ',partNameList)
Figure 2. Output of ‘Part lists with Collections and evalTcl() postquery’
Example 03 - Macro wiht GUI#
1from hw import *
2from hw.hv import *
3from hwx.xmlui import gui
4from hwx import gui as gui2
5import os
6import itertools
7
8def MyCustomGui():
9
10 # Method called on clicking 'Close'.
11 def onClose(event):
12 dialog.Hide()
13
14 def onRun(event):
15 dialog.Hide()
16 postprocAuto(modelFile.value, resultFile.value, folderSel.value)
17 gui2.tellUser('Done!')
18
19 label1 = gui.Label(text='Model File')
20 modelFile = gui.OpenFileEntry(placeholdertext='Model File')
21 label2 = gui.Label(text='Result File')
22 resultFile = gui.OpenFileEntry(placeholdertext='Result File')
23 label3 = gui.Label(text='Screenshot Folder')
24 folderSel = gui.ChooseDirEntry(tooltip='Select output directory')
25
26 close = gui.Button('Close', command=onClose)
27 create = gui.Button('Run', command=onRun)
28
29 # Default file settings for quick demo purposes
30 if True:
31 src_path = os.path.dirname(os.path.abspath(__file__))
32 modelFile.value = os.path.join(src_path, "aerobox", "aerobox.fem").replace("\\","/")
33 resultFile.value = os.path.join(src_path, "aerobox", "aerobox-LC1-2.op2").replace("\\","/")
34 folderSel.value = os.path.join(src_path, "outDir").replace("\\","/")
35
36 mainFrame = gui.VFrame(
37 (label1, 20, modelFile),
38 (label2, 20, resultFile),
39 (label3, 20, folderSel),
40 (create,close)
41 )
42
43 dialog = gui2.Dialog(caption = "Post Automation")
44 dialog.addChildren(mainFrame)
45 dialog.width=400
46 dialog.height=100
47 dialog.show()
48
49
50def postprocAuto(modelPath, resultPath, outDir):
51
52 # Create Session Pointer
53 ses = Session()
54 # New
55 ses.new()
56
57 # Define Capture Image Tool
58 capture = CaptureImageTool()
59 capture.type = 'jpg'
60 capture.width = 1200
61 capture.height = 800
62
63 #Define H3D export
64 exportH3D = ExportModelH3D(animation=True,previewImage=False,compressOutput=True,compressionLoss=0.05)
65
66 # Dictionary with dataType dependent result scalar settings
67 resDict = {
68 'Displacement' : ['Mag','X','Y','Z'],
69 'Composite Stress' : ['vonMises','P1 (major)','P2 (mid)','P3 (minor)'],
70 'Composite Strain' : ['vonMises','XX','YY','ZZ'],
71 'Stress' : ['vonMises','MaxShear','In-plane P1 (major)','In-plane P2 (minor)']
72 }
73
74 # Dictionary with dataType dependent legend settings (precsion, numerical format,
75 legDict = {
76 'Displacement' : [5,'scientific',2],
77 'Composite Stress' : [6,'engineering',4],
78 'Composite Strain' : [7,'fixed',6],
79 'Stress' : [10,'engineering',2]
80 }
81 # Change window type
82 ses.get(Window).type = 'animation'
83
84 startPageId=ses.get(Page).id+1
85
86 # Loop over data types, 1 page per data type
87 for dType in list(resDict.keys()):
88 ap = Page(title=dType,layout = 9)
89 ses.setActive(Page,page=ap)
90
91 # Loop over data components, one window per component
92 for i, w in enumerate(ses.getWindows()):
93 dComp = resDict.get(dType)[i]
94 ses.setActive(Window,window=w)
95
96 # Load Model
97 w.addModelAndResult(modelPath, result=resultPath)
98
99 # Set scalar results
100 res = ses.get(Result)
101 resScalar = ses.get(ResultDefinitionScalar)
102 resScalar.setAttributes(dataType=dType,dataComponent=dComp)
103
104 # Plot results
105 res.plot(resScalar)
106
107 # Define legend settings
108 leg=ses.get(LegendScalar)
109 leg.setAttributes(numberOfLevels =legDict.get(dType)[0],
110 numericFormat =legDict.get(dType)[1],
111 numericPrecision=legDict.get(dType)[2])
112
113 # Define ISO settings
114 resIso = ses.get(ResultDefinitionIso)
115 resIso.setAttributes(dataType=dType,dataComponent=dComp)
116 dispIso = ses.get(ResultDisplayIso)
117 res.plotIso(resIso)
118
119 # Set ISO value dependent on min/max
120 dispIso.value=leg.minValue+(leg.maxValue-leg.minValue)/5
121
122 # Set animation frame 1
123 animTool=AnimationTool()
124 animTool.currentFrame=1
125
126 # Capture jpg
127 jpgPath = os.path.join(outDir,dType+' - '+dComp+'_iso_view.jpg')
128 capture.file = jpgPath
129 capture.capture()
130
131 # Capture H3D
132 h3dPath = os.path.join(outDir,dType+' - '+dComp+'.h3d')
133 exportH3D.setAttributes(file=h3dPath,window=w)
134 exportH3D.export()
135
136 # Use Model, Collection and Part class to isolate component
137 if True:
138 mod=ses.get(Model)
139 col=Collection(Part)
140 mod.hide(col)
141 mod.get(Part,172).visibility=True
142 # Use evalHWC isolate component for export
143 else:
144 evalHWC('hide component all')
145 evalHWC('show component 172')
146
147 # Set Views and export
148 evalHWC('view orientation left')
149 jpgPath = os.path.join(outDir,dType+' - '+dComp+'_left_view.jpg')
150 capture.file = jpgPath
151 evalHWC('show component all')
152 evalHWC('view orientation iso')
153
154 ses.setActive(Page,id=startPageId)
155
156if __name__ == "__main__":
157 MyCustomGui()
Figure 3. Start GUI and exported images / H3D’s of ‘Macro wiht GUI’
Figure 4. Page created for one data type by ‘Macro wiht GUI’
Example 04 - Contour Maximum by Sphere#
1from hw import *
2from hw.hv import *
3import os
4
5scriptDir = os.path.abspath(os.path.dirname(__file__))
6modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
7resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
8
9hotspotRadius = 400
10
11# Load Model
12ses = Session()
13ses.new()
14page=ses.get(Page)
15win=ses.get(Window)
16win.type = 'animation'
17win.addModelAndResult(modelFile, result=resultFile)
18
19# Contour scalar
20res = ses.get(Result)
21resScalar = ses.get(ResultDefinitionScalar)
22resScalar.setAttributes(dataType='Composite Stress',dataComponent='vonMises',layer='Max')
23res.plot(resScalar)
24
25# Create Collection via TopN filter
26maxElemCol=Collection(Element,populate=False)
27elemFilter=FilterByScalar(operator='topN',value=1)
28maxElemCol.addByFilter(elemFilter)
29
30# Get centroid of element with maximum scalar value
31maxElem=maxElemCol.getEntities()[0]
32centroid=maxElem.centroid
33
34# Create collection with given radius
35sphereCol=Collection(Element,populate=False)
36sphereFilter=FilterBySphere(x=centroid[0],
37 y=centroid[1],
38 z=centroid[2],
39 radius=hotspotRadius)
40sphereCol.addByFilter(sphereFilter)
41
42# Define font
43headFont=Font(size=14,style='bold')
44
45# Modify legend
46legend=ses.get(LegendScalar)
47legend.setAttributes(headerText='Hostpot Radius = '+str(hotspotRadius),
48 headerVisible=True,
49 headerFont=headFont,
50 numberOfLevels=8,
51 numericFormat='fixed',
52 numericPrecision=0)
53
54# Contour only sphere collection
55resScalar.collection=sphereCol
56res.plot(resScalar)
57
58# Attach max note with evalHWC
59maxId = str(maxElem.id)
60maxLabel = 'Max Element '+maxId
61evalHWC('annotation note create "'+maxLabel+'"')
62evalHWC('annotation note "'+maxLabel+'" attach entity element '+maxId)
63evalHWC('annotation note "'+maxLabel+'" \
64 display text= "Max Element: {entity.id}\\nMax Value: {entity.contour_val}" \
65 movetoentity=true \
66 filltransparency=false \
67 fillcolor="255 255 255"')
68
69# Set frame with AnimationTool()
70animTool=AnimationTool()
71animTool.currentFrame=1
72
73# Modify view with evalHWC
74evalHWC('view orientation iso')
Figure 5. Output of ‘Contour Maximum by Sphere
Example 05 - Notes attached to Entities#
1from hw import *
2from hw.hv import *
3import itertools
4import os
5
6scriptDir = os.path.abspath(os.path.dirname(__file__))
7modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
8resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
9
10ses = Session()
11ses.new()
12win=ses.get(Window)
13win.type = 'animation'
14
15win.addModelAndResult(modelFile, result=resultFile)
16res = ses.get(Result)
17resScalar = ResultDefinitionScalar(dataType='Composite Stress',
18 dataComponent='vonMises',
19 layer='Max')
20res.plot(resScalar)
21animTool=AnimationTool()
22animTool.currentFrame=1
23evalHWC('view orientation iso')
24
25noteDict = {
26 'elements' : [493, 353, 674, 733],
27 'fontSizes' : [16, 12, 12, 12],
28 'colors' : ['#FF0000','#FFFFFF','#FFFFFF','#FFFFFF']
29}
30
31for (elem,fsize,col) in zip(noteDict.get('elements'),noteDict.get('fontSizes'),noteDict.get('colors')):
32 n=Note(label='Element '+str(elem),
33 attachmentType='element',
34 attachment =[1, 'element', elem],
35 text='Element: {entity.id}\nValue = {entity.contour_val}',
36 textColorMode='user',
37 textColor=col,
38 borderColorMode='user',
39 borderColor=(20, 20, 20),
40 fontSize=fsize,
41 transparency=False,
42 moveToEntity=True,
43 screenAnchor=False)
44
45fieldDic=n.getFieldDictionary()
46for key in list(fieldDic.keys()):
47 print('{:35s} {:3s} {:50s}'.format(key,' = ',fieldDic[key]))
Figure 6. Notes attached to entites with getFieldDictionary() output
Example 06 - Planar and Spherical Section Cuts#
1from hw import *
2from hw.hv import *
3import itertools
4import os
5
6ses = Session()
7ses.new()
8
9scriptDir = os.path.abspath(os.path.dirname(__file__))
10modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
11resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
12
13# Dictionary with dataType dependent result scalar settings
14resDict = {
15 'Displacement' : ['Mag','X','Y','Z'],
16 'Stress' : ['vonMises','MaxShear','In-plane P1 (major)','In-plane P2 (minor)']
17 }
18
19# Change window type
20ses.get(Window).type = 'animation'
21
22startPageId=ses.get(Page).id+1
23
24# Loop over data types, 1 page per data type
25for dType in list(resDict.keys()):
26 ap = Page(title=dType,layout = 9)
27 ses.setActive(Page,page=ap)
28
29 # Loop over data components, one window per component
30 for i, w in enumerate(ses.getWindows()):
31 dComp = resDict.get(dType)[i]
32 ses.setActive(Window,window=w)
33
34 # Load Model
35 w.addModelAndResult(modelFile, result=resultFile)
36
37 # Set scalar results
38 res = ses.get(Result)
39 resScalar = ses.get(ResultDefinitionScalar)
40 resScalar.setAttributes(dataType=dType,dataComponent=dComp)
41
42 # Plot results
43 res.plot(resScalar)
44
45 # Set frame with AnimationTool()
46 animTool=AnimationTool()
47 # animTool.currentFrame=1
48
49 # Modify view with evalHWC
50 evalHWC('view orientation iso')
51
52 # Add SectionCut at Max Entity
53 entityFilter=FilterByScalar(operator='topN',value=1)
54 if dType == 'Displacement':
55 # Set animation frame 1
56 animTool=AnimationTool()
57 animTool.currentFrame=1
58 # Create Collection via TopN filter
59 maxNodeCol=Collection(Node,populate=False)
60 maxNodeCol.addByFilter(entityFilter)
61 # Get centroid of element with maximum scalar value
62 maxNode=maxNodeCol.getEntities()[0]
63 # Add SectionCut Planar
64 secPlanar = SectionCutPlanar(
65 label='Node '+ str(maxNode.id) ,
66 gridSpaceX=100,
67 gridSpaceY=100,
68 gridText=True
69 )
70 secPlanar.setOrientationByAxis('y')
71 secPlanar.setBaseNode(maxNode.id)
72 evalHWC('view fit')
73 secPlanar.setAttributes(featureLines=True,transparency=True)
74 elif dType == 'Stress':
75 # Create Collection via TopN filter
76 maxElemCol=Collection(Element,populate=False)
77 maxElemCol.addByFilter(entityFilter)
78 # Get centroid of element with maximum scalar value
79 maxElem=maxElemCol.getEntities()[0]
80 baseCoords=maxElem.centroid
81 # Add Section Cut Spherical
82 secRadius = 600
83 secSphere = SectionCutSpherical(
84 label='Element '+str(maxElem.id),
85 radius=secRadius
86 )
87 secSphere.center=baseCoords
88 evalHWC('view fit')
89 secSphere.setAttributes(featureLines=True,transparency=True)
Figure 7. Planar and spherical sections positoned using Collections and TopN filter
Example 07 - Log HWC in Python#
1import os
2from hw.utils import *
3
4scriptDir = os.path.abspath(os.path.dirname(__file__))
5modelFile = os.path.join(scriptDir,'aerobox','aerobox.fem')
6resultFile = os.path.join(scriptDir,'aerobox','aerobox-LC1-2.op2')
7##################################################
8# BEGIN: HyperWorks 24
9# TIME: 08:22:17 PM
10# DATE: 02/04/24
11##################################################
12
13evalHWC('delete session')
14evalHWC('hwd page current activewindow=1')
15evalHWC('hwd window type=HyperView')
16evalHWC('delete session')
17evalHWC('hwd window type = HyperView')
18evalHWC('open animation modelandresult ' + modelFile + ' ' + resultFile)
19evalHWC('view fit allframes = true')
20evalHWC('hwd page current layout = 9')
21evalHWC('hwd window copy')
22evalHWC('hwd window paste window = 2')
23evalHWC('hwd page current activewindow = 3')
24evalHWC('hwd window paste')
25evalHWC('hwd page current activewindow = 4')
26evalHWC('hwd window paste')
27evalHWC('hwd page copy')
28evalHWC('hwd page add title = Untitled')
29evalHWC('hwd page paste')
30evalHWC('hwd page overlay page = 2')
Figure 8. Recording of copying/overlaying windows and pages