itcpr 2.0.1__tar.gz → 2.0.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: itcpr
3
- Version: 2.0.1
3
+ Version: 2.0.2
4
4
  Summary: Physics-focused data analysis and plotting toolkit by ITCPR
5
5
  Author: Md Abdus Sami Akanda
6
6
  License: MIT
@@ -0,0 +1,133 @@
1
+ import os
2
+ import time
3
+ import csv
4
+ import matplotlib
5
+ matplotlib.use('Agg')
6
+ import matplotlib.pyplot as plt
7
+ import kwant
8
+ import numpy as np
9
+
10
+ def simulate(
11
+ syst,
12
+ energies,
13
+ main_file="main.py",
14
+ transmission_pairs=[(1, 0)],
15
+ labels=None,
16
+ plot=True,
17
+ save_csv=True,
18
+ save_fig=True,
19
+ save_structure=True,
20
+ save_ldos=False,
21
+ save_wavefunction=False,
22
+ save_current=False,
23
+ save_lead_bands=False,
24
+ selected_energy_for_local=0.1
25
+ ):
26
+ base_name = os.path.splitext(os.path.basename(main_file))[0]
27
+ out_dir = f"{base_name}.out"
28
+ os.makedirs(out_dir, exist_ok=True)
29
+
30
+ log_path = os.path.join(out_dir, f"{base_name}.log")
31
+ fig_path = os.path.join(out_dir, f"{base_name}_conductance.png")
32
+ csv_path = os.path.join(out_dir, f"{base_name}_conductance.csv")
33
+ struct_path = os.path.join(out_dir, f"{base_name}_structure.png")
34
+
35
+ def log(msg):
36
+ timestamp = time.strftime("[%Y-%m-%d %H:%M:%S]")
37
+ with open(log_path, "a") as f:
38
+ f.write(f"{timestamp} {msg}\n")
39
+
40
+ def save_array_to_csv(array, headers, path):
41
+ with open(path, "w", newline="") as f:
42
+ writer = csv.writer(f)
43
+ writer.writerow(headers)
44
+ for i, val in enumerate(array):
45
+ writer.writerow([i, val])
46
+ log(f"CSV saved to {path}")
47
+
48
+ log("Simulation started.")
49
+
50
+ if isinstance(syst, kwant.builder.Builder):
51
+ syst = syst.finalized()
52
+ log("System finalized.")
53
+
54
+ if labels is None:
55
+ labels = [f"T({out},{in_})" for out, in_ in transmission_pairs]
56
+
57
+ transmissions = {label: [] for label in labels}
58
+
59
+ for energy in energies:
60
+ smatrix = kwant.smatrix(syst, energy)
61
+ for label, (out_lead, in_lead) in zip(labels, transmission_pairs):
62
+ transmissions[label].append(smatrix.transmission(out_lead, in_lead))
63
+
64
+ if save_csv:
65
+ with open(csv_path, "w", newline="") as f:
66
+ writer = csv.writer(f)
67
+ writer.writerow(["Energy [t]"] + labels)
68
+ for i in range(len(energies)):
69
+ row = [energies[i]] + [transmissions[label][i] for label in labels]
70
+ writer.writerow(row)
71
+ log(f"Conductance CSV saved to {csv_path}")
72
+
73
+ if save_fig or plot:
74
+ plt.figure()
75
+ for label in labels:
76
+ plt.plot(energies, transmissions[label], label=label)
77
+ plt.xlabel("energy [t]")
78
+ plt.ylabel("conductance [e^2/h]")
79
+ plt.title("Conductance vs Energy")
80
+ plt.grid(True)
81
+ plt.legend()
82
+ plt.tight_layout()
83
+ if save_fig:
84
+ plt.savefig(fig_path)
85
+ log(f"Conductance plot saved to {fig_path}")
86
+ if plot:
87
+ plt.show()
88
+
89
+ if save_structure:
90
+ kwant.plot(syst, file=struct_path, show=False)
91
+ log(f"Structure plot saved to {struct_path}")
92
+
93
+ if save_ldos:
94
+ ldos = kwant.ldos(syst, selected_energy_for_local)
95
+ ldos_path = os.path.join(out_dir, f"{base_name}_ldos.png")
96
+ kwant.plot(ldos, file=ldos_path, show=False, colorbar=True)
97
+ log(f"LDOS plot saved to {ldos_path}")
98
+
99
+ # Save LDOS CSV
100
+ ldos_csv = os.path.join(out_dir, f"{base_name}_ldos.csv")
101
+ save_array_to_csv(ldos, ["site_index", "ldos"], ldos_csv)
102
+
103
+ if save_wavefunction:
104
+ wf = kwant.wave_function(syst, selected_energy_for_local)
105
+ psi = wf(0)[0]
106
+ wf_path = os.path.join(out_dir, f"{base_name}_wavefunction.png")
107
+ kwant.plot(abs(psi)**2, file=wf_path, show=False, colorbar=True)
108
+ log(f"Wavefunction plot saved to {wf_path}")
109
+
110
+ # Save Wavefunction CSV
111
+ wf_csv = os.path.join(out_dir, f"{base_name}_wavefunction.csv")
112
+ save_array_to_csv(abs(psi)**2, ["site_index", "probability"], wf_csv)
113
+
114
+ if save_current:
115
+ wf = kwant.wave_function(syst, selected_energy_for_local)
116
+ psi = wf(0)[0]
117
+ current_op = kwant.operator.Current(syst)
118
+ current = current_op(psi)
119
+ current_path = os.path.join(out_dir, f"{base_name}_current.png")
120
+ kwant.plot(current, file=current_path, show=False, width=0.05)
121
+ log(f"Current plot saved to {current_path}")
122
+
123
+ # Save Current CSV
124
+ current_csv = os.path.join(out_dir, f"{base_name}_current.csv")
125
+ save_array_to_csv(current, ["hopping_index", "current"], current_csv)
126
+
127
+ if save_lead_bands:
128
+ bands_path = os.path.join(out_dir, f"{base_name}_lead_bands.png")
129
+ kwant.plotter.bands(syst.leads[0], file=bands_path, show=False)
130
+ log(f"🎶 Lead band structure plot saved to {bands_path}")
131
+
132
+ log("Simulation complete.\n")
133
+ return transmissions
@@ -0,0 +1,297 @@
1
+ import numpy as np
2
+ import matplotlib.pyplot as plt
3
+ import pandas as pd
4
+ from mpl_toolkits.mplot3d import Axes3D
5
+ import struct
6
+ from scipy.interpolate import interp1d
7
+ import os
8
+ import csv
9
+ import glob
10
+
11
+ def simple_plot(
12
+ filepath,
13
+ components=["mx", "my", "mz"],
14
+ title="Magnetization vs Time",
15
+ xlabel="Time (s)",
16
+ ylabel="Magnetization",
17
+ colors=None,
18
+ labels=None,
19
+ grid=True,
20
+ figsize=(10, 6),
21
+ show=True,
22
+ three_d=False
23
+ ):
24
+ try:
25
+ # Open file manually, read header line
26
+ with open(filepath, 'r') as f:
27
+ header_line = f.readline().lstrip("#").strip()
28
+ column_names = [col.strip().split()[0] for col in header_line.split('\t')]
29
+
30
+ # Load data with cleaned column names
31
+ df = pd.read_csv(filepath, sep=r'\s+', engine='python', skiprows=1, names=column_names)
32
+ print("✅ Cleaned columns:", df.columns.tolist())
33
+ except Exception as e:
34
+ raise ValueError(f"❌ Failed to load file {filepath}: {e}")
35
+
36
+ if three_d:
37
+ title = 'Magnetization dynamics in 3d'
38
+ if all(col in df.columns for col in ["mx", "my", "mz"]):
39
+ fig = plt.figure(figsize=figsize)
40
+ ax = fig.add_subplot(111, projection='3d')
41
+ ax.plot(df["mx"], df["my"], df["mz"], color='blue')
42
+ ax.set_xlabel("Mx")
43
+ ax.set_ylabel("My")
44
+ ax.set_zlabel("Mz")
45
+ ax.set_title(title)
46
+ if grid:
47
+ ax.grid(True)
48
+ if show:
49
+ plt.show()
50
+ else:
51
+ print("⚠️ Cannot plot in 3D. One or more of mx, my, mz not found in columns.")
52
+ return
53
+
54
+ # 2D plot path
55
+ time_col = "t"
56
+ time = df[time_col]
57
+
58
+ plt.figure(figsize=figsize)
59
+
60
+ for i, comp in enumerate(components):
61
+ if comp in df.columns:
62
+ color = colors[i] if colors and i < len(colors) else None
63
+ label = labels[i] if labels and i < len(labels) else comp
64
+ plt.plot(time, df[comp], label=str(label), color=color)
65
+ else:
66
+ print(f"⚠️ Warning: Component '{comp}' not found in columns.")
67
+
68
+ plt.xlabel(xlabel)
69
+ plt.ylabel(ylabel)
70
+ plt.title(title)
71
+ plt.xlim([time.min(), time.max()])
72
+ plt.xticks(rotation=45)
73
+ plt.tight_layout()
74
+ plt.gca().set_aspect('auto', adjustable='box')
75
+ plt.axhline(0, color='black', lw=0.5, ls='--')
76
+ plt.axvline(0, color='black', lw=0.5, ls='--')
77
+ plt.axhline(1, color='black', lw=0.5, ls='--')
78
+ plt.axvline(1, color='black', lw=0.5, ls='--')
79
+ plt.axhline(-1, color='black', lw=0.5, ls='--')
80
+ plt.axvline(-1, color='black', lw=0.5, ls='--')
81
+ if grid:
82
+ plt.grid(True)
83
+ plt.legend()
84
+ plt.tight_layout()
85
+ if show:
86
+ plt.show()
87
+
88
+ # mumax_analysis.py
89
+ def load_oommf_domfile(filepath, verbose=True):
90
+ HEADER_STR1 = 'OOMMF: rectangular mesh v1.0'
91
+ HEADER_STR2 = '# OOMMF OVF 2.0'
92
+
93
+ with open(filepath, 'rb') as f:
94
+ header = f.readline().decode('utf-8').strip()
95
+ if HEADER_STR1 in header:
96
+ ovf_version = 1
97
+ elif HEADER_STR2 in header:
98
+ ovf_version = 2
99
+ else:
100
+ raise ValueError(f"Unknown OVF header format: {header}")
101
+
102
+ lines = []
103
+ while True:
104
+ pos = f.tell()
105
+ line = f.readline().decode('utf-8', errors='ignore').strip()
106
+ lines.append(line)
107
+ if 'Begin: Data' in line:
108
+ f.seek(pos)
109
+ break
110
+
111
+ def extract(pattern):
112
+ for l in lines:
113
+ if pattern in l:
114
+ return float(l.split(pattern)[-1].strip())
115
+ return None
116
+
117
+ nx, ny, nz = [int(extract(f'{k}:')) for k in ['xnodes', 'ynodes', 'znodes']]
118
+ dx, dy, dz = [extract(f'{k}:') for k in ['xstepsize', 'ystepsize', 'zstepsize']]
119
+ xo, yo, zo = [extract(f'{k}:') for k in ['xbase', 'ybase', 'zbase']]
120
+
121
+ dtype = None
122
+ for l in lines:
123
+ if 'Binary 4' in l:
124
+ dtype = 'f'
125
+ break
126
+ elif 'Binary 8' in l:
127
+ dtype = 'd'
128
+ break
129
+ elif 'Text' in l:
130
+ dtype = 'text'
131
+ break
132
+
133
+ data = {
134
+ 'nx': nx, 'ny': ny, 'nz': nz,
135
+ 'dx': dx, 'dy': dy, 'dz': dz,
136
+ 'xo': xo, 'yo': yo, 'zo': zo,
137
+ }
138
+
139
+ if dtype == 'text':
140
+ while True:
141
+ line = f.readline().decode('utf-8', errors='ignore').strip()
142
+ if line.startswith('# Begin: Data'):
143
+ break
144
+ vals = []
145
+ for _ in range(nx * ny * nz):
146
+ line = f.readline().decode('utf-8')
147
+ vals.append(list(map(float, line.strip().split())))
148
+ vals = np.array(vals)
149
+ if vals.shape[1] == 3:
150
+ data['Mx'] = vals[:, 0].reshape((nz, ny, nx))
151
+ data['My'] = vals[:, 1].reshape((nz, ny, nx))
152
+ data['Mz'] = vals[:, 2].reshape((nz, ny, nx))
153
+ else:
154
+ data['geom'] = vals[:, 0].reshape((nz, ny, nx))
155
+ else:
156
+ while True:
157
+ line = f.readline().decode('utf-8', errors='ignore')
158
+ if line.startswith('# Begin: Data'):
159
+ break
160
+ raw = f.read(nx * ny * nz * 3 * struct.calcsize(dtype))
161
+ vals = struct.unpack(f'{nx*ny*nz*3}{dtype}', raw)
162
+ vals = np.array(vals)
163
+ data['Mx'] = vals[0::3].reshape((nz, ny, nx))
164
+ data['My'] = vals[1::3].reshape((nz, ny, nx))
165
+ data['Mz'] = vals[2::3].reshape((nz, ny, nx))
166
+
167
+ return data
168
+
169
+ def load_mumax_txt(filepath):
170
+ with open(filepath, 'r') as f:
171
+ header = f.readline().strip().split('\t')
172
+ data = np.loadtxt(filepath, skiprows=1)
173
+ return data, header
174
+
175
+ def rearange_mumax_table_output(data, header=None):
176
+ dat = {}
177
+ if header is None and data.shape[1] >= 4:
178
+ dat['# t (s)'] = data[:, 0]
179
+ dat['mx ()'] = data[:, 1]
180
+ dat['my ()'] = data[:, 2]
181
+ dat['mz ()'] = data[:, 3]
182
+ elif header:
183
+ for i, name in enumerate(header):
184
+ dat[name.strip()] = data[:, i]
185
+ else:
186
+ raise ValueError("Insufficient data or header")
187
+ return dat
188
+
189
+ def perform_simple_fft(x, y, extra_padding=1):
190
+ dt = np.mean(np.diff(x))
191
+ tmax = np.max(x)
192
+ nt = len(x)
193
+ Npts = 2 ** (int(np.ceil(np.log2(nt))) + extra_padding)
194
+ fNy = 1 / (2 * dt)
195
+ df = fNy / (Npts / 2)
196
+ f = np.arange(0, fNy + df, df)
197
+
198
+ y_interp = y
199
+ if not np.allclose(np.diff(x), dt, atol=1e-16):
200
+ x_fixed = np.linspace(0, tmax, nt)
201
+ interp_func = interp1d(x, y, kind='linear', fill_value="extrapolate")
202
+ y_interp = interp_func(x_fixed)
203
+ x = x_fixed
204
+
205
+ fft_vals = np.fft.fft(y_interp, n=Npts)
206
+ fft_trim = fft_vals[:len(f)]
207
+ return f, fft_trim
208
+
209
+ def perform_fft_mumax_output(dat, fft_params, plot_flag=True, save_prefix=None):
210
+ out = {}
211
+ out['t'] = dat['# t (s)']
212
+ out['mx'] = dat['mx ()']
213
+ out['my'] = dat['my ()']
214
+ out['mz'] = dat['mz ()']
215
+
216
+ f, fft_mx = perform_simple_fft(dat['# t (s)'], dat['mx ()'], fft_params.get('extra_padding', 1))
217
+ _, fft_my = perform_simple_fft(dat['# t (s)'], dat['my ()'], fft_params.get('extra_padding', 1))
218
+ _, fft_mz = perform_simple_fft(dat['# t (s)'], dat['mz ()'], fft_params.get('extra_padding', 1))
219
+
220
+ out['f'] = f
221
+ out['fft_mx'] = fft_mx
222
+ out['fft_my'] = fft_my
223
+ out['fft_mz'] = fft_mz
224
+
225
+ if plot_flag:
226
+ plt.figure()
227
+ plt.subplot(2, 2, 1)
228
+ plt.plot(dat['# t (s)'], dat['mx ()']); plt.xlabel('Time'); plt.ylabel('mx')
229
+ plt.subplot(2, 2, 2)
230
+ plt.plot(dat['# t (s)'], dat['my ()']); plt.xlabel('Time'); plt.ylabel('my')
231
+ plt.subplot(2, 2, 3)
232
+ plt.plot(dat['# t (s)'], dat['mz ()']); plt.xlabel('Time'); plt.ylabel('mz')
233
+ plt.tight_layout()
234
+ if save_prefix:
235
+ plt.savefig(f"{save_prefix}_m_vs_t_check.png", dpi=300)
236
+
237
+ plt.figure()
238
+ plt.plot(f, np.abs(fft_mz))
239
+ plt.xlabel('Frequency (GHz)'); plt.ylabel('Amplitude')
240
+ plt.title('FFT of Mz')
241
+ plt.grid(True)
242
+ if save_prefix:
243
+ plt.savefig(f"{save_prefix}_fft_peaks.png", dpi=300)
244
+
245
+ if save_prefix:
246
+ with open(f"{save_prefix}_fft_output.csv", "w", newline='') as csvfile:
247
+ writer = csv.writer(csvfile)
248
+ writer.writerow(['f', 'abs_fft_mx', 'arg_fft_mx', 'abs_fft_my', 'arg_fft_my', 'abs_fft_mz', 'arg_fft_mz'])
249
+ for i in range(len(f)):
250
+ row = [f[i], abs(fft_mx[i]), np.angle(fft_mx[i]),
251
+ abs(fft_my[i]), np.angle(fft_my[i]),
252
+ abs(fft_mz[i]), np.angle(fft_mz[i])]
253
+ writer.writerow(row)
254
+
255
+ return out
256
+
257
+
258
+ def func_do_fk_fft_of_m_vs_xt(folder, file_prefix, title, save_prefix, extra_padding=2, fmax=25, kmax=40):
259
+ files = sorted(glob.glob(os.path.join(folder, file_prefix + '*.ovf')))
260
+ mdata_list = []
261
+ for file in files:
262
+ dat = load_oommf_domfile(file, verbose=False)
263
+ mdata_list.append(dat['mz ()'][0]) # assuming layer 0 (2D)
264
+
265
+ m_stack = np.stack(mdata_list, axis=0) # shape: (nt, ny, nx)
266
+ nt, ny, nx = m_stack.shape
267
+ m_xt = m_stack[:, ny // 2, :] # take a 1D line at the center y
268
+
269
+ t = np.linspace(0, nt, nt) # dummy time steps (uniform)
270
+ x = np.linspace(0, nx, nx)
271
+
272
+ f, fft_t = perform_simple_fft(t, m_xt.T, extra_padding)
273
+ k, fft_k = perform_simple_fft(x, m_xt, extra_padding)
274
+
275
+ # 2D FFT (space-time)
276
+ fk_fft = np.fft.fft2(m_xt, s=[len(f), len(k)])
277
+ fk_abs = np.abs(np.fft.fftshift(fk_fft))
278
+
279
+ f_axis = np.fft.fftshift(np.fft.fftfreq(len(f), d=(t[1]-t[0])))
280
+ k_axis = np.fft.fftshift(np.fft.fftfreq(len(k), d=(x[1]-x[0])))
281
+
282
+ # Save CSVs
283
+ np.savetxt(f"{save_prefix}_mz1_mFFT2.csv", fk_abs, delimiter=',')
284
+ np.savetxt(f"{save_prefix}_freq_mFFT2.csv", f_axis, delimiter=',')
285
+ np.savetxt(f"{save_prefix}_k_mFFT2.csv", k_axis, delimiter=',')
286
+
287
+ # Plot
288
+ plt.figure(figsize=(6, 4))
289
+ plt.imshow(fk_abs, extent=[k_axis[0], k_axis[-1], f_axis[0], f_axis[-1]], origin='lower', aspect='auto')
290
+ plt.colorbar(label='|FFT(Mz)|')
291
+ plt.xlabel('k [1/μm]')
292
+ plt.ylabel('f [GHz]')
293
+ plt.title(f"2D FFT of Mz: {title}")
294
+ plt.savefig(f"{save_prefix}_2dfft.png", dpi=300)
295
+ plt.close()
296
+
297
+ return f_axis, k_axis, fk_abs
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: itcpr
3
- Version: 2.0.1
3
+ Version: 2.0.2
4
4
  Summary: Physics-focused data analysis and plotting toolkit by ITCPR
5
5
  Author: Md Abdus Sami Akanda
6
6
  License: MIT
@@ -2,6 +2,7 @@ LICENSE
2
2
  README.md
3
3
  pyproject.toml
4
4
  itcpr/__init__.py
5
+ itcpr/kwant.py
5
6
  itcpr/mumax3.py
6
7
  itcpr.egg-info/PKG-INFO
7
8
  itcpr.egg-info/SOURCES.txt
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "itcpr"
3
- version = "2.0.1"
3
+ version = "2.0.2"
4
4
  description = "Physics-focused data analysis and plotting toolkit by ITCPR"
5
5
  authors = [{name = "Md Abdus Sami Akanda"}]
6
6
  readme = "README.md"
@@ -1,71 +0,0 @@
1
- import matplotlib.pyplot as plt
2
- import pandas as pd
3
- from mpl_toolkits.mplot3d import Axes3D
4
-
5
- def plot(
6
- filepath,
7
- components=["mx", "my", "mz"],
8
- title="Magnetization vs Time",
9
- xlabel="Time (s)",
10
- ylabel="Magnetization",
11
- colors=None,
12
- labels=None,
13
- grid=True,
14
- figsize=(10, 6),
15
- show=True,
16
- three_d=False
17
- ):
18
- try:
19
- # Open file manually, read header line
20
- with open(filepath, 'r') as f:
21
- header_line = f.readline().lstrip("#").strip()
22
- column_names = [col.strip().split()[0] for col in header_line.split('\t')]
23
-
24
- # Load data with cleaned column names
25
- df = pd.read_csv(filepath, sep=r'\s+', engine='python', skiprows=1, names=column_names)
26
- print("✅ Cleaned columns:", df.columns.tolist())
27
- except Exception as e:
28
- raise ValueError(f"❌ Failed to load file {filepath}: {e}")
29
-
30
- if three_d:
31
- title = 'Magnetization dynamics in 3d'
32
- if all(col in df.columns for col in ["mx", "my", "mz"]):
33
- fig = plt.figure(figsize=figsize)
34
- ax = fig.add_subplot(111, projection='3d')
35
- ax.plot(df["mx"], df["my"], df["mz"], color='blue')
36
- ax.set_xlabel("Mx")
37
- ax.set_ylabel("My")
38
- ax.set_zlabel("Mz")
39
- ax.set_title(title)
40
- if grid:
41
- ax.grid(True)
42
- if show:
43
- plt.show()
44
- else:
45
- print("⚠️ Cannot plot in 3D. One or more of mx, my, mz not found in columns.")
46
- return
47
-
48
- # 2D plot path
49
- time_col = "t"
50
- time = df[time_col]
51
-
52
- plt.figure(figsize=figsize)
53
-
54
- for i, comp in enumerate(components):
55
- if comp in df.columns:
56
- color = colors[i] if colors and i < len(colors) else None
57
- label = labels[i] if labels and i < len(labels) else comp
58
- plt.plot(time, df[comp], label=str(label), color=color)
59
- else:
60
- print(f"⚠️ Warning: Component '{comp}' not found in columns.")
61
-
62
- plt.xlabel(xlabel)
63
- plt.ylabel(ylabel)
64
- plt.title(title)
65
- if grid:
66
- plt.grid(True)
67
- plt.legend()
68
- plt.tight_layout()
69
- if show:
70
- plt.show()
71
-
File without changes
File without changes
File without changes
File without changes
File without changes