Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
mdSolidSolutionNoiseSample/main.py
Go to the documentation of this file.
1import os
2import sys
3#import vtk
4import glob
5import string
6import numpy as np
7import matplotlib.pyplot as plt
8
9#plt.rcParams["text.usetex"] = True
10import matplotlib as mpl
11import matplotlib.transforms as mtransforms
12
13sys.path.append("../../build/tools/pyMoDELib/")
14import pyMoDELib
15from scipy.signal import correlate2d
16from scipy.stats import norm
17from matplotlib import cm
18from matplotlib.colors import Normalize
19
20sys.path.append("../../python")
21from modlibUtils import *
22from pathlib import Path
23
24# Define all file templates (using pathlib for cross-platform paths)
25file_templates = {
26 "dd_file": Path("../../Library/DislocationDynamics/DD.txt"),
27 "noise_file": Path("../../Library/GlidePlaneNoise/MDSolidSolution.txt"),
28 "material_file": Path("../../Library/Materials/FeCrAl_Fe.txt"),
29 "elastic_deformation_file": Path(
30 "../../Library/ElasticDeformation/ElasticDeformation.txt"
31 ),
32 "mesh": Path("../../Library/Meshes/unitCube24.msh"),
33 "microstructure": Path(
34 "../../Library/Microstructures/periodicDipoleIndividual.txt"
35 ),
36}
37
38MDSolidSolution_parameters = {
39 "variables": {
40 # Scalar parameters (use setInputVariable)
41 "type": "MDSolidSolutionNoise",
42 "tag": 1,
43 "seed": 2,
44 "outputNoise": 1,
45 "a_cai_SI": 1,
46 # File paths (convert to absolute paths)
47 "correlationFile_xz": Path(
48 "../../Library/GlidePlaneNoise/MoDELCompatible_FeCr8_xz.vtk"
49 ).resolve(),
50 "correlationFile_yz": Path(
51 "../../Library/GlidePlaneNoise/MoDELCompatible_FeCr8_yz.vtk"
52 ).resolve(),
53 },
54 "vectors": {
55 # Vector parameters with comments (use setInputVector)
56 "gridSize": {
57 "value": np.array([100, 100, 1]),
58 "comment": "number of grid points in each direction",
59 },
60 "gridSpacing_SI": {
61 "value": np.array([1.0e-10, 1.0e-10, 1e-10]),
62 "comment": "grid spacing in each direction",
63 },
64 },
65 "copy_to": "inputFiles/MDSolidSolution.txt",
66}
67
68Material_parameters = {
69 "variables": {
70 "enabledSlipSystems": "Shockley",
71 #'glidePlaneNoise': ['MDSolidSolution.txt', 'MDStackingFault.txt'],
72 "glidePlaneNoise": "MDSolidSolution.txt",
73 "atomsPerUnitCell": "1",
74 "dislocationMobilityType": "default",
75 },
76 "copy_to": "inputFiles/FeCrAl_Fe.txt",
77}
78
79Polycrystal_parameters = {
80 "parameters": {
81 "absoluteTemperature": 1,
82 "grain1globalX1": np.array([0, 1, 1]),
83 "grain1globalX3": np.array([-1, 1, -1]),
84 "boxEdges": np.array([[0, 1, 1], [-2, -1, 1], [-1, 1, -1]]),
85 "boxScaling": np.array([200, 200, 200]),
86 #'X0': np.array([0.5, 0.5, 0.5]),
87 "X0": np.array([0.0, 0.0, 0.0]),
88 "periodicFaceIDs": np.array([0, 1, 2, 3, 4, 5]),
89 "gridSpacing_SI": np.array([1.0e-10, 1.0e-10]),
90 }
91}
92
93def processInitialConfigurations() -> None:
94 # Copy all template files
95 print("\033[1;32mCopying template files...\033[0m")
96 for key, src_path in file_templates.items():
97 dest = f"inputFiles/{src_path.name}"
98 shutil.copy2(src_path.resolve(), dest)
99 # shutil.copy2(src_path, dest)
100 print(f"Created {dest}")
101
102 print("\033[1;32mCreating noiseFile\033[0m")
103 # copy noise file into inputFiles
104 shutil.copy2(
105 MDSolidSolution_parameters["variables"]["correlationFile_xz"], "inputFiles/"
106 )
107 shutil.copy2(
108 MDSolidSolution_parameters["variables"]["correlationFile_yz"], "inputFiles/"
109 )
110 # copy declared variables to the configuration txt file
111 for param, value in MDSolidSolution_parameters["variables"].items():
112 if "correlationFile" in param:
113 relativePath = f"{str(value).split('/')[-1]}"
114 setInputVariable(MDSolidSolution_parameters["copy_to"], param, relativePath)
115 else:
116 setInputVariable(MDSolidSolution_parameters["copy_to"], param, str(value))
117 for param, data in MDSolidSolution_parameters["vectors"].items():
118 setInputVector(
119 MDSolidSolution_parameters["copy_to"], param, data["value"], data["comment"]
120 )
121
122 # Process material file
123 print("\033[1;32mCreating materialFile...\033[0m")
124 # print(Material_parameters['variables'].items())
125 matParams = Material_parameters["variables"]
126 setInputVariable(
127 Material_parameters["copy_to"],
128 "enabledSlipSystems",
129 matParams["enabledSlipSystems"],
130 )
131
132 setInputVariable(
133 Material_parameters["copy_to"], "glidePlaneNoise", matParams["glidePlaneNoise"]
134 )
135
136 setInputVariable(
137 Material_parameters["copy_to"],
138 "atomsPerUnitCell",
139 matParams["atomsPerUnitCell"],
140 )
141 setInputVariable(
142 Material_parameters["copy_to"],
143 "dislocationMobilityType",
144 matParams["dislocationMobilityType"],
145 )
146
147 # Process polycrystal
148 # pf = PolyCrystalFile('FeCrAl_Fe.txt')
149 pf = PolyCrystalFile(Material_parameters["copy_to"].split("/")[-1])
150 # pf.meshFile='unitCube24.msh'
151 pf.meshFile = f'{str(file_templates["mesh"]).split("/")[-1]}'
152 for param, value in Polycrystal_parameters["parameters"].items():
153 setattr(pf, param, value)
154 pf.write("inputFiles")
155
156
157def circularShift(corrArray: np.ndarray, gridSize: np.ndarray) -> np.ndarray:
158 NX, NY = np.squeeze(gridSize[0]), np.squeeze(gridSize[1])
159 shiftY = NY / 2
160 shiftX = NX / 2
161 tempArr = np.zeros(NX * NY)
162 for y in np.arange(NY):
163 newY = int((y + shiftY) % NY)
164 for x in np.arange(NX):
165 newX = int((x + shiftX) % NX)
166 tempArr[newY * NX + newX] += corrArray[y * NX + x]
167 return tempArr
168
169
170def main() -> int:
171 # Preparing input files
172 folders = ["inputFiles"]
173 for x in folders:
174 # remove existing data
175 if os.path.exists(x):
176 shutil.rmtree(x)
177 # create necessary folder structure for the simulation
178 os.makedirs(x)
179
180 # set simulation parameters in inputFiles
181 processInitialConfigurations()
182
183 simulationDir = os.path.abspath(".")
184 ddBase = pyMoDELib.DefectiveCrystalBase(simulationDir)
185
186 matFile = "inputFiles/FeCrAl_Fe.txt"
187 absoluteTemp = 1
188 mat = pyMoDELib.PolycrystallineMaterialBase(matFile, absoluteTemp)
189 b_SI = getValueInFile(f"{matFile}", "b_SI")
190 mu0_SI = getValueInFile(f"{matFile}", "mu0_SI")
191 rho_SI = getValueInFile(f"{matFile}", "rho_SI")
192
193 tag = "1"
194 originalCorrFile_xz = "./inputFiles/MoDELCompatible_FeCr8_xz.vtk"
195 originalCorrFile_yz = "./inputFiles/MoDELCompatible_FeCr8_yz.vtk"
196 seed = 0
197 gridSize = np.array([100, 100, 1])
198 gridSpacing = np.array([1e-10, 1e-10, 1e-10]) / b_SI
199 latticeBasis = np.array([[1, 0], [0, 1]]).reshape(2, 2)
200
201 a_cai_SI = 1e-10 / b_SI # in meter
202 ssNoise = pyMoDELib.MDSolidSolutionNoise(
203 mat,
204 tag,
205 originalCorrFile_xz,
206 originalCorrFile_yz,
207 seed,
208 gridSize.reshape(3, 1),
209 gridSpacing.reshape(3, 1),
210 latticeBasis,
211 a_cai_SI,
212 )
213 realizationNum = 100
214 sampledNoises = np.array(ssNoise.sampleAverageNoise(realizationNum)) * mu0_SI**2
215 # Get all even indices (0, 2, 4,...) for xz
216 xzNoises = sampledNoises[::2]
217 # Get all odd indices (1, 3, 5,...) for yz
218 yzNoises = sampledNoises[1::2]
219
220 fig, axs = plt.subplots(1, 2, figsize=(16,6), dpi=200)
221 # (returns a veiw if possible), flattens the array for histogram
222 xzNoises = xzNoises.ravel()
223 yzNoises = yzNoises.ravel()
224 axs[0].hist(xzNoises, density=True, alpha=0.3, bins='auto', label=f"R{realizationNum}")
225 axs[1].hist(yzNoises, density=True, alpha=0.3, bins='auto', label=f"R{realizationNum}")
226
227 std_xz = np.std(xzNoises)
228 std_yz = np.std(yzNoises)
229 print(f"std_xz = {std_xz} Pa2")
230 print(f"std_yz = {std_yz} Pa2")
231
232 # Annotate in the top right, offsetting each annotation
233 #axs[0].text(
234 # 0.98, 0.95 - 0.05*i,
235 # f'R{realizationNum} = STD {std_xz:.3g} Pa2',
236 # transform=axs[0].transAxes,
237 # ha='right',
238 # va='top'
239 #)
240 #axs[1].text(
241 # 0.98, 0.95 - 0.05*i,
242 # f'R{realizationNum} = STD {std_yz:.3g} Pa2',
243 # transform=axs[1].transAxes,
244 # ha='right',
245 # va='top'
246 #)
247
248 axs[0].grid(True)
249 axs[0].set_title(f"noise xz")
250 axs[0].set_xlabel(f"")
251 axs[0].set_ylabel(f"")
252 axs[0].legend()
253 axs[1].grid(True)
254 axs[1].set_title(f"noise yz")
255 axs[1].set_xlabel(f"")
256 axs[1].set_ylabel(f"")
257 axs[1].legend()
258 fig.savefig(f'sampledNoiseDistribution_R{realizationNum}.png')
259 plt.close()
260
261 return 0
262
263
264if __name__ == "__main__":
265 main()
REAL split