Page MenuHomec4science

utils.py
No OneTemporary

File Metadata

Created
Thu, Mar 20, 09:08

utils.py

# -*- coding: utf-8 -*-
"""
Created on Tue Dec 26 07:14:15 2023
@author: srpv
contact: vigneashwara.solairajapandiyan@empa.ch
contact: vigneashwara.pandiyan@tii.ae
The codes in this following script will be used for the publication of the following work
"Dynamics of in-situ alloying of Ti6Al4V-Fe by means of acoustic emission monitoring
supported by operando synchrotron X-ray diffraction"
@any reuse of this code should be authorized by the first owner, code author
"""
# %%
# Librariies to import
import matplotlib.pyplot as plt
import numpy as np
from prettytable import PrettyTable
import torch.nn as nn
import torch
import pandas as pd
''' The script is more hard code than being generic'''
marker = ["*", ">", "X", "o", "s", "d"]
color = ['blue', 'green', 'red', 'cyan', 'orange', 'purple']
mnist_classes = ['Ti64', 'Ti64_3Fe', 'Ti64_6Fe']
graph_title = "Feature space distribution"
def init_weights(m):
if isinstance(m, nn.Conv1d):
torch.nn.init.kaiming_normal_(m.weight)
def count_parameters(model):
table = PrettyTable(["Modules", "Parameters"])
total_params = 0
for name, parameter in model.named_parameters():
if not parameter.requires_grad:
continue
param = parameter.numel()
table.add_row([name, param])
total_params += param
print(table)
print(f"Total Trainable Params: {total_params}")
return total_params
def plot_embeddings(embeddings, targets, graph_name_2D, xlim=None, ylim=None):
plt.figure(figsize=(7, 5))
count = 0
for i in np.unique(targets):
inds = np.where(targets == i)[0]
plt.scatter(embeddings[inds, 0], embeddings[inds, 1], alpha=0.7,
color=color[count], marker=marker[count], s=100)
count = count+1
if xlim:
plt.xlim(xlim[0], xlim[1])
if ylim:
plt.ylim(ylim[0], ylim[1])
plt.legend(mnist_classes, bbox_to_anchor=(1.32, 1.05))
plt.xlabel('Weights_1', labelpad=10)
plt.ylabel('Weights_2', labelpad=10)
plt.title(str(graph_title), fontsize=15)
plt.savefig(graph_name_2D, bbox_inches='tight', dpi=600)
plt.show()
def Three_embeddings(embeddings, targets, graph_name, ang, xlim=None, ylim=None):
group = targets
df2 = pd.DataFrame(group)
df2.columns = ['Categorical']
df2 = df2['Categorical'].replace(0, 'Ti64')
df2 = pd.DataFrame(df2)
df2 = df2['Categorical'].replace(1, 'Ti64_3Fe')
df2 = pd.DataFrame(df2)
df2 = df2['Categorical'].replace(2, 'Ti64_6Fe')
df2 = pd.DataFrame(df2)
group = pd.DataFrame(df2)
group = group.to_numpy()
group = np.ravel(group)
x1 = embeddings[:, 0]
x2 = embeddings[:, 1]
x3 = embeddings[:, 2]
df = pd.DataFrame(dict(x=x1, y=x2, z=x3, label=group))
groups = df.groupby('label')
uniq = list(set(df['label']))
uniq = ['Ti64', 'Ti64_3Fe', 'Ti64_6Fe']
fig = plt.figure(figsize=(12, 6), dpi=100)
fig.set_facecolor('white')
plt.rcParams["legend.markerscale"] = 2
ax = plt.axes(projection='3d')
ax.grid(False)
ax.view_init(azim=ang) # 115
marker = ["*", ">", "X", "o", "s", "d"]
color = ['green', 'red', 'blue', 'cyan', 'orange', 'purple']
ax.set_facecolor('white')
ax.w_xaxis.pane.fill = False
ax.w_yaxis.pane.fill = False
ax.w_zaxis.pane.fill = False
ax.xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
ax.zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))
# make the grid lines transparent
ax.xaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)
ax.yaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)
ax.zaxis._axinfo["grid"]['color'] = (1, 1, 1, 0)
graph_title = "Feature space distribution"
j = 0
for i in uniq:
print(i)
indx = group == i
a = x1[indx]
b = x2[indx]
c = x3[indx]
ax.plot(a, b, c, color=color[j], label=uniq[j], marker=marker[j], linestyle='', ms=7)
j = j+1
plt.xlabel('Weights_1', labelpad=10)
plt.ylabel('Weights_2', labelpad=10)
ax.set_zlabel('Weights_3', labelpad=10)
plt.title(str(graph_title), fontsize=15)
plt.legend(markerscale=20)
plt.locator_params(nbins=6)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.legend(loc='upper left', frameon=False)
plt.savefig(graph_name, bbox_inches='tight', dpi=400)
plt.show()
return ax, fig
def dataprocessing(df):
database = df
print(database.shape)
database = database.apply(lambda x: (x - np.mean(x))/np.std(x), axis=1)
# anomaly_database=anomaly_database.to_numpy().astype(np.float64)
return database

Event Timeline