Particles2023AnalysisHung Namespace Reference

Functions

def plot_result_GL (gl_file)
 Plot the GL data. More...
 
def predict_model (file_name, num_nodes, num_layer)
 Train and evaluate a neural network model for angle of repose prediction. More...
 
def random_forest (file_name)
 Train and evaluate a random forest model for angle of repose prediction. More...
 
def plot_4d (file_name)
 Plot a 3D scatter plot of the training data. More...
 
def plot_relationship (file_name, save)
 Plot the relationship between input parameters and the angle of repose. More...
 
def get_correlation (file_name)
 
def write_calibration_script (str var, str material)
 Generate a calibration script for simulation. More...
 

Variables

dictionary params
 
string file_name_eskal = "Eskal150NN.csv"
 
string file_name_sand = "SandNN.csv"
 
string file_name = "SandNN.csv"
 
def res = predict_model(file_name, j, i)
 
string out = str(i) + ',' + str(j) + ',' + str(res) + "\n"
 

Function Documentation

◆ get_correlation()

def Particles2023AnalysisHung.get_correlation (   file_name)
@brief Calculate the correlation between input parameters and the angle of repose.

This function calculates the correlation matrix between input parameters and the angle of repose.

@param[in] file_name Path to the input data file.

@return The correlation matrix.
216 def get_correlation(file_name):
217  """
218  @brief Calculate the correlation between input parameters and the angle of repose.
219 
220  This function calculates the correlation matrix between input parameters and the angle of repose.
221 
222  @param[in] file_name Path to the input data file.
223 
224  @return The correlation matrix.
225  """
226  pd_data = pd.read_csv(file_name)
227  pd_data.iloc[:, 4] = pd_data.iloc[:, 4] / 90
228  return pd_data.corr().iloc[[4], 0:4]
229 
230 
def get_correlation(file_name)
Definition: Particles2023AnalysisHung.py:216

◆ plot_4d()

def Particles2023AnalysisHung.plot_4d (   file_name)

Plot a 3D scatter plot of the training data.

This function creates a 3D scatter plot for the first three dimensions of the data, using angle of repose for color coding.

Parameters
[in]file_namePath to the input data file.
166 def plot_4d(file_name):
167  """!
168  @brief Plot a 3D scatter plot of the training data.
169 
170  This function creates a 3D scatter plot for the first three dimensions of the data,
171  using angle of repose for color coding.
172 
173  @param[in] file_name Path to the input data file.
174  """
175  data = np.loadtxt(file_name, skiprows=1, delimiter=",")
176  # np.meshgrid
177  X, Y, Z = (data[:, 0], data[:, 1], data[:, 2])
178  T = data[:, 4]
179  fig = plt.figure()
180  ax = plt.axes(projection="3d")
181  # Creating plot
182  ax.scatter3D(X, Y, Z, c=T, alpha=0.7, marker='.')
183  plt.show()
184 
185 
def plot_4d(file_name)
Plot a 3D scatter plot of the training data.
Definition: Particles2023AnalysisHung.py:166

◆ plot_relationship()

def Particles2023AnalysisHung.plot_relationship (   file_name,
  save 
)

Plot the relationship between input parameters and the angle of repose.

This function creates scatter plots to visualize the relationship between each input parameter and the angle of repose.

Parameters
[in]file_namePath to the input data file.
[in]savePath to save the generated plot.
186 def plot_relationship(file_name, save):
187  """!
188  @brief Plot the relationship between input parameters and the angle of repose.
189 
190  This function creates scatter plots to visualize the relationship between each input parameter
191  and the angle of repose.
192 
193  @param[in] file_name Path to the input data file.
194  @param[in] save Path to save the generated plot.
195  """
196  data = np.loadtxt(file_name, skiprows=1, delimiter=",")
197  # data_fig_name = file_name.split(".")[0] + "_dataDistribution"
198  # angle_fig_name = file_name.split(".")[0] + "_angleDistribtion"
199  fig, axes = plt.subplots(1, 4, dpi=100, figsize=(12, 3))
200  name = ['Restitution coefficient', 'Sliding friction', 'Rolling friction', 'Bond number', 'Angle of repose']
201  for i in range(4):
202  if i == 0:
203  axes[i].set_ylabel(name[4])
204  axes[i].scatter(data[:, i], data[:, 4])
205  axes[i].axhline(y=33, xmin=0, xmax=1, c='red' , )
206  # label='Experimental value = $33^{\circ}$')
207  axes[i].set_xlabel(name[i])
208  # axes[i].legend(bbox_to_anchor=(0, 1.02, 1, 0.2), loc="lower left",
209  # mode="expand", borderaxespad=0, ncol=3)
210  axes[i].set_ylim((20, 35))
211 
212  plt.tight_layout()
213  plt.savefig(save, bbox_inches="tight")
214 
215 
def plot_relationship(file_name, save)
Plot the relationship between input parameters and the angle of repose.
Definition: Particles2023AnalysisHung.py:186

◆ plot_result_GL()

def Particles2023AnalysisHung.plot_result_GL (   gl_file)

Plot the GL data.

This function reads the data from a given file and plots the data.

Parameters
[in]gl_filePath to the GL data file.
41 def plot_result_GL(gl_file):
42  """!
43  @brief Plot the GL data.
44 
45  This function reads the data from a given file and plots the data.
46 
47  @param[in] gl_file Path to the GL data file.
48  """
49  data = np.loadtxt(gl_file, delimiter=";", encoding='utf-8-sig')
50  angle = data[:, 4]
51  res_coef = data[:, 0]
52  sliding = data[:, 1]
53  rolling = data[:, 2]
54  bond = data[:, 3]
55 
56  fig, axes = plt.subplots(1, 4, dpi=100, figsize=(7, 5), sharey=True, sharex=False)
57  axes[0].scatter(res_coef[0], angle[0], c='b')
58  color = ['r', 'g', 'y', 'k']
59  for i in range(1, 4, 1):
60  for j in range(4):
61  axes[i].scatter(data[:, i][j], angle[j], c=color[i])
62  axes[i].scatter(data[:, i][j], angle[j], c=color[i])
63  axes[i].scatter(data[:, i][j], angle[j], c=color[i])
64  axes[i].scatter(data[:, i][j], angle[j], c=color[i])
65 
66  plt.show()
67  # axes[1].scatter(sliding[1], angle[1], c='r')
68  # axes[1].scatter(sliding[2], angle[2], c='r')
69  # axes[1].scatter(sliding[3], angle[3], c='r')
70  # axes[1].scatter(sliding[4], angle[4], c='r')
71 
72 
73 # def plot_data_distribution(file_name, save):
74 # data = np.loadtxt(file_name, skiprows=1, delimiter=",")
75 # data_fig_name = file_name.split(".")[0] + "_dataDistribution"
76 # angle_fig_name = file_name.split(".")[0] + "_angleDistribtion"
77 # restitution_coefficient = data[:, 0]
78 # sliding_friction = data[:, 1]
79 # rolling_friction = data[:, 2]
80 # bond_number = data[:, 3]
81 # angle = data[:, 4]
82 #
83 # fig, axes = plt.subplots(1, 5, dpi=100, figsize=(7, 5), sharey=True, sharex=False)
84 # axes[0].hist(restitution_coefficient, bins=10, color="red", alpha=0.5, edgecolor='black')
85 # axes[1].hist(sliding_friction, bins=10, color="green", alpha=0.5, edgecolor='black')
86 # axes[2].hist(rolling_friction, bins=10, color="yellow", alpha=0.5, edgecolor='black')
87 # axes[3].hist(bond_number, bins=10, color="blue", alpha=0.5, edgecolor='black')
88 # axes[4].hist(angle, bins=10, color="pink", alpha=0.5, edgecolor='black')
89 #
90 # axes[0].set(xlabel="Restitution Coefficient")
91 # axes[1].set(xlabel="Sliding Friction")
92 # axes[2].set(xlabel="Rolling Friction")
93 # axes[3].set(xlabel="Bond Number")
94 # axes[4].set(xlabel="Static AoR")
95 # # plt.savefig(data_fig_name)
96 
def plot_result_GL(gl_file)
Plot the GL data.
Definition: Particles2023AnalysisHung.py:41

◆ predict_model()

def Particles2023AnalysisHung.predict_model (   file_name,
  num_nodes,
  num_layer 
)

Train and evaluate a neural network model for angle of repose prediction.

This function trains a neural network model using the given data and evaluates its performance.

Parameters
[in]file_namePath to the input data file.
[in]num_nodesNumber of nodes in the hidden layers of the neural network.
[in]num_layerNumber of hidden layers in the neural network.
Returns
The evaluation result of the test data set.
97 def predict_model(file_name, num_nodes, num_layer):
98  """!
99  @brief Train and evaluate a neural network model for angle of repose prediction.
100 
101  This function trains a neural network model using the given data and evaluates its performance.
102 
103  @param[in] file_name Path to the input data file.
104  @param[in] num_nodes Number of nodes in the hidden layers of the neural network.
105  @param[in] num_layer Number of hidden layers in the neural network.
106 
107  @return The evaluation result of the test data set.
108  """
109  data = np.loadtxt(file_name, skiprows=1, delimiter=",")
110  angle = data[:, 4] / 90
111  micro_param = data[:, 0:4]
112  x_train, x_test, y_train, y_test = train_test_split(micro_param, angle, test_size=0.15)
113 
114  model_relu = Sequential() # create a sequential model.
115  model_relu.add(layers.Dense(num_nodes, input_dim=4, activation='relu')) # input layer with 4 microparameters.
116  for _ in range(num_layer - 2): # add hidden layers with hidden nodes
117  model_relu.add(layers.Dense(num_nodes, input_dim=num_nodes, activation='relu'))
118  model_relu.add(layers.Dense(1, input_dim=num_nodes, activation='linear'))
119 
120  model_relu.compile(optimizer='Adam', loss="mean_absolute_error", metrics=tfa.metrics.RSquare()) # compile model/
121  fit_result = model_relu.fit(x_train, y_train, epochs=50, batch_size=32, verbose=0, validation_split=0.05)
122  val_result = model_relu.evaluate(x_test, y_test)
123  print(fit_result.history['val_loss'][-1], fit_result.history['val_r_square'][-1])
124  if val_result[0] < 0.02 and fit_result.history['val_loss'][-1] < 0.02:
125  model_name = file_name + "_" + str(num_layer) + "-" + str(num_nodes) + "-" + str(val_result[0]) + \
126  "-" + str(val_result[1])
127  if "Sand_bew" in file_name:
128  model_relu.save("model/Sand/" + model_name)
129  elif "Eskal" in file_name:
130  model_relu.save("model/Eskal/" + model_name)
131  return val_result #
132 
133 
134 
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE Packet print(const Packet &a)
Definition: GenericPacketMath.h:1166
@ Sequential
Definition: Constants.h:360
def predict_model(file_name, num_nodes, num_layer)
Train and evaluate a neural network model for angle of repose prediction.
Definition: Particles2023AnalysisHung.py:97
str
Definition: compute_granudrum_aor.py:141

References Eigen::internal.print(), Eigen.Sequential, and compute_granudrum_aor.str.

◆ random_forest()

def Particles2023AnalysisHung.random_forest (   file_name)

Train and evaluate a random forest model for angle of repose prediction.

This function trains a random forest model using the given data and evaluates its performance.

Parameters
[in]file_namePath to the input data file.
Returns
The mean absolute error of the model.
135 def random_forest(file_name):
136  """!
137  @brief Train and evaluate a random forest model for angle of repose prediction.
138 
139  This function trains a random forest model using the given data and evaluates its performance.
140 
141  @param[in] file_name Path to the input data file.
142 
143  @return The mean absolute error of the model.
144  """
145  data = np.loadtxt(file_name, skiprows=1, delimiter=",")
146  angle = data[:, 4] / 90
147  micro_param = data[:, 0:4]
148  while True:
149  x_train, x_test, y_train, y_test = train_test_split(micro_param, angle, test_size=0.2)
150  regressor = RandomForestRegressor(random_state=0, criterion="absolute_error") # random forest in scikit learn.
151  regressor.fit(x_train, y_train)
152 
153  y_pred = regressor.predict(x_test)
154  error = mean_absolute_error(y_test, y_pred)
155  cross_val = abs(np.mean(cross_val_score(regressor, x_train, y_train, cv=5, scoring='neg_mean_absolute_error')))
156  print(cross_val)
157  if error < 0.012:
158  print("dumping")
159  joblib.dump(regressor, "model/random_forest_{}.joblib".format(file_name))
160  break
161 
162  return error
163 
164 
165 
AnnoyingScalar abs(const AnnoyingScalar &x)
Definition: AnnoyingScalar.h:135
def random_forest(file_name)
Train and evaluate a random forest model for angle of repose prediction.
Definition: Particles2023AnalysisHung.py:135
std::string format(const std::string &str, const std::vector< std::string > &find, const std::vector< std::string > &replace)
Definition: openglsupport.cpp:217

References abs(), format(), and Eigen::internal.print().

◆ write_calibration_script()

def Particles2023AnalysisHung.write_calibration_script ( str  var,
str  material 
)

Generate a calibration script for simulation.

This function generates a calibration script for simulation based on the provided parameters.

Parameters
[in]varString containing the parameters for the simulation.
[in]materialThe material type for the simulation.
Returns
The generated calibration script.
231 def write_calibration_script(var: str, material: str):
232  """!
233  @brief Generate a calibration script for simulation.
234 
235  This function generates a calibration script for simulation based on the provided parameters.
236 
237  @param[in] var String containing the parameters for the simulation.
238  @param[in] material The material type for the simulation.
239 
240  @return The generated calibration script.
241  """
242  param_list = var.split(" ")
243  param_str = ""
244  for param in param_list:
245  param_str += param + "_"
246 
247  if material == "Sand":
248  density = 2653
249  psd_str = "cumulative volume diameter 3e-4 0.0621 4.25e-4 0.24 5e-4 0.55 6e-4 1"
250  elif material == "Eskal":
251  density = 2737
252  psd_str = "cumulative volume diameter 9.7e-5 0.1 1.38e-4 0.5 1.94e-4 0.9"
253  else:
254  return
255 
256  return "srun --ntasks=1 " \
257  "/home/s2096307/Calibration/cmake-build-release-remote-host/Drivers/Calibration/CalibrationHeap " \
258  "-speciesType {} -species LinearViscoelasticFrictionReversibleAdhesiveSpecies -density {} " \
259  "-psd {} -collisionTime 0.000067997 -torsionFriction 0 " \
260  "-normalStress 1000 800 600 400 200 -restitutionCoefficient {} -slidingFriction {} " \
261  "-rollingFriction {} -bondNumber {} " \
262  "-param {} &".format(material, density, psd_str,
263  param_list[0], param_list[1], param_list[2], param_list[3], param_str)
264 
265 
266 # def remake_file(file_name):
267 # fin = open(file_name, "rt")
268 # # read file contents to string
269 # data = fin.read()
270 # # replace all occurrences of the required string
271 # data = data.replace('[', '')
272 # data = data.replace(']', '')
273 # # close the input file
274 # fin.close()
275 # # open the input file in write mode
276 # fin = open(file_name, "wt")
277 # # overrite the input file with the resulting data
278 # fin.write(data)
279 # # close the file
280 # fin.close()
281 
282 
283 # def plot_density(file_name, save):
284 # data = np.loadtxt(file_name, skiprows=1, delimiter=",")
285 # fig, axes = plt.subplots(1, 4, dpi=100, figsize=(12, 3))
286 # for i in range(4):
287 # h = axes[i].hist2d(data[:, i], data[:, 4])
288 # axes[i].axhline(y=33, xmin=0, xmax=1, c='red')
289 # # , label='Experimental value = $33^{\circ}$')
290 #
291 #
292 # fig.colorbar(h[3])
293 # plt.tight_layout()
294 
295 
296 
def write_calibration_script(str var, str material)
Generate a calibration script for simulation.
Definition: Particles2023AnalysisHung.py:231

References format().

Variable Documentation

◆ file_name

◆ file_name_eskal

string Particles2023AnalysisHung.file_name_eskal = "Eskal150NN.csv"

◆ file_name_sand

string Particles2023AnalysisHung.file_name_sand = "SandNN.csv"

◆ out

string Particles2023AnalysisHung.out = str(i) + ',' + str(j) + ',' + str(res) + "\n"

◆ params

◆ res

def Particles2023AnalysisHung.res = predict_model(file_name, j, i)