-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfepx.py
1364 lines (1116 loc) · 56.4 KB
/
fepx.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
import os
import fnmatch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.mlab import griddata
from matplotlib.collections import LineCollection, PolyCollection
from matplotlib import animation
from IPython.display import clear_output
import pyevtk.vtk
import vtk
from vtk.util import numpy_support as vnp
from .quat import Quat
class Mesh(object):
### object variables ###
# meshDir
# dataDir
### MESH DATA ###
# numElmts(int)
# numNodes(int)
# elType(int)
# elmtCon[numElmnts, 10](int) - Nodes for each element - node numbers are 0 based. row-major
# nodePos[numNodes, 3](float) - Initial position of each node. col-major
# numGrains(int) - number of grains in mesh
# elmtGrain[numElmts](int) - Grain ID of each element - grain ID is 1 based
# elmtPhase[numElmts](int) - Phase ID of each element - phase ID is 1 based
# grainOris[numGrains, 3](float) - Initial Euler angles of each grain (Bunge, radians). col-major
### SIMULATION DATA ###
# numFrames(int) - Number of load steps output
# numProcs(int) - Number of cores the simulation was run on
# numSlipSys(int) - Number of slip systems
# simData - Dictionary of arrays storing loaded simulation data. Arrays stored in column major order.
# simData['nodePos'][numElmts, 3, numFrames+1](float) - Node positions
# simData['angle'][numElmts, 3, numFrames+1](float) - Euler angles of each element (Bunge, radians)
# simData['ori'][numElmts, numFrames+1](Quat) - Quat of orientation of each element
# misOri
# Key values for simulation data. Loaded are loaded from file while created are calclated here.
simDataKeysStatic = (
"nodePos",
"nodeVel",
"angle",
"hardness",
"strain",
"stress",
"shearRate",
"effDefRate",
"effPlasticDefRate",
"eqvStrain",
"eqvPlasticStrain",
"backstress"
)
# Any sim data with 3 components is assumed to be a vector unless added to this list
simDataKeysNotVectorStatic = (
"angle",
)
def __init__(self, name, meshDir="./", dataDir="./", grainFilename=None):
MESH_FILE_EX = "mesh"
GRAIN_FILE_EX = "grain"
ORI_FILE_EX = "ori"
self.meshName = name
self.meshDir = meshDir if meshDir[-1] == "/" else "{:s}{:s}".format(meshDir, "/")
self.dataDir = dataDir if dataDir[-1] == "/" else "{:s}{:s}".format(dataDir, "/")
if grainFilename is None:
grainFilename = name
# open mesh file
fileName = "{:s}{:s}.{:s}".format(self.meshDir, name, MESH_FILE_EX)
meshFile = open(fileName, "rb")
# read header
header = meshFile.readline()
self.numElmts, self.numNodes, self.elType = (int(x) for x in header.split())
# read element connectivity data
self.elmtCon = np.genfromtxt(meshFile,
dtype=int,
max_rows=self.numElmts,
usecols=list(range(1, 11)))
# read node positions
self.nodePos = np.asfortranarray(np.genfromtxt(meshFile,
dtype=float,
max_rows=self.numNodes,
usecols=[1, 2, 3]))
# read number of surfaces
self.numSurfaces = int(next(meshFile))
self.surfaces = []
for i in range(self.numSurfaces):
numElmts = int(next(meshFile))
elmtCon = np.genfromtxt(meshFile,
dtype=int,
max_rows=numElmts)
self.surfaces.append(Surface(i,
self,
numElmts,
np.ascontiguousarray(elmtCon[:, 0]),
np.ascontiguousarray(elmtCon[:, 1:])))
# close mesh file
meshFile.close()
# open grain file
fileName = "{:s}{:s}.{:s}".format(self.meshDir, grainFilename, GRAIN_FILE_EX)
grainFile = open(fileName, "rb")
# read header
header = grainFile.readline()
_, self.numGrains = (int(x) for x in header.split())
# read grain and phase info for each element
self.elmtGrain, self.elmtPhase = np.ascontiguousarray(np.genfromtxt(grainFile,
dtype=int,
unpack=True,
max_rows=self.numElmts))
# close grain file
grainFile.close()
# open ori file and read orientation of each grain (Kocks Euler angles in degrees)
fileName = "{:s}{:s}.{:s}".format(self.meshDir, name, ORI_FILE_EX)
self.grainOris = np.asfortranarray(np.genfromtxt(fileName,
dtype=float,
skip_header=2,
max_rows=self.numGrains,
usecols=[0, 1, 2]))
# convert to Bunge Euler angles in radians
self.grainOris *= (np.pi / 180)
self.grainOris[:, 0] += np.pi / 2
self.grainOris[:, 2] *= -1
self.grainOris[:, 2] += np.pi / 2
# create empty dictionary for storing simulaton data
self.simData = {}
# set to none so we tell if element stats have been loaded
self.elStats = None
self.simDataKeysDyn = []
self.simDataKeysNotVectorDyn = []
@property
def simDataKeys(self):
return Mesh.simDataKeysStatic + tuple(self.simDataKeysDyn)
@property
def simDataKeysNotVector(self):
return Mesh.simDataKeysNotVectorStatic + tuple(self.simDataKeysNotVectorDyn)
def simMetaData(self, dataKey):
"""Produces a dictionary of metadata for the given datakey. Meta data consists of:
- dataKey (string)
- includesInitial (bool)
- numComponents (int)
- numFrames (int)
- nodeData (bool): True if node data
- elmtData (bool): True if element data
- grainData (bool): True if grain data
- shape (tuple): shape of data array
- notVector (bool): True if the data components do not represent a vector
Args:
dataKey (string): Sim datakey
Returns:
dict: Metadata
"""
includesInitial = self.simData[dataKey].shape[-1] == self.numFrames + 1
numComponents = self.simData[dataKey].shape[-2] if len(self.simData[dataKey].shape) == 3 else 1
nodeData = self.simData[dataKey].shape[0] == self.numNodes
elmtData = self.simData[dataKey].shape[0] == self.numElmts
grainData = self.simData[dataKey].shape[0] == self.numGrains
notVector = dataKey in self.simDataKeysNotVector
metaData = {
"dataKey": dataKey,
"includesInitial": includesInitial,
"numComponents": numComponents,
"numFrames": self.simData[dataKey].shape[-1],
"nodeData": nodeData,
"elmtData": elmtData,
"grainData": grainData,
"shape": self.simData[dataKey].shape,
"notVector": notVector
}
return metaData
def simDataInfo(self):
for key, data in self.simData.items():
print("{:s} {}".format(key, data.shape))
def setSimParams(self, numProcs=-1, numFrames=-1, numSlipSys=-1):
if numProcs > 0:
self.numProcs = numProcs
if numFrames > 0:
self.numFrames = numFrames
if numSlipSys > 0:
self.numSlipSys = numSlipSys
def _validateSimDataKey(self, dataKey, fieldType=None):
if dataKey in self.simData:
if fieldType is None:
return True
else:
if type(fieldType) is str:
fieldType = [fieldType]
simMetaData = self.simMetaData(dataKey)
if ("node" in fieldType and simMetaData['nodeData']):
return True
elif ("element" in fieldType and simMetaData['elmtData']):
return True
elif ("grain" in fieldType and simMetaData['grainData']):
return True
else:
raise Exception("{:} data required.".format(fieldType))
elif dataKey in self.simDataKeys:
raise Exception("{:} data is not loaded.".format(dataKey))
else:
raise Exception("\"{:}\" is not available.".format(dataKey))
def _validateFrameNums(self, frameNums):
# frameNums: frame or list of frames to run calculation for. -1 for all
if type(frameNums) != list:
if type(frameNums) == int:
if frameNums < 0:
frameNums = list(range(self.numFrames + 1))
else:
frameNums = [frameNums]
else:
raise Exception("Only an integer or list allowed for frame nums.")
return frameNums
def createSimData(self, dataKey, data, isNotVector=False):
self.simDataKeysDyn.append(dataKey)
self.simData[dataKey] = np.asfortranarray(data)
if isNotVector:
self.simDataKeysNotVectorDyn.append(dataKey)
def removeSimData(self, dataKey):
try:
del self.simData[dataKey]
if dataKey in self.simDataKeysDyn:
self.simDataKeysDyn.remove(dataKey)
if dataKey in self.simDataKeysNotVectorDyn:
self.simDataKeysNotVectorDyn.remove(dataKey)
except KeyError:
raise KeyError("Sim data '{:}' not found.".format(dataKey))
def saveArchSimData(self, dataKey, saveDir=None):
import os
try:
data = self.simData[dataKey]
except KeyError:
raise KeyError("Sim data '{:}' not found.".format(dataKey))
# Create save directory if it doesn't exist
if saveDir is None:
saveDir = self.dataDir + 'saved_data/'
if not os.path.exists(saveDir):
os.makedirs(saveDir)
# Save data to file
fileName = "{:}{:}.npz".format(saveDir, dataKey)
np.savez_compressed(fileName, data=data)
def loadArchSimData(self, dataKey, saveDir=None):
if saveDir is None:
saveDir = self.dataDir + 'saved_data/'
# Load from file
fileName = "{:}{:}.npz".format(saveDir, dataKey)
data = np.load(fileName)['data']
# doesn't save the state of isNotVector
self.createSimData(dataKey, data)
def loadFrameData(self, dataName, initialIncd, usecols=None, frameNums=-1, numProcs=-1, numFrames=-1, numSlipSys=-1):
self.setSimParams(numProcs=numProcs, numFrames=numFrames, numSlipSys=numSlipSys)
if frameNums != -1:
frameNums = self._validateFrameNums(frameNums)
frameNums.sort()
if initialIncd:
if frameNums[0] != 0:
frameNums = [0, ] + frameNums
print("Initial values must be loaded if available.")
else:
if frameNums[0] == 0:
raise Exception("{:s} does not include initial data".format(dataName))
frameNums = [i - 1 for i in frameNums]
# +1 if initial values are also stored
numFrames = (self.numFrames + 1) if initialIncd else self.numFrames
singleData = False
loadedData = []
for i in range(self.numProcs):
# load data per processor
fileName = "{:s}post.{:s}.{:d}".format(self.dataDir, dataName, i)
loadedDataTemp = np.loadtxt(fileName, dtype=float, comments="%", usecols=usecols, unpack=True)
if len(loadedDataTemp.shape) == 1:
# scalar data
singleData = True
# reshape into 2d array with 2nd dim for each frame
cols, = loadedDataTemp.shape
perFrame = int(cols / numFrames)
loadedDataTemp = np.reshape(loadedDataTemp, (perFrame, numFrames), order='F')
else:
# vector data
# reshape into 3d array with 3rd dim for each frame
rows, cols = loadedDataTemp.shape
perFrame = int(cols / numFrames)
loadedDataTemp = np.reshape(loadedDataTemp, (rows, perFrame, numFrames), order='F')
if frameNums != -1:
loadedDataTemp = loadedDataTemp[..., frameNums]
loadedData.append(loadedDataTemp)
# concatenate data from all processors into one array and transpose first 2 axes if vectr data
# make data contiguous in memory in column major order
if singleData:
return np.asfortranarray(np.concatenate(loadedData, axis=0))
else:
return np.asfortranarray(np.transpose(np.concatenate(loadedData, axis=1), axes=(1, 0, 2)))
def loadSimData(self, dataKeys, forceLoad=False, frameNums=-1, numProcs=-1, numFrames=-1, numSlipSys=-1):
self.setSimParams(numProcs=numProcs, numFrames=numFrames, numSlipSys=numSlipSys)
simDataLoadFunctions = {
"nodePos": self.loadNodePosData,
"nodeVel": self.loadNodeVelData,
"angle": self.loadAngleData,
"hardness": self.loadHardnessData,
"strain": self.loadStrainData,
"stress": self.loadStressData,
"shearRate": self.loadShearRateData,
"effDefRate": self.loadEffDefRateData,
"effPlasticDefRate": self.loadEffPlasticDefRateData,
"eqvStrain": self.loadEqvStrainData,
"eqvPlasticStrain": self.loadEqvPlasticStrainData,
"backstress": self.loadBackstressData
}
for dataKey in dataKeys:
if dataKey in Mesh.simDataKeysStatic:
if forceLoad or (dataKey not in self.simData):
simDataLoadFunctions[dataKey](frameNums=frameNums)
print("Finished loading {:} data.".format(dataKey))
else:
print("{:} data already loaded.".format(dataKey))
else:
print("\"{:}\" is not a valid sim data key.".format(dataKey))
# load node positions for each frame of the simulation
def loadNodePosData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['nodePos'] = self.loadFrameData("adx",
True,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadNodeVelData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['nodeVel'] = self.loadFrameData("advel",
True,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadAngleData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['angle'] = self.loadFrameData("ang",
True,
usecols=[1, 2, 3],
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
# Covert to Bunge rep. in radians (were Kocks in degrees)
self.simData['angle'] *= (np.pi / 180)
self.simData['angle'][:, 0, :] += np.pi / 2
self.simData['angle'][:, 2, :] *= -1
self.simData['angle'][:, 2, :] += np.pi / 2
oriData = Quat.createManyQuats(np.swapaxes(self.simData['angle'], 0, 1))
self.createSimData("ori", oriData)
def loadHardnessData(self, frameNums=-1, numProcs=-1, numFrames=-1, numSlipSys=-1):
self.simData['hardness'] = self.loadFrameData("crss",
True,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames,
numSlipSys=numSlipSys)
def loadStrainData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['strain'] = self.loadFrameData("strain",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadStressData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['stress'] = self.loadFrameData("stress",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadShearRateData(self, frameNums=-1, numProcs=-1, numFrames=-1, numSlipSys=-1):
self.simData['shearRate'] = self.loadFrameData("gammadot",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames,
numSlipSys=numSlipSys)
def loadEffDefRateData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['effDefRate'] = self.loadFrameData("deff",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadEffPlasticDefRateData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['effPlasticDefRate'] = self.loadFrameData("dpeff",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadEqvStrainData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['eqvStrain'] = self.loadFrameData("eqstrain",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadEqvPlasticStrainData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['eqvPlasticStrain'] = self.loadFrameData("eqplstrain",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadBackstressData(self, frameNums=-1, numProcs=-1, numFrames=-1):
self.simData['backstress'] = self.loadFrameData("backstress",
False,
frameNums=frameNums,
numProcs=numProcs,
numFrames=numFrames)
def loadMeshElStatsData(self, name):
# open mesh stats file
ELSTAT_FILE_EX = "stelt3d"
fileName = "{:s}{:s}.{:s}".format(self.meshDir, name, ELSTAT_FILE_EX)
elStatFile = open(fileName, "r")
# read grain and phase info for each element
elStats = np.loadtxt(elStatFile)
if elStats.shape[0] != self.numElmts:
print("Problem with element stats file. Missing element data.")
else:
self.elStats = np.asfortranarray(elStats)
self.meshElStatNames = ["ID",
"coord-x", "coord-y", "coord-z",
"elset (grains)", "partition", "volume",
"2dmeshp-x", "2dmeshp-y", "2dmeshp-z",
"2dmeshd",
"2dmeshv-x", "2dmeshv-y", "2dmeshv-z",
"2dmeshn-x", "2dmeshn-y", "2dmeshn-z"]
def calcMeshSize(self):
maxNodePos = self.nodePos.max(axis=0)
minNodePos = self.nodePos.min(axis=0)
meshSize = np.abs(maxNodePos - minNodePos)
return meshSize
def constructVtkMesh(self):
"""Create VTK mesh using initial (undeformaed) node positions
Returns:
vtkUnstructuredGrid: VTK mesh
"""
CON_ORDER = [0, 2, 4, 9, 1, 3, 5, 6, 7, 8] # corners, then midpoints
ELMT_TYPE = 24
# create vtk point array for node positions
points = vtk.vtkPoints()
for coord in self.nodePos:
points.InsertNextPoint(coord)
# create vtk unstructured grid and assign point array
uGrid = vtk.vtkUnstructuredGrid()
uGrid.SetPoints(points)
# add cells to unstructured grid
con = vtk.vtkIdList()
for elmtCon in self.elmtCon:
con.Reset()
for pointID in elmtCon[CON_ORDER]:
con.InsertNextId(pointID)
uGrid.InsertNextCell(ELMT_TYPE, con)
return uGrid
def calcGradient(self, inDataKey, outDataKey):
"""Calculate gradient of simulation data wrt initial coordinates
Args:
inDataKey (string): Sim data key to caluclate gradient of
outDataKey (string): Sim data key to store result
"""
# validate input data
self._validateSimDataKey(inDataKey, fieldType="node")
# create array to store gradient
simMetaData = self.simMetaData(inDataKey)
inDataShape = simMetaData['shape']
if simMetaData['numComponents'] == 1:
gradient = np.empty((inDataShape[0], 3, inDataShape[1]))
else:
gradient = np.empty((inDataShape[0], 3 * inDataShape[1], inDataShape[2]))
# create VTK mesh
uGrid = self.constructVtkMesh()
numFrames = inDataShape[-1]
for i in range(numFrames):
# add point data to unstructured grid
vtkData = vnp.numpy_to_vtk(np.ascontiguousarray(self.simData[inDataKey][..., i]))
vtkData.SetName(inDataKey)
uGrid.GetPointData().AddArray(vtkData);
# apply vtk gradient filter
gradFilter = vtk.vtkGradientFilter()
gradFilter.SetInputDataObject(uGrid)
gradFilter.SetInputScalars(vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, inDataKey)
gradFilter.Update()
# collect output
gradient[:, :, i] = vnp.vtk_to_numpy(
gradFilter.GetOutput().GetPointData().GetArray('Gradients')
)
# Garbage collection before next frame
gradFilter = None
uGrid.GetPointData().RemoveArray(inDataKey);
vtkData = None
self.createSimData(outDataKey, gradient)
def nodeToElmtData(self, inDataKey, outDataKey):
"""Convert node data to element data using VTK framework
Args:
inDataKey (string): Sim data key to convert
outDataKey (string): Sim data key to store result
"""
# validate input data
self._validateSimDataKey(inDataKey, fieldType="node")
# create array to store element data
simMetaData = self.simMetaData(inDataKey)
inDataShape = simMetaData['shape']
elmtData = np.empty((self.numElmts,) + inDataShape[1:])
# create VTK mesh
uGrid = self.constructVtkMesh()
numFrames = inDataShape[-1]
for i in range(numFrames):
# add point data to unstructured grid
vtkData = vnp.numpy_to_vtk(np.ascontiguousarray(self.simData[inDataKey][..., i]))
vtkData.SetName(inDataKey)
uGrid.GetPointData().AddArray(vtkData);
# apply point to cell data fiter
conversionFilter = vtk.vtkPointDataToCellData()
conversionFilter.SetInputDataObject(uGrid)
conversionFilter.Update()
# collect output
elmtData[..., i] = vnp.vtk_to_numpy(
conversionFilter.GetOutput().GetCellData().GetArray(inDataKey)
)
# Garbage collection before next frame
conversionFilter = None
uGrid.GetPointData().RemoveArray(inDataKey);
uGrid.GetCellData().RemoveArray(inDataKey);
vtkData = None
self.createSimData(outDataKey, elmtData)
def calcMisori(self, frameNums):
frameNums = self._validateFrameNums(frameNums)
# create arrays to store misori data
self.createSimData("misOri", np.zeros(self.simData['ori'].shape, dtype=float))
self.createSimData("avMisOri", np.zeros([self.numGrains, self.simData['ori'].shape[1]], dtype=float))
self.createSimData("maxMisOri", np.zeros([self.numGrains, self.simData['ori'].shape[1]], dtype=float))
self.createSimData("avOri", np.zeros([self.numGrains, self.simData['ori'].shape[1]], dtype=Quat))
symmetry = 'cubic'
# Loop over frames
for i, frameNum in enumerate(frameNums):
# Loop over grains
for grainID in range(1, self.numGrains + 1):
# select grains based on grainID
selected = np.where(self.elmtGrain == grainID)[0]
quats = self.simData['ori'][selected, frameNum]
quatCompsSym = Quat.calcSymEqvs(quats, symmetry)
averageOri = Quat.calcAverageOri(quatCompsSym)
misOriArray, _ = Quat.calcMisOri(quatCompsSym, averageOri)
self.simData['misOri'][selected, frameNum] = misOriArray
self.simData['avMisOri'][grainID - 1, frameNum] = misOriArray.mean()
self.simData['maxMisOri'][grainID - 1, frameNum] = misOriArray.min()
self.simData['avOri'][grainID - 1, frameNum] = averageOri
clear_output()
print("Frame {:d} of {:d} done.".format(i + 1, len(frameNums)))
self.simData['misOri'][:, frameNums] = np.arccos(self.simData['misOri'][:, frameNums]) * 360 / np.pi
self.simData['avMisOri'][:, frameNums] = np.arccos(self.simData['avMisOri'][:, frameNums]) * 360 / np.pi
self.simData['maxMisOri'][:, frameNums] = np.arccos(self.simData['maxMisOri'][:, frameNums]) * 360 / np.pi
def calcGrainAverage(self, inDataKey, outDataKey=None):
"""Calculate grain avergae of elemnet data.
Args:
inDataKey (str): Data key of input data
outDataKey (None, optional): Data key to save data to. If none given then the data is returned from the function
Returns:
Array: Grain average data or nothing if outDataKey specified.
"""
# validate input data
self._validateSimDataKey(inDataKey, fieldType="element")
inMetaData = self.simMetaData(inDataKey)
outDataShape = (self.numGrains,) + inMetaData['shape'][1:]
grainData = np.empty(outDataShape)
for i in range(self.numGrains):
grainData[i] = self.simData[inDataKey][self.elmtGrain == (i + 1), ...].mean(axis=0)
if outDataKey is None:
return grainData
else:
self.createSimData(outDataKey, grainData, isNotVector=inMetaData['notVector'])
return
def writeVTU(self, fileName, frameNums, outputs, times=None, useInitialNodePos=True):
"""Write data out to VTK compatible files. Files are output to the data directory.
Args:
fileName (string): Base name of output files.
frameNums (lst(int)): The simlation frames to output. Either an integer for a single
frame, a list of ints for many or -1 for all. 0 is intial and 1 is first sim output
outputs (list(string)): The properties to be output. Current options are misOri, gammadot,
backstress and elStats.
times (list(float), optional): The time at each frame (only used for labeling)
useInitialNodePos (bool, optional): If false uses updateded node positions from each frame. Default: True.
"""
# Constants
CON_ORDER = [0, 2, 4, 9, 1, 3, 5, 6, 7, 8] # corners, then midpoints
ELMT_TYPE = 24
FILE_POSTFIX = ""
# create arrays for element type, conneectivity offset and node positions
cell_types = np.empty(self.numElmts, dtype='uint8')
# cell_types[:] = pyevtk.vtk.VtkQuadraticTetra.tid
cell_types[:] = ELMT_TYPE
offsets = np.arange(start=10, stop=10 * (self.numElmts + 1), step=10, dtype=int)
if useInitialNodePos:
x = self.nodePos[:, 0]
y = self.nodePos[:, 1]
z = self.nodePos[:, 2]
# check frameNums and times are valid
frameNums = self._validateFrameNums(frameNums)
if times is None:
times = frameNums
# validate outputs
includeElStats = False
# list of tuples includng validated name, if includes initial data,
# number of data fields and if nodal or elemental data (true for nodal)
simMetaDatas = []
for dataKey in outputs:
if dataKey in self.simData:
# add metadata to list. node data fields to the start and element data fields to the end
simMetaData = self.simMetaData(dataKey)
if simMetaData['nodeData']:
simMetaDatas.insert(0, simMetaData)
else:
simMetaDatas.append(simMetaData)
elif dataKey == "elStats":
if self.elStats is not None:
includeElStats = True
else:
print("Element stats have not been loaded")
elif dataKey in self.simDataKeys:
print("{:} data is not loaded.".format(dataKey))
else:
print("\"{:}\" is not a valid output data key.".format(dataKey))
# open vtk group file
fileNameFull = "{:s}{:s}{:s}".format(self.dataDir, fileName, FILE_POSTFIX)
print(fileNameFull)
vtgFile = pyevtk.vtk.VtkGroup(fileNameFull)
for frameNum in frameNums:
# write frame vtu file path to vtk group file (this needed modification to
# evtk module to write paths not relative to the current working directory)
fileNameFull = "{:s}{:s}.{:d}.vtu".format(fileName, FILE_POSTFIX, frameNum)
vtgFile.addFile(fileNameFull, times[frameNum], relToCWD=False)
# open vtu file and write root elements (node positions, element connectivity and type)
fileNameFull = "{:s}{:s}{:s}.{:d}".format(self.dataDir, fileName, FILE_POSTFIX, frameNum)
vtuFile = pyevtk.vtk.VtkFile(fileNameFull, pyevtk.vtk.VtkUnstructuredGrid)
vtuFile.openGrid()
vtuFile.openPiece(ncells=self.numElmts, npoints=self.numNodes)
if not useInitialNodePos:
x = self.simData['nodePos'][:, 0, frameNum]
y = self.simData['nodePos'][:, 1, frameNum]
z = self.simData['nodePos'][:, 2, frameNum]
vtuFile.openElement("Points")
vtuFile.addData("points", (x, y, z))
vtuFile.closeElement("Points")
vtuFile.openElement("Cells")
# vtuFile.addData("connectivity", self.elmtCon.flatten())
vtuFile.addHeader("connectivity", self.elmtCon.dtype.name, self.elmtCon.size, 1)
vtuFile.addData("offsets", offsets)
vtuFile.addData("types", cell_types)
vtuFile.closeElement("Cells")
# Add headers of simulation point data
vtuFile.openElement("PointData")
# loop over outputs adding headers if node data
for simMetaData in simMetaDatas:
if (simMetaData['includesInitial'] or (frameNum > 0)) and simMetaData['nodeData']:
dataKey = simMetaData['dataKey']
trueFrameNum = frameNum if simMetaData['includesInitial'] else frameNum - 1
# check if single or multiple variable output
if simMetaData['numComponents'] == 1:
# add single header to file
vtuFile.addHeader(
dataKey,
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, trueFrameNum].size,
1
)
elif (simMetaData['numComponents'] == 3) and (dataKey not in self.simDataKeysNotVector):
# add single header to file with 3 components for vector
vtuFile.addHeader(
dataKey,
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, 0, trueFrameNum].size,
3
)
else:
# add multiple headers to file
for i in range(simMetaData['numComponents']):
vtuFile.addHeader(
"{:s} {:d}".format(dataKey, i + 1),
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, i, trueFrameNum].size,
1
)
vtuFile.closeElement("PointData")
# Add headers of simulation cell data
vtuFile.openElement("CellData")
# loop over outputs adding headers if element data
for simMetaData in simMetaDatas:
if (simMetaData['includesInitial'] or (frameNum > 0)) and simMetaData['elmtData']:
dataKey = simMetaData['dataKey']
trueFrameNum = frameNum if simMetaData['includesInitial'] else frameNum - 1
# check if single or multiple variable output
if simMetaData['numComponents'] == 1:
# add single header to file
vtuFile.addHeader(
dataKey,
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, trueFrameNum].size,
1
)
elif (simMetaData['numComponents'] == 3) and (dataKey not in self.simDataKeysNotVector):
# add single header to file with 3 components for vector
vtuFile.addHeader(
dataKey,
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, 0, trueFrameNum].size,
3
)
else:
# add multiple headers to file
for i in range(simMetaData['numComponents']):
vtuFile.addHeader(
"{:s} {:d}".format(dataKey, i + 1),
self.simData[dataKey].dtype.name,
self.simData[dataKey][:, i, trueFrameNum].size,
1
)
# write element stats headers if required and on first frame
if includeElStats and (frameNum == 0):
for i in range(self.elStats.shape[1]):
vtuFile.addHeader("Element stat - {:}".format(self.meshElStatNames[i]),
self.elStats.dtype.name,
self.elStats[:, i].size,
1)
vtuFile.closeElement("CellData")
vtuFile.closePiece()
vtuFile.closeGrid()
# add actual data to file
# mesh defiition stuff
vtuFile.appendData((x, y, z))
vtuFile.appendData(self.elmtCon[:, CON_ORDER].flatten()).appendData(offsets).appendData(cell_types)
# simulation data
# loop over outputs adding data
for simMetaData in simMetaDatas:
if simMetaData['includesInitial'] or (frameNum > 0):
dataKey = simMetaData['dataKey']
trueFrameNum = frameNum if simMetaData['includesInitial'] else frameNum - 1
# check if single or multiple variable output
if simMetaData['numComponents'] == 1:
# add single data set
vtuFile.appendData(self.simData[dataKey][:, trueFrameNum])
elif (simMetaData['numComponents'] == 3) and (dataKey not in self.simDataKeysNotVector):
# add vector data set
vtuFile.appendData((
self.simData[dataKey][:, 0, trueFrameNum],
self.simData[dataKey][:, 1, trueFrameNum],
self.simData[dataKey][:, 2, trueFrameNum]
))
else:
# add multiple data sets
for i in range(simMetaData['numComponents']):
vtuFile.appendData(self.simData[dataKey][:, i, trueFrameNum])
# write element stats data if required and on first frame
if includeElStats and (frameNum == 0):
for i in range(self.elStats.shape[1]):
vtuFile.appendData(self.elStats[:, i])
vtuFile.save()
vtgFile.save()
@staticmethod
def combineFiles(baseDir, inDirs, outDir):
"""Combine output files from multiple simulations. If a simulation was run in smaller parts
Args:
baseDir (string): Base directory of whole simulation. No trailing slash
inDirs (List(string)): List of simulation directory names to
combine (baseDir/inDir). No trailing slash
outDir (string): Directory to output combined files to (baseDir/outDir)
"""
# no trailing slashes on directory names and inDirs is a list
fileNames = []
for fileName in os.listdir("{:s}/{:s}".format(baseDir, inDirs[0])):
if (fnmatch.fnmatch(fileName, "post.*") and
fileName != "post.conv" and fileName != "post.stats" and not
(fnmatch.fnmatch(fileName, "post.debug.*") or
fnmatch.fnmatch(fileName, "post.log.*") or
fnmatch.fnmatch(fileName, "post.restart.*")
)):
fileNames.append(fileName)
if not os.path.isdir("{:s}/{:s}".format(baseDir, outDir)):
os.mkdir("{:s}/{:s}".format(baseDir, outDir))
for fileName in fileNames:
outFile = open("{:s}/{:s}/{:s}".format(baseDir, outDir, fileName), 'w')
for inDir in inDirs:
inFile = open("{:s}/{:s}/{:s}".format(baseDir, inDir, fileName), 'r')
for line in inFile:
outFile.write(line)
inFile.close()
outFile.close()
class Surface(object):
def __init__(self, surfNum, mesh, numElmts, elmtIDs, elmtCon):
self.surfNum = surfNum # Number of surface in mesh (0 based)
self.mesh = mesh
self.numElmts = numElmts
self.elmtIDs = elmtIDs # Mesh global element IDs
self.elmtCon = elmtCon # Mesh global node IDs
self.nodeIDs = np.unique(self.elmtCon.flatten()) # Mesh global node IDs
self.numNodes = len(self.nodeIDs)
self.forceCalc = False # Set to true to force recalcualtion of all below
self._elmtEdges = None
self._elmtNeighbours = None
self._elmtNeighbourEdges = None
self._grainEdges = None
self._meshEdges = None
self._neighbourNetwork = None
self._elmtIDsLayer = None
@property
def elmtGrain(self):
"""Returns an array of grain IDs for elements in the surface (note grain IDs are 1 based)
"""
return self.mesh.elmtGrain[self.elmtIDs]
@property
def grainIDs(self):
"""Returns an array of grain IDs included in the surface
"""
return np.unique(self.elmtGrain)
# properties postfixed with 'Layer' are equivalent to those without but take
# the first 3d layer of elements not just those with a face in the surface
@property
def elmtIDsLayer(self):
if (self._elmtIDsLayer is None) or self.forceCalc:
# just corner nodes
surfaceNodeIDs = np.unique(self.elmtCon[:, (0, 2, 4)].flatten())
# All elements that have a node in the surface
surfaceElmtIDs = []
# Find elements with a corner node in the surface
for elmtID in range(self.mesh.numElmts):
for nodeID in self.mesh.elmtCon[elmtID, (0, 2, 4, 9)]:
if nodeID in surfaceNodeIDs:
surfaceElmtIDs.append(elmtID)
break
self._elmtIDsLayer = np.array(surfaceElmtIDs)
return self._elmtIDsLayer
@property
def elmtGrainLayer(self):
"""Returns an array of grain IDs for elements in the surface (note grain IDs are 1 based)
"""
return self.mesh.elmtGrain[self.elmtIDsLayer]
@property
def grainIDsLayer(self):
"""Returns an array of grain IDs included in the surface
"""
return np.unique(self.elmtGrainLayer)