ararpy 0.1.199__py3-none-any.whl → 0.2.2__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.
Files changed (41) hide show
  1. ararpy/Example - Check arr.py +52 -0
  2. ararpy/Example - Granite Cooling History.py +411 -0
  3. ararpy/Example - Plot temperature calibration.py +291 -0
  4. ararpy/Example - Show MDD results.py +561 -0
  5. ararpy/Example - Show all Kfs age spectra.py +344 -0
  6. ararpy/Example - Show random walk results.py +363 -0
  7. ararpy/Example - Tc calculation.py +437 -0
  8. ararpy/__init__.py +3 -4
  9. ararpy/calc/age.py +34 -36
  10. ararpy/calc/arr.py +0 -20
  11. ararpy/calc/basic.py +26 -3
  12. ararpy/calc/corr.py +131 -85
  13. ararpy/calc/jvalue.py +7 -5
  14. ararpy/calc/plot.py +1 -2
  15. ararpy/calc/raw_funcs.py +41 -2
  16. ararpy/calc/regression.py +224 -132
  17. ararpy/files/arr_file.py +2 -1
  18. ararpy/files/basic.py +0 -22
  19. ararpy/files/calc_file.py +107 -84
  20. ararpy/files/raw_file.py +242 -229
  21. ararpy/smp/basic.py +133 -34
  22. ararpy/smp/calculation.py +6 -6
  23. ararpy/smp/corr.py +339 -153
  24. ararpy/smp/diffusion_funcs.py +345 -36
  25. ararpy/smp/export.py +247 -129
  26. ararpy/smp/info.py +2 -2
  27. ararpy/smp/initial.py +93 -45
  28. ararpy/smp/json.py +2 -2
  29. ararpy/smp/plots.py +144 -164
  30. ararpy/smp/raw.py +11 -15
  31. ararpy/smp/sample.py +222 -181
  32. ararpy/smp/style.py +26 -7
  33. ararpy/smp/table.py +42 -33
  34. ararpy/thermo/atomic_level_random_walk.py +56 -48
  35. ararpy/thermo/basic.py +2 -2
  36. {ararpy-0.1.199.dist-info → ararpy-0.2.2.dist-info}/METADATA +10 -1
  37. ararpy-0.2.2.dist-info/RECORD +73 -0
  38. {ararpy-0.1.199.dist-info → ararpy-0.2.2.dist-info}/WHEEL +1 -1
  39. ararpy-0.1.199.dist-info/RECORD +0 -66
  40. {ararpy-0.1.199.dist-info → ararpy-0.2.2.dist-info}/licenses/LICENSE +0 -0
  41. {ararpy-0.1.199.dist-info → ararpy-0.2.2.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,363 @@
1
+ # Copyright (C) 2025 Yang. - All Rights Reserved
2
+
3
+ #!/usr/bin/env python
4
+ # -*- coding: UTF-8 -*-
5
+ """
6
+ # ==========================================
7
+ # Copyright 2025 Yang
8
+ # ararpy - Example - Show random walk results
9
+ # ==========================================
10
+ #
11
+ #
12
+ #
13
+ """
14
+
15
+ import ararpy as ap
16
+ import numpy as np
17
+ import pdf_maker as pm
18
+ import os
19
+
20
+ import matplotlib
21
+ from matplotlib.collections import PathCollection
22
+
23
+ matplotlib.use('TkAgg')
24
+ matplotlib.rc('font',family='Arial', size=10)
25
+ import matplotlib.pyplot as plt
26
+ # 设置全局字体,确保中文正常显示
27
+ # plt.rcParams["font.family"] = ["SimHei"] # 中文字体
28
+ # plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
29
+
30
+
31
+ main_color = ['#397DA1', '#BA5624', '#212121', '#6C5D1E', '#BC3D85', '#3C6933'] # blue red black
32
+ middle_color = ['#83CDFA', '#F1B595', '#737373', '#C0A737', '#E9CDE1', '#84B775']
33
+ shallow_color = ['#E0F1FE', '#FBEBE3', '#DDDDDD', '#F9E16F', '#CB73B0', '#B8F1A7']
34
+
35
+ colors =[
36
+ '#397DA1', '#BA5624', '#212121', '#6C5D1E', '#BC3D85', '#3C6933',
37
+ '#83CDFA', '#F1B595', '#737373', '#C0A737', '#E9CDE1', '#84B775',
38
+ '#E0F1FE', '#FBEBE3', '#DDDDDD', '#F9E16F', '#CB73B0', '#B8F1A7',
39
+ ]
40
+
41
+
42
+ def export_to_pdf(axs, filename="unknown"):
43
+
44
+ params_list = {
45
+ "page_size": 'a4', "ppi": 72, "width": 9.5, "height": 6,
46
+ "pt_width": 0.8, "pt_height": 0.8, "pt_left": 0.16, "pt_bottom": 0.18,
47
+ "offset_top": 0, "offset_right": 0, "offset_bottom": 20, "offset_left": 30,
48
+ "plot_together": False, "show_frame": False,
49
+ 'xlabel_offset': 8, 'ylabel_offset': 2
50
+ }
51
+
52
+ plot_data = {
53
+ "data": [transform(axs)],
54
+ "file_name": filename,
55
+ "plot_names": [f"plotname"],
56
+ }
57
+
58
+ filepath = os.path.join(r"C:\Users\Young\Downloads", f"{filename}.pdf")
59
+ cvs = [[ap.smp.export.get_cv_from_dict(plot, **params_list) for plot in plot_data['data']]]
60
+ for i in range(len(cvs[0])):
61
+ pt = cvs[0][i]._plot_areas[0]
62
+ title = pt.get_comp(comp_name="title")
63
+ title._y -= 2
64
+ title._z_index = 999
65
+ pt.text(50, title._y, text=f"({['a', 'b', 'c', 'd'][i]})", coordinate='pt', clip=False, size=8, z_index=299, v_align='top')
66
+ for comp in pt._components:
67
+ if isinstance(comp, pm.Scatter):
68
+ comp._type = 'rec'
69
+ comp._size = 1.5
70
+ for index, legned in enumerate(list(filter(lambda cp: cp.name() == 'legend', pt._components))):
71
+ legned._size = 7
72
+ legned._z_index = 250
73
+ legned._h_align = "left"
74
+ legned._v_align = "center"
75
+ if i == 0: # age spectra
76
+ legned._x = 175
77
+ legned._y = 40 + index * 10
78
+ elif i == 1: # cooling history
79
+ legned._x = 65
80
+ legned._y = 135 - index * 10
81
+ elif i == 2: # arrhenius
82
+ legned._x = 75
83
+ legned._y = 40 + index * 10
84
+ else:
85
+ legned._x = 65
86
+ legned._y = 40 + index * 10
87
+ for comp in pt._components:
88
+ if legned._text in comp.name() and "legend" in comp.name():
89
+ comp._z_index = 250
90
+ if isinstance(comp, pm.Scatter):
91
+ comp._x = legned._x - 10
92
+ comp._y = legned._y
93
+ if isinstance(comp, pm.Line):
94
+ comp._start = [legned._x - 16, legned._y]
95
+ comp._end = [legned._x - 4, legned._y]
96
+
97
+
98
+ filepath = ap.smp.export.export_chart_to_pdf(cvs, filename, filepath)
99
+
100
+ return filepath
101
+
102
+
103
+ def read_sample(arr_file_path):
104
+ # 读取样品信息
105
+ if not arr_file_path.endswith('.arr'):
106
+ for root, dirs, files in os.walk(arr_file_path):
107
+ for file in files:
108
+ if file.endswith('.arr'):
109
+ arr_file_path = os.path.join(arr_file_path, file)
110
+ break
111
+ print(f"arr file: {arr_file_path}")
112
+ sample = ap.from_arr(file_path=arr_file_path)
113
+ name = sample.name()
114
+ sequence = sample.sequence()
115
+ nsteps = sequence.size
116
+ te = np.array(sample.TotalParam[124], dtype=np.float64)
117
+ ti = (np.array(sample.TotalParam[123], dtype=np.float64) / 60).round(2) # time in minute
118
+ nindex = {"40": 24, "39": 20, "38": 10, "37": 8, "36": 0}
119
+ argon = "39"
120
+ if argon in list(nindex.keys()):
121
+ ar = np.array(sample.DegasValues[nindex[argon]], dtype=np.float64) # 20-21 Argon
122
+ sar = np.array(sample.DegasValues[nindex[argon] + 1], dtype=np.float64)
123
+ elif argon == 'total':
124
+ all_ar = np.array(sample.CorrectedValues, dtype=np.float64) # 20-21 Argon
125
+ ar, sar = ap.calc.arr.add(*all_ar.reshape(5, 2, len(all_ar[0])))
126
+ ar = np.array(ar)
127
+ sar = np.array(sar)
128
+ else:
129
+ raise KeyError
130
+ age = np.array(sample.ApparentAgeValues[2], dtype=np.float64) # 2-3 age
131
+ sage = np.array(sample.ApparentAgeValues[3], dtype=np.float64)
132
+ f = np.cumsum(ar) / ar.sum()
133
+
134
+ # 组合data
135
+ dr2 = [1 for i in range(nsteps)]
136
+ ln_dr2 = [1 for i in range(nsteps)]
137
+ wt = [1 for i in range(nsteps)]
138
+ data = np.array([sequence.value, te, ti, age, sage, ar, sar, f, dr2, ln_dr2, wt]).tolist()
139
+ data.insert(0, (np.where(np.array(data[3]) > 0, True, False) & np.isfinite(data[3])).tolist())
140
+ data.insert(1, [1 for i in range(nsteps)])
141
+ for row in ap.calc.arr.transpose(data):
142
+ print(row)
143
+ return data, name
144
+
145
+
146
+ def read_ads(ads_file_path):
147
+ released = []
148
+ release_name = []
149
+
150
+ ads_released = []
151
+ index = 1
152
+ if os.path.isdir(ads_file_path):
153
+ for (dirpath, dirnames, fs) in os.walk(ads_file_path):
154
+ for f in fs:
155
+ if f.endswith(".ads"):
156
+ file_path = os.path.join(ads_file_path, f)
157
+ if not os.path.exists(file_path):
158
+ continue
159
+ # if "k=100" not in f:
160
+ # continue
161
+ index += 1
162
+ release_name.append(f"Released{index}: {f}")
163
+ diff = ap.thermo.arw.read_ads(file_path)
164
+ print(f"{f = }, {len(diff.released_per_step) = }, {diff.atom_density = :.0e}")
165
+ print(f"{'kJ/mol, '.join([str(dom.energy / 1000) for dom in diff.domains])}")
166
+ print(f"{'kcal/mol, '.join([str(dom.energy / 4.181 / 1000) for dom in diff.domains])}")
167
+ ads_released.append(np.array(diff.released_per_step) / diff.natoms)
168
+
169
+
170
+ # for i in range(len(ads_released)):
171
+ # released.append([i + 1, sum(ar[0:i + 1]) / sum(ar), *ads_released[i]])
172
+ #
173
+ # spectra_data.append(released)
174
+
175
+ return ads_released, release_name
176
+
177
+
178
+ def plot_diff(loc, arr_file_path=None, argon=39):
179
+ ads_released, release_name = read_ads(loc)
180
+
181
+ fig, axs = plt.subplots(1, 1, figsize=(12, 8))
182
+
183
+ index = 0
184
+ for index, each_line in enumerate(ads_released):
185
+ axs.plot(list(range(1, len(each_line) + 1)), each_line, c=colors[index], linewidth=1, label=release_name[index])
186
+
187
+ if arr_file_path is not None:
188
+ sample = ap.from_arr(file_path=arr_file_path)
189
+ nindex = {"40": 24, "39": 20, "38": 10, "37": 8, "36": 0}
190
+ argon = str(argon)
191
+ if argon in list(nindex.keys()):
192
+ ar = np.array(sample.DegasValues[nindex[argon]], dtype=np.float64) # 20-21 Argon
193
+ sar = np.array(sample.DegasValues[nindex[argon] + 1], dtype=np.float64)
194
+ elif argon == 'total':
195
+ all_ar = np.array(sample.CorrectedValues, dtype=np.float64) # 20-21 Argon
196
+ ar, sar = ap.calc.arr.add(*all_ar.reshape(5, 2, len(all_ar[0])))
197
+ ar = np.array(ar)
198
+ sar = np.array(sar)
199
+ else:
200
+ raise KeyError
201
+ axs.plot(list(range(1, len(ar) + 1)), np.cumsum(ar) / np.sum(ar), c=colors[index+1], linewidth=1, label=f"{sample.name()}")
202
+
203
+ axs.set_title(f'Ads released', loc='center', y=1,)
204
+ axs.set_xlabel(f'Steps',)
205
+ axs.set_ylabel(f'Aumulative Argon Released (100%)',)
206
+ axs.legend(loc='lower right')
207
+ fig.tight_layout()
208
+ plt.show()
209
+
210
+ export_to_pdf(axs, filename="test_ads")
211
+
212
+
213
+ def plot_spectra(loc, arr_file_path=None, argon=39, loc39=""):
214
+
215
+ ar = []
216
+ name = ""
217
+ if arr_file_path is not None:
218
+ sample = ap.from_arr(file_path=arr_file_path)
219
+ name = sample.name()
220
+ ar39 = np.array(sample.DegasValues[20], dtype=np.float64) # 20-21 Argon
221
+ ar40 = np.array(sample.DegasValues[24], dtype=np.float64)
222
+ print(f"{ar40 = }")
223
+
224
+
225
+
226
+ ads_released_ar40, release_name = read_ads(loc)
227
+ ads_released_ar39, release_name = read_ads(loc39)
228
+
229
+ fig, axs = plt.subplots(1, 1, figsize=(12, 8))
230
+
231
+ index = 0
232
+ for index, each_line in enumerate(ads_released_ar40):
233
+ _ = np.array(each_line) * sum(ar40)
234
+ ar40_model = [_[0]]
235
+ for i in range(1, len(_)):
236
+ ar40_model.append(_[i] - _[i - 1])
237
+
238
+ _ = np.array(ads_released_ar39[0]) * sum(ar39)
239
+ ar39_model = [_[0]]
240
+ for i in range(1, len(_)):
241
+ ar39_model.append(_[i] - _[i - 1])
242
+ ar39_model = ar39_model[:58]
243
+ print(f"{len(ar39_model) = }, {len(ar40_model) = }")
244
+
245
+ x, y1, y2 = ap.calc.spectra.get_data(np.array(ar40_model)/np.array(ar39_model), np.zeros(len(ar39_model)), ar39_model)
246
+ axs.plot(x, y1, c=colors[index], linewidth=1, label=release_name[index])
247
+
248
+ x, y1, y2 = ap.calc.spectra.get_data(ar40/ar39, np.zeros(len(ar40)), ar39)
249
+ axs.plot(x, y1, c=colors[index+1], linewidth=1, label=f"{name}")
250
+
251
+ axs.set_title(f'Ads spectra', loc='center', y=1,)
252
+ axs.set_xlabel(f'Steps',)
253
+ axs.set_ylabel(f'Aumulative Argon Released (100%)',)
254
+ axs.set_ylim(0, 8)
255
+ axs.legend(loc='lower right')
256
+ fig.tight_layout()
257
+ plt.show()
258
+
259
+ export_to_pdf(axs, filename="test_ads")
260
+
261
+
262
+
263
+ def transform(ax: plt.Axes):
264
+ xlabels = [i.get_text().replace('−', '-') for i in ax.get_xticklabels()]
265
+ ylabels = [i.get_text().replace('−', '-') for i in ax.get_yticklabels()]
266
+ linestyles = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
267
+
268
+ series = []
269
+ for i, line in enumerate(ax.lines):
270
+ xy_data = line.get_xydata() # [[x1, y1], [x2, y2], ...]
271
+ line_style = linestyles.get(line.get_linestyle(), 'solid')
272
+ series.append({
273
+ 'type': 'series.line', 'id': f'line-{i}', 'name': f'line-{i}',
274
+ 'color': line.get_color(), 'line_width': 1, 'line_style': line_style,
275
+ 'data': xy_data, 'line_caps': 'none'
276
+ })
277
+ if bool(line._marker):
278
+ series.append({
279
+ 'type': 'series.scatter', 'id': f'line-marker-{i}', 'name': f'line-marker-{i}',
280
+ 'stroke_color': line.get_markeredgecolor(), 'fill_color': line.get_markerfacecolor(),
281
+ 'data': xy_data, 'size': 2,
282
+ # 'symbol': line._marker.markers.get(line.get_marker(), 'square'),
283
+ 'symbol': 'rec'
284
+ })
285
+ for i, collection in enumerate(ax.collections):
286
+ series.append({
287
+ 'type': 'series.scatter', 'id': f'scatter-{i}', 'name': f'{collection.get_label()}',
288
+ 'stroke_color': collection.get_edgecolor()[0][:3], 'fill_color': collection.get_edgecolor()[0][:3],
289
+ 'data': collection.get_offsets(), 'size': 2,
290
+ 'symbol': 'rec'
291
+ })
292
+
293
+ for i, text in enumerate(ax.texts):
294
+ xy_data = text.get_position() # [[x1, y1], [x2, y2], ...]
295
+ series.append({
296
+ 'type': 'series.text', 'id': f'text-{i}', 'name': f'text-{i}',
297
+ 'color': text.get_color(), 'data': [xy_data], 'text': text.get_text().replace('\n', '<r>'),
298
+ 'size': 8
299
+ })
300
+
301
+ series.append({
302
+ 'type': 'series.text', 'id': f'title', 'name': f'title',
303
+ 'color': 'black', 'data': [[sum(ax.get_xlim()) / 2, ax.get_ylim()[1]]],
304
+ 'h_align': "middle", 'v_align': "top",
305
+ 'text': ax.get_title(), 'size': 8
306
+ })
307
+
308
+ if ax.legend_ is not None:
309
+ for handle, text in zip(ax.legend_.legend_handles, ax.legend_.texts):
310
+ series.append({
311
+ 'type': 'series.text', 'id': f'legend', 'name': f'legend',
312
+ 'color': text.get_color(), 'data': [[ax.get_xlim()[0], ax.get_ylim()[0]]],
313
+ 'h_align': "left", 'v_align': "bottom",
314
+ 'text': text.get_text(), 'size': 8
315
+ })
316
+ if isinstance(handle, plt.Line2D):
317
+ series.append({
318
+ 'type': 'series.line', 'id': f'legend-line', 'name': f'legend-line-{text.get_text()}',
319
+ 'color': handle.get_color(), 'data':[[ax.get_xlim()[0], ax.get_ylim()[0]], [ax.get_xlim()[1], ax.get_ylim()[1]]],
320
+ 'line_width': 1, 'line_style': linestyles.get(handle.get_linestyle(), 'solid')
321
+ })
322
+ if isinstance(handle, PathCollection):
323
+ stroke_c = handle.get_edgecolor()[0][:3]
324
+ stroke_c = f"#{int(stroke_c[0]*255):02x}{int(stroke_c[1]*255):02x}{int(stroke_c[2]*255):02x}"
325
+ fill_c = handle.get_facecolor()[0][:3]
326
+ fill_c = f"#{int(fill_c[0]*255):02x}{int(fill_c[1]*255):02x}{int(fill_c[2]*255):02x}"
327
+ series.append({
328
+ 'type': 'series.scatter', 'id': f'legend-scatter', 'name': f'legend-scatter-{text.get_text()}',
329
+ 'stroke_color': stroke_c, 'fill_color': fill_c,
330
+ 'data': [[sum(ax.get_xlim()) / 2, sum(ax.get_ylim()) / 2]],
331
+ 'size': 2, 'symbol': 'rec'
332
+ })
333
+
334
+ data = {
335
+ 'xAxis': [{
336
+ 'extent': ax.get_xlim(), 'interval': xlabels, 'title': ax.get_xlabel(),
337
+ 'nameLocation': 'middle', 'show_frame': True, 'label_size': 8, 'title_size': 8,
338
+ }],
339
+ 'yAxis': [{
340
+ 'extent': ax.get_ylim(), 'interval': ylabels, 'title': ax.get_ylabel(),
341
+ 'nameLocation': 'middle', 'show_frame': True, 'label_size': 8, 'title_size': 8,
342
+ }],
343
+ 'series': series
344
+ }
345
+
346
+ # print(data)
347
+ return data
348
+
349
+
350
+ if __name__ == "__main__":
351
+ loc = r"D:\DjangoProjects\webarar\private\mdd\20240920_24FY88a\1doms"
352
+ loc = r"D:\DjangoProjects\webarar\private\mdd\20240920_24FY88a\2doms"
353
+ loc = r"D:\DjangoProjects\webarar\private\mdd\20240920_24FY88a\5doms"
354
+ loc = r"D:\DjangoProjects\webarar\private\mdd\20240920_24FY88a\6doms"
355
+ # loc = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\thermo-history-0628"
356
+ # loc = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\thermo-history-0628\heating_experiment"
357
+ loc = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\thermo-history-0919\lab"
358
+ loc2 = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\thermo-history-0919\ar39"
359
+ # loc = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\thermo-history-0919\ar39"
360
+ # arr_file_path = r"D:\DjangoProjects\webarar\private\mdd\20240920_24FY88a\20240920_24FY88a.arr"
361
+ arr_file_path = r"D:\DjangoProjects\webarar\private\mdd\24FY88a-Ar40\20240920_24FY88a-smooth.arr"
362
+ # plot_diff(loc, arr_file_path, argon=39)
363
+ plot_spectra(loc, arr_file_path, argon=40, loc39=loc2)