Mechanics of Defect Evolution Library
Loading...
Searching...
No Matches
mdSolidSolutionCorrelations/main.py
Go to the documentation of this file.
1import os
2import sys
3import 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": 1e-16,
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
93
94def readVTKnoise(fname: str):
95 reader = vtk.vtkGenericDataObjectReader()
96 reader.SetFileName(fname) # declare the vtk filename
97 reader.ReadAllVectorsOn() # read all vector data
98 reader.ReadAllScalarsOn() # read all scalar data
99 reader.Update() # update to new file
100 # read data dimensions
101 dims = [0, 0, 0]
102 reader.GetOutput().GetDimensions(dims)
103 NX, NY, NZ = dims
104 # NX, NY, NZ = reader.GetOutput().GetDimensions()
105 # creates dynamic point data object
106 pointData = reader.GetOutput().GetPointData()
107
108 # Initialize a list to store scalar arrays
109 scalarArrays = []
110 # Iterate over the number of arrays in pointData
111 for i in range(pointData.GetNumberOfArrays()):
112 array = pointData.GetArray(i)
113 # Check if it's a scalar array
114 if array.GetNumberOfComponents() == 1:
115 scalarArrays.append(np.array(array))
116 noiseScalars = scalarArrays[0]
117 noiseScalars = np.reshape(noiseScalars, shape=(NX, NY))
118 return noiseScalars, dims
119
120
121def processInitialConfigurations() -> None:
122 # Copy all template files
123 print("\033[1;32mCopying template files...\033[0m")
124 for key, src_path in file_templates.items():
125 dest = f"inputFiles/{src_path.name}"
126 shutil.copy2(src_path.resolve(), dest)
127 # shutil.copy2(src_path, dest)
128 print(f"Created {dest}")
129
130 print("\033[1;32mCreating noiseFile\033[0m")
131 # copy noise file into inputFiles
132 shutil.copy2(
133 MDSolidSolution_parameters["variables"]["correlationFile_xz"], "inputFiles/"
134 )
135 shutil.copy2(
136 MDSolidSolution_parameters["variables"]["correlationFile_yz"], "inputFiles/"
137 )
138 # copy declared variables to the configuration txt file
139 for param, value in MDSolidSolution_parameters["variables"].items():
140 if "correlationFile" in param:
141 relativePath = f"{str(value).split('/')[-1]}"
142 setInputVariable(MDSolidSolution_parameters["copy_to"], param, relativePath)
143 else:
144 setInputVariable(MDSolidSolution_parameters["copy_to"], param, str(value))
145 for param, data in MDSolidSolution_parameters["vectors"].items():
147 MDSolidSolution_parameters["copy_to"], param, data["value"], data["comment"]
148 )
149
150 # Process material file
151 print("\033[1;32mCreating materialFile...\033[0m")
152 # print(Material_parameters['variables'].items())
153 matParams = Material_parameters["variables"]
155 Material_parameters["copy_to"],
156 "enabledSlipSystems",
157 matParams["enabledSlipSystems"],
158 )
159
161 Material_parameters["copy_to"], "glidePlaneNoise", matParams["glidePlaneNoise"]
162 )
163
165 Material_parameters["copy_to"],
166 "atomsPerUnitCell",
167 matParams["atomsPerUnitCell"],
168 )
170 Material_parameters["copy_to"],
171 "dislocationMobilityType",
172 matParams["dislocationMobilityType"],
173 )
174
175 # Process polycrystal
176 # pf = PolyCrystalFile('FeCrAl_Fe.txt')
177 pf = PolyCrystalFile(Material_parameters["copy_to"].split("/")[-1])
178 # pf.meshFile='unitCube24.msh'
179 pf.meshFile = f'{str(file_templates["mesh"]).split("/")[-1]}'
180 for param, value in Polycrystal_parameters["parameters"].items():
181 setattr(pf, param, value)
182 pf.write("inputFiles")
183
184
185def circularShift(corrArray: np.ndarray, gridSize: np.ndarray) -> np.ndarray:
186 NX, NY = np.squeeze(gridSize[0]), np.squeeze(gridSize[1])
187 shiftY = NY / 2
188 shiftX = NX / 2
189 tempArr = np.zeros(NX * NY)
190 for y in np.arange(NY):
191 newY = int((y + shiftY) % NY)
192 for x in np.arange(NX):
193 newX = int((x + shiftX) % NX)
194 tempArr[newY * NX + newX] += corrArray[y * NX + x]
195 return tempArr
196
197
198def main() -> int:
199 # Preparing input files
200 folders = ["inputFiles"]
201 for x in folders:
202 # remove existing data
203 if os.path.exists(x):
204 shutil.rmtree(x)
205 # create necessary folder structure for the simulation
206 os.makedirs(x)
207
208 # set simulation parameters in inputFiles
210
211 simulationDir = os.path.abspath(".")
212 ddBase = pyMoDELib.DefectiveCrystalBase(simulationDir)
213
214 matFile = "inputFiles/FeCrAl_Fe.txt"
215 absoluteTemp = 1
216 mat = pyMoDELib.PolycrystallineMaterialBase(matFile, absoluteTemp)
217 b_SI = getValueInFile(f"{matFile}", "b_SI")
218 mu0_SI = getValueInFile(f"{matFile}", "mu0_SI")
219 rho_SI = getValueInFile(f"{matFile}", "rho_SI")
220
221 tag = "1"
222 originalCorrFile_xz = "./inputFiles/MoDELCompatible_FeCr8_xz.vtk"
223 originalCorrFile_yz = "./inputFiles/MoDELCompatible_FeCr8_yz.vtk"
224 seed = 1
225 gridSize = np.array([100, 100, 1])
226 gridSpacing = np.array([1e-10, 1e-10, 1e-10]) / b_SI
227 latticeBasis = np.array([[1, 0], [0, 1]]).reshape(2, 2)
228 a_cai_SI = 1e-10 / b_SI
229
230 ssNoise = pyMoDELib.MDSolidSolutionNoise(
231 mat,
232 tag,
233 originalCorrFile_xz,
234 originalCorrFile_yz,
235 seed,
236 gridSize.reshape(3, 1),
237 gridSpacing.reshape(3, 1),
238 latticeBasis,
239 a_cai_SI,
240 )
241 realizationNum = 100
242 corr_xz, corr_yz = np.array(ssNoise.averageNoiseCorrelation(realizationNum)) * mu0_SI**2
243
244 corr_xz = circularShift(corr_xz, gridSize)
245 corr_yz = circularShift(corr_yz, gridSize)
246 corr_xz = corr_xz.reshape(100, 100)
247 corr_yz = corr_yz.reshape(100, 100)
248
249 fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), dpi=200)
250 # First plot with colorbar
251 axes[0].set_title("corr_xz")
252 im0 = axes[0].imshow(corr_xz, cmap="coolwarm", origin="lower")
253 fig.colorbar(im0, ax=axes[0], label="Pa2")
254 axes[0].set_xlabel("X")
255 axes[0].set_ylabel("Y")
256
257 # Second plot with colorbar
258 axes[1].set_title("corr_yz")
259 im1 = axes[1].imshow(corr_yz, cmap="coolwarm", origin="lower")
260 fig.colorbar(im1, ax=axes[1], label="Pa2")
261 axes[1].set_xlabel("X")
262 axes[1].set_ylabel("Y")
263 plt.tight_layout()
264 fig.savefig(f"ensemCorrSS_R{realizationNum}.png", transparent=True)
265
266 return 0
267
268
269if __name__ == "__main__":
270 main()
np.ndarray circularShift(np.ndarray corrArray, np.ndarray gridSize)
setInputVector(fileName, variable, newVal, newCom)
setInputVariable(fileName, variable, newVal)
getValueInFile(fileName, variable)
REAL split