Skip to content
Snippets Groups Projects
Commit 54b5dd5e authored by Brian Christopher Wasels's avatar Brian Christopher Wasels
Browse files

visualierungsscript update

parent bceae19f
Branches
No related tags found
No related merge requests found
No preview for this file type
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
import matplotlib import matplotlib
import numpy as np import numpy as np
import pyvista as pv import pyvista as pv
from matplotlib.colors import ListedColormap from matplotlib.colors import ListedColormap
from matplotlib.pyplot import figure from matplotlib.pyplot import figure
from matplotlib import colors from matplotlib import colors
import torch import torch
import copy import copy
import UNet_V16 as UNet import UNet_V16 as UNet
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
def predict_stress(image_id, normalization, model, dataset,grain_data, UNet, device,threshold = 0.15): def predict_stress(image_id, normalization, model, dataset,grain_data, UNet, device,threshold = 0.15):
input, output = dataset[image_id] input, output = dataset[image_id]
grain,_ = grain_data[image_id] grain,_ = grain_data[image_id]
grain = copy.deepcopy(grain) grain = copy.deepcopy(grain)
grain = torch.unsqueeze(grain,0) grain = torch.unsqueeze(grain,0)
grain = grain.detach().numpy() grain = grain.detach().numpy()
input = copy.deepcopy(input) input = copy.deepcopy(input)
output = copy.deepcopy(output) output = copy.deepcopy(output)
input = torch.unsqueeze(input,0) input = torch.unsqueeze(input,0)
output = torch.unsqueeze(output,0) output = torch.unsqueeze(output,0)
xb = UNet.to_device(input, device) xb = UNet.to_device(input, device)
model.eval() model.eval()
prediction = model(xb) prediction = model(xb)
input = input.detach().numpy() input = input.detach().numpy()
prediction = prediction.detach().numpy() prediction = prediction.detach().numpy()
output = output.detach().numpy() output = output.detach().numpy()
prediction = rescale(prediction, normalization) prediction = rescale(prediction, normalization)
output = rescale(output, normalization) output = rescale(output, normalization)
error = (abs(output - prediction)/output) error = (abs(output - prediction)/output)
print(f'Maximum error is : {error.max()*100.:.4} %') print(f'Maximum error is : {error.max()*100.:.4} %')
print(f'average error is : {error.mean()*100.:.4} %') print(f'average error is : {error.mean()*100.:.4} %')
right_predic = (error < threshold).sum() right_predic = (error < threshold).sum()
print(f'{(right_predic/error.size)*100.:.4}% of voxels have a diviation less than {threshold*100.}%') print(f'{(right_predic/error.size)*100.:.4}% of voxels have a diviation less than {threshold*100.}%')
grains = grain_matrix(grain) grains = grain_matrix(grain)
return error,grains,prediction, output return error,grains,prediction, output
def grain_matrix(input): def grain_matrix(input):
matrix_grains = input[0,0,:,:,:] matrix_grains = input[0,0,:,:,:]
matrix_ferrit = input[0,5,:,:,:] #matrix with elements = 1 if the phase is ferrit else 0 matrix_ferrit = input[0,5,:,:,:] #matrix with elements = 1 if the phase is ferrit else 0
#unique_angles = np.unique(matrix_grains) #unique_angles = np.unique(matrix_grains)
matrix_ferrit_grains = np.multiply(matrix_grains, matrix_ferrit)# matrix where only the ferrit grains are nonzero matrix_ferrit_grains = np.multiply(matrix_grains, matrix_ferrit)# matrix where only the ferrit grains are nonzero
index_ferrit_angles = np.unique(matrix_ferrit_grains[matrix_ferrit_grains != 0]) index_ferrit_angles = np.unique(matrix_ferrit_grains[matrix_ferrit_grains != 0])
index_martensite_angles = np.setdiff1d(np.unique(matrix_grains),index_ferrit_angles) index_martensite_angles = np.setdiff1d(np.unique(matrix_grains),index_ferrit_angles)
for index, angle in enumerate(index_ferrit_angles): for index, angle in enumerate(index_ferrit_angles):
matrix_grains[matrix_grains == angle] = (index) # matrix with id for each grain add 1 to perfome the elementwise multiplication to get the index of phase grains matrix_grains[matrix_grains == angle] = (index) # matrix with id for each grain add 1 to perfome the elementwise multiplication to get the index of phase grains
for index, angle in enumerate(index_martensite_angles): for index, angle in enumerate(index_martensite_angles):
matrix_grains[matrix_grains == angle] = (index + len(index_ferrit_angles) +100) # matrix with id for each grain add 1 to perfome the elementwise multiplication to get the index of phase grains matrix_grains[matrix_grains == angle] = (index + len(index_ferrit_angles) +100) # matrix with id for each grain add 1 to perfome the elementwise multiplication to get the index of phase grains
return matrix_grains return matrix_grains
def rescale(output, normalization): def rescale(output, normalization):
output_rescale = output.reshape(output.shape[2],output.shape[3],output.shape[4]) output_rescale = output.reshape(output.shape[2],output.shape[3],output.shape[4])
if normalization is not None: if normalization is not None:
min_label, max_label = normalization min_label, max_label = normalization
output_rescale *= max_label output_rescale *= max_label
output_rescale += min_label output_rescale += min_label
return output_rescale return output_rescale
def export_vtk(error, grains, stress, label,path): def export_vtk(error, grains, stress, label,path):
grid = pv.UniformGrid() grid = pv.UniformGrid()
grid.dimensions = np.array(error.shape) +1 grid.dimensions = np.array(error.shape) +1
grid.spacing = (1,1,1) grid.spacing = (1,1,1)
grid.cell_data["error"] = error.flatten(order = "F") grid.cell_data["error"] = error.flatten(order = "F")
grid.cell_data["grain"] = grains.flatten(order = "F") grid.cell_data["grain"] = grains.flatten(order = "F")
grid.cell_data["stress"] = stress.flatten(order = "F") grid.cell_data["stress"] = stress.flatten(order = "F")
grid.cell_data["label"] = label.flatten(order = "F") grid.cell_data["label"] = label.flatten(order = "F")
grid.save(f'{path}.vtk') grid.save(f'{path}.vtk')
def get_colormap(mesh): def get_colormap(mesh):
black = np.array([11/256, 11/256, 11/256, 1]) black = np.array([11/256, 11/256, 11/256, 1])
yellow = np.array([255/256, 237/256, 0/256, 1]) yellow = np.array([255/256, 237/256, 0/256, 1])
orange = np.array([245/256, 167/256, 0/256, 1]) orange = np.array([245/256, 167/256, 0/256, 1])
red = np.array([203/256, 6/256, 29/256, 1]) red = np.array([203/256, 6/256, 29/256, 1])
bordeaux = np.array([160/256, 15/256, 53/256, 1]) bordeaux = np.array([160/256, 15/256, 53/256, 1])
blue = np.array([0/256, 84/256, 159/256, 1]) blue = np.array([0/256, 84/256, 159/256, 1])
mapping = np.linspace(mesh['error'].min(), mesh['error'].max(),256) mapping = np.linspace(mesh['error'].min(), mesh['error'].max(),256)
newcolors = np.empty((256,4)) newcolors = np.empty((256,4))
newcolors[mapping >=0.15] = red newcolors[mapping >=0.15] = red
#newcolors[mapping <0.5] = red #newcolors[mapping <0.5] = red
#newcolors[mapping <0.3] = orange #newcolors[mapping <0.3] = orange
newcolors[mapping <0.15] = blue newcolors[mapping <0.15] = blue
#newcolors[mapping <0.05] = black #newcolors[mapping <0.05] = black
return ListedColormap(newcolors) return ListedColormap(newcolors)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
path_to_UNET = 'F:/RWTH/HiWi_IEHK/DAMASK3' path_to_UNET = 'E:/Data/damask3'
export_path = 'F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_angles' export_path = 'E:/Data/damask3/Bericht/vtk/result_angles'
UNet = UNet UNet = UNet
Training_data_32 = torch.load(f'{path_to_UNET}/UNet/Input/TD_norm_32_angles.pt') Training_data_32 = torch.load(f'{path_to_UNET}/UNet/Input/TD_norm_32_angles.pt')
normalization_32 = np.load(f'{path_to_UNET}/UNet/Input/Norm_min_max_32_phase.npy', allow_pickle=True) normalization_32 = np.load(f'{path_to_UNET}/UNet/Input/Norm_min_max_32_phase.npy', allow_pickle=True)
grain_data_32 = torch.load(f'{path_to_UNET}/UNet/Input/TD_norm_32_angles.pt') grain_data_32 = torch.load(f'{path_to_UNET}/UNet/Input/TD_norm_32_angles.pt')
model = UNet.UNet() model = UNet.UNet()
model.load_state_dict(torch.load(f'{path_to_UNET}/UNet/output/V16/Unet_dict_V16.pth',map_location=torch.device('cpu'))) model.load_state_dict(torch.load(f'{path_to_UNET}/UNet/output/V16/Unet_dict_V16.pth',map_location=torch.device('cpu')))
device = UNet.get_default_device() device = UNet.get_default_device()
model = UNet.to_device(model.double(), device) model = UNet.to_device(model.double(), device)
#sample_index = np.random.randint(low=0, high=len(Training_data_32)) #sample_index = np.random.randint(low=0, high=len(Training_data_32))
sample_index = 1288 sample_index = 1288
print(f'sample number: {sample_index}') print(f'sample number: {sample_index}')
error,grains,prediction,label= predict_stress(sample_index, normalization = normalization_32, model = model, device=device, dataset = Training_data_32,grain_data =grain_data_32,UNet=UNet, threshold=0.15) error,grains,prediction,label= predict_stress(sample_index, normalization = normalization_32, model = model, device=device, dataset = Training_data_32,grain_data =grain_data_32,UNet=UNet, threshold=0.15)
export_vtk(error,grains,prediction,label,export_path) export_vtk(error,grains,prediction,label,export_path)
``` ```
%% Output %% Output
no GPU found no GPU found
sample number: 1288 sample number: 1288
Maximum error is : 124.2 % Maximum error is : 124.2 %
average error is : 9.365 % average error is : 9.365 %
78.4% of voxels have a diviation less than 15.0% 78.4% of voxels have a diviation less than 15.0%
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grid= pv.read('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_angles.vtk') grid= pv.read('E:/Data/damask3/Bericht/vtk/result_angles.vtk')
slice= grid.slice() slice= grid.slice()
pv.global_theme.font.color = 'black' pv.global_theme.font.color = 'black'
pv.global_theme.font.size = 50 pv.global_theme.font.size = 50
slice['stress'] = slice['stress']/1000000000 slice['stress'] = slice['stress']/1000000000
slice['label'] = slice['label']/1000000000
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grid
```
%% Output
UniformGrid (0x20607430d60)
N Cells: 32768
N Points: 35937
X Bounds: 0.000e+00, 3.200e+01
Y Bounds: 0.000e+00, 3.200e+01
Z Bounds: 0.000e+00, 3.200e+01
Dimensions: 33, 33, 33
Spacing: 1.000e+00, 1.000e+00, 1.000e+00
N Arrays: 1
%% Cell type:code id: tags:
``` python
%%capture %%capture
p = pv.Plotter(off_screen=True) p = pv.Plotter(off_screen=True)
sargs_grain= dict( sargs_grain= dict(
title='Phase', title='Phase',
n_labels = 0 n_labels = 0
) )
annotations_grain = { annotations_grain = {
slice['grain'].min(): 'Ferrite', slice['grain'].min(): 'Ferrite',
slice['grain'].max(): 'Martensite', slice['grain'].max(): 'Martensite',
} }
p.add_mesh(slice,scalars="grain",annotations = annotations_grain,cmap='RdBu',scalar_bar_args=sargs_grain ) p.add_mesh(slice,scalars="grain",annotations = annotations_grain,cmap='RdBu',scalar_bar_args=sargs_grain )
p.view_zy() p.view_zy()
p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/grain.png',transparent_background=True) p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/grain.png',transparent_background=True)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%%capture %%capture
p = pv.Plotter(off_screen=True) p = pv.Plotter(off_screen=True)
sargs_error= dict( sargs_error= dict(
title='Error', title='Error',
n_labels = 20 n_labels = 20
) )
annotations_error = { annotations_error = {
0.15: '15%' 0.15: '15%'
} }
colormap_error = get_colormap(slice) colormap_error = get_colormap(slice)
#grid.plot(scalars="error",notebook=False,cmap=colormap_error) #grid.plot(scalars="error",notebook=False,cmap=colormap_error)
p.add_mesh(slice,scalars="error",cmap=colormap_error, annotations=annotations_error, scalar_bar_args=sargs_error) p.add_mesh(slice,scalars="error",cmap=colormap_error, annotations=annotations_error, scalar_bar_args=sargs_error)
p.view_zy() p.view_zy()
p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/error.png',transparent_background=True) p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/error.png',transparent_background=True)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%%capture %%capture
p = pv.Plotter(off_screen=True) p = pv.Plotter(off_screen=True)
sargs = dict( sargs = dict(
title='Stress U-Net (GPa)', title='Stress U-Net (GPa)',
n_labels=2, n_labels=2,
) )
p.add_mesh(slice,scalars="stress",scalar_bar_args=sargs,name='Stress (GPa)') p.add_mesh(slice,scalars="stress",scalar_bar_args=sargs,name='Stress (GPa)')
p.view_zy() p.view_zy()
p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/stress.png',transparent_background=True) p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/stress.png',transparent_background=True)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
%%capture plt.figure(figsize=(12,12))
p = pv.Plotter(off_screen=True) data = slice['label'].reshape(32,32)
sargs = dict(
title='Stress DAMASK (GPa)', data = np.flip(data,1)
n_labels=2, data = np.rot90(data,1)
) plt.imshow(data,cmap='viridis',origin='lower',vmin=0.9,vmax=3.2)
p.add_mesh(slice,scalars="label",scalar_bar_args=sargs,name='Stress DAMASK (GPa)')
p.view_zy() plt.colorbar(orientation="horizontal")
p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/stress_DAMASK.png',transparent_background=True) plt.show()
#plt.savefig('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True)
``` ```
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
grid_angles= pv.read('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_angles.vtk') grid_angles= pv.read('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_angles.vtk')
grid_phase = pv.read('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_phase.vtk') grid_phase = pv.read('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/result_phase.vtk')
divnorm=colors.TwoSlopeNorm(vmin=-0.15, vcenter=0., vmax=0.15) divnorm=colors.TwoSlopeNorm(vmin=-0.15, vcenter=0., vmax=0.15)
difference =(grid_angles['error'] - grid_phase['error']) difference =(grid_angles['error'] - grid_phase['error'])
grid = pv.UniformGrid() grid = pv.UniformGrid()
grid.dimensions =(33,33,33) grid.dimensions =(33,33,33)
grid.spacing = (1,1,1) grid.spacing = (1,1,1)
grid.cell_data["difference"] = difference.flatten(order = "F") grid.cell_data["difference"] = difference.flatten(order = "F")
slice= grid.slice() slice= grid.slice()
#data = slice['difference'].reshape(32,32)
#annotations_difference = {
# 0: '0%'
#}
#p = pv.Plotter(off_screen=False)
#sargs_difference= dict(
# title='Difference',
# n_labels = 2
# )
#grid.plot(scalars="error",notebook=False,cmap=colormap_error)
#p.add_mesh(slice,scalars="difference",scalar_bar_args = sargs_difference, annotations=annotations_difference,cmap='coolwarm', norm=divnorm)
plt.figure(figsize=(12,12)) plt.figure(figsize=(12,12))
data = slice['difference'].reshape(32,32) data = slice['difference'].reshape(32,32)
data = np.flip(data,1) data = np.flip(data,1)
data = np.rot90(data,1) data = np.rot90(data,1)
plt.imshow(data,norm=divnorm,cmap='coolwarm',origin='lower') plt.imshow(data,norm=divnorm,cmap='coolwarm',origin='lower')
#plt.tick_params(axis=’x’, which=’both’, bottom=False, top=False, labelbottom=False)
plt.colorbar(orientation="horizontal") plt.colorbar(orientation="horizontal")
#plt.show() #plt.show()
plt.savefig('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True) plt.savefig('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True)
#p.screenshot('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True)
``` ```
%% Output %% Output
C:\Users\CHRIST~1\AppData\Local\Temp/ipykernel_16636/1273089677.py:30: MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "transparent_background" which is no longer supported as of 3.3 and will become an error in 3.6 C:\Users\CHRIST~1\AppData\Local\Temp/ipykernel_16636/1273089677.py:30: MatplotlibDeprecationWarning: savefig() got unexpected keyword argument "transparent_background" which is no longer supported as of 3.3 and will become an error in 3.6
plt.savefig('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True) plt.savefig('F:/RWTH/HiWi_IEHK/DAMASK3/Bericht/vtk/difference.png',transparent_background=True)
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
slice == grid['difference'][0,:,:] slice == grid['difference'][0,:,:]
``` ```
%% Output %% Output
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
IndexError Traceback (most recent call last) IndexError Traceback (most recent call last)
C:\Users\CHRIST~1\AppData\Local\Temp/ipykernel_16636/473156033.py in <module> C:\Users\CHRIST~1\AppData\Local\Temp/ipykernel_16636/473156033.py in <module>
----> 1 slice == grid['difference'][0,:,:] ----> 1 slice == grid['difference'][0,:,:]
IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed IndexError: too many indices for array: array is 1-dimensional, but 3 were indexed
%% Cell type:code id: tags: %% Cell type:code id: tags:
``` python ``` python
for index in range(len(Training_data_angles)): for index in range(len(Training_data_angles)):
_,label_phase = Training_data_phase[index] _,label_phase = Training_data_phase[index]
_,label_angles = Training_data_angles[index] _,label_angles = Training_data_angles[index]
if not label_phase.equal(label_angles): if not label_phase.equal(label_angles):
print('problem') print('problem')
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment