PyGamLab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3623 @@
1
+ '''
2
+ Data_Analysis.py :
3
+
4
+
5
+
6
+
7
+
8
+
9
+
10
+
11
+
12
+ '''
13
+
14
+ #" IN GOD WE TRUST, ALL OTHERS MUST BRING DATA"
15
+ # -W. Edwards Deming
16
+ #------------------------------------------------------------------------------
17
+ # Copyright 2023 The Gamlab Authors. All Rights Reserved.
18
+ # Licensed under the Apache License, Version 2.0 (the "License");
19
+ # you may not use this file except in compliance with the License.
20
+ # You may obtain a copy of the License at
21
+ # http://www.apache.org/licenses/LICENSE-2.0
22
+ # Unless required by applicable law or agreed to in writing, software
23
+ # distributed under the License is distributed on an "AS IS" BASIS,
24
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
25
+ # See the License for the specific language governing permissions and
26
+ # limitations under the License.
27
+ #------------------------------------------------------------------------------
28
+ '''
29
+ The Scientific experimental simulation library
30
+ -------------------------------------------------------------------------------
31
+ Graphen & Advanced Material Laboratory
32
+
33
+ it aimes to provide new scientist to use data,simlation, prepared data
34
+ and Artificial intelligence models.
35
+
36
+ See http://gamlab.aut.ac.ir for complete documentation.
37
+ '''
38
+ __doc__='''
39
+
40
+ @author: Ali Pilehvar Meibody (Alipilehvar1999@gmail.com)
41
+
42
+ 888 888
43
+ .d8888b .d88b. 88888b.d88b. 888 .d88b. 888
44
+ d88P" d88""88b 888 "888 "88b 888 d88""88b 88888PP
45
+ 888 8888 888 888 888 888 888 888 888 888 888 888
46
+ Y88b. 88 Y88..88PP. 888 888 888 888...... Y88..88PP. 888 888
47
+ "Y8888P8 "Y88P8888 888 888 888 888888888 "Y88P8888 88888888
48
+
49
+
50
+ @Director of Gamlab: Professor M. Naderi (Mnaderi@aut.ac.ir)
51
+
52
+ @Graphene Advanced Material Laboratory: https://www.GamLab.Aut.ac.ir
53
+
54
+
55
+ @Co-authors:
56
+ '''
57
+
58
+
59
+ #import-----------------------------------------
60
+ import math
61
+ import statistics
62
+ import numpy as np
63
+ import pandas as pd
64
+ #import matplotlib as plt
65
+ import matplotlib.pyplot as plt
66
+ from sklearn.linear_model import LinearRegression
67
+ from matplotlib.ticker import AutoMinorLocator
68
+ import seaborn as sns
69
+ from scipy import stats
70
+ from scipy.integrate import solve_bvp
71
+
72
+
73
+
74
+ def pressure_volume_ideal_gases(file,which):
75
+ '''
76
+ By using this function, the relationship between pressure and volume
77
+ of ideal gases in thermodynamic will be shown.
78
+
79
+ input_file : .csv format
80
+ *the file must be inserted in csv.
81
+
82
+ whhch: str
83
+ what do you want this function to do?
84
+
85
+ '''
86
+
87
+ mydf=pd.read_csv(file)
88
+
89
+ if which=='plot':
90
+ pressure=mydf['pressure']
91
+ volume=mydf['volume']
92
+
93
+ plt.plot(volume,pressure)
94
+ plt.title('volume_pressure_chart')
95
+ plt.xlabel('pressure')
96
+ plt.ylabel('volume')
97
+ font_title={'family':'serif','color':'black','size':18}
98
+ font_label={'family':'serif','color':'red','size':12}
99
+ plt.show()
100
+
101
+
102
+ elif which=='min pressure':
103
+ min_pressure=mydf['pressure'].min()
104
+ return min_pressure
105
+
106
+ elif which=='max pressure':
107
+ max_pressure=mydf['pressure'].max()
108
+ return max_pressure
109
+
110
+ elif which=='min volume':
111
+ min_volume=mydf['volume'].min()
112
+ return min_volume
113
+
114
+ elif which=='max volume':
115
+ max_volume=mydf['volume'].max()
116
+ return max_volume
117
+
118
+ elif which=='average pressure':
119
+ average_pressure=statistics.mean(pressure)
120
+ return average_pressure
121
+
122
+ elif which=='average volume':
123
+ average_volume=statistics.mean(volume)
124
+ return average_volume
125
+
126
+ elif which=='temperature':
127
+ n=1
128
+ R=0.821
129
+ temperature=(pressure*volume)/(n*R)
130
+ '''
131
+ This formula is from 'Introduction To The thermodinamics Of Materials
132
+ David R. Gaskell'
133
+
134
+ '''
135
+ return temperature
136
+
137
+ else:
138
+ print('No answer found')
139
+
140
+
141
+
142
+
143
+
144
+ def Energie(input_file,which):
145
+ '''
146
+ This is a function to drawing a plot or to calculating
147
+ the amount of Energie of a Motor to (open/close) a Valve in a cycle, which takes 2.7 secound to open and to close.
148
+
149
+ ----------
150
+ input_file : .xlsx format
151
+ the file must be inserted in xlsx.
152
+ which : int
153
+ draw : Drawing a Plot
154
+ calculate : Calculate the Consupmtion Energie in [mWs]
155
+ please say which work we do ( 1 or 2).
156
+
157
+ '''
158
+
159
+ mydf=pd.read_excel(input_file)
160
+
161
+
162
+ if which=='draw':
163
+ #get the data on each columns
164
+
165
+ A=mydf['Angle[°]']
166
+
167
+ Energie =mydf['Energie']
168
+
169
+ #plotting data
170
+ plt.plot(A, Energie,color = 'green')
171
+ plt.title('Energie of OTT Motor 185000 Cycle')
172
+ plt.xlabel('Angle[°]')
173
+ plt.ylabel('Consupmtion Energie')
174
+ plt.show()
175
+
176
+
177
+ if which=='calculate':
178
+ mydf=pd.DataFrame(mydf,columns=['Angle[°]','Power[mW]','Time for a Cycle','Energie'])
179
+
180
+ summ = mydf['Energie'].sum() # The amount of Energie for a half Cycle of Duty in mWs
181
+
182
+ summ =( summ * 2)/1000 # The amount of Consumption Energie for a Dutycycle in Ws
183
+
184
+ return summ
185
+
186
+
187
+
188
+
189
+
190
+ def Stress_Strain1(input_file,which,count):
191
+ '''
192
+ This function claculates the stress and strain
193
+ Parameters from load and elongation data
194
+ ----------
195
+ input_file : .csv format
196
+ the file must be inserted in csv.
197
+ whcih : str
198
+ please say which work we do ( plot or calculate?).
199
+ count: int
200
+ please enter the yarn count in Tex
201
+ remember: gauge length has been set in 250 mm
202
+ '''
203
+
204
+ #convert the file
205
+ mydf=pd.read_csv(input_file)
206
+
207
+ if which=='plot':
208
+
209
+ stress=mydf['Load']/count
210
+ strain=mydf['Extension']/250
211
+ plt.plot(stress,strain)
212
+ plt.title('stress-strain curve')
213
+ plt.xlabel('stress')
214
+ plt.ylabel('strain')
215
+ plt.show()
216
+
217
+
218
+ if which=='max stress':
219
+ stress_max=mydf['stress'].max()
220
+ return stress_max
221
+
222
+ if which=='max strain':
223
+ strain_max=mydf['strain'].max()
224
+ return strain_max
225
+
226
+
227
+
228
+
229
+ def Strain_Stress2(df,operation):
230
+ '''
231
+
232
+
233
+ This function gets data and an operation .
234
+ It plots Stress-Strain curve if the oepration is plot
235
+ and finds the UTS value (which is the ultimate tensile strength) otherwise.
236
+ ------------------------------
237
+ Parameters
238
+ ----------
239
+ df : DataFrame
240
+ It has 2 columns: DL(which is length in mm) & F (which is the force in N).
241
+ operation :
242
+ It tells the function to whether Plot the curve or find the UTS valu.
243
+
244
+ Returns
245
+ -------
246
+ The Stress-Strain curve or the amount of UTS
247
+
248
+ '''
249
+ L0 = 40
250
+ #L0: initial length of the sample
251
+ D0 = 9
252
+ #D0: initial diameter of the sample
253
+ A0 = math.pi / 4 * (D0 ** 2)
254
+ df['e'] = df['DL'] / L0
255
+ df['S'] = df['F'] / A0
256
+ if operation == 'PLOT':
257
+ plt.scatter(df['e'], df['S'])
258
+ plt.xlabel('e')
259
+ plt.ylabel('S')
260
+ plt.title('S vs e Plot')
261
+ plt.grid(True)
262
+ plt.show()
263
+ elif operation == 'UTS':
264
+ return df['S'].max()
265
+ else:
266
+ print("Please enter proper operation")
267
+ return
268
+
269
+
270
+
271
+
272
+
273
+
274
+ def Stress_Strain3(input_data, action):
275
+ stress = input_data['Stress (MPa)']
276
+ strain = input_data['Strain (%)']
277
+
278
+ if action == 'plot':
279
+ # Plotting data
280
+ fig, ax = plt.subplots(figsize=(8, 6))
281
+ plt.plot(strain, stress, linewidth=2, color='royalblue', marker='o', markersize=5, label='Stress-Strain Curve')
282
+ plt.title('Stress-Strain Curve', fontsize=16)
283
+ plt.xlabel('Strain (%)', fontsize=14)
284
+ plt.ylabel('Stress (MPa)', fontsize=14)
285
+ plt.xlim([0, strain.max()])
286
+ plt.ylim([0, stress.max()])
287
+ plt.grid(True, linestyle='--', alpha=0.6)
288
+ plt.legend()
289
+
290
+ elif action == 'max stress':
291
+ # Calculation of the maximum stress
292
+ stress_max = stress.max()
293
+ return stress_max
294
+
295
+ elif action == 'young modulus':
296
+ # Calculation of Young's Modulus
297
+ slope_intercept = np.polyfit(strain, stress, 1)
298
+ return slope_intercept[0]
299
+
300
+ def Stress_Strain4(file_path, D0, L0):
301
+ '''
302
+ This function uses the data file
303
+ that contains length and force, calculates the engineering, true
304
+ and yielding stress and strain and also draws a graph of these.
305
+
306
+ Parameters:
307
+ D0(mm): First Qatar to calculate stress
308
+ L0(mm): First Length to canculate strain
309
+ F(N): The force applied to the object during this test
310
+ DL(mm): Length changes
311
+
312
+ Returns:
313
+ Depending on the operation selected,
314
+ it returns calculated values, plots,
315
+ advanced analysis, or saves results.
316
+ '''
317
+ try:
318
+ data = pd.read_excel(file_path)
319
+
320
+ except FileNotFoundError:
321
+ print("File not found. Please check the file path.")
322
+ return
323
+
324
+ A0 = math.pi * (D0/2)**2
325
+
326
+ data['stress'] = data['F (N)'] / A0
327
+ data['strain'] = (data['DL (mm)'] - L0) / L0
328
+
329
+ data['true_stress'] = data['F (N)'] / A0
330
+ data['true_strain'] = np.log(1 + data['strain'])
331
+
332
+ yield_point = data.loc[data['stress'].idxmax()]
333
+ permanent_strain = data['strain'].iloc[-1]
334
+
335
+ plt.figure(figsize=(12, 8))
336
+ plt.plot(data['strain'], data['stress'], label='Engineering Stress-Strain', marker='o', color='b', linestyle='-')
337
+ plt.plot(data['true_strain'], data['true_stress'], label='True Stress-Strain', marker='x', color='r', linestyle='--')
338
+ plt.scatter(yield_point['strain'], yield_point['stress'], color='g', label='Yield Point')
339
+ plt.annotate(f"Yield Point: Strain={yield_point['strain']:.2f}, Stress={yield_point['stress']:.2f}", (yield_point['strain'], yield_point['stress']), textcoords="offset points", xytext=(0,10), ha='center')
340
+ plt.xlabel('Strain')
341
+ plt.ylabel('Stress (MPa)')
342
+ plt.title('Stress-Strain Curve')
343
+ plt.grid(True)
344
+ plt.legend()
345
+ plt.show()
346
+
347
+ print("Columns in the data:")
348
+ print(data.columns)
349
+
350
+ print("\nFirst few rows of the data:")
351
+ print(data.head())
352
+
353
+ print("\nYield Point Information:")
354
+ print(yield_point)
355
+ print("Permanent Strain:", permanent_strain)
356
+
357
+
358
+
359
+
360
+ def Stress_Strain5(input_data, action):
361
+ stress = input_data['Stress (MPa)']
362
+ strain = input_data['Strain (%)']
363
+
364
+ if action == 'plot':
365
+ # Plotting data
366
+ fig, ax = plt.subplots(figsize=(8, 6))
367
+ plt.plot(strain, stress, linewidth=2, color='royalblue', marker='o', markersize=5, label='Stress-Strain Curve')
368
+ plt.title('Stress-Strain Curve', fontsize=16)
369
+ plt.xlabel('Strain (%)', fontsize=14)
370
+ plt.ylabel('Stress (MPa)', fontsize=14)
371
+ plt.xlim([0, strain.max()])
372
+ plt.ylim([0, stress.max()])
373
+ plt.grid(True, linestyle='--', alpha=0.6)
374
+ plt.legend()
375
+
376
+ elif action == 'max stress':
377
+ # Calculation of the maximum stress
378
+ stress_max = stress.max()
379
+ return stress_max
380
+
381
+ elif action == 'young modulus':
382
+ # Calculation of Young's Modulus
383
+ slope_intercept = np.polyfit(strain, stress, 1)
384
+ return slope_intercept[0]
385
+
386
+
387
+
388
+ def aerospace_analysis (CSV,which):
389
+ '''
390
+ this function has the ability to convert your datas into
391
+ answers that you need
392
+ your datas should be in Newton and M**2 format
393
+ in this program we will be using presure as the output data
394
+ if you want to make a sketch Use === Plot
395
+ if you want to check the max_presure use === MaxPer
396
+ '''
397
+ mydf = pd.read_csv(CSV)
398
+ mydff = np.array(mydf)
399
+ mydf1 = pd.DataFrame(mydff,columns=['Newton','Area'])
400
+ mydf2 = mydf1['Newton']/mydf1['Area']
401
+ mydf3 = pd.concat(mydf1,mydf2)
402
+ if which == 'Plot':
403
+ plt.plot(mydf1['Newton'],mydf1['Area'])
404
+ plt.xlabel('Area')
405
+ plt.ylabel('Newton')
406
+ plt.show()
407
+ if which == 'MaxPer':
408
+ max_p = mydf3.max()
409
+ return max_p
410
+
411
+
412
+
413
+
414
+ def XRD_Analysis(file,which,peak=0):
415
+ '''
416
+
417
+
418
+ Parameters
419
+ ----------
420
+ file : str
421
+ the variable in which you saved the .cvs file path
422
+ which : str
423
+ which operation you want to perform on the file
424
+ peak : float, optional
425
+ 2θ for the peak you want to analyse. The default is 0.
426
+
427
+ Returns
428
+ -------
429
+ fwhm : float
430
+ value of FWHM for the peak you specified.
431
+
432
+ '''
433
+
434
+ df=pd.read_csv(file)
435
+ npar=pd.DataFrame.to_numpy(df)
436
+
437
+ if which=='plot':
438
+ angle=df['angle']
439
+ intensity=df['intensity']
440
+ plt.plot(angle,intensity,color='k')
441
+ font_title={'family':'serif','color':'blue','size':20}
442
+ plt.title('XRD pattern',fontdict=font_title)
443
+ font_label={'family':'times new roman','color':'black','size':15}
444
+ plt.xlabel('angle (2θ)',fontdict=font_label)
445
+ plt.ylabel('intensity (a.u.)',fontdict=font_label)
446
+ plt.grid(axis='x',which='both')
447
+ plt.xticks(np.arange(0,max(angle),5))
448
+ plt.xlim([np.min(npar,axis=0)[0], np.max(npar,axis=0)[0]])
449
+ plt.yticks([])
450
+ plt.ylim([0, 1.1*np.max(npar,axis=0)[1]])
451
+ plt.tick_params(axis='x',direction='in')
452
+ plt.show()
453
+ return None
454
+ elif which=='fwhm':
455
+ diff=int((npar[1,0]-npar[0,0])*1000)/2000
456
+ for i in range(int(len(npar)/2)+1):
457
+ if -diff<npar[i,0]-peak<diff:
458
+ pl=i
459
+ ph=i
460
+ p=i
461
+ break
462
+ while pl>0:
463
+ if ((npar[pl,1]-npar[pl-1,1])/(npar[pl-1,1]-npar[pl-2,1]))>1.04 and (npar[pl-1,1]-np.min(npar,axis=0)[1])/(np.max(npar,axis=0)[1]-np.min(npar,axis=0)[1])<0.4:
464
+ in_low_1=npar[pl-1,1]
465
+ break
466
+ pl=pl-1
467
+ while ph>0:
468
+ if ((npar[ph+2,1]-npar[ph+1,1])/(npar[ph+1,1]-npar[ph,1]))<0.96 and (npar[ph+1,1]-np.min(npar,axis=0)[1])/(np.max(npar,axis=0)[1]-np.min(npar,axis=0)[1])<0.4:
469
+ in_low_2=npar[ph+1,1]
470
+ break
471
+ ph=ph+1
472
+ in_low=(in_low_1+in_low_2)/2
473
+ h=npar[p,1]-in_low
474
+ hm=in_low+h/2
475
+ diff_in=[]
476
+ hm_i=[]
477
+ for l in range(len(npar)-1):
478
+ diff_in.append((npar[l+1,1]-npar[l,1])/2)
479
+ for j in range(2):
480
+ for k in range(int(len(npar)/2)+1):
481
+ c=((-1)**j)*k
482
+ if abs(npar[p+c,1]-hm)<abs(max(diff_in)):
483
+ hm_i.append(p+c)
484
+ break
485
+ fwhm=npar[hm_i[0],0]-npar[hm_i[1],0]
486
+ return fwhm
487
+ else:
488
+ print('The which argument not valid')
489
+ return None
490
+
491
+
492
+
493
+
494
+
495
+
496
+ def Diabetes_Dataset(f, work):
497
+ """
498
+ Reads a diabetes dataset from a CSV file
499
+
500
+ Parameters:
501
+ f (str): The file path of the CSV file containing the diabetes dataset.
502
+ work (str): The task to perform. Supported values are:
503
+ - 'has_diabetes': Counts the number of individuals who have diabetes.
504
+ - 'percent_has_diabetes_25': Calculates the percentage of individuals under 25 who have diabetes.
505
+ - 'percent_has_diabetes_25_to_30': Calculates the percentage of individuals between 25 to 30 who have diabetes.
506
+ - 'percent_has_diabetes_30_to_40': Calculates the percentage of individuals between 30 to 40 who have diabetes.
507
+ - 'percent_has_diabetes_40_and_50': Calculates the percentage of individuals between 40 to 50 who have diabetes.
508
+ - 'percent_has_diabetes_20_to_40': Calculates the percentage of individuals between 20 to 40 who have diabetes.
509
+ - 'percent_has_diabetes_30_to_50': Calculates the percentage of individuals between 30 to 50 who have diabetes.
510
+ - 'percent_has_diabetes_50_80': Calculates the percentage of individuals between 50 to 80 who have diabetes.
511
+ - 'rel_bmi_to_diabetes_30_to_40': Calculates the percentage of individuals with BMI between 30 to 40 who have diabetes.
512
+ - 'rel_bmi_to_diabetes_20_to_30': Calculates the percentage of individuals with BMI between 20 to 30 who have diabetes.
513
+ - 'histo': Plots a histogram of ages.
514
+ - 'max_age': Finds the maximum age in the dataset.
515
+ - 'min_age': Finds the minimum age in the dataset.
516
+ - 'max_age_has_diabetes': Finds the individuals with the maximum age who have diabetes.
517
+ - 'min_age_has_diabetes': Finds the individuals with the minimum age who have diabetes.
518
+ """
519
+ read_data = pd.read_csv(f)
520
+
521
+ if work == 'has_diabetes':
522
+ all_outcome = read_data['Outcome']
523
+ has_diabetes = []
524
+ for i in all_outcome:
525
+ if i == 1:
526
+ has_diabetes.append(i)
527
+ text = f'all Outcome is {len(all_outcome)} and has diabetes is {len(has_diabetes)}'
528
+ return text
529
+ elif work == 'percent_has_diabetes_25':
530
+ has_diabetes_25 = len(read_data[(read_data['Age'] <= 25) & (read_data['Outcome'] == 1)])
531
+ less_then_25 = len(
532
+ read_data[(read_data['Age'] <= 25) & ((read_data['Outcome'] == 1) | (read_data['Outcome'] == 0))])
533
+ percent = has_diabetes_25 * (100 / less_then_25)
534
+ return percent
535
+ elif work == 'percent_has_diabetes_25_to_30':
536
+ between_25_to_30 = read_data[((read_data['Age'] > 25) & (read_data['Age'] <= 30)) & (read_data['Outcome'] == 1)]
537
+ all_outcome_25_to_30 = read_data[((read_data['Age'] > 25) & (read_data['Age'] <= 30)) &
538
+ ((read_data['Outcome'] == 1) | read_data['Outcome'] == 0)]
539
+ percent = len(between_25_to_30) * (100 / len(all_outcome_25_to_30))
540
+ elif work == 'percent_has_diabetes_30_to_40':
541
+ between_30_to_40 = read_data[((read_data['Age'] > 30) & (read_data['Age'] <= 40)) & (read_data['Outcome'] == 1)]
542
+ all_outcome_30_to_40 = read_data[((read_data['Age'] > 30) & (read_data['Age'] <= 40)) &
543
+ ((read_data['Outcome'] == 1) | (read_data['Outcome'] == 0))]
544
+ percent = len(between_30_to_40) * (100 / len(all_outcome_30_to_40))
545
+ return percent
546
+ elif work == 'percent_has_diabetes_40_to_50':
547
+ has_diabetes_40_to_50 = read_data[((read_data['Age'] > 40) & (read_data['Age'] <= 50)) &
548
+ (read_data['Outcome'] == 1)]
549
+ all_outcome_40_to_50 = read_data[((read_data['Age'] > 40) & (read_data['Age'] <= 50)) &
550
+ ((read_data['Outcome'] == 1) | (read_data['Outcome'] == 0))]
551
+ percent = len(has_diabetes_40_to_50) * (100 / len(all_outcome_40_to_50))
552
+ return percent
553
+
554
+ elif work == 'percent_has_diabetes_20_to_40':
555
+ age_groups = [(18, 30)]
556
+ for age_group in age_groups:
557
+ min_age, max_age = age_group
558
+ data = read_data[(read_data['Age'] >= min_age) & (read_data['Age'] <= max_age)]
559
+ has_diabetes = len(data[data['Outcome'] == 1])
560
+ all_data = len(data)
561
+ percent = has_diabetes * (100 / all_data)
562
+ return percent
563
+ elif work == 'percent_has_diabetes_30_to_50':
564
+ age_groups = [(30, 50)]
565
+ for age_group in age_groups:
566
+ min_age, max_age = age_group
567
+ data = read_data[(read_data['Age'] >= min_age) & (read_data['Age'] <= max_age)]
568
+ has_diabetes = data[data['Outcome'] == 1]
569
+ percent = len(has_diabetes) * (100 / len(data))
570
+ return percent
571
+ elif work == 'percent_has_diabetes_50_80':
572
+ age_groups = [(50, 80)]
573
+ for age_group in age_groups:
574
+ min_age, max_age = age_group
575
+ data = read_data[(read_data['Age'] >= min_age) & (read_data['Age'] <= max_age)]
576
+ has_diabetes = data[data['Outcome'] == 1]
577
+ percent = len(has_diabetes) * (100 / len(data))
578
+ return percent
579
+ elif work == 'rel_bmi_to_diabetes_30_to_40':
580
+ bmi_groups = [(30, 40)]
581
+ for bmi_group in bmi_groups:
582
+ min_bmi, max_bmi = bmi_group
583
+ data = read_data[(read_data['BMI'] >= min_bmi) & (read_data['BMI'] <= max_bmi)]
584
+ has_diabetes = data[data['Outcome'] == 1]
585
+ percent = len(has_diabetes) * (100 / len(data))
586
+ return percent
587
+ elif work == 'rel_bmi_to_diabetes_20_to_30':
588
+ bmi_groups = [(20, 30)]
589
+ for bmi_group in bmi_groups:
590
+ min_bmi, max_bmi = bmi_group
591
+ data = read_data[(read_data['BMI'] >= min_bmi) & (read_data['BMI'] < max_bmi)]
592
+ has_diabetes = data[data['Outcome'] == 1]
593
+ percent = len(has_diabetes) * (100 / len(data))
594
+ return percent
595
+ elif work == 'histo':
596
+ ages = read_data['Age']
597
+ plt.hist(ages, bins=20, color='skyblue', edgecolor='green')
598
+ plt.show()
599
+ elif work == 'max_age':
600
+ age = read_data['Age']
601
+ max_age = np.max(age)
602
+ return max_age
603
+ elif work == 'min_age':
604
+ age = read_data['Age']
605
+ min_age = np.min(age)
606
+ return min_age
607
+ elif work == 'max_age_has_diabetes':
608
+ max_ages = read_data['Age'].max()
609
+ has_diabetes = read_data[((read_data['Age'] == max_ages) & (read_data['Outcome'] == 1))]
610
+ return has_diabetes
611
+ elif work == 'min_age_has_diabetes':
612
+ min_ages = read_data['Age'].min()
613
+ has_diabetes = read_data[((read_data['Age'] == min_ages) & (read_data['Outcome'] == 1))]
614
+ return has_diabetes
615
+ else:
616
+ raise Exception('invalid command')
617
+
618
+
619
+ def Income_Developer(file, work):
620
+ """
621
+ Reads income data from a CSV file and displays graphs based on the specified task.
622
+
623
+ Parameters:
624
+ file (str): The file path of the CSV file containing the income dataset.
625
+ work (str): The task to perform. Supported values are:
626
+
627
+ - 'plot_data': Displays a line plot of income over age for Python and JavaScript developers.
628
+ - 'bar_data': Displays a bar plot of income over age for Python and JavaScript developers.
629
+ - 'max_salary_data': Displays a bar plot showing the maximum income for Python and JavaScript developers.
630
+ - 'plot_bar_data': Displays both bar and line plots of income over age for Python and JavaScript developers.
631
+ - 'max_salary_data_by_age': Displays a bar plot showing the maximum income for Python and JavaScript developers based on age.
632
+ - 'alph_data': Displays a bar plot with different alpha values for Python and JavaScript developers.
633
+ - 'show_by_side_by_side_data': Displays two bar plots side by side for Python and JavaScript developers with age on the x-axis and income on the y-axis.
634
+
635
+ """
636
+
637
+ # read file
638
+ data = pd.read_csv(file)
639
+
640
+ # style plt
641
+ plt.style.use('fast')
642
+
643
+ # get data
644
+ python_data = data[(data['Language'] == 'python')]
645
+ js_data = data[(data['Language'] == 'js')]
646
+
647
+ # get age data
648
+ python_ages = python_data['Age']
649
+ js_ages = js_data['Age']
650
+ ages_x = np.arange(18, 49)
651
+
652
+ # get income data
653
+ python_income = python_data['Income']
654
+ js_income = js_data['Income']
655
+
656
+ # get max income data
657
+ max_income_python = python_data['Income'].max()
658
+ max_income_js = js_data['Income'].max()
659
+
660
+
661
+
662
+ if work == 'plot_data':
663
+ # show plot data
664
+ plt.plot(python_ages, python_income, color='skyblue', label='Python')
665
+ plt.plot(js_ages, js_income, color='green', label='js')
666
+ plt.legend()
667
+ plt.show()
668
+ elif work == 'bar_data':
669
+ # show bar data
670
+ plt.bar(python_ages, python_income, color='skyblue', label='Python')
671
+ plt.bar(js_ages, js_income, color='green', label='js')
672
+ plt.legend()
673
+ plt.show()
674
+ elif work == 'max_salary_data':
675
+ plt.bar(['python', 'js'], [max_income_python, max_income_js], color=['skyblue', 'green'],
676
+ label=['python', 'js'])
677
+ plt.legend()
678
+ plt.show()
679
+ elif work == 'plot_bar_data':
680
+ plt.bar(python_ages, python_income, color='skyblue', label='Python')
681
+ plt.bar(js_ages, js_income, color='green', label='js')
682
+ plt.plot(python_ages, python_income, color='blue', label='python')
683
+ plt.plot(js_ages, js_income, color='yellow', label='js')
684
+ plt.legend()
685
+ plt.show()
686
+ elif work == 'max_salary_data_by_age':
687
+ python_row = python_data[python_data['Income'] == max_income_python]
688
+ js_row = js_data[js_data['Income'] == max_income_js]
689
+ age_py = python_row['Age']
690
+ age_js = js_row['Age']
691
+ income_py = python_row['Income']
692
+ income_js = js_row['Income']
693
+ plt.bar(age_py, income_py, color='skyblue', label='Python')
694
+ plt.bar(age_js, income_js, color='green', label='js')
695
+ plt.legend()
696
+ plt.show()
697
+ elif work == 'alph_data':
698
+ plt.bar(python_ages, python_income, color='skyblue', label='python', alpha=0.8)
699
+ plt.bar(js_ages, js_income, color='green', label='js', alpha=0.4)
700
+ plt.legend()
701
+ plt.show()
702
+ elif work == 'show_by_side_by_side_data':
703
+ my_width = 0.6
704
+ age = np.arange(len(np.arange(18, 49)))
705
+ plt.bar(age + my_width, python_income, color='skyblue', label='python', width=0.4)
706
+ plt.bar(age, js_income, color='green', label='js', width=0.4)
707
+ plt.xticks(ticks=age, labels=ages_x)
708
+ plt.xlabel('age')
709
+ plt.ylabel('salary')
710
+ plt.legend()
711
+ plt.show()
712
+ else:
713
+ raise Exception('invalid command')
714
+
715
+
716
+
717
+
718
+
719
+
720
+ def LN_S_E(df, operation):
721
+ '''
722
+
723
+
724
+ This function plots the ELASTIC part of the true stress-strain curve
725
+ and can also calculate the Young's Modulus(E).
726
+ ----------
727
+ df : DataFrame
728
+ It has 2 columns: DL(which is length in mm) & F (which is the force in N).
729
+ operation :
730
+ It tells the function to whether Plot the curve or calculate the Young's Modulus(E).
731
+
732
+ Returns
733
+ -------
734
+ The elastic part of the true stress-strain curve or the amount of E
735
+
736
+ '''
737
+ L0 = 40
738
+ D0 = 9
739
+ A0 = math.pi / 4 * (D0 ** 2)
740
+ df['e'] = df['DL'] / L0
741
+ df['S'] = df['F'] / A0
742
+ df['eps'] = np.log(1 + df['e'])
743
+ df['sig'] = df['S'] * (1 + df['e'])
744
+ filtered_index = df[(df['eps'] >= 0.04) & (df['eps'] <= 0.08)].index
745
+ "the elastic part of the curve is where the true strain(eps) is from 0.04 to 0.08"
746
+
747
+ df['selected_ln_eps'] = np.nan
748
+
749
+ df.loc[filtered_index, 'selected_ln_eps'] = df.loc[filtered_index, 'eps']
750
+ df['selected_ln_eps'] = np.where(~df['selected_ln_eps'].isna(), np.log(df['selected_ln_eps']), df['selected_ln_eps'])
751
+ df['selected_ln_sig'] = np.nan
752
+
753
+ df.loc[filtered_index, 'selected_ln_sig'] = df.loc[filtered_index, 'sig']
754
+ df['selected_ln_sig'] = np.where(~df['selected_ln_sig'].isna(), np.log(df['selected_ln_sig']), df['selected_ln_sig'])
755
+
756
+
757
+ if operation == 'PLOT':
758
+ plt.scatter(df['selected_ln_eps'].dropna(), df['selected_ln_sig'].dropna())
759
+ plt.xlabel('ln_eps')
760
+ plt.ylabel('ln_sig')
761
+ plt.title('ln(sig) vs ln(eps) Plot')
762
+ plt.grid(True)
763
+ plt.show()
764
+ elif operation == 'YOUNG_MODULUS':
765
+ X = df['selected_ln_eps'].dropna().values.reshape(-1, 1) # Independent variable
766
+ y = df['selected_ln_sig'].dropna().values.reshape(-1, 1) # Dependent variable
767
+ model = LinearRegression()
768
+ model.fit(X, y)
769
+ intercept = model.intercept_[0]
770
+ return math.exp(intercept)
771
+
772
+ else:
773
+ print("Please enter proper operation")
774
+ return
775
+
776
+
777
+
778
+
779
+ def Oxygen_Heat_Capacity_Analysis(file_path):
780
+ '''
781
+ This function reads the temperature and heat capacity information
782
+ from the Excel file and then calculates the enthalpy and entropy values
783
+ and draws their graphs.
784
+
785
+ Parameters:
786
+ T: Oxygen temperature
787
+ Cp: Heat capacity at constant pressure in different oxygen temperature ranges
788
+
789
+ Return:
790
+ The values of enthalpy, entropy and their graph according to temperature
791
+ Heat capacity graph according to temperature
792
+ '''
793
+
794
+ data = pd.read_excel(file_path)
795
+
796
+ print("value of T column")
797
+ print(data["T"])
798
+
799
+ print("value of cp column")
800
+ print(data["Cp"])
801
+
802
+ data['Enthalpy'] = data['Cp'].cumsum()
803
+ data['Entropy'] = data['Enthalpy'] / data['T']
804
+
805
+ fig, axs = plt.subplots(1, 2, figsize=(16, 6))
806
+ axs[0].plot(data['T'], data['Cp'])
807
+ axs[0].set_xlabel('Temperature (T)')
808
+ axs[0].set_ylabel('Heat Capacity (Cp)')
809
+ axs[0].set_title('Heat Capacity vs Temperature')
810
+
811
+ axs[1].plot(data['T'], data['Enthalpy'], label='Enthalpy')
812
+ axs[1].plot(data['T'], data['Entropy'], label='Entropy')
813
+ axs[1].set_xlabel('Temperature (T)')
814
+ axs[1].set_ylabel('Enthalpy and Entropy')
815
+ axs[1].set_title('Enthalpy and Entropy vs Temperature')
816
+ axs[1].legend()
817
+
818
+ plt.tight_layout()
819
+ plt.show()
820
+
821
+
822
+
823
+
824
+
825
+
826
+
827
+
828
+ def Compression_Test(Data,Operator,Sample_Name,Density=0):
829
+ """
830
+
831
+
832
+ Parameters
833
+ ----------
834
+ Data : DataFrame
835
+ Compression test data including stress and strain.
836
+ Operator : str
837
+ The action that needs to be done on the data (plot or S_max).
838
+ plot: Plots a stress-strain diagram.
839
+ Sample_Name : str
840
+ Sample name.
841
+ Density : float, optional
842
+ Density of the sample. The default is 0.
843
+
844
+ Returns
845
+ -------
846
+ float
847
+ If the operator is given S_max, it returns maximum strength.
848
+ If the operator is given S_max/Density, it returns specific maximum strength.
849
+
850
+ """
851
+
852
+ e=Data["e"]
853
+ S=Data["S (Mpa)"]
854
+
855
+ if Operator=="S_max":
856
+
857
+ S_max=S.max()
858
+ return S_max
859
+
860
+ elif Operator=="S_max/Density" and Density!=0:
861
+ S_max=S.max()
862
+ S_max_Density=S_max/Density
863
+ return S_max_Density
864
+
865
+ elif Operator=="plot":
866
+
867
+ font_label={ 'family' : 'Times new roman' ,
868
+ 'color' : 'black' ,
869
+ 'size' : 15 }
870
+
871
+ font_legend={ 'family' : 'Times new roman' ,
872
+ 'size' : 13 }
873
+
874
+
875
+ plt.plot(e,S,label=Sample_Name,linewidth=3)
876
+ plt.xlabel("e",fontdict=font_label,labelpad=5)
877
+ plt.ylabel("S (Mpa)",fontdict=font_label,labelpad=5)
878
+
879
+ plt.autoscale()
880
+ plt.gca().xaxis.set_minor_locator(AutoMinorLocator(2))
881
+ plt.gca().yaxis.set_minor_locator(AutoMinorLocator(2))
882
+ plt.legend(frameon=False,prop=font_legend)
883
+ plt.tick_params(axis='both', width=2)
884
+ plt.tick_params(axis='both', which='minor', width=1)
885
+ plt.gca().spines['bottom'].set_linewidth(2)
886
+ plt.gca().spines['left'].set_linewidth(2)
887
+ plt.gca().spines['top'].set_linewidth(2)
888
+ plt.gca().spines['right'].set_linewidth(2)
889
+ plt.tick_params(axis='both', labelsize=11)
890
+
891
+
892
+
893
+
894
+ def DMTA_Test(Data2,Operator,Sample_Name):
895
+ """
896
+
897
+
898
+ Parameters
899
+ ----------
900
+ Data : DataFrame
901
+ DMTA test data including storage modulus, loss modulus and tanδ.
902
+ Operator : str
903
+ The action that needs to be done on the data (storage_max, loss_max, tan_max, plot_storage, plot_loss or plot_tan).
904
+ Sample_Name : str
905
+ Sample name.
906
+
907
+ Returns
908
+ -------
909
+ float
910
+ If the operator is given storage_max, it returns maximum storage modulus.
911
+ If the operator is given loss_max, it returns maximum loss modulus.
912
+ If the operator is given Tan_max, it returns maximum Tanδ.
913
+
914
+ """
915
+
916
+ Frequency=Data2["Frequency (Hz)"]
917
+ Storage_Modulus=Data2["E'-Storage Modulus (Mpa)"]
918
+ Loss_Modulus=Data2.iloc[:,13].copy()
919
+ Tanδ=Data2["Tanδ"]
920
+
921
+ if Operator=="storage_max":
922
+ Storage_max=Storage_Modulus.max()
923
+ return Storage_max
924
+
925
+ elif Operator=="loss_max":
926
+ Loss_max=Loss_Modulus.max()
927
+ return Loss_max
928
+
929
+ elif Operator=="tan_max":
930
+ Tan_max=Tanδ.max()
931
+ return Tan_max
932
+
933
+ elif Operator=="plot_storage":
934
+
935
+ font_label={ 'family' : 'Times new roman' ,
936
+ 'color' : 'black' ,
937
+ 'size' : 15 }
938
+
939
+ font_legend={ 'family' : 'Times new roman' ,
940
+ 'size' : 13 }
941
+
942
+
943
+ plt.plot(Frequency,Storage_Modulus,label=Sample_Name,linewidth=3)
944
+ plt.xlabel("Frequency (Hz)",fontdict=font_label,labelpad=5)
945
+ plt.ylabel("E'-Storage Modulus (Mpa)",fontdict=font_label,labelpad=5)
946
+
947
+ plt.autoscale()
948
+ plt.gca().xaxis.set_minor_locator(AutoMinorLocator(2))
949
+ plt.gca().yaxis.set_minor_locator(AutoMinorLocator(2))
950
+ plt.legend(frameon=False,prop=font_legend)
951
+ plt.tick_params(axis='both', width=2)
952
+ plt.tick_params(axis='both', which='minor', width=1)
953
+ plt.gca().spines['bottom'].set_linewidth(2)
954
+ plt.gca().spines['left'].set_linewidth(2)
955
+ plt.gca().spines['top'].set_linewidth(2)
956
+ plt.gca().spines['right'].set_linewidth(2)
957
+ plt.tick_params(axis='both', labelsize=11)
958
+
959
+ elif Operator=="plot_loss":
960
+
961
+ font_label={ 'family' : 'Times new roman' ,
962
+ 'color' : 'black' ,
963
+ 'size' : 15 }
964
+
965
+ font_legend={ 'family' : 'Times new roman' ,
966
+ 'size' : 13 }
967
+
968
+
969
+ plt.plot(Frequency,Loss_Modulus,label=Sample_Name,linewidth=3)
970
+ plt.xlabel("Frequency (Hz)",fontdict=font_label,labelpad=5)
971
+ plt.ylabel("E''-Loss Modulus (Mpa)",fontdict=font_label,labelpad=5)
972
+
973
+ plt.autoscale()
974
+ plt.gca().xaxis.set_minor_locator(AutoMinorLocator(2))
975
+ plt.gca().yaxis.set_minor_locator(AutoMinorLocator(2))
976
+ plt.legend(frameon=False,prop=font_legend)
977
+ plt.tick_params(axis='both', width=2)
978
+ plt.tick_params(axis='both', which='minor', width=1)
979
+ plt.gca().spines['bottom'].set_linewidth(2)
980
+ plt.gca().spines['left'].set_linewidth(2)
981
+ plt.gca().spines['top'].set_linewidth(2)
982
+ plt.gca().spines['right'].set_linewidth(2)
983
+ plt.tick_params(axis='both', labelsize=11)
984
+
985
+ elif Operator=="plot_tan":
986
+
987
+ font_label={ 'family' : 'Times new roman' ,
988
+ 'color' : 'black' ,
989
+ 'size' : 15 }
990
+
991
+ font_legend={ 'family' : 'Times new roman' ,
992
+ 'size' : 13 }
993
+
994
+
995
+ plt.plot(Frequency,Tanδ,label=Sample_Name,linewidth=3)
996
+ plt.xlabel("Frequency (Hz)",fontdict=font_label,labelpad=5)
997
+ plt.ylabel("Tanδ",fontdict=font_label,labelpad=5)
998
+
999
+ plt.autoscale()
1000
+ plt.gca().xaxis.set_minor_locator(AutoMinorLocator(2))
1001
+ plt.gca().yaxis.set_minor_locator(AutoMinorLocator(2))
1002
+ plt.legend(frameon=False,prop=font_legend)
1003
+ plt.tick_params(axis='both', width=2)
1004
+ plt.tick_params(axis='both', which='minor', width=1)
1005
+ plt.gca().spines['bottom'].set_linewidth(2)
1006
+ plt.gca().spines['left'].set_linewidth(2)
1007
+ plt.gca().spines['top'].set_linewidth(2)
1008
+ plt.gca().spines['right'].set_linewidth(2)
1009
+ plt.tick_params(axis='both', labelsize=11)
1010
+
1011
+
1012
+
1013
+
1014
+ def Find_Max_Vertical_Velocity(data):
1015
+ '''
1016
+ This function gets the data results of flow velocity simulation for natural convection of a molten in a cavity.
1017
+ and as the output, it shows the plot of flow velocity vs x
1018
+ and also it returns the maximum velocity and the location where that velocity belogs to.
1019
+ '''
1020
+
1021
+ x=np.array(data['x(m)'])
1022
+ u=np.array(data['u(m/s)'])
1023
+ u_max=np.max(u)#the max value of the velocity
1024
+ index_max=np.argmax(u)#the index of which this value exists in
1025
+ loc_max=x[index_max]#the location of the maximum velocity
1026
+ print('The maximum value of Flow Velocity for this problem is:',u_max)
1027
+ print('Also this maximum value occurs in this location:',loc_max)
1028
+
1029
+ plt.scatter(x,u)
1030
+ plt.title('Flow Velocity',c='blue',family='times new roman',size=20,pad=20)
1031
+ plt.xlabel('x (m)',size=15,c='green')
1032
+ plt.ylabel('u velocity (m/s)',size=15,c='green')
1033
+ plt.show()
1034
+
1035
+ return u_max,loc_max
1036
+
1037
+
1038
+
1039
+
1040
+ def Solidification_Start(data,Temp_sol):
1041
+ '''
1042
+ This function gets the temperature values of a molten along with its solidus temperature as inputs,
1043
+ and if the solidification process has started it returns true and if not it returns false.
1044
+ it also plots the temperature values in the center line.
1045
+ note that this function has simplified the problem and many other parameters should be taken into consideration.
1046
+ '''
1047
+
1048
+ x=np.array(data['x(m)'])
1049
+ y=np.array(data['T(K)'])
1050
+ plt.scatter(x,y)
1051
+ plt.title('Temperature Profile',c='blue',family='times new roman',size=20,pad=20)
1052
+ plt.xlabel('x (m)',size=15,c='green')
1053
+ plt.ylabel('Temperature (K)',size=15,c='green')
1054
+ plt.show()
1055
+ Temp_Min=np.min(y)
1056
+ if Temp_Min>Temp_sol:
1057
+ print('The solidification process has not started yet.')
1058
+ else:
1059
+ print('The solidification process has started.')
1060
+
1061
+
1062
+ if Temp_Min>Temp_sol:
1063
+ return False
1064
+ else:
1065
+ return True
1066
+
1067
+
1068
+
1069
+
1070
+
1071
+
1072
+
1073
+
1074
+
1075
+ def Sakhti_ab( data):
1076
+ '''
1077
+ Parameters
1078
+ ----------
1079
+ data : exel
1080
+ شامل تمامی داده های مورد نیاز برای بررسی سختی آب میباشد.
1081
+
1082
+ Returns
1083
+ -------
1084
+ data : plot
1085
+ plot mizan sakhti ab dar nemoone ha.
1086
+ arraye
1087
+ jadval nahayi.
1088
+
1089
+ '''
1090
+
1091
+ unavalable_water=[]
1092
+
1093
+ drop_index= data[data['Cu']>20].index
1094
+ for i in drop_index:
1095
+ unavalable_water.append(data.loc[[i],['name']])
1096
+ data= data.drop(drop_index)
1097
+
1098
+ drop_index= data[data['Ni']>10].index
1099
+ for i in drop_index:
1100
+ unavalable_water.append(data.loc[[i],['name']])
1101
+ data= data.drop(drop_index)
1102
+
1103
+ drop_index= data[data['Zn']>10].index
1104
+ for i in drop_index:
1105
+ unavalable_water.append(data.loc[[i],['name']])
1106
+ data= data.drop(drop_index)
1107
+
1108
+ drop_index= data[data['pyro']>100].index
1109
+ for i in drop_index:
1110
+ unavalable_water.append(data.loc[[i],['name']])
1111
+ data= data.drop(drop_index)
1112
+
1113
+ drop_index= data[data['Cya']>2].index
1114
+ for i in drop_index:
1115
+ unavalable_water.append(data.loc[[i],['name']])
1116
+ data= data.drop(drop_index)
1117
+ #======
1118
+
1119
+ mg = np.array(data['Mg'])
1120
+ ca = np.array(data['Ca'])
1121
+ names= np.array(data['name'])
1122
+
1123
+ ppm = np.array([])
1124
+ ca = (ca*2.5)
1125
+ mg = (mg*4.12)
1126
+ ppm = ca + mg
1127
+ plt.bar(ppm,names)
1128
+
1129
+ return data,plt.show()
1130
+
1131
+
1132
+
1133
+
1134
+ def Wear_Rate(w,work,S,F):
1135
+ '''
1136
+ w : dataframe contains 2 columns
1137
+ bayad shamele 2 soton bashad ke dar yek soton vazn nemoone ghabl az test andazegiri shavad ,
1138
+ dar yek soton vazne nemone pas az etmame test.
1139
+
1140
+ S haman masate laghzesh hine azmone sayesh ast. S bayad bar hasbe metr bashad.
1141
+
1142
+ F barabare niroyee ast ke be pin vared shode ast , azmon ba an anjam shode ast. F bayad bar hasbe newton bashad
1143
+ '''
1144
+ w.columns
1145
+ wb=np.array(w['weight befor test'])
1146
+ # khate bala soton avval ra joda mikonad yani vazne nemone ghabl az azmoon.
1147
+ wa=np.array(w['weight after test'])
1148
+ # khate bala soton dovvom ra joda mikonad yani vazne nemone baa'd az azmoon.
1149
+ wl=np.subtract(wb,wa)
1150
+ # khate bala kaheshe vazne nemoone pas az azmoon ra hesab mikonad.
1151
+ m=wl.mean()
1152
+ # khate bala miangine kaheshe vazne nemoone ra hesab mikonad.
1153
+ if work=='wear rate':
1154
+ WR= m/(S*F)
1155
+ # WR yani Wear Rate va nerkhe sayesh ra hesab mikonad.
1156
+ return WR
1157
+
1158
+
1159
+
1160
+
1161
+ def Wear_Bar(list_1,work='bar'):
1162
+ # manzoor az bar nemoodare mile ee ast.
1163
+ new_list=[]
1164
+ if work=='bar':
1165
+ for i in list_1:
1166
+ # be komake halgheye for nerkhe sayeshe tamame nemoone ha ra hesab mikonim.
1167
+ aa=Wear_Rate(i,'wear rate',300,5)
1168
+ new_list.append(aa)
1169
+ # nerkhe sayeshe har nemoon ra be yek lidt ezafe mikonim.
1170
+ x=np.array(['A','B','C','D','E'])
1171
+ y=np.array(new_list)
1172
+ plt.bar(x,y,color='g',width=0.5)
1173
+ # nemidare mile ee ra ba dastoore plt.bar rasm mikonim.
1174
+ plt.title('The amount of wear rate for samples',c='g',size=14)
1175
+ plt.ylabel('Wear Rate(mg/N.m',size=12,color='k')
1176
+ plt.show()
1177
+
1178
+
1179
+
1180
+
1181
+
1182
+
1183
+
1184
+
1185
+
1186
+
1187
+ def Polarization(b,work):
1188
+ '''
1189
+ d: dadehaye azmayeshgah shmele ghegaliye jaryan va potansiel hastand.
1190
+ '''
1191
+
1192
+ font_1={'family': 'serif',
1193
+ 'color': 'b',
1194
+ 'size':14}
1195
+
1196
+ font_2={'family': 'serif',
1197
+ 'color': 'k',
1198
+ 'size':12}
1199
+
1200
+ b.columns
1201
+ cd=np.array(b['Current density'])
1202
+ # cd haman ghegaliye jaryan ast.
1203
+ cp=np.array(b['Potential'])
1204
+ # cp haman potansiel ast.
1205
+ cdl=np.log(cd)
1206
+ # dadehaye ghegaliye jaryan bayad logaritni shavand.
1207
+ if work=='plot':
1208
+ # in ghesmat marboot be rasme nemoodare polarizasion ast.
1209
+ plt.plot(cdl,cp,c='r',linewidth=3)
1210
+ plt.title('Polarization Curve',fontdict=font_1,pad=15)
1211
+ plt.xlabel('Log i(A/cm2)',fontdict=font_2)
1212
+ plt.ylabel('E(V Ag/AgCl)',fontdict=font_2)
1213
+ # dar 3 khate bala az font haye sakhte shode estefade shod.
1214
+ plt.show()
1215
+ if work=='corrosion potential':
1216
+ # in ghesmat marboot be mohasebeye potansiele khordegi ast.
1217
+ c=cdl.min()
1218
+ # meghdare minimume ghegalie jaryan ra miyabim ta potansiele mirboot be an ra peyda konim ke an,
1219
+ # potansiele khordegi ast.
1220
+ d=np.where(cdl==c)
1221
+ # baraye yaftane mahale minimume ghegalie jaryan.
1222
+ e=b.loc[d]
1223
+ f=np.array(e)
1224
+ g=f[0,1]
1225
+ return g
1226
+
1227
+
1228
+
1229
+
1230
+
1231
+
1232
+
1233
+
1234
+ def Xrd_Analysis(data, operation):
1235
+
1236
+ '''
1237
+ XRD is a nondestructive technique that provides detailed
1238
+ information about the crystallographic structure, chemical
1239
+ -----------------------------------------------------------
1240
+ composition, and physical properties of a material
1241
+ this function return max intensity of xrd pattern and degree
1242
+ of difraction. also based on user requierment return specified plot.
1243
+ statistics analysis is presented too.
1244
+ ----------------------------------------------------------
1245
+ Parameters
1246
+ ----------
1247
+ data : DataFrame
1248
+ data set include tow features:
1249
+ 1. degree (2* degree of difraction)
1250
+ 2. intensity
1251
+ operation : str
1252
+ determine an operation which apply on data
1253
+ possible values:
1254
+ information
1255
+ max intensity
1256
+ scatter plot
1257
+ line graph
1258
+ Returns
1259
+ -------
1260
+ max intensity and degree of max intensity
1261
+ or
1262
+ plot
1263
+
1264
+ '''
1265
+
1266
+ font_title = { 'family' : 'serif','color' :'black' , 'size' : 15 }
1267
+ font_x = {'family' : 'serif','color' : 'black', 'size' : 10 }
1268
+ font_y = { 'family' : 'serif','color' : 'black', 'size' : 10}
1269
+
1270
+
1271
+ if operation == 'max intensity':
1272
+ max_intensity = data['intensity'].max()
1273
+ specified_intensity = data['intensity'] == max_intensity
1274
+ related_vlues = data [specified_intensity]
1275
+ return related_vlues
1276
+
1277
+ elif operation == 'scatter plot':
1278
+ y = np.array(data['intensity'])
1279
+ x = np.array(data['degree'])
1280
+ plt.scatter(x, y, marker = '^', color = 'red', edgecolors='brown')
1281
+ plt.title('XRD pattern',fontdict=font_title )
1282
+ plt.xlabel('Degree',fontdict=font_x)
1283
+ plt.ylabel('Intensity',fontdict=font_y)
1284
+ plt.show()
1285
+
1286
+ elif operation == 'line graph':
1287
+ y = np.array(data['intensity'])
1288
+ x = np.array(data['degree'])
1289
+ plt.plot(x,y, color = 'green', linewidth = 0.5)
1290
+ plt.title('XRD pattern',fontdict=font_title )
1291
+ plt.xlabel('Degree',fontdict=font_x)
1292
+ plt.ylabel('Intensity',fontdict=font_y)
1293
+ plt.show()
1294
+
1295
+ elif operation == 'line graph fill between':
1296
+ y = np.array(data['intensity'])
1297
+ x = np.array(data['degree'])
1298
+ plt.fill_between( x, y, color="#C8D700" , alpha = 0.3)
1299
+ plt.plot(x, y, color='#36BD00', linewidth = 0.5)
1300
+ plt.title('XRD pattern',fontdict=font_title )
1301
+ plt.xlabel('Degree',fontdict=font_x)
1302
+ plt.ylabel('Intensity',fontdict=font_y)
1303
+ plt.show()
1304
+
1305
+
1306
+ def Statitical_Analysis(data, operation):
1307
+ '''
1308
+ this function calculate quantile, IQR, min, max, median,and
1309
+ zscore for each features of data set. also it is presented
1310
+ plot.
1311
+ -----------------------------------------------------------
1312
+ Parameters
1313
+ ----------
1314
+ data : data frame
1315
+
1316
+ opertaion : str
1317
+ possible values:.
1318
+ 1. statistics
1319
+ 2. histogram
1320
+ 3. correlation
1321
+ 4.pairplot
1322
+ Returns
1323
+ -------
1324
+ 1. quantile
1325
+ 2. min
1326
+ 3. max
1327
+ 4. median
1328
+ 5. zscore
1329
+ 6. determined plot
1330
+ '''
1331
+ font_title = { 'family' : 'serif','color' :'black' , 'size' : 15 }
1332
+ font_x = {'family' : 'serif','color' : 'black', 'size' : 10 }
1333
+ font_y = { 'family' : 'serif','color' : 'black', 'size' : 10}
1334
+
1335
+ if operation == 'statistics':
1336
+ for c in data.columns:
1337
+ if (data[c].dtype == int) | (data[c].dtypes == float):
1338
+
1339
+ Q1 = data[c].quantile(.25)
1340
+ Q3 = data[c].quantile(.75)
1341
+ IQR = Q3 -Q1
1342
+
1343
+ min_value = data[c].min()
1344
+ max_value = data[c].max()
1345
+ median_value = data[c].median()
1346
+
1347
+ z_score = np.abs(stats.zscore(data[c]))
1348
+
1349
+ print('feature name : ', c,
1350
+ '\n min = ', min_value,
1351
+ 'max = ',max_value ,
1352
+ 'median = ',median_value ,
1353
+ 'Q1 = ', Q1, 'Q3 = ', Q3, 'IQR = ', IQR,
1354
+ 'ZScore = ', z_score)
1355
+
1356
+ for c in data.columns:
1357
+ if operation == 'histogram':
1358
+
1359
+ if (data[c].dtype == int) | (data[c].dtypes == float):
1360
+
1361
+ plt.hist(data[c], label = c, color = 'green',
1362
+ edgecolor = 'black', linewidth = 0.5)
1363
+
1364
+ plt. legend()
1365
+ plt.title('distribution', fontdict=font_title)
1366
+ plt.xlabel('bins', fontdict = font_x)
1367
+ plt.ylabel('frequency', fontdict = font_y)
1368
+ plt.show()
1369
+
1370
+ if operation == 'correaltion':
1371
+ plt.figure(figsize=(18,12), dpi= 200)
1372
+
1373
+ sns.heatmap(data.corr(), xticklabels=data.columns,
1374
+ yticklabels=data.columns, center=0, annot=True,cmap = 'coolwarm')
1375
+
1376
+ plt.title('correalation', fontdict=font_title)
1377
+ plt.show()
1378
+ if operation == 'pairplot':
1379
+ plt.figure(figsize=(18,12), dpi= 200)
1380
+ sns.pairplot(data, vars = data.columns, markers = '*', kind = 'reg')
1381
+ plt.title('relation between columns', fontdict=font_title)
1382
+ plt.show()
1383
+
1384
+
1385
+
1386
+
1387
+ def Blood_Pressure(data1,operation):
1388
+ '''
1389
+ Blood is divided into two main values: systolic blood pressure and diastolic blood pressure.
1390
+ Systolic blood pressure represents the blood pressure at the moment the heart muscle contracts,
1391
+ while diastolic blood pressure represents the blood pressure at the moment the heart muscle relaxes.
1392
+
1393
+ This function gives us their average systolic and diastolic blood pressure
1394
+ And it shows us the blood pressure chart of 40-year-old Balinese people
1395
+ Parameters
1396
+ ----------
1397
+ data1 : int
1398
+ systolic,diastolic
1399
+ operation : strig
1400
+ operator
1401
+ Returns
1402
+ -------
1403
+ None.
1404
+
1405
+ '''
1406
+ a=data1['Systolic']
1407
+ b=data1['Diastolic']
1408
+
1409
+
1410
+ if operation=='average1':
1411
+ c=b.mean()
1412
+ return c
1413
+ if operation=='average2':
1414
+ c=a.mean()
1415
+ return c
1416
+ if operation=='plot':
1417
+ plt.plot(a,b,marker='o',ms=10,mec='r')
1418
+ plt.xlabel('Systolic')
1419
+ plt.ylabel('Diastolic')
1420
+ plt.title('Blood_Pressure')
1421
+ plt.show()
1422
+
1423
+
1424
+
1425
+ def Pulse(data2,operation):
1426
+ '''
1427
+ This function gives us the maximum and minimum pulse of people over forty years old
1428
+ in the test and draws the pulse graph of people.
1429
+ And by using the frequency of the pulses, it is obtained
1430
+
1431
+ Parameters
1432
+ ----------
1433
+ data2 : int
1434
+ Pulse
1435
+ operation : string
1436
+ operator
1437
+
1438
+ Returns
1439
+ -------
1440
+ None.
1441
+
1442
+ '''
1443
+ p=data2['pulse']
1444
+ if operation=='maximum':
1445
+ c=p.max()
1446
+ return c
1447
+ if operation=='minimum':
1448
+ c=p.min()
1449
+ return c
1450
+ if operation=='plot':
1451
+ plt.hist(p)
1452
+ plt.title('Pulse')
1453
+ plt.show()
1454
+
1455
+
1456
+
1457
+
1458
+
1459
+
1460
+ def Color_Feature(filee,kar):
1461
+
1462
+ '''
1463
+
1464
+ Parameters
1465
+ ----------
1466
+ filee : DataFrame
1467
+ data from excel.
1468
+ kar : str
1469
+ plot or calculate?
1470
+
1471
+ Returns
1472
+ a number as a delta_E : array or plot a diagram
1473
+
1474
+ '''
1475
+ l=filee['l']
1476
+ a= filee['a']
1477
+ b= filee['b']
1478
+ if kar=='calculate':
1479
+ l_=[]
1480
+ a_=[]
1481
+ b_=[]
1482
+ for i in l:
1483
+ l_.append((i-l[5])**2)
1484
+ for i in a:
1485
+ a_.append((i-a[5])**2)
1486
+ for i in b:
1487
+ b_.append((i-b[5])**2)
1488
+
1489
+ sum1 = np.add(l_,a_)
1490
+ sum_=np.add(sum1,b_)
1491
+ squrt_=[]
1492
+ for i in sum_:
1493
+ squrt_.append(math.sqrt(i))
1494
+ delta_E= np.array(squrt_)
1495
+ return delta_E
1496
+ if kar=='plot':
1497
+ fig = plt.figure()
1498
+ ax= fig.add_subplot(111,projection='3d')
1499
+ ax.set_xlabel('l*')
1500
+ ax.set_ylabel('a*')
1501
+ img= ax.scatter(l,a,b,color='r')
1502
+ ax.set_title('l* a* b* of color')
1503
+ img.show()
1504
+
1505
+
1506
+
1507
+
1508
+ def Particles_Size(filee1,kar1):
1509
+
1510
+ '''
1511
+
1512
+
1513
+ Parameters
1514
+ ----------
1515
+ filee1 : DataFrame
1516
+ Data from excel.
1517
+ kar1 : str
1518
+ plot or calculation.
1519
+
1520
+ Returns
1521
+ a number as an average size or plot a diagram.
1522
+
1523
+
1524
+ '''
1525
+ x= filee1['size']
1526
+ y= filee1['distribution']
1527
+
1528
+ if kar1=='calculate':
1529
+ size=filee1['size']
1530
+ average=statistics.mean(size)
1531
+ print('your average size is:')
1532
+ return average
1533
+ if kar1=='plot':
1534
+ x= filee1['size']
1535
+ y= filee1['distribution']
1536
+ font_x={'family':'Times New Roman',
1537
+ 'color':'k',
1538
+ 'size':'15'}
1539
+ font_y={'family':'Times New Roman',
1540
+ 'color':'k',
1541
+ 'size':'15'}
1542
+ plt.xlabel('size(nm)',fontdict=font_x)
1543
+ plt.ylabel('intensity(%)',fontdict=font_y)
1544
+ plt.plot(x,y)
1545
+
1546
+
1547
+
1548
+
1549
+
1550
+ def Price_Change(data,operation):
1551
+ '''Parameters
1552
+ ----------
1553
+ data : Csv File
1554
+ data ha darbare vizhegi haye gheymat yek saham dar yek rooz mibashad
1555
+ descrription
1556
+
1557
+ operation : az beyn "mohasebe" va "plot"yeki ra entekhab konid
1558
+ in function bishtarin va kamtarin gheymat saham dar yek rooz ra migirad
1559
+ va damane taghyirat gheymat ra ba "plot"rasm mikonad va ba "mohasebe"
1560
+ return mikonad
1561
+ '''
1562
+ if operation=="plot":
1563
+ plt.plot(data.High - data.Low)
1564
+ if operation=="mohasebe":
1565
+ data["taghyir"]=data['High']-data['Low']
1566
+ new_data=data[["High","Low","taghyir"]]
1567
+ return new_data["taghyir"]
1568
+
1569
+
1570
+
1571
+
1572
+ def New_Case_Corona_Propotion(data,operation):
1573
+ ''' Parameters
1574
+ ----------
1575
+ data : Csv File
1576
+ data hayi darbare amar corona virus dar keshvar haye mokhtalef
1577
+ operation : az beyn "plot" va "nesbat" yeki ra mitavanid entekhab konid
1578
+ in tabe nesbat new case haye coronavirus be case haye ghabli ra
1579
+ ba "plot" rasm mikonad va ba "nesbat" return mikonad
1580
+
1581
+ '''
1582
+ if operation=="plot":
1583
+ plt.plot(data.Cases-data.New_cases)
1584
+ if operation=="nesbat":
1585
+ data["New_Propotion"]=data["New_cases"]/data["Cases"]
1586
+ return data.New_Propotion
1587
+
1588
+
1589
+
1590
+
1591
+
1592
+ def Load_Position_Convertor(Data,Operation,Area,Length):
1593
+ '''
1594
+ This function receives an input file containing Load-Position data, as well as the cross-sectional area and gauge length of the part, and according to the user's needs, it can:
1595
+ 1-Load-Position Curve (LPC)
1596
+ 2-Stress-Strain Calculation (SSCal)
1597
+ 3-Stress-Strain Curve (SSC)
1598
+ 4-Normalized Stress-Strain Calculation (NSSCal)
1599
+ 5-Normalized Stress-Strain Curve (NSSC)
1600
+ 6-Energy Absorption Density Calculation (EADCal)
1601
+
1602
+ Parameters
1603
+ ----------
1604
+ Data : xlsx
1605
+ Need two columns containing Load-Position information.
1606
+ Operation : str
1607
+ It specifies the process that should be performed on the entered information.
1608
+ Area : float
1609
+ The surface examined in the tensile or compression test.
1610
+ Length : TYPE
1611
+ Gauge length checked in tension or compression test.
1612
+
1613
+ Returns
1614
+ -------
1615
+ EAD : float
1616
+ Energy absorption desity of meta-materials such as metal foams.
1617
+
1618
+ '''
1619
+
1620
+ Load=np.array(Data['Load (kN)'])
1621
+ Position=np.array(Data['Position (mm)'])
1622
+
1623
+
1624
+ if Operation=='Load-Position Curve' or 'LPC':
1625
+ plt.plot(Position,Load,c='teal',lw='1')
1626
+ title_font={'family':'times new roman','color':'black','size':'14'}
1627
+ label_font={'family':'times new roman','color':'black','size':'12'}
1628
+ plt.title('Load-Position',fontdict=title_font,loc='center',pad=10)
1629
+ plt.xlabel('Position (mm)',fontdict=label_font,labelpad=5)
1630
+ plt.xlim(0,np.max(Position))
1631
+ plt.ylabel('Load (kN)',fontdict=label_font,labelpad=5)
1632
+ plt.ylim(0,np.max(Load))
1633
+ plt.grid(linewidth=0.5,color='grey',alpha=0.4)
1634
+ plt.show()
1635
+ elif Operation=='Stress-Strain Calculation' or 'SSCal':
1636
+ Strain=Position/Length
1637
+ Stress=(Load*1000)/Area
1638
+ Stress_Strain=np.dstack((Strain,Stress))
1639
+ return Stress_Strain
1640
+ elif Operation=='Stress-Strain Curve' or 'SSC':
1641
+ Strain=Position/Length
1642
+ Stress=(Load*1000)/Area
1643
+ plt.plot(Strain,Stress,c='teal',lw='1')
1644
+ plt.title('Stress-Strain',fontdict=title_font,loc='center',pad=10)
1645
+ plt.xlabel('Strain (-)',fontdict=label_font,labelpad=5)
1646
+ plt.ylabel('Stress (MPa)',fontdict=label_font,labelpad=5)
1647
+ plt.grid(linewidth=0.5,color='grey',alpha=0.4)
1648
+ plt.show()
1649
+ elif Operation=='Normal Stress-Strain Calculation' or 'NSSCal':
1650
+ N_Strain=Strain/Strain.max()
1651
+ N_Stress=Stress/Stress.max()
1652
+ N_Stress_Strain=np.dstack(N_Strain,N_Stress)
1653
+ return N_Stress_Strain
1654
+ elif Operation=='Normal Stress-Strain Curve' or "NSSC":
1655
+ N_Strain=Strain/Strain.max()
1656
+ N_Stress=Stress/Stress.max()
1657
+ plt.plot(N_Strain,N_Stress,c='teal',lw='1')
1658
+ plt.title('Normal Stress-Strain',fontdict=title_font,loc='center',pad=10)
1659
+ plt.xlabel('Normal Strain (-)',fontdict=label_font,labelpad=5)
1660
+ plt.xlim(0,1)
1661
+ plt.ylabel('Normal Stress (-)',fontdict=label_font,labelpad=5)
1662
+ plt.ylim(0,1)
1663
+ plt.grid(linewidth=0.5,color='grey',alpha=0.4)
1664
+ plt.show()
1665
+ elif Operation=='EAD Calcultion' or 'EADCal':
1666
+ EAD=np.trapz(Stress,Strain)
1667
+ return EAD
1668
+
1669
+
1670
+
1671
+
1672
+
1673
+
1674
+
1675
+ def Brain_Data_example():
1676
+ """
1677
+ This function prompts the user to input values for sudiom and potasiom along with time increments,
1678
+ creates a DataFrame with the provided data, and returns it.
1679
+ """
1680
+ # Initialize an empty dictionary to store the data
1681
+ data = {
1682
+ 'sudiom':[],
1683
+ 'potasiom':[],
1684
+ 'time': []
1685
+ }
1686
+
1687
+ # Prompt the user to enter the number of entries
1688
+ Num_Entries = int(input('Your entries ion ? --> '))
1689
+ time = 0 # Initial time value
1690
+ counter = 1 # Initial counter value
1691
+
1692
+ # Loop to input data from the user
1693
+ for i in range(Num_Entries):
1694
+ sudiom = float(input(f'sudiom {counter}: ')) # Prompt for sudiom input
1695
+ potasiom = float(input(f'potasiom {counter}: ')) # Prompt for potasiom input
1696
+ counter += 1 # Increment counter
1697
+
1698
+ # Append the input values to the data dictionary
1699
+ data['sudiom'].append(sudiom)
1700
+ data['potasiom'].append(potasiom)
1701
+ data['time'].append(time) # Append the time value
1702
+ time += 0.1 # Increment time by 0.1 for each entry
1703
+
1704
+ # Convert the data dictionary to a pandas DataFrame and return it
1705
+ df = pd.DataFrame(data)
1706
+ return df
1707
+
1708
+ def Brain_Plot_3D(df):
1709
+ """
1710
+ This function takes a DataFrame containing sudiom, potasiom, and time data and plots
1711
+ them in both 2D and 3D. It also compares the mean values of sudiom and potasiom to decide
1712
+ which one to plot in 3D.
1713
+ """
1714
+ # Create a new figure with a specified size
1715
+ fig = plt.figure(figsize=(16, 6))
1716
+
1717
+ # Create subplots: one for 2D plot and one for 3D plot
1718
+ ax1 = fig.add_subplot(121)
1719
+ ax2 = fig.add_subplot(122, projection='3d')
1720
+
1721
+ # Plot 2D lines for sudiom and potasiom
1722
+ ax1.plot(df['time'], df['sudiom'], label='Sudiom', color='red')
1723
+ ax1.plot(df['time'], df['potasiom'], label='Potasiom', color='blue')
1724
+
1725
+ # Set labels and title for the 2D plot
1726
+ ax1.set_xlabel('Time')
1727
+ ax1.set_ylabel('Values')
1728
+ ax1.set_title('Sudiom and Potasiom')
1729
+
1730
+ # Plot 3D points based on the mean values of sudiom and potasiom
1731
+ if df['sudiom'].mean() > df['potasiom'].mean():
1732
+ ax2.plot(df['time'], df['sudiom'], zs=df['potasiom'], zdir='y', c='r', marker='o', label='Sudiom')
1733
+ else:
1734
+ ax2.plot(df['time'], df['potasiom'], zs=df['sudiom'], zdir='y', c='b', marker='x', label='Potasiom')
1735
+
1736
+ # Set labels and title for the 3D plot
1737
+ ax2.set_xlabel('Time')
1738
+ ax2.set_ylabel('Sudiom')
1739
+ ax2.set_zlabel('Potasiom')
1740
+ ax2.set_title('Brain Data (3D)')
1741
+
1742
+ # Add a legend to the 3D plot
1743
+ ax2.legend()
1744
+
1745
+ # Show the plots
1746
+ plt.show()
1747
+
1748
+
1749
+
1750
+
1751
+ '''
1752
+
1753
+ #Importing experimental datas
1754
+ Experimental_Datas=pd.read_excel('C://Users//nasim//Documents//python//Rejection-Flux.xlsx')
1755
+
1756
+ #operating condition of filteration
1757
+ Dox_Size=1.68*10**-9 #m (Solute radius)
1758
+ Pump_Pressure=4*10**5 #pa (Pressure of pump)
1759
+ Bulk_Concentration=9.2*10**-5 #mol/m3 (Concentration of solute in polluted water)
1760
+
1761
+ #experimental Datas:
1762
+ Pore_Sizes=np.array(Experimental_Datas['Membrane Pore Size '])
1763
+ Experimental_Rejection=np.array(Experimental_Datas['Experimental Rejection'])
1764
+ Experimental_Flux=np.array(Experimental_Datas['Experimental Flux'])
1765
+ Experimental_Zeta=np.array(Experimental_Datas['Mean Zeta Potential (mV)'])
1766
+ Membrane_Code=np.array(Experimental_Datas['Membrane Name'])
1767
+
1768
+
1769
+ def Membrane_Rejection(Ex_R,Ex_J,rs,rp,Zeta,Cm,DelP):
1770
+ #constants:
1771
+ D=10**-9
1772
+ RR=8.314
1773
+ T=298
1774
+
1775
+ #rejection calculation
1776
+ Calculated_Rejection=np.array([(1-2*(1-(rs/rp)**2)+(1-(rs/rp)**4))]) #Ferry-Rankin equation
1777
+
1778
+ #error evaluation:
1779
+ errorr=abs((Ex_R-Calculated_Rejection)/Ex_R)
1780
+ error=np.array(errorr)
1781
+ Mean_Error=np.mean(error)
1782
+ if Mean_Error<0.15: #if mean error is less than 15% the assumption that the separation performance is due to sieving mechanism, is true
1783
+ return Calculated_Rejection
1784
+ print('Separation performance is due to sieving mechanism')
1785
+
1786
+ else:
1787
+ theta=rs/rp
1788
+ mean_theta=np.mean(theta)
1789
+ Ka=(1+3.867*theta-1.907*theta**2-0.834*theta**3)/(1+1.867*theta-0.741*theta**2) #convection steric hindreance factor
1790
+
1791
+ a=[]
1792
+ for i in theta:
1793
+ a.append(math.log10(i))
1794
+ a1=np.array(a)
1795
+ Kd=((1+(9/8)*a1*theta-1.56*theta+0.53*theta**2+1.95*theta**3-2.82*theta**4+0.27*theta**5+1.1*theta**6-0.44*theta**7)/((1-theta)**2)) ##convection steric hindreance factor
1796
+
1797
+ phiSi=(1-(rs/rp))**2
1798
+
1799
+ exjka=[]
1800
+ JKa=Ex_J*Ka/Kd
1801
+ for i in JKa:
1802
+ exjka.append(np.exp(-0.11*10**6*i))
1803
+
1804
+ #rejection calculation
1805
+ Calculated_Rejection2=1-((Ka*phiSi)/(1-(1-Ka*phiSi)*exjka)) #Simplified DSPM-DE Model
1806
+
1807
+ #error evaluation:
1808
+ errorrr=abs((Ex_R-Calculated_Rejection2)/Ex_R)
1809
+ error2=np.array(errorrr)
1810
+ Mean_Error2=np.mean(error2)
1811
+ if Mean_Error2<0.15:
1812
+ print('Separation performance is due to Sieving Mechanism & Hindrance Transport')
1813
+ return Calculated_Rejection2
1814
+ else:
1815
+ Xd=-0.00027+0.001*Zeta
1816
+
1817
+ plt.plot(Xd,Zeta,marker='o',ms=10,mec='palevioletred',mfc='palevioletred',color='TEAL',linewidth=5)
1818
+
1819
+ ax = plt.gca()
1820
+ ax.set_facecolor('ghostwhite')
1821
+
1822
+ font_t={'family':'serif','color':'black','size':15}
1823
+ font_x={'family':'serif','color':'black','size':10}
1824
+ font_y={'family':'serif','color':'black','size':10}
1825
+
1826
+ plt.title('Zeta Potential vs Xd',fontdict=font_t)
1827
+ plt.xlabel('Membrane Pore Density (mol/lit)',fontdict=font_x)
1828
+ plt.ylabel('Zeta Potential (mV)',fontdict=font_y)
1829
+
1830
+
1831
+ etha=abs(Xd/Cm)
1832
+ sigma=1-2/((etha)+(etha**2+4)**0.5)
1833
+ omega=D/(RR*T)*(1-sigma)
1834
+ Pe=0.14*10**-3*Ex_J/D
1835
+
1836
+ FF=[]
1837
+ n=(-(1-sigma)*D*Pe/(RR*T*omega))
1838
+ for i in n:
1839
+ FF.append(np.exp(i))
1840
+ F=np.array(FF)
1841
+
1842
+ #rejection calculation
1843
+ Calculated_Rejection3=sigma*(1-F)/(1-sigma*F) #Spiegler-Kedem equation
1844
+ print('Separation performance is due to Donnan Effect')
1845
+ return Calculated_Rejection3
1846
+
1847
+ Rejection=Membrane_Rejection(Experimental_Rejection,Experimental_Flux,Dox_Size,Pore_Sizes,Experimental_Zeta,Bulk_Concentration,Pump_Pressure)
1848
+
1849
+ print (Rejection)
1850
+
1851
+ eror=abs(Experimental_Rejection-Rejection/Experimental_Rejection)
1852
+ eror=np.array(eror)
1853
+ Mean_Eror=np.mean(eror)*100
1854
+
1855
+ m='average error in this model is '+ str(Mean_Eror) +' percent'
1856
+ print(m)
1857
+
1858
+ '''
1859
+
1860
+ #________________________________Flux Calculation______________________________
1861
+ '''
1862
+
1863
+ #Importing experimental datas
1864
+ Experimental_Datas=pd.read_excel('C://Users//nasim//Documents//python//Flux.xlsx')
1865
+ Pump_DeltaP=4*10**5
1866
+ Diffusivity=10**-9
1867
+ Thickness=0.11*10**-3
1868
+ Bulk_Concentration=9.2*10**-5
1869
+ Pore_Size=np.array(Experimental_Datas['Pore Size'])
1870
+ Porosity=np.array(Experimental_Datas['Porosity'])
1871
+ Membrane_Code=np.array(Experimental_Datas['Membrane Code'])
1872
+ Permeat_Concentration=np.array(Experimental_Datas['Permeate Concentration'])
1873
+
1874
+ def Membrane_Flux(r,e,p,l,Cp,Cb):
1875
+ mean_pore_size=np.mean(Pore_Size)
1876
+ if mean_pore_size<1*10**-9:
1877
+ J=(D*(Cb-Cp))/l
1878
+ print('Membrane is dense and permeability should be calculated based on Darcy law.')
1879
+ else:
1880
+ J=(r**2*e*p)/(8*10**-3*l)
1881
+ print('Membrane is porous and permeability should be calculated based on Hagen–Poiseuille equation.')
1882
+ return J
1883
+ Flux=Membrane_Flux(Pore_Size,Porosity,Pump_DeltaP,Thickness,Permeat_Concentration,Bulk_Concentration)
1884
+
1885
+ plt.bar(Membrane_Code,Flux,color='mediumvioletred', width=0.3)
1886
+
1887
+
1888
+ font_ttt={'family':'serif','color':'black','size':15}
1889
+ font_xxx={'family':'serif','color':'black','size':10}
1890
+ font_yyy={'family':'serif','color':'black','size':10}
1891
+
1892
+ plt.title('Mmebrane Flux',fontdict=font_ttt,pad=25)
1893
+ plt.xlabel('Membrane code',fontdict=font_xxx)
1894
+ plt.ylabel('Mmebrane Pure Water Flux (m/s) ',fontdict=font_yyy)
1895
+ plt.show()
1896
+
1897
+ #________________________________Film Treory___________________________________
1898
+
1899
+ #Importing experimental datas
1900
+ Experimental_Datas=pd.read_excel('C://Users//nasim//Documents//python//Film Theory.xlsx')
1901
+
1902
+ Membrane_length=0.09
1903
+ Mmembrane_width=0.04
1904
+ Mmebrane_thickness=0.11 *10**-3
1905
+ Velocity=0.5
1906
+ Bulk_Concentration=9.2*10**-5
1907
+ Permeate_Concentration=np.array(Experimental_Datas['Permeate Concentration'])
1908
+ Flux=np.array(Experimental_Datas['Flux'])
1909
+ Membrane_Code=np.array(Experimental_Datas['Membrane Code'])
1910
+
1911
+ def Membrane_Concentration(a,b,u,J,Cb,Cp,l):
1912
+ dh=4*a*b/(a+b)
1913
+ Re=1000*u*dh/(10**-3)
1914
+ Sc=10**-3/(1000*10**-9)
1915
+ k=((0.664*Re**0.5*Sc**0.33*(dh/l)**0.5)*10**-9)/dh
1916
+
1917
+ v=[]
1918
+ Jk=J/k
1919
+ for i in Jk:
1920
+ v.append(np.exp(i))
1921
+
1922
+ Cm=(Cb-Cp)*v+Cp
1923
+ Polarization=(Cm-Cb)/Cb
1924
+ mean_Polarization=np.mean(Polarization)
1925
+
1926
+ if mean_Polarization<0.05:
1927
+ print('Concentration polarization is neglible. So, membrane has a low probability for fouling.')
1928
+ else:
1929
+ print('Concentration polarization is high. So, fouling may occures.')
1930
+
1931
+
1932
+ return(Cm)
1933
+
1934
+ Membrane_Surface_Concentration=Membrane_Concentration(Membrane_length,Mmembrane_width,Velocity,Flux,Bulk_Concentration,Permeate_Concentration,Mmebrane_thickness)
1935
+
1936
+ plt.bar(Membrane_Code, Membrane_Surface_Concentration,color='mediumvioletred', width=0.3)
1937
+
1938
+
1939
+ font_tt={'family':'serif','color':'black','size':15}
1940
+ font_xx={'family':'serif','color':'black','size':10}
1941
+ font_yy={'family':'serif','color':'black','size':10}
1942
+
1943
+ plt.title('Mmebrane Surface Concentration',fontdict=font_tt,pad=20)
1944
+ plt.xlabel('Membrane code',fontdict=font_xx)
1945
+ plt.ylabel('Cm',fontdict=font_yy)
1946
+ plt.show()
1947
+
1948
+
1949
+ '''
1950
+
1951
+
1952
+
1953
+
1954
+
1955
+
1956
+
1957
+ def SI_Calculation(f_loc,P,PC,Density=1):
1958
+
1959
+
1960
+
1961
+ '''
1962
+
1963
+ This function is used for Separation Index Calculation
1964
+
1965
+
1966
+ P : Pressure (bar)
1967
+
1968
+ Density : Feed Density(g/cm3)
1969
+
1970
+ PC : Pollutant concentration in Feed (g/L)
1971
+
1972
+ Returns Separation Index and Flux & Rejection & Rejection Charts
1973
+
1974
+ '''
1975
+
1976
+
1977
+
1978
+ Data=pd.read_excel(f_loc)
1979
+
1980
+ Data.columns
1981
+
1982
+ J=Data['Flux']
1983
+
1984
+ R=Data['Rejection']
1985
+
1986
+
1987
+
1988
+ SI=(Density-(1-R)*PC/1000)*(J/(P*((1-R)**0.41)))
1989
+
1990
+ Mem_Code=np.array(Data['Mem Code'])
1991
+
1992
+ Flux=np.array(Data['Flux'])
1993
+
1994
+ Rejection=np.array(Data['Rejection'])
1995
+
1996
+
1997
+
1998
+ font={'family':'serif','color':'k','size':'20'}
1999
+
2000
+
2001
+
2002
+ c=np.array([])
2003
+
2004
+ for i in range (0,len(Flux)):
2005
+
2006
+ if Flux[i]<100:
2007
+
2008
+ a=np.array(['.'])
2009
+
2010
+ c=np.concatenate((c,a))
2011
+
2012
+ elif Flux[i]<200:
2013
+
2014
+ a=np.array(['o'])
2015
+
2016
+ c=np.concatenate((c,a))
2017
+
2018
+ else:
2019
+
2020
+ a=np.array(['O'])
2021
+
2022
+ c=np.concatenate((c,a))
2023
+
2024
+ fig, ax = plt.subplots()
2025
+
2026
+
2027
+
2028
+ bar_labels=['.:Low Flux','o:Medium Flux','O:High Flux']
2029
+
2030
+ for i in range(0,len(Flux)-3):
2031
+
2032
+ m=['_.']
2033
+
2034
+ bar_labels=bar_labels+m
2035
+
2036
+
2037
+
2038
+ ax.bar(Mem_Code,Flux,color='w',edgecolor='c',hatch=c,linewidth=1,yerr=10,ecolor='c',width=0.85,label=bar_labels)
2039
+
2040
+ plt.title('Flux Chart',fontdict=font)
2041
+
2042
+ plt.xlabel('Membrane code',fontdict=font)
2043
+
2044
+ plt.ylabel('Flux',fontdict=font)
2045
+
2046
+ ax.legend(title='Flux Range')
2047
+
2048
+ plt.show()
2049
+
2050
+
2051
+
2052
+ d=np.array([])
2053
+
2054
+ for i in range (0,len(Rejection)):
2055
+
2056
+ if Rejection[i]<0.6:
2057
+
2058
+ a=np.array(['.'])
2059
+
2060
+ d=np.concatenate((d,a))
2061
+
2062
+ elif Rejection[i]<0.75:
2063
+
2064
+ a=np.array(['o'])
2065
+
2066
+ d=np.concatenate((d,a))
2067
+
2068
+ else:
2069
+
2070
+ a=np.array(['O'])
2071
+
2072
+ d=np.concatenate((d,a))
2073
+
2074
+ fig, ax = plt.subplots()
2075
+
2076
+
2077
+
2078
+ bar_labels=['.:Low Rejection','o:Medium Rejection','O:High Rejection']
2079
+
2080
+ for i in range(0,len(Rejection)-3):
2081
+
2082
+ m=['_.']
2083
+
2084
+ bar_labels=bar_labels+m
2085
+
2086
+
2087
+
2088
+ ax.bar(Mem_Code,Rejection,color='w',edgecolor='c',hatch=d,linewidth=1,yerr=0.01,ecolor='c',width=0.85,label=bar_labels)
2089
+
2090
+ plt.title('Rejection Chart',fontdict=font)
2091
+
2092
+ plt.xlabel('Membrane code',fontdict=font)
2093
+
2094
+ plt.ylabel('Rejection',fontdict=font)
2095
+
2096
+ ax.legend(title='Rejection Range')
2097
+
2098
+ plt.show()
2099
+
2100
+
2101
+
2102
+ f=np.array([])
2103
+
2104
+ for i in range (0,len(SI)):
2105
+
2106
+ if SI[i]<250:
2107
+
2108
+ a=np.array(['.'])
2109
+
2110
+ f=np.concatenate((f,a))
2111
+
2112
+ elif SI[i]<500:
2113
+
2114
+ a=np.array(['o'])
2115
+
2116
+ f=np.concatenate((f,a))
2117
+
2118
+ else:
2119
+
2120
+ a=np.array(['O'])
2121
+
2122
+ f=np.concatenate((f,a))
2123
+
2124
+ fig, ax = plt.subplots()
2125
+
2126
+
2127
+
2128
+ bar_labels=['.:Low SI','o:Medium SI','O:High SI']
2129
+
2130
+ for i in range(0,len(SI)-3):
2131
+
2132
+ m=['_.']
2133
+
2134
+ bar_labels=bar_labels+m
2135
+
2136
+
2137
+
2138
+ ax.bar(Mem_Code,SI,color='w',edgecolor='c',hatch=f,linewidth=1,yerr=10,ecolor='c',width=0.85,label=bar_labels)
2139
+
2140
+ plt.title('SI Chart',fontdict=font)
2141
+
2142
+ plt.xlabel('Membrane code',fontdict=font)
2143
+
2144
+ plt.ylabel('SI',fontdict=font)
2145
+
2146
+ ax.legend(title='SI Range')
2147
+
2148
+ plt.show()
2149
+
2150
+
2151
+
2152
+ return SI
2153
+
2154
+
2155
+
2156
+
2157
+
2158
+
2159
+
2160
+ def Porosity(e_loc,Density=1):
2161
+
2162
+
2163
+
2164
+ '''
2165
+
2166
+ Ww : weight of wet samples (g)
2167
+
2168
+ Wd : weight of dry samples (g)
2169
+
2170
+ V : denotes the sample volume (cm3)
2171
+
2172
+ Density : is the water density (g/cm3).The default is 1.
2173
+
2174
+ Returns the porosity of membranes
2175
+
2176
+ '''
2177
+
2178
+
2179
+
2180
+ Porosity_Data=pd.read_excel(e_loc)
2181
+
2182
+ Porosity_Data.columns
2183
+
2184
+ Ww=Porosity_Data['Ww']
2185
+
2186
+ Wd=Porosity_Data['Wd']
2187
+
2188
+ V=Porosity_Data['V']
2189
+
2190
+
2191
+
2192
+ Porosity=(Ww-Wd)/(Density*V)
2193
+
2194
+ membrane=np.array(Porosity_Data['membrane'])
2195
+
2196
+
2197
+
2198
+ font={'family':'serif','color':'k','size':'20'}
2199
+
2200
+
2201
+
2202
+ c=np.array([])
2203
+
2204
+ for i in range (0,len(Porosity)):
2205
+
2206
+ if Porosity[i]<0.9:
2207
+
2208
+ a=np.array(['.'])
2209
+
2210
+ c=np.concatenate((c,a))
2211
+
2212
+ elif Porosity[i]<1:
2213
+
2214
+ a=np.array(['o'])
2215
+
2216
+ c=np.concatenate((c,a))
2217
+
2218
+ else:
2219
+
2220
+ a=np.array(['O'])
2221
+
2222
+ c=np.concatenate((c,a))
2223
+
2224
+ fig, ax = plt.subplots()
2225
+
2226
+
2227
+
2228
+ bar_labels=['.:Low Porosity','o:Medium Porosity','O:High Porosity']
2229
+
2230
+ for i in range(0,len(Porosity)-3):
2231
+
2232
+ m=['_.']
2233
+
2234
+ bar_labels=bar_labels+m
2235
+
2236
+
2237
+
2238
+ ax.bar(membrane,Porosity,color='w',edgecolor='c',hatch=c,linewidth=1,yerr=0.05,ecolor='c',width=0.85,label=bar_labels)
2239
+
2240
+ plt.title('Porosity Chart',fontdict=font)
2241
+
2242
+ plt.xlabel('membrane',fontdict=font)
2243
+
2244
+ plt.ylabel('Porosity',fontdict=font)
2245
+
2246
+ ax.legend(title='Porosity Range')
2247
+
2248
+ plt.show()
2249
+
2250
+
2251
+
2252
+ return Porosity
2253
+
2254
+
2255
+
2256
+
2257
+ def Tortuosity(e_loc):
2258
+
2259
+
2260
+
2261
+ '''
2262
+
2263
+ Returns the Pore Tortuosity of membranes
2264
+
2265
+ '''
2266
+
2267
+
2268
+
2269
+ Porosity_Data=pd.read_excel(e_loc)
2270
+
2271
+ Tortuosity=((2-Porosity)**2)/Porosity
2272
+
2273
+ membrane=np.array(Porosity_Data['membrane'])
2274
+
2275
+
2276
+
2277
+ font={'family':'serif','color':'k','size':'20'}
2278
+
2279
+
2280
+
2281
+ c=np.array([])
2282
+
2283
+ for i in range (0,len(Tortuosity)):
2284
+
2285
+ if Tortuosity[i]<0.75:
2286
+
2287
+ a=np.array(['.'])
2288
+
2289
+ c=np.concatenate((c,a))
2290
+
2291
+ elif Tortuosity[i]<1.25:
2292
+
2293
+ a=np.array(['o'])
2294
+
2295
+ c=np.concatenate((c,a))
2296
+
2297
+ else:
2298
+
2299
+ a=np.array(['O'])
2300
+
2301
+ c=np.concatenate((c,a))
2302
+
2303
+ fig, ax = plt.subplots()
2304
+
2305
+
2306
+
2307
+ bar_labels=['.:Low Tortuosity','o:Medium Tortuosity','O:High Tortuosity']
2308
+
2309
+ for i in range(0,len(Tortuosity)-3):
2310
+
2311
+ m=['_.']
2312
+
2313
+ bar_labels=bar_labels+m
2314
+
2315
+
2316
+
2317
+ ax.bar(membrane,Tortuosity,color='w',edgecolor='c',hatch=c,linewidth=1,yerr=0.05,ecolor='c',width=0.85,label=bar_labels)
2318
+
2319
+ plt.title('Tortuosity Chart',fontdict=font)
2320
+
2321
+ plt.xlabel('membrane',fontdict=font)
2322
+
2323
+ plt.ylabel('Tortuosity',fontdict=font)
2324
+
2325
+ ax.legend(title='Tortuosity Range')
2326
+
2327
+ plt.show()
2328
+
2329
+
2330
+
2331
+ return Tortuosity
2332
+
2333
+
2334
+
2335
+
2336
+
2337
+
2338
+
2339
+ def Pore_Size(g_loc,A,P,Vis=8.9*1e-4):
2340
+
2341
+
2342
+
2343
+ '''
2344
+
2345
+ A=shows the membrane effective surface area (m2)
2346
+
2347
+ P : indicates the utilized operational pressure (Pa)
2348
+
2349
+ Vis : represents the water viscosity (Pa⋅s). The default is 8.9*1e-4.
2350
+
2351
+ Returns the Pore Size of membranes in nm
2352
+
2353
+ '''
2354
+
2355
+
2356
+
2357
+ Pore_Size_Data=pd.read_excel(g_loc)
2358
+
2359
+ Pore_Size_Data.columns
2360
+
2361
+ q=Pore_Size_Data['q']
2362
+
2363
+ l=Pore_Size_Data['l']
2364
+
2365
+
2366
+
2367
+ Pore_Size=((2.9-1.75*Porosity)*(8*Vis*q*l/1000)/(Porosity*A*P))**(0.5)*1E9
2368
+
2369
+ membrane=np.array(Pore_Size_Data['membrane'])
2370
+
2371
+
2372
+
2373
+ font={'family':'serif','color':'k','size':'20'}
2374
+
2375
+
2376
+
2377
+ c=np.array([])
2378
+
2379
+ for i in range (0,len(Pore_Size)):
2380
+
2381
+ if Pore_Size[i]<4.5:
2382
+
2383
+ a=np.array(['.'])
2384
+
2385
+ c=np.concatenate((c,a))
2386
+
2387
+ elif Pore_Size[i]<5.5:
2388
+
2389
+ a=np.array(['o'])
2390
+
2391
+ c=np.concatenate((c,a))
2392
+
2393
+ else:
2394
+
2395
+ a=np.array(['O'])
2396
+
2397
+ c=np.concatenate((c,a))
2398
+
2399
+ fig, ax = plt.subplots()
2400
+
2401
+
2402
+
2403
+ bar_labels=['.:Low Pore_Size','o:Medium Pore_Size','O:High Pore_Size']
2404
+
2405
+ for i in range(0,len(Pore_Size)-3):
2406
+
2407
+ m=['_.']
2408
+
2409
+ bar_labels=bar_labels+m
2410
+
2411
+
2412
+
2413
+ ax.bar(membrane,Pore_Size,color='w',edgecolor='c',hatch=c,linewidth=1,yerr=0.05,ecolor='c',width=0.85,label=bar_labels)
2414
+
2415
+ plt.title('Pore_Size Chart',fontdict=font)
2416
+
2417
+ plt.xlabel('membrane',fontdict=font)
2418
+
2419
+ plt.ylabel('Pore Size',fontdict=font)
2420
+
2421
+ ax.legend(title='Pore_Size Range')
2422
+
2423
+ plt.show()
2424
+
2425
+
2426
+
2427
+ return Pore_Size
2428
+
2429
+
2430
+
2431
+
2432
+
2433
+
2434
+
2435
+
2436
+ def Membrane_Rejection(Experimental_Datas):
2437
+ Dox_Size=1.68*10**-9 #m
2438
+ Pore_Sizes=np.array(Experimental_Datas['Membrane Pore Size '])
2439
+ Calculated_Rejection=(1-2*(1-(Dox_Size/Pore_Sizes)**2)+(1-(Dox_Size/Pore_Sizes)**4))
2440
+ Experimental_Rejection=np.array(Experimental_Datas['Experimental Rejection'])
2441
+ error=abs((Experimental_Rejection-Calculated_Rejection)/Experimental_Rejection)
2442
+ Mean_Error=np.mean(error)
2443
+ if Mean_Error<0.05:
2444
+ Rejection=Calculated_Rejection
2445
+ return(Rejection)
2446
+ print('Separation performance is due to sieving mechanism')
2447
+ else:
2448
+ Zeta_Potential=np.array(Experimental_Datas['Mean Zeta Potential (mV)'])
2449
+ Xd=-0.27+2.8*Zeta_Potential #a corralation between zeta potential and membrane charge density. it is worth noty that zeta potential is a measurable parameter while,membrane charge density is not.
2450
+ theta = (1-Dox_Size/Pore_Sizes)**2
2451
+ Kc =(2-theta)*(1+0.054*Dox_Size/Pore_Sizes-0.988*(Dox_Size/Pore_Sizes)**2+0.441*(Dox_Size/Pore_Sizes)**3)
2452
+ Kd=1-2.3*Dox_Size/Pore_Sizes+1.15*(Dox_Size/Pore_Sizes)**2+0.224*(Dox_Size/Pore_Sizes)**3
2453
+ C0=9.2*10**-5
2454
+ Cp=C0
2455
+
2456
+ def ODE_Function(x,c,Cp): #Define simultaneous ODE equations
2457
+ Experimental_J=np.array(Experimental_Datas['Experimental Flux'])
2458
+ z = 1
2459
+ D=10**-9
2460
+ Dp=Kd*D
2461
+ dcdx = Experimental_J/Dp*(Kc*c-Cp)-z*c*(Experimental_J*z/Dp*(Kc*c-Cp))/((z**2*c))
2462
+ return dcdx
2463
+
2464
+ def Boundary_Conditions(ca,cb,Cp):
2465
+ T=298
2466
+ F=96487
2467
+ R=8.314
2468
+ z=1
2469
+
2470
+ a1=(abs(Xd)/(z*C0*theta))
2471
+ phiDa=[]
2472
+ for i in a1:
2473
+ phiDa.append(math.log10(i)/(F*z/R/T))
2474
+ phiDa_array=np.array(phiDa)
2475
+ c0_m=C0*theta*np.exp(-F*z*phiDa_array/R/T)
2476
+
2477
+ a2=(abs(Xd)/(z*Cp*theta))
2478
+ phiDb=[]
2479
+ for i in a2:
2480
+ phiDb.append(math.log10(i)/(F*z/R/T))
2481
+ phiDb_array=np.array(phiDb)
2482
+ cb_m=Cp*theta*np.exp(-F*z*phiDb_array/R/T)
2483
+
2484
+ return np.array([c0_m - ca[0], cb_m - cb[-1]])
2485
+ x = np.linspace(0, 0.14,6)
2486
+ y= np.zeros((1, x.size))
2487
+ p = np.array([Cp])
2488
+ res= solve_bvp(ODE_Function,Boundary_Conditions,x,y,p=p)
2489
+ x_plot = np.linspace(0, 0.14, 100)
2490
+ res_plot=res.sol(x_plot)[1]
2491
+ cp= res_plot[-1]
2492
+ Rejection=1-cp/C0
2493
+ return(Rejection)
2494
+
2495
+
2496
+
2497
+
2498
+
2499
+
2500
+
2501
+
2502
+
2503
+ def XRD_Analysis2(file,which,peak=0):
2504
+ '''
2505
+
2506
+
2507
+ Parameters
2508
+ ----------
2509
+ file : str
2510
+ the variable in which you saved the .cvs file path
2511
+ which : str
2512
+ which operation you want to perform on the file
2513
+ peak : float, optional
2514
+ 2θ for the peak you want to analyse. The default is 0.
2515
+
2516
+ Returns
2517
+ -------
2518
+ fwhm : float
2519
+ value of FWHM for the peak you specified.
2520
+
2521
+ '''
2522
+
2523
+ df=pd.read_csv(file)
2524
+ npar=pd.DataFrame.to_numpy(df)
2525
+
2526
+ if which=='plot':
2527
+ angle=df['angle']
2528
+ intensity=df['intensity']
2529
+ plt.plot(angle,intensity,color='k')
2530
+ font_title={'family':'serif','color':'blue','size':20}
2531
+ plt.title('XRD pattern',fontdict=font_title)
2532
+ font_label={'family':'times new roman','color':'black','size':15}
2533
+ plt.xlabel('angle (2θ)',fontdict=font_label)
2534
+ plt.ylabel('intensity (a.u.)',fontdict=font_label)
2535
+ plt.grid(axis='x',which='both')
2536
+ plt.xticks(np.arange(0,max(angle),5))
2537
+ plt.xlim([np.min(npar,axis=0)[0], np.max(npar,axis=0)[0]])
2538
+ plt.yticks([])
2539
+ plt.ylim([0, 1.1*np.max(npar,axis=0)[1]])
2540
+ plt.tick_params(axis='x',direction='in')
2541
+ plt.show()
2542
+ return None
2543
+ elif which=='fwhm':
2544
+ diff=int((npar[1,0]-npar[0,0])*1000)/2000
2545
+ for i in range(int(len(npar)/2)+1):
2546
+ if -diff<npar[i,0]-peak<diff:
2547
+ pl=i
2548
+ ph=i
2549
+ p=i
2550
+ break
2551
+ while pl>0:
2552
+ if ((npar[pl,1]-npar[pl-1,1])/(npar[pl-1,1]-npar[pl-2,1]))>1.04 and (npar[pl-1,1]-np.min(npar,axis=0)[1])/(np.max(npar,axis=0)[1]-np.min(npar,axis=0)[1])<0.4:
2553
+ in_low_1=npar[pl-1,1]
2554
+ break
2555
+ pl=pl-1
2556
+ while ph>0:
2557
+ if ((npar[ph+2,1]-npar[ph+1,1])/(npar[ph+1,1]-npar[ph,1]))<0.96 and (npar[ph+1,1]-np.min(npar,axis=0)[1])/(np.max(npar,axis=0)[1]-np.min(npar,axis=0)[1])<0.4:
2558
+ in_low_2=npar[ph+1,1]
2559
+ break
2560
+ ph=ph+1
2561
+ in_low=(in_low_1+in_low_2)/2
2562
+ h=npar[p,1]-in_low
2563
+ hm=in_low+h/2
2564
+ diff_in=[]
2565
+ hm_i=[]
2566
+ for l in range(len(npar)-1):
2567
+ diff_in.append((npar[l+1,1]-npar[l,1])/2)
2568
+ for j in range(2):
2569
+ for k in range(int(len(npar)/2)+1):
2570
+ c=((-1)**j)*k
2571
+ if abs(npar[p+c,1]-hm)<abs(max(diff_in)):
2572
+ hm_i.append(p+c)
2573
+ break
2574
+ fwhm=npar[hm_i[0],0]-npar[hm_i[1],0]
2575
+ return fwhm
2576
+ else:
2577
+ print('The which argument not valid')
2578
+ return None
2579
+
2580
+
2581
+
2582
+
2583
+
2584
+
2585
+ def aerospace2 (CSV,which):
2586
+ '''
2587
+ this function has the ability to convert your datas into
2588
+ answers that you need
2589
+ your datas should be in Newton and M**2 format
2590
+ in this program we will be using presure as the output data
2591
+ if you want to make a sketch Use === Plot
2592
+ if you want to check the max_presure use === MaxPer
2593
+ '''
2594
+ mydf = pd.read_csv(CSV)
2595
+ mydff = np.array(mydf)
2596
+ mydf1 = pd.DataFrame(mydff,columns=['Newton','Area'])
2597
+ mydf2 = mydf1['Newton']/mydf1['Area']
2598
+ mydf3 = pd.concat(mydf1,mydf2)
2599
+ if which == 'Plot':
2600
+ plt.plot(mydf1['Newton'],mydf1['Area'])
2601
+ plt.xlabel('Area')
2602
+ plt.ylabel('Newton')
2603
+ plt.show()
2604
+ if which == 'MaxPer':
2605
+ max_p = mydf3.max()
2606
+ return max_p
2607
+
2608
+
2609
+
2610
+
2611
+
2612
+
2613
+
2614
+
2615
+
2616
+
2617
+
2618
+ def Gradient_descent(dataset , which, alpha=0.001):
2619
+ '''
2620
+
2621
+
2622
+ Parameters
2623
+ ----------
2624
+ dataset : str
2625
+ path of your data set .
2626
+ which : str
2627
+ plot or cost(calculuates how much error is there in the prediction).
2628
+ alpha : float, optional
2629
+ the learning rate(the size of the baby step that we will take for each of the variables). The default is 0.001.
2630
+
2631
+
2632
+ '''
2633
+ data=pd.read_csv(dataset)
2634
+ data=data.ffill()
2635
+
2636
+
2637
+ if which=='plot':
2638
+ plt.xlabel(data.columns[0])
2639
+ plt.ylabel(data.columns[1])
2640
+ rename_dict={data.columns[0]:'x',data.columns[1]: 'y'}
2641
+ data=data.rename(columns=rename_dict)
2642
+ x=list(data['x'])
2643
+ y=list(data['y'])
2644
+ plt.plot(x, y,'o')
2645
+ plt.show()
2646
+
2647
+
2648
+
2649
+ if which=='cost':
2650
+ def cost_function(l,c,p,x,y):
2651
+
2652
+ '''
2653
+ The linear equation for a line: y=p*x+c
2654
+
2655
+ Parameters
2656
+ ----------
2657
+ l : int
2658
+ is the number of records.
2659
+ x,y,p,c: int
2660
+
2661
+ Returns
2662
+ -------
2663
+ finds the square of the difference..
2664
+ '''
2665
+ return 1/2/l * sum([(c + p* np.asarray([x[i]]) - y[i])**2 for i in range(l)])
2666
+
2667
+
2668
+
2669
+
2670
+
2671
+ c=0
2672
+ l = len(data)
2673
+ p=1
2674
+ oldcost=0
2675
+ #oldcost is a variable that we will use to save the cost (error) in the last iteration so that we can compare with the current iteration.
2676
+ newcost=0
2677
+ gr0=0
2678
+ #the amount by which we will change the 'c' variable
2679
+ gr1=0
2680
+ #the amount by which we will change the 'x' variable
2681
+ rename_dict={data.columns[0]:'x',data.columns[1]: 'y'}
2682
+ data=data.rename(columns=rename_dict)
2683
+ x=data['x']
2684
+ y=data['y']
2685
+ for i in range(100000000000):
2686
+ for j in range(l):
2687
+ # this 'for loop' essentially finds the average value by which we will change the gradients.
2688
+ gr0=gr0+((c + p * x[i]) - y[i])
2689
+ gr1=gr1+(((c+p* x[i]) - y[i]) * x[i])
2690
+ gr0 = gr0/l
2691
+ gr1 = gr1/l
2692
+ # changing the value of 'p' and 'c' to see how it impacts to our cost(error)
2693
+ c=c-alpha*gr0
2694
+ p=p-alpha*gr1
2695
+
2696
+
2697
+ newcost=cost_function(len(data), c, p, x, y)
2698
+ #If the change in cost (error), is less than particular number(here we use 0.001).it has probably reduce the cost(error) as much as it can.
2699
+ if abs(oldcost-newcost)<0.001:
2700
+
2701
+ return newcost
2702
+ break
2703
+ else:
2704
+ oldcost=newcost
2705
+
2706
+
2707
+
2708
+
2709
+
2710
+
2711
+
2712
+
2713
+ def Energie2(input_file,which):
2714
+ '''
2715
+ This is a function to drawing a plot or to calculating
2716
+ the amount of Energie of a Motor to (open/close) a Valve in a cycle, which takes 2.7 secound to open and to close.
2717
+
2718
+ ----------
2719
+ input_file : .xlsx format
2720
+ the file must be inserted in xlsx.
2721
+ which : int
2722
+ 1 : Drawing a Plot
2723
+ 2 : Calculate the Consupmtion Energie in [mWs]
2724
+ please say which work we do ( 1 or 2).
2725
+
2726
+ '''
2727
+
2728
+ input_file = 'C:\\Users\\Fust\\Desktop\\Book1.xlsx'
2729
+
2730
+ mydf=pd.read_excel(input_file)
2731
+
2732
+
2733
+ if which==1:
2734
+ #get the data on each columns
2735
+
2736
+ A=mydf['Angle[°]']
2737
+
2738
+ Energie =mydf['Energie']
2739
+
2740
+ #plotting data
2741
+ plt.plot(A, Energie,color = 'green')
2742
+ plt.title('Energie of OTT Motor 185000 Cycle')
2743
+ plt.xlabel('Angle[°]')
2744
+ plt.ylabel('Consupmtion Energie')
2745
+ plt.show()
2746
+
2747
+
2748
+ if which==2:
2749
+ mydf=pd.DataFrame(mydf,columns=['Angle[°]','Power[mW]','Time for a Cycle','Energie'])
2750
+
2751
+ summ = mydf['Energie'].sum() # The amount of Energie for a half Cycle of Duty in mWs
2752
+
2753
+ summ =( summ * 2)/1000 # The amount of Consumption Energie for a Dutycycle in Ws
2754
+
2755
+ return summ
2756
+
2757
+
2758
+
2759
+
2760
+
2761
+ def fatigue(f_loc,which):
2762
+ new_data=pd.read_csv(f_loc)
2763
+
2764
+ if which=='plot':
2765
+ x=new_data['LoadCycles']
2766
+ y=new_data['LoadRange']
2767
+ plt.title('F-N',fontsize=22,c='#1f77b4')
2768
+ plt.plot(x,y,'o-r',c='#9467bd')
2769
+ plt.xlabel('LoadCycles(n)',fontsize=20,c='#2ca02c')
2770
+ plt.ylabel('LoadRange(KN)',fontsize=20,c='#bcbd22')
2771
+ plt.xlim(0,2700)
2772
+ plt.ylim(0,40)
2773
+ plt.show()
2774
+
2775
+ if which=='max_LoadRange':
2776
+ m=new_data['LoadRange'].max()
2777
+ return m
2778
+
2779
+ if which=='max_LoadCycles':
2780
+ n=new_data['LoadCycles'].max()
2781
+ return n
2782
+
2783
+
2784
+
2785
+
2786
+
2787
+
2788
+ def Signal_To_Noise_Ratio(data,application):
2789
+ '''
2790
+
2791
+ Parameters
2792
+ ----------
2793
+ data : DataFrame
2794
+ consists of your experimental data in 3 columns:
2795
+ 1- location: the place you've measured signal and noise
2796
+ 2- signal strength: the power of signal in dbm
2797
+ 3- noise power: the power of noise in dbm
2798
+ application : string
2799
+ there is 3 application available:
2800
+ 1- plot signal: plots signal column
2801
+ 2- plot noise: plots noise column
2802
+ 3- plot SNR: plots the signal-to-noise ratio
2803
+
2804
+ Returns
2805
+ -------
2806
+ mx : float
2807
+ the maximum signal-to-noise ratio in dbm
2808
+
2809
+ '''
2810
+ location=np.array(data['location'])
2811
+ signal=np.array(data['Signal Strength'])
2812
+ noise=np.array(data['Noise Power'])
2813
+ snr=signal-noise
2814
+
2815
+
2816
+ if str(application).lower()=='plot signal' :
2817
+ plt.plot(location,signal)
2818
+ plt.title('signal power in every place')
2819
+ plt.xlabel('place')
2820
+ plt.ylabel('signal power in dbm')
2821
+ plt.grid()
2822
+ plt.show()
2823
+ elif str(application).lower()=='plot noise' :
2824
+ plt.plot(location,noise)
2825
+ plt.title('noise power in every place')
2826
+ plt.xlabel('place')
2827
+ plt.ylabel('noise power in dbm')
2828
+ plt.grid()
2829
+ plt.show()
2830
+ elif str(application).lower()=='plot snr' :
2831
+ plt.plot(location,snr)
2832
+ plt.title('SNR in every place')
2833
+ plt.xlabel('place')
2834
+ plt.ylabel('SNR in db')
2835
+ plt.grid()
2836
+ plt.show()
2837
+
2838
+
2839
+ mx=snr.max()
2840
+ return mx
2841
+
2842
+
2843
+
2844
+ def polarization_control(Data,Application):
2845
+ '''
2846
+
2847
+
2848
+ Parameters
2849
+ ----------
2850
+ Data : DataFrame : The results of the polymerization of a polymer control laboratory are given
2851
+ that included four columns: time, temperature, pressure,
2852
+ and reaction percentage of the polymer product.
2853
+ DESCRIPTION.
2854
+ Application : float
2855
+ Six applications are done in this function.
2856
+ 1) Application = 'temp_time' : Temperature is plotted according to time.
2857
+ 2) Application = 'pressure_time' : Pressure is plotted according to time.
2858
+ 3) Application = 'Percent_time' : The percentage of reaction is plotted over time.
2859
+ 4) Application = '100% reaction': If the percentage of polymerization reaction proceed to 100, the temperature and pressure of polymerization is printed and returned.
2860
+ 5) Application = 'Max_pressyre': It returns maximum pressure of process.
2861
+ 6) Application = 'Max_temp': It returns maximum temperature of process.
2862
+ Returns
2863
+ -------
2864
+ float
2865
+ It returns temperature and pressure of process according to related application.
2866
+
2867
+ '''
2868
+
2869
+ time = np.array(Data['time'])
2870
+ temp = np.array(Data['temp'])
2871
+ pressure = np.array(Data['pessure'])
2872
+ reaction_percent = np.array(Data['percent'])
2873
+
2874
+ if Application == 'temp_time':
2875
+ plt.plot(time, temp, c = 'g',linewidth = 1.5)
2876
+ xylable_font={'family': 'serif',
2877
+ 'color': 'black' ,
2878
+ 'size': 16 }
2879
+ title_font={'family': 'serif',
2880
+ 'color': 'black' ,
2881
+ 'size': 16 }
2882
+ plt.title('Temperature variation',fontdict = title_font)
2883
+ plt.xlabel('time(s)',fontdict = xylable_font)
2884
+ plt.ylabel('Temperature (C)',fontdict = xylable_font)
2885
+ # plt.legend(['Temperature'])
2886
+ plt.show()
2887
+
2888
+ elif Application == 'pressure_time':
2889
+ plt.plot(time, pressure , c = 'r',linewidth = 1.5)
2890
+ xylable_font={'family': 'serif',
2891
+ 'color': 'black' ,
2892
+ 'size': 16 }
2893
+ title_font={'family': 'serif',
2894
+ 'color': 'black' ,
2895
+ 'size': 16 }
2896
+ plt.title('Pressure variation',fontdict = title_font)
2897
+ plt.xlabel('time(s)',fontdict = xylable_font)
2898
+ plt.ylabel('Pressure (Pa)',fontdict = xylable_font)
2899
+ # plt.legend(['Pressure'])
2900
+ plt.show()
2901
+
2902
+ elif Application == 'Percent_time':
2903
+ plt.plot(time, reaction_percent, c = 'b',linewidth = 1.5)
2904
+ xylable_font={'family': 'serif',
2905
+ 'color': 'black' ,
2906
+ 'size': 16 }
2907
+ title_font={'family': 'serif',
2908
+ 'color': 'black' ,
2909
+ 'size': 16 }
2910
+ plt.title('Progress variation',fontdict = title_font)
2911
+ plt.xlabel('time(s)',fontdict = xylable_font)
2912
+ plt.ylabel('Reaction percent',fontdict = xylable_font)
2913
+ # plt.legend([ 'reaction_percent'])
2914
+ plt.show()
2915
+
2916
+ elif Application == '100% reaction':
2917
+ reaction_percent_p=np.arange(0,301)/3
2918
+ L = len(reaction_percent_p)
2919
+ for i in range(L):
2920
+ if reaction_percent_p[i] == 100:
2921
+ print('tempreature and pessure for 100% progress are','tempreature =',temp[i],'(C)', 'pessure=', pressure[i],'(Pa)')
2922
+ return (temp[i], pressure[i])
2923
+ elif Application == 'Max_pressyre':
2924
+ return pressure.max()
2925
+ elif Application == 'Max_temp':
2926
+ return temp.max()
2927
+
2928
+
2929
+
2930
+
2931
+ def Desulfurization_Rate(Data,application):
2932
+ '''
2933
+
2934
+ Parameters
2935
+ ----------
2936
+ Data : Data Frame
2937
+ experimental data (excel).
2938
+ application :
2939
+ 1.plot
2940
+ 2.Max_Removal_With_Ultrasonic
2941
+ 3.Max_Removal_Without_Ultrasonic
2942
+
2943
+ Returns
2944
+
2945
+ '''
2946
+ x=np.array(Data['Time'])
2947
+ y1=np.array(Data['Desulfurization_With_Ultrasonic'])
2948
+ y2=np.array(Data['Desulfurization_Without_Ultrasonic'])
2949
+
2950
+ if application=='plot':
2951
+ plt.plot(x,y1,marker='*',mec='r',mfc='y',ms=14,ls='-',linewidth=5,color='r',label='With_Ultrasonic')
2952
+ plt.plot(x,y2,marker='*',mec='g',mfc='y',ms=14,ls='--',linewidth=5,color='g',label='Without_Ultrasonic')
2953
+
2954
+ myfont={ 'family': 'serif' ,
2955
+ 'color': 'red' ,
2956
+ 'size': 15 }
2957
+
2958
+ plt.xlabel('Time')
2959
+ plt.ylabel('Desulfurization')
2960
+ plt.title('Sulfur_Removal_Plot',fontdict=myfont)
2961
+ plt.legend()
2962
+ plt.show()
2963
+
2964
+ elif application=='Max_Removal_With_Ultrasonic':
2965
+ Max_Removal_With_Ultrasonic=y1.max()
2966
+ return Max_Removal_With_Ultrasonic
2967
+
2968
+ elif application=='Max_Removal_Without_Ultrasonic':
2969
+ Max_Removal_Without_Ultrasonic=y2.max()
2970
+ return Max_Removal_Without_Ultrasonic
2971
+
2972
+
2973
+
2974
+
2975
+ def XRD_ZnO(XRD,application):
2976
+ '''
2977
+
2978
+
2979
+ Parameters
2980
+ ----------
2981
+ XRD : DataFrame
2982
+ Data containing XRD data.
2983
+ application : str
2984
+ Type of application 'plot','FWHM','Scherrer'.
2985
+ plot:To draw the figure.
2986
+ FWHM:Width at Half Maximum.
2987
+ Scherrer:To calculate the crystallite size.
2988
+
2989
+ Returns
2990
+ FWHM,Scherrer
2991
+ -------
2992
+ None.
2993
+
2994
+ '''
2995
+ Angles=np.array(XRD['Angle'])
2996
+ Intensities=np.array(XRD['Det1Disc1'])
2997
+ if application=='plot':
2998
+ plt.plot(Angles,Intensities,c='red')
2999
+ plt.title('XRD Pattern')
3000
+ plt.xlabel('2theta (degrees)')
3001
+ plt.ylabel('Intensity')
3002
+ plt.show()
3003
+ elif application in ['FWHM', 'Scherrer']:
3004
+ max_intensity = np.max(Intensities)
3005
+ half_max = max_intensity / 2
3006
+ indices = []
3007
+ half_max = max_intensity / 2
3008
+ for i in range(len(Intensities)):
3009
+ if Intensities[i] >= half_max:
3010
+ indices.append(i)
3011
+
3012
+
3013
+ if len(indices) > 0:
3014
+ left_index = np.min(indices)
3015
+ right_index = np.max(indices)
3016
+
3017
+
3018
+ FWHM = Angles[right_index] - Angles[left_index]
3019
+ if application == 'FWHM':
3020
+ return FWHM
3021
+
3022
+ elif application =='Scherrer':
3023
+ mean_2theta = Angles[indices].mean()
3024
+
3025
+
3026
+ theta = mean_2theta / 2
3027
+ FWHM_rad = ((3.14/180)*FWHM)
3028
+ theta_rad = ((3.14/180)*theta)
3029
+ crystal_size = (0.9 * 1.5406) / (FWHM_rad * np.cos(theta_rad))
3030
+
3031
+ return crystal_size
3032
+
3033
+
3034
+
3035
+
3036
+ def XRD4(data,application):
3037
+ '''
3038
+ This function plots the XRD curve .
3039
+
3040
+ Parameters
3041
+ ----------
3042
+ data : DataFrame
3043
+ data is XRD data include Intensity (a.u.) and 2θ (degree).
3044
+ application : str
3045
+ application is the function that you want to apply to your data:
3046
+ - plot : ُPlot the XRD curve
3047
+ - maxintensity : Determining the maximum intensity.
3048
+ - meantheta : Determining the mean of theta angles.
3049
+
3050
+
3051
+ Returns
3052
+ -------
3053
+ plot, maxintensity, meantheta
3054
+
3055
+ '''
3056
+
3057
+ data.columns = ('2θ (degree)','Intensity (a.u.)')
3058
+ Intensity = np.array(data['Intensity (a.u.)'])
3059
+ Theta = np.array(data['2θ (degree)'])
3060
+
3061
+ if application.upper() == 'PLOT':
3062
+ font1 = {'family':'Times New Roman', 'color':'black', 'size':16}
3063
+ font2 = {'family':'Times New Roman', 'color':'black', 'size':14}
3064
+ plt.plot(Theta, Intensity, linewidth=0.8, c='k')
3065
+ plt.title('XRD', fontdict = font1)
3066
+ plt.xlabel('2θ (degree)', fontdict = font2)
3067
+ plt.ylabel('Intensity (a.u.)', fontdict = font2)
3068
+ plt.show()
3069
+
3070
+ elif application.upper() == 'MAXINTENSITY':
3071
+ maxintensity = Intensity.max()
3072
+ return maxintensity
3073
+
3074
+ elif application.upper() == 'MEANTHETA':
3075
+ E = 0
3076
+ for i in Theta:
3077
+ theta = i / 2
3078
+ E = E + theta #sum of numbers
3079
+ M = E / len(Theta) #Mean
3080
+ return M
3081
+
3082
+
3083
+
3084
+
3085
+ def Stress_Strain6(data,application):
3086
+ '''
3087
+ this function converts F and dD to Stress and Strain by thickness(1.55mm), width(3.2mm) and parallel length(35mm).
3088
+
3089
+ Parameters
3090
+ ----------
3091
+ data : DataFrame
3092
+ this DataFrame contains F(N) and dD(mm) received from the tensil test machine.
3093
+ application : str
3094
+ application determines the expected output of Stress_Strain function.
3095
+
3096
+ Returns
3097
+ -------
3098
+ int, float or plot
3099
+ return may be elongation at break, strength or a plot.
3100
+
3101
+ '''
3102
+
3103
+ stress=np.array([data['F']/(1.55*3.2)])
3104
+ strain=np.array([(data['dD']/35)*100])
3105
+ if application.upper()=='ELONGATION AT BREAK':
3106
+ elongation_at_break=np.max(strain)
3107
+ print(elongation_at_break,'%')
3108
+ return elongation_at_break
3109
+ elif application.upper()=='STRENGTH':
3110
+ strength=np.max(stress)
3111
+ print(strength,'N/mm2')
3112
+ return strength
3113
+ elif application.upper()=='PLOT':
3114
+ myfont_title={'family':'sans-serif',
3115
+ 'color':'black',
3116
+ 'size':20}
3117
+ myfont_lables={'family':'Tahoma',
3118
+ 'color':'green',
3119
+ 'size':16}
3120
+ plt.plot(strain,stress,ls='--',c='g',linewidth=10)
3121
+ plt.title('Stress-Strain',fontdict=myfont_title)
3122
+ plt.xlabel('Strain(%)',fontdict=myfont_lables)
3123
+ plt.ylabel('Stress(N/mm2)',fontdict=myfont_lables)
3124
+ plt.show()
3125
+
3126
+
3127
+
3128
+
3129
+
3130
+
3131
+ def Imerssion_Test(data,application):
3132
+ '''
3133
+
3134
+
3135
+ Parameters
3136
+ ----------
3137
+ data : .excel .csv
3138
+ columns name:time, Mg, Mg_H, Mg_Pl, Mg_HPl
3139
+ application :
3140
+ plot:drawing the changes of weight(%) on time(days)
3141
+ More_Bioactive: the sample with more weight gain in result more bioactive
3142
+ Less_Bioactive: the sample with more weight loss in result less bioactive
3143
+
3144
+ '''
3145
+ x=np.array(data['time'])
3146
+ y1=np.array(data['Mg_HPl'])
3147
+ y2=np.array(data['Mg_H'])
3148
+ y3=np.array(data['Mg_Pl'])
3149
+ y4=np.array(data['Mg'])
3150
+ if application=='plot':
3151
+ plt.plot(x,y1,marker='o',label='Mg_HPl')
3152
+ plt.plot(x,y2,marker='*',label='Mg_H')
3153
+ plt.plot(x,y3,marker='^',label='Mg_Pl')
3154
+ plt.plot(x,y4,marker='+',label='Mg')
3155
+ plt.title('The graph of changes in the weight of the samples in the SBF solution',c='r')
3156
+ plt.xlabel('Imerssion Time(day)',c='g')
3157
+ plt.ylabel('Weight Gain(%)',c='g')
3158
+ plt.legend()
3159
+ plt.show()
3160
+ elif application=='More_Bioactive':
3161
+ max_weight_gain=data[['Mg','Mg_H','Mg_Pl','Mg_HPl' ]].max()
3162
+ max_weight_gainn=max_weight_gain.max()
3163
+ more_bioactive=data.columns[data.isin ([max_weight_gainn]).any()]
3164
+ return more_bioactive
3165
+ elif application=='Less_Bioactive':
3166
+ max_weight_loss=data[['Mg','Mg_H','Mg_Pl','Mg_HPl' ]].min()
3167
+ max_weight_losss=max_weight_loss.min()
3168
+ less_bioactive=data.columns[data.isin ([max_weight_losss]).any()]
3169
+ return less_bioactive
3170
+
3171
+
3172
+
3173
+
3174
+ def Conversion(data,app):
3175
+ '''
3176
+ This program is related to a chemical reaction laboratory, which has been measured in a table at a certain temperature,
3177
+ pressure and time, with a one-second interval,and gives you the highest conversion percentage at a given temperature and pressure.
3178
+ It also draws graphs of conversion percentage, temperature and pressure in terms of time.
3179
+
3180
+ Parameters
3181
+ ----------
3182
+ data : DataFrame of pandas or array of numpy
3183
+ please be careful about the inputs: your table should contain about 100 index and 4 columns.
3184
+ app : str
3185
+ Only write "PLOT_TEMP" if you want to draw the figure tempreturre over time,else if you want to draw pressure on time write
3186
+ 'PLOT_pressure' or write 'PLOT_CONVERSION' if you want the conversion on time figure.
3187
+ or write "MAXIMUM CONVERSION" if you want the maximum number of conversions at a specific temperature and pressure.
3188
+ Otherwise, you will see the error message below.
3189
+
3190
+ TypeError
3191
+ The datas or application is not entered correctly
3192
+
3193
+ Returns
3194
+ -------
3195
+ index_max_conv : str
3196
+ this will gives you the highest convertion index.
3197
+
3198
+ '''
3199
+ sotune1=np.array(data['time'])
3200
+ sotune2=np.array(data['temp'])
3201
+ sotune3=np.array(data['pressure'])
3202
+ sotune4=np.array(data['conv'])
3203
+ if app.upper()=='PLOT_TEMP':
3204
+ plt.plot(sotune2, sotune1,color='black')
3205
+ plt.title('temprature over time')
3206
+ plt.xlabel('time(second)')
3207
+ plt.ylabel('temprature(celsious) ')
3208
+ plt.grid()
3209
+ plt.show()
3210
+
3211
+ elif app.upper()=='PLOT_PRESSURE':
3212
+ plt.plot(sotune3, sotune1,color='red')
3213
+ plt.title('pressure over time')
3214
+ plt.xlabel('time(second)')
3215
+ plt.ylabel('pressure(bar) ')
3216
+ plt.grid()
3217
+ plt.show()
3218
+
3219
+ elif app.upper()=='PLOT_CONVERSION':
3220
+ plt.plot(sotune4, sotune1,color='blue')
3221
+ plt.title('conversion over time')
3222
+ plt.xlabel('time(second)')
3223
+ plt.ylabel('conversion(%) ')
3224
+ plt.grid()
3225
+ plt.show()
3226
+
3227
+ elif app.upper()=='MAXIMUM CONVERSION':
3228
+ maxstress=sotune4.max()
3229
+ maxstrain=sotune2.max()
3230
+ print('maximum of tempreture is ' , maxstrain )
3231
+ print('maximum of conversion is ' , maxstress )
3232
+ index_max_conv=np.argmax(sotune4)
3233
+ print('The tempreture in maximum conversion is ' , sotune2[index_max_conv] ,
3234
+ 'and the preesure is ' ,sotune3[index_max_conv] )
3235
+ return index_max_conv
3236
+
3237
+ else:
3238
+ raise TypeError ('The datas or application is not entered correctly.')
3239
+ return sotune1
3240
+ return sotune2
3241
+ return sotune3
3242
+ return sotune4
3243
+
3244
+
3245
+
3246
+
3247
+
3248
+ def Import_Data(File_Directory=None):
3249
+
3250
+
3251
+ if File_Directory is None:
3252
+ raise TypeError('Please enter the file directory to open!')
3253
+
3254
+
3255
+
3256
+ try:
3257
+ data=pd.read_csv(File_Directory)
3258
+
3259
+
3260
+ #for examle -->data=pd.read_csv('C:\\Users\\Parsis.Co\\Desktop\\CV.csv')
3261
+
3262
+
3263
+ #1--->File not find (by 'FileNotFoundError')
3264
+ except FileNotFoundError:
3265
+ raise FileNotFoundError('Unfortunately, the desired file <',File_Directory,'>is not available ')
3266
+
3267
+
3268
+
3269
+ #2---> File is empty (by 'pd.errors.EmptyDataError')
3270
+ except pd.errors.EmptyDataError:
3271
+ raise ValueError('The file: ',data, ' is empty. please a correct file.')
3272
+
3273
+
3274
+ #3--->Format is wrong (by 'pd.errors.ParserError')
3275
+ except pd.errors.ParserError:
3276
+ raise ValueError('The file format is not valid, please import a <csv> format file')
3277
+
3278
+
3279
+ #4--->remove empty cells
3280
+ if data.isnull().values.any():
3281
+ print('Empty cell founded and removed ')
3282
+ data.dropna(inplace=True)
3283
+
3284
+
3285
+ #5--->turn object to numeric form for both columns
3286
+ for x in data['P']:
3287
+ if data['P'].dtype=='object':
3288
+ print('object element founded in potential column and converted to numeric form')
3289
+ data['P']=pd.to_numeric(data['P'])
3290
+
3291
+ for y in data['C']:
3292
+ if data['C'].dtype=='object':
3293
+ print('object element founded in current density column and converted to numeric')
3294
+ data['P']=pd.to_numeric(data['P'])
3295
+
3296
+
3297
+ #6--->remove duplicated data
3298
+ if data.duplicated().any():
3299
+ print('Duolicated elemets in rows founded and removed ')
3300
+ data=data.drop_duplicates()
3301
+
3302
+
3303
+ return data
3304
+
3305
+
3306
+
3307
+
3308
+
3309
+ def CV(data=None,Application=None, is_reversible=None):
3310
+ '''
3311
+
3312
+
3313
+ Parameters
3314
+ ----------
3315
+ data : DataFrame
3316
+ Enter your .csv format file as pd.DataFrame.
3317
+ Data is the potential vs. current density expoted from the potentiostate device to study electrochemical of your fabricated electrode.
3318
+ To use this function correctly, the potential column should named as 'P' and your current density column should named as 'C'
3319
+
3320
+ Application : str
3321
+ Please enter the application you want to do for your data, including: plot, maxcurrent, peakpotential, charge, and Diffusion-coefficient.
3322
+ is_reversible : bool, optional
3323
+ If your reaction id reversible please enter 'True', and if the reaction is irreversible enter 'False' to calculate the Diffusion coefficient for your reaction.
3324
+
3325
+ Application=plot (type=plot)--> Plot a cyclic voltammogram (current density vs. potential)
3326
+ Application= maxcurrent (type=float)--> the function returns the peak of current that the current density id maximum.
3327
+ Application= peakpotential (type=float)--> the function returns the potential which attributed to maxmum current or peak current.
3328
+ Application=charge (type=float)--> The function returns the charge corresponding to the integration of the plot.
3329
+ Application=Diffusion_coefficient (type=float)--> The function returns the value according the andles-Sevcik aquation depends on reversiblly of irreversibly of reaction.
3330
+
3331
+
3332
+ '''
3333
+ title_style={'family':'times new roman',
3334
+ 'color':'red',
3335
+ 'size':28}
3336
+ label_style={'family':'times new roman',
3337
+ 'color':'black',
3338
+ 'size':18}
3339
+
3340
+ #--> ensure the defined-file name (data) is in calling section
3341
+
3342
+ if data is None:
3343
+ raise ValueError('Please enter the file name and make sure you import your file as DataFrame')
3344
+
3345
+ #--> ensure the user enter the application in calling section
3346
+
3347
+ if Application is None:
3348
+ raise ValueError('Please enter an application for your CV data')
3349
+
3350
+
3351
+ if Application=='plot':
3352
+ potential=np.array(data['P'])
3353
+ current_density=np.array(data['C'])
3354
+ plt.plot(potential,current_density,c='c', linewidth=3)
3355
+ plt.title('Cyclic Voltammetry',fontdict=title_style)
3356
+ plt.xlabel('Potential (V) vs. Ag/AgCl',fontdict=label_style)
3357
+ plt.ylabel('Current Density (mA/cm^2)',fontdict=label_style)
3358
+ plt.grid(color='gray',linewidth=0.5)
3359
+ plt.show()
3360
+
3361
+
3362
+ elif Application=='maxcurrent':
3363
+ maxcurrent=data['C'].max()
3364
+ print('The maximum current density value is: ', maxcurrent, 'mA/cm^2')
3365
+ return maxcurrent
3366
+
3367
+
3368
+ elif Application=='peakpotential':
3369
+ maxcurrent=data['C'].max()
3370
+ maxcurrentindex=data['C'].idxmax()
3371
+ peakpotetial=data.loc[maxcurrentindex,'P']
3372
+ print('The peak potential corresponding to the maximum current is: ',peakpotetial)
3373
+ return peakpotetial
3374
+
3375
+ elif Application=='charge':
3376
+ potential=np.array(data['P'])
3377
+ current_density=np.array(data['C'])
3378
+ charge=np.trapezoid(current_density,potential)
3379
+ print('The charge for your CV is= ', charge, 'c')
3380
+ return charge
3381
+
3382
+
3383
+
3384
+
3385
+ elif Application=='Diffusion_Coefficient': #(Peak_Current,A,C,Scan_Rate,n,is_reversible):
3386
+ maxcurrent=data['C'].max()
3387
+ Area=0.0123
3388
+ C=0.2
3389
+ Scan_Rate=50
3390
+ n=1
3391
+
3392
+ if is_reversible is None:
3393
+ raise ValueError ('Please enter <True> if the reaction is reversible, else enter <False>')
3394
+
3395
+ if is_reversible:
3396
+ Diffusion_Coefficient=(maxcurrent/((2.65*10**5)*(n**(3/2))*Area*C*(Scan_Rate**(1/2))))**2
3397
+
3398
+ else:
3399
+ Diffusion_Coefficient=(maxcurrent/(0.446*(n**(3/2))*Area*C*(Scan_Rate**(1/2))))**2
3400
+
3401
+
3402
+ print('The value of Diffusion coefficient for your electrochemical reaction is:',Diffusion_Coefficient )
3403
+ return Diffusion_Coefficient
3404
+
3405
+
3406
+
3407
+
3408
+ def Product_Of_Vectors(data,app):
3409
+
3410
+ '''
3411
+ do bordar (two vectors) be onvane voroodi migirad, va anha ra baham zarb mikonad.
3412
+
3413
+ Parameters
3414
+ ----------
3415
+ data : float
3416
+ yek matrix ba do sotoon ast ke sotoone aval, bordar avval, va digari bordar dovvom.
3417
+ app : str
3418
+ plot agar bashe, rasm mikoneh, ertebat do bordar ro ba ham va agar
3419
+ calculate bood zarb dakheli bordar avval ba tranahadeh bordar dovvom
3420
+ ra mohasebeh mikonad.
3421
+
3422
+ Returns
3423
+ -------
3424
+ output : float
3425
+ Production of vectors.
3426
+
3427
+ '''
3428
+ x=np.array(data['vector1'])
3429
+ y=np.array(data['vector2'])
3430
+
3431
+ if app=='plot':
3432
+ plt.plot(x,y,marker='<',ms=10,mfc='tab:orange',mec='c',c='tab:blue',linewidth=2)
3433
+ plt.title('nemoodar')
3434
+ plt.xlabel('vector1')
3435
+ plt.ylabel('vector2')
3436
+ plt.show()
3437
+ elif app=='calculate':
3438
+ y1=np.transpose(y)
3439
+ output=np.dot(x,y1)
3440
+ return output
3441
+
3442
+
3443
+
3444
+ def Echelon_Matrix(data,ap):
3445
+ '''
3446
+ یک ماتریس 90در 200 داریم که مثلا 200 مولفه را در مورد سلامت نود نفر جمع آوری کردیم
3447
+ و حالا میخواهیم ببینیم که کدوم یکی از این مولفه ها اضافی هستند و اطلاعات خوبی
3448
+ از سلامتی افراد نمیده. هدفمون اینه که ماتریس را به صورت سطری پلکانی
3449
+ در آوریم یعنی بالا مثلثیش کنیم و مولفه های مهم رو پیدا کنیم.
3450
+ Parameters
3451
+ ----------
3452
+ data : float
3453
+ This is a matrix with more than 50 rows and columns.
3454
+ ap : str
3455
+ plot agar bashe, rasm mikoneh, ertebat sotoone 10 , 50 ro ba ham va agar
3456
+ up bood matrix ra be soorat satri pelekani mikonad.
3457
+
3458
+ Returns
3459
+ -------
3460
+ A : float
3461
+ This is a triangular matrix.
3462
+
3463
+ '''
3464
+ x=np.array(data[:,10])
3465
+ y=np.array(data[:,50])
3466
+ if ap=='plot':
3467
+ plt.plot(x,y,marker='4',ms=20,mec='y',c='tab:purple',ls='--')
3468
+ plt.title('nemoodare ertebat ghand khoon va vazn')
3469
+ plt.xlabel('vazn')
3470
+ plt.ylabel('ghand khoon')
3471
+ plt.show()
3472
+ elif ap=='up':
3473
+ A=np.triu(data)
3474
+ return A
3475
+
3476
+
3477
+
3478
+
3479
+
3480
+ def Fatigue_Test_Analysis(data,application):
3481
+ '''
3482
+
3483
+
3484
+ Parameters
3485
+ ----------
3486
+ data : data is the exel file with the two columns (stress_amplitude column and number_of_cycles column)
3487
+ application : plot , max stress amplitude , fatigue strength , fatigue life , stress in one cycle , Sa ,
3488
+ fatigue limit , std stress , std cycles
3489
+
3490
+
3491
+ Returns
3492
+ -------
3493
+ plot: S-N plot
3494
+ fatigue strength: استحکام خستگی
3495
+ fatigue life: عمر خستگی
3496
+ stress in one cycle: Basquin's equation to define B constant.The B is the value of the stress at one cycle.
3497
+ Sa: max stress amplitude in cycle.
3498
+ fatigue limit: The time of cycle that stress no change.
3499
+ std stress: انحراف معیار تنش‌ها
3500
+ std cycles: انحراف معیارا سیکل‌ها
3501
+
3502
+ '''
3503
+ stress_amplitude = np.array(data["stress_amplitude"])
3504
+ number_of_cycles = np.array(data["number_of_cycles"])
3505
+
3506
+
3507
+ if application=="plot":
3508
+ title_font={"color":"black",
3509
+ 'family':'Merriweather',
3510
+ 'size': 20 }
3511
+
3512
+ xy_label_font={"color":"Magenta",
3513
+ 'family':'Merriweather',
3514
+ 'size': 12 }
3515
+
3516
+ plt.plot(number_of_cycles,stress_amplitude,marker='o',c='c',mec='k',mfc='r',label='S-N Curve',linewidth=3)
3517
+ plt.title('S-N Curve (Fatigue Test)',fontdict=title_font,pad=13)
3518
+ plt.xscale('log')
3519
+ plt.xlabel('Number of Cycles to Failure (N)',fontdict=xy_label_font)
3520
+ plt.ylabel('Stress Amplitude (MPa)',fontdict=xy_label_font)
3521
+ plt.grid()
3522
+ plt.legend()
3523
+ plt.show()
3524
+
3525
+ if application=='max stress amplitude' :
3526
+ max_stress_amplitude=np.max(stress_amplitude)
3527
+ return max_stress_amplitude
3528
+
3529
+ if application=='fatigue strength' :
3530
+ fatigue_strengt=np.mean(stress_amplitude)
3531
+ return fatigue_strengt
3532
+
3533
+ if application=="fatigue life" :
3534
+ fatigue_life = np.mean(number_of_cycles)
3535
+ return fatigue_life
3536
+
3537
+ if application=='stress in one cycle' :
3538
+ n=np.log10(number_of_cycles[0])-np.log10(number_of_cycles[1])
3539
+ m=np.log10(stress_amplitude[1])-np.log10(stress_amplitude[0])
3540
+ slope=n/m
3541
+ stress_in_one_cycle=number_of_cycles[0]*2*((stress_amplitude[0])**slope)
3542
+ return stress_in_one_cycle
3543
+
3544
+ if application=='Sa' :
3545
+ i=np.where(number_of_cycles==1)
3546
+ Sa=stress_amplitude[i]
3547
+ return Sa
3548
+
3549
+ if application=='fatigue limit' :
3550
+ repetative_index = None
3551
+ for i in range(0,len(stress_amplitude)-1) :
3552
+ if stress_amplitude[i]==stress_amplitude[i+1] and repetative_index==None :
3553
+ repetative_index=i
3554
+ elif stress_amplitude[i]!=stress_amplitude[i+1] :
3555
+ repetative_index=None
3556
+ fatigue_limit=number_of_cycles[repetative_index]
3557
+ return fatigue_limit
3558
+
3559
+ if application=='std stress' :
3560
+ std_stress = np.std(stress_amplitude)
3561
+ return std_stress
3562
+
3563
+ if application=='std cycles' :
3564
+ std_cycles = np.std(number_of_cycles)
3565
+ return std_cycles
3566
+
3567
+
3568
+
3569
+
3570
+
3571
+ def Price_BTC(Data,application):
3572
+ '''
3573
+
3574
+ Parameters
3575
+ ----------
3576
+ Data : int
3577
+ This function needs an excel with two columns (Price and Date)
3578
+ application : str
3579
+ These are some ways you can use this function :
3580
+ plot
3581
+ Max_Price
3582
+ Max_Date
3583
+ Min_Price
3584
+ Min_Price
3585
+
3586
+
3587
+ Returns
3588
+ -------
3589
+ Plot and int
3590
+ plot of price per date
3591
+ Date of Maximum and minimum Price
3592
+
3593
+ '''
3594
+ Price = np.array(Data['Price'])
3595
+ Date = np.array(Data['Date'])
3596
+ APP = application.upper()
3597
+
3598
+ if APP == 'PLOT' :
3599
+ plt.plot(Date,Price,ms=3,mfc='b',c='k',linewidth=3)
3600
+ plt.title('Price of BTC')
3601
+ plt.ylabel('(US)Price')
3602
+ plt.xlabel('Date(AD)')
3603
+ plt.show()
3604
+
3605
+ elif APP =='MAX_PRICE' :
3606
+ return Date[np.argmax(Price)], Price.max()
3607
+
3608
+ elif APP == 'MAX_DATE' :
3609
+ return Date[-1], Price[-1]
3610
+
3611
+ elif APP == 'MIN_PRICE' :
3612
+ return Date[np.argmin(Price)] , Price.min()
3613
+
3614
+ elif APP == 'MIN_DATE':
3615
+ return Date[0],Price[0]
3616
+
3617
+
3618
+
3619
+
3620
+
3621
+
3622
+
3623
+