Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
modlibUtils.py
Go to the documentation of this file.
1import sys, string, os, fileinput, shutil
2from fractions import Fraction
3import numpy as np
4# evl file
5
6class EVL:
7 nodes=np.empty([0,0])
8
9class AUX:
10 meshNodes=np.empty([0,0])
11 gaussPoints=np.empty([0,0])
12 periodicPatches=np.empty([0,0])
13
14
15class PolyCrystalFile(dict):
16 materialFile=''
17 crystalStructure=''
18 absoluteTemperature=300.0
19 dislocationMobilityType='default'
20 meshFile='../../Library/Meshes/unitCube.msh'
21 grain1globalX1=np.array([1,0,0]) # overwritten if alignToSlipSystem0=true
22 grain1globalX3=np.array([0,0,1]) # overwritten if alignToSlipSystem0=true
23 A=np.zeros((3,3))
24 invA=np.zeros((3,3))
25 alignToSlipSystem0=0
26 boxEdges=np.array([[1,0,0],[0,1,0],[0,0,1]]) # i-th row is the direction of i-th box edge. Overwritten if alignToSlipSystem0=true
27 boxEdgesLatticeDirections=np.zeros((3,3)) # i-th col is the lattice direction of i-th box edge. Overwritten if alignToSlipSystem0=true
28 boxEdgesLatticeLengths=np.array([1.,1.,1.]) # i-th element is the length of the lattice direction of i-th box edge. Overwritten if alignToSlipSystem0=true
29 boxScaling=np.array([1000,1000,1000]) # must be a vector of integers
30 C2G=np.zeros((3,3))
31 F=np.zeros((3,3))
32 X0=np.array([0,0,0])
33 periodicFaceIDs=np.array([0,1,2,3,4,5])
34
35 def __init__(self, materialFile):
36 self.materialFile = materialFile
37 self.crystalStructure = getStringInFile('inputFiles/'+materialFile,'crystalStructure')
38 if self.crystalStructure == 'FCC':
39 self.A=np.array([[0.,1.,1.],[1.,0.,1.],[1.,1.,0.]])/np.sqrt(2.0)
40 elif self.crystalStructure == 'BCC':
41 self.A=np.array([[-1.,1.,1.],[1.,-1.,1.],[1.,1.,-1.]])/np.sqrt(3.0)
42 elif self.crystalStructure == 'HEX':
43 self.A=np.array([[1.,0.5,0.],[0.,0.5*np.sqrt(3.),0.],[0.,0.,np.sqrt(8.0/3.0)]])
44 elif self.crystalStructure == 'CubicFluorite':
45 self.A=np.array([[0.,1.,1.],[1.,0.,1.],[1.,1.,0.]])/np.sqrt(2.0)
46 else:
47 raise Exception("Unkonwn crystalStructure "+self.crystalStructure)
48 self.invA=np.linalg.inv(self.A)
49 np.set_printoptions(precision=15)
50
51 def compute(self):
52 if self.alignToSlipSystem0:
53 if self.crystalStructure == 'BCC':
54 self.grain1globalX1=np.array([1,1,-1]) # overwrite
55 self.grain1globalX3=np.array([1,0,1]) # overwrite
56 elif self.crystalStructure == 'FCC':
57 self.grain1globalX1=np.array([0,1,1]) # overwrite
58 self.grain1globalX3=np.array([-1,1,-1]) # overwrite
59 elif self.crystalStructure == 'CubicFluorite':
60 self.grain1globalX1=np.array([0,1,1]) # overwrite
61 self.grain1globalX3=np.array([-1,1,-1]) # overwrite
62 elif self.crystalStructure == 'HEX':
63 self.grain1globalX1=np.array([1,0,0]) # overwrite
64 self.grain1globalX3=np.array([0,0,1]) # overwrite
65 else:
66 raise Exception("Unkonwn crystalStructure "+self.crystalStructure)
67
68 x1=self.grain1globalX1/np.linalg.norm(self.grain1globalX1);
69 x3=self.grain1globalX3/np.linalg.norm(self.grain1globalX3);
70 self.C2G=np.array([x1,np.cross(x3,x1),x3]);
71
72 if self.alignToSlipSystem0:
73 self.boxEdges=self.C2G
74
75 # Find lattice vectors (columns of L) aligned to boxEdges
76 B=self.invA@self.boxEdges.transpose()
77 for j in range(0, 3):
78 b=B[:,j]/np.max(np.abs(B[:,j]))
79 n=np.array([0,0,0], dtype=int)
80 d=np.array([1,1,1], dtype=int)
81 for i in range(0, 3):
82 f=Fraction(b[i]).limit_denominator(100)
83 n[i]=f.numerator
84 d[i]=f.denominator
85 dp=np.prod(d);
86 nr=np.array([1,1,1], dtype=int)
87 for i in range(0, 3):
88 nr[i]=n[i]*dp/d[i]
89 self.boxEdgesLatticeDirections[:,j]=self.A@nr.transpose()
90 self.boxEdgesLatticeLengths[j]=np.linalg.norm(self.boxEdgesLatticeDirections[:,j])
91 self.F[:,j]=self.C2G@self.boxEdgesLatticeDirections[:,j]*np.round(self.boxScaling[j]/self.boxEdgesLatticeLengths[j])
92
93 def write(self,folderName):
94 self.compute()
95 polyFile = open(folderName+'/polycrystal.txt', 'w')
96 polyFile.write('materialFile='+self.materialFile+';\n')
97 polyFile.write('absoluteTemperature='+str(self.absoluteTemperature)+'; # [K] simulation temperature \n')
98 polyFile.write('meshFile='+self.meshFile+'; # mesh file \n')
99 polyFile.write('C2G1='+' '.join(map(str, self.C2G[0,:]))+'\n')
100 polyFile.write(' '+' '.join(map(str, self.C2G[1,:]))+'\n')
101 polyFile.write(' '+' '.join(map(str, self.C2G[2,:]))+'; # crystal rotation matrix \n')
102 polyFile.write('F='+' '.join(map(str, self.F[0,:]))+'\n')
103 polyFile.write(' '+' '.join(map(str, self.F[1,:]))+'\n')
104 polyFile.write(' '+' '.join(map(str, self.F[2,:]))+'; # mesh deformation gradient. Mesh nodes X are mapped to x=F*(X-X0) \n')
105 polyFile.write('X0='+' '.join(map(str, self.X0))+'; # mesh shift. Mesh nodes X are mapped to x=F*(X-X0) \n')
106 polyFile.write('periodicFaceIDs='+' '.join(map(str, self.periodicFaceIDs))+'; # Seed face IDs selecting active translations from the full detected lattice; -1 enables all \n')
107 polyFile.close()
108
109def readEVLtxt(filename):
110 evlFile = open(filename+'.txt', "r")
111 numNetNodes=int(evlFile.readline().rstrip())
112 numLoops=int(evlFile.readline().rstrip())
113 numLinks=int(evlFile.readline().rstrip())
114 numLoopNodes=int(evlFile.readline().rstrip())
115 numSpInc=int(evlFile.readline().rstrip())
116 numPolyInc=int(evlFile.readline().rstrip())
117 numPolyIncNodes=int(evlFile.readline().rstrip())
118 numPolyIncEdges=int(evlFile.readline().rstrip())
119 numEDrow=int(evlFile.readline().rstrip())
120 numCDrow=int(evlFile.readline().rstrip())
121 evl=EVL();
122 evl.nodes=np.empty([numNetNodes, 3])
123 for k in np.arange(numNetNodes):
124 data=np.fromstring(evlFile.readline().rstrip(), sep=' ')
125 evl.nodes[k,:]=data[1:4]
126 return evl
127
128def readAUXtxt(filename):
129 auxFile = open(filename+'.txt', "r")
130 numNodes=int(auxFile.readline().rstrip())
131 numGPs=int(auxFile.readline().rstrip())
132 numPGPP=int(auxFile.readline().rstrip())
133 aux=AUX();
134 aux.gaussPoints=np.empty([numGPs, 41])
135 for k in np.arange(numNodes):
136 np.meshNodes=np.fromstring(auxFile.readline().rstrip(), sep=' ')
137 for k in np.arange(numGPs):
138 aux.gaussPoints[k,:]=np.fromstring(auxFile.readline().rstrip(), sep=' ')
139 return aux
140
141def getStringInFile(fileName,variable):
142 with open(fileName) as f:
143 datafile = f.readlines()
144 found = False # This isn't really necessary
145 for line in datafile:
146# print(line)
147 if variable in line:
148 # found = True # Not necessary
149 foundEqual=line.find('=');
150 foundSemiCol=line.find(';');
151 if line[0:foundEqual].strip()==variable:
152 return line[foundEqual+1:foundSemiCol].strip()
153 return 'Not Found' # Because you finished the search without finding
154
155def getValueInFile(fileName,variable):
156 return float(getStringInFile(fileName,variable))
157
158def readFfile(folder):
159 F=np.loadtxt(folder +'/F_0.txt');
160 with open('./F/F_labels.txt') as f:
161 lines = f.readlines()
162 for idx in range(len(lines)):
163 lines[idx] = lines[idx].rstrip()
164 return F,lines
165
166def getFarray(F,Flabels,label):
167 k=0;
168 for line in Flabels:
169 if line==label:
170 if F.ndim==1:
171 return F[k]
172 else:
173 return F[:,k]
174 k=k+1
175 return np.zeros(shape=(0,0))
176
177def setInputVariable(fileName,variable,newVal):
178 variable=variable.strip()
179 with fileinput.FileInput(fileName, inplace=True) as file:
180 for line in file:
181 if variable in line:
182 foundPound=line.find('#');
183 foundEqual=line.find('=');
184 foundSemiCol=line.find(';');
185 if (foundPound==-1 or foundPound > foundSemiCol) and (foundSemiCol>foundEqual) and (variable == line[0:foundEqual].strip()):
186 oldVal=line[foundEqual+1:foundSemiCol]
187 line = line.replace(oldVal,newVal)
188 print(line, file=sys.stderr)
189 sys.stdout.write(line)
190
191def setInputMatrix(fileName,variable,newVal):
192 with fileinput.FileInput(fileName, inplace=True) as file:
193 num_rows, num_cols = newVal.shape
194 if num_rows==1:
195 raise ValueError(variable+' is a vector. Use setInputVector instead of setInputMatrix')
196 writeLine=True
197 for line in file:
198 foundPound=line.find('#');
199 foundEqual=line.find('=');
200 foundSemiCol=line.find(';');
201 if (foundPound==-1 or foundPound > foundSemiCol) and foundEqual>0:
202 writeLine=True
203# if variable in line:
204 if (variable == line[0:foundEqual].strip()):
205 if foundPound==-1 and foundEqual>=len(variable):
206 line=variable+'='
207 for i in range(0,num_rows-1):
208 line=line+' '.join(map(str, newVal[i,:]))+'\n'
209 line=line+' '.join(map(str, newVal[num_rows-1,:]))+';\n'
210 sys.stdout.write(line)
211 writeLine=False # need to skip lines until we find another variable declaration to erase old matrix
212 if writeLine:
213 sys.stdout.write(line)
214
215def setInputVector(fileName,variable,newVal,newCom):
216 with fileinput.FileInput(fileName, inplace=True) as file:
217 for line in file:
218 foundPound=line.find('#');
219 foundEqual=line.find('=');
220 foundSemiCol=line.find(';');
221 #if (foundPound==-1 or foundPound > foundSemiCol) and foundEqual>0 and variable in line:
222 if (foundPound==-1 or foundPound > foundSemiCol) and foundEqual>0 and (variable == line[0:foundEqual].strip()):
223 line=variable+'='+' '.join(map(str, newVal))+'; # '+newCom+'\n'
224 print(line, file=sys.stderr)
225 sys.stdout.write(line)
226
227
228def angleAxis(theta,a):
229 a=a/np.linalg.norm(a) # normalize axis a
230 return np.identity(3)*np.cos(theta)+np.array([[0,-a[2],a[1]],[a[2],0,-a[0]],[-a[1],a[0],0]])*np.sin(theta)+np.outer(a,a)*(1-np.cos(theta))
__init__(self, materialFile)
write(self, folderName)
setInputVector(fileName, variable, newVal, newCom)
readFfile(folder)
setInputVariable(fileName, variable, newVal)
getStringInFile(fileName, variable)
setInputMatrix(fileName, variable, newVal)
getFarray(F, Flabels, label)
readEVLtxt(filename)
readAUXtxt(filename)
angleAxis(theta, a)
getValueInFile(fileName, variable)