NSFopen 2.2.1__tar.gz → 2.2.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.
Files changed (59) hide show
  1. nsfopen-2.2.2/NSFopen/_version.py +1 -0
  2. nsfopen-2.2.2/NSFopen/read/read.py +650 -0
  3. {NSFopen-2.2.1 → nsfopen-2.2.2/NSFopen.egg-info}/PKG-INFO +1 -1
  4. {NSFopen-2.2.1/NSFopen.egg-info → nsfopen-2.2.2}/PKG-INFO +1 -1
  5. NSFopen-2.2.1/NSFopen/_version.py +0 -1
  6. NSFopen-2.2.1/NSFopen/read/read.py +0 -526
  7. {NSFopen-2.2.1 → nsfopen-2.2.2}/LICENSE +0 -0
  8. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/__init__.py +0 -0
  9. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Calculate_Roughness/Calculate_Roughness.html +0 -0
  10. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Calculate_Roughness/Calculate_Roughness.ipynb +0 -0
  11. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Calculate_Roughness/Calculate_Roughness.py +0 -0
  12. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Calculate_Roughness/__pycache__/Calculate_Roughness.cpython-310.pyc +0 -0
  13. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Calculate_Roughness/sapphire.nid +0 -0
  14. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Force_Spectroscopy/Force_Spectroscopy.html +0 -0
  15. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Force_Spectroscopy/Force_Spectroscopy.ipynb +0 -0
  16. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Force_Spectroscopy/Force_Spectroscopy.py +0 -0
  17. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Force_Spectroscopy/spectroscopy.nid +0 -0
  18. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Lateral_Force/Lateral Force Processing.html +0 -0
  19. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Lateral_Force/Lateral Force Processing.ipynb +0 -0
  20. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Lateral_Force/Lateral Force Processing.py +0 -0
  21. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Lateral_Force/SBS-PMMA.nid +0 -0
  22. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/Plane_Removal.html +0 -0
  23. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/Plane_Removal.ipynb +0 -0
  24. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/Plane_Removal.py +0 -0
  25. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/circles.nid +0 -0
  26. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/circles_holes.nid +0 -0
  27. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/grid.nid +0 -0
  28. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plane_Removal/squares_holes.nid +0 -0
  29. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plotting_Data/MoS2.nid +0 -0
  30. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plotting_Data/Plotting Data.html +0 -0
  31. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plotting_Data/Plotting Data.ipynb +0 -0
  32. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Plotting_Data/Plotting Data.py +0 -0
  33. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Sharpen_Image/Sharpen Image.html +0 -0
  34. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Sharpen_Image/Sharpen Image.ipynb +0 -0
  35. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Sharpen_Image/Sharpen Image.py +0 -0
  36. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Sharpen_Image/grid.nid +0 -0
  37. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Sharpen_Image/img.jpg +0 -0
  38. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/Spring_Constant.html +0 -0
  39. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/Spring_Constant.ipynb +0 -0
  40. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/Spring_Constant.py +0 -0
  41. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/__pycache__/Spring_Constant.cpython-310.pyc +0 -0
  42. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/__pycache__/__init__.cpython-310.pyc +0 -0
  43. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/sader.py +0 -0
  44. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/thermal.nid +0 -0
  45. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/example/Spring_Constant/thermal.png +0 -0
  46. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/process/__init__.py +0 -0
  47. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/process/process.py +0 -0
  48. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/read/__init__.py +0 -0
  49. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen/read/read_beta.py +0 -0
  50. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/SOURCES.txt +0 -0
  51. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/dependency_links.txt +0 -0
  52. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/entry_points.txt +0 -0
  53. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/not-zip-safe +0 -0
  54. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/requires.txt +0 -0
  55. {NSFopen-2.2.1 → nsfopen-2.2.2}/NSFopen.egg-info/top_level.txt +0 -0
  56. {NSFopen-2.2.1 → nsfopen-2.2.2}/README.md +0 -0
  57. {NSFopen-2.2.1 → nsfopen-2.2.2}/pyproject.toml +0 -0
  58. {NSFopen-2.2.1 → nsfopen-2.2.2}/setup.cfg +0 -0
  59. {NSFopen-2.2.1 → nsfopen-2.2.2}/setup.py +0 -0
@@ -0,0 +1 @@
1
+ __version__ = "2.2.2"
@@ -0,0 +1,650 @@
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ Created on Mon Apr 23 15:17:03 2018
4
+
5
+ Copyright (c) 2018 nelson<at>nanosurf.com
6
+
7
+ Permission is hereby granted, free of charge, to any person obtaining a copy
8
+ of this software and associated documentation files (the "Software"), to deal
9
+ in the Software without restriction, including without limitation the rights
10
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11
+ copies of the Software, and to permit persons to whom the Software is
12
+ furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all
15
+ copies or substantial portions of the Software.
16
+
17
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23
+ SOFTWARE.
24
+
25
+ """
26
+
27
+
28
+ import re
29
+ import numpy as np
30
+ import h5py
31
+ import pandas as pd
32
+ import sys, os
33
+ import time
34
+
35
+
36
+ class read:
37
+ def __init__(self, filename=None, **kwargs):
38
+ self.filename = filename
39
+ self.data = None
40
+ self.param = None
41
+
42
+ if not filename:
43
+ print("\nFile required!\n")
44
+ return
45
+
46
+ _, ext = os.path.splitext(filename)
47
+ if ext == ".nid":
48
+ nid = nid_read(filename=filename, **kwargs)
49
+ self.data = nid.data
50
+ self.param = nid.param
51
+
52
+ elif ext == ".nhf":
53
+ nhf = nhf_read(filename)
54
+
55
+ self.data = nhf.data
56
+ self.param = nhf.param
57
+
58
+ else:
59
+ print("Not a valid filetype")
60
+ return
61
+
62
+
63
+ class nid_read:
64
+ def __init__(self, filename=None, dataframe=True, verbose=False):
65
+ self.filename = filename
66
+ self.data = None
67
+ self.param = None
68
+
69
+ if not filename:
70
+ print("\nFile required!\n")
71
+ return
72
+
73
+ self.__dataframe = dataframe
74
+ self.verbose = verbose
75
+ # names of the channels that can be opened. Can be added to.
76
+ self.data_names = [
77
+ "Spec forward",
78
+ "Spec backward",
79
+ "Spec fwd pause",
80
+ "Spec bwd pause",
81
+ "Scan forward",
82
+ "Scan backward",
83
+ "2nd scan forward",
84
+ "2nd scan backward",
85
+ "Frequency sweep",
86
+ "Frequency sweep SHO",
87
+ "Spectrum FFT",
88
+ "Spectrum Fit",
89
+ ]
90
+ self.data_types = [1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 2, 2]
91
+
92
+ self.read()
93
+
94
+ def read(self):
95
+ t = time.time()
96
+
97
+ encode = "ANSI"
98
+ # encode = 'UTF-8'
99
+ encode = "ISO-8859-1"
100
+
101
+ # isolates header from data file
102
+ if self.verbose:
103
+ print("Reading Header")
104
+
105
+ fid = open(self.filename, "rb")
106
+ data_in = fid.read().split(b"\n\r\n\r")
107
+ fid.close()
108
+
109
+ head = np.array(data_in[0].split(b"\r\n"))
110
+ boo = head == b""
111
+ indices = np.nonzero(boo[1:] != boo[:-1])[0] + 1
112
+ head = np.split(head, indices)
113
+
114
+ head = [h for h in head if len(h) > 1]
115
+
116
+ header = {}
117
+ for h in head:
118
+ title = h[0].decode(encode)[1:-1]
119
+ data = h[1:]
120
+ values = {}
121
+ for d in data:
122
+ val = d.decode(encode).split("=")
123
+ values[val[0]] = val[1].rstrip()
124
+ header[title] = values
125
+
126
+ param = {}
127
+
128
+ def from_array(key, param):
129
+ return float(header[key][param].split(",")[4])
130
+
131
+ def get_values(key, param, df=False):
132
+ string = header[key][param]
133
+
134
+ ty, val, unit = re.search(
135
+ r"(\S)\[(.*)\]\*\[(.*)\]", string
136
+ ).groups()
137
+ if ty == "D":
138
+ val = float(val)
139
+ if ty == "B":
140
+ val = bool(val)
141
+ if ty == "L":
142
+ val = int(val)
143
+ if ty == "V":
144
+ val = [float(v) for v in val.split(",")]
145
+ unit = [str(u) for u in unit.split(",")]
146
+ out = {"Value": val, "Unit": unit}
147
+ if df:
148
+ if len(out) == 1:
149
+ return pd.DataFrame(out)
150
+ else:
151
+ return pd.DataFrame(out)
152
+ else:
153
+ return out
154
+
155
+ groupNames = []
156
+ dataSet = []
157
+
158
+ ds = "DataSet"
159
+ grCnt = int(header[ds]["GroupCount"])
160
+ for gr in range(grCnt):
161
+ groupNames.append(header[ds]["Gr" + str(gr) + "-Name"])
162
+ gc = int(header[ds]["Gr" + str(gr) + "-Count"])
163
+
164
+ for g in range(gc):
165
+ key = "Gr" + str(gr) + "-Ch" + str(g)
166
+ if key in header[ds]:
167
+ dataSet.append(header[ds][key])
168
+
169
+ terms = [
170
+ "Frame",
171
+ "Points",
172
+ "Lines",
173
+ "SaveBits",
174
+ "Dim0Min",
175
+ "Dim0Range",
176
+ "Dim0Unit",
177
+ "Dim1Min",
178
+ "Dim1Range",
179
+ "Dim1Unit",
180
+ "Dim2Min",
181
+ "Dim2Range",
182
+ "Dim2Unit",
183
+ "Dim2Name",
184
+ ]
185
+
186
+ types = [0, 1, 1, 1, 2, 2, 0, 2, 2, 0, 2, 2, 0, 0]
187
+
188
+ # 0 = string, 1 = integer, 2 = float
189
+ typ = [lambda x: str(x), lambda x: int(x), lambda x: float(x)]
190
+
191
+ for term, ty in zip(terms, types):
192
+ val = []
193
+ for d in dataSet:
194
+ h = header[d]
195
+ if term in h:
196
+ val.append(typ[ty](h[term]))
197
+
198
+ param[term] = val
199
+
200
+ # for spectroscopy with maps
201
+ dataPoints = []
202
+ for d in dataSet:
203
+ h = header[d]
204
+ linePoints = []
205
+ if "LineDim0Min" in h:
206
+ for key, value in h.items():
207
+ if re.match(r"LineDim\d*Points", key):
208
+ linePoints.append(int(value))
209
+ dataPoints.append(np.array(linePoints))
210
+ param["LinePoints"] = dataPoints
211
+
212
+ cantilever = {}
213
+ key = "DataSet\\Calibration\\Cantilever"
214
+ if key in header:
215
+ cantilever = {
216
+ "Manufacturer": header[key]["Manufacturer"],
217
+ "Name": header[key]["Name"],
218
+ }
219
+
220
+ propcount = int(header[key]["PropCount"])
221
+ for i in range(propcount):
222
+ cantilever["Prop" + str(i)] = get_values(key, "Prop" + str(i))
223
+
224
+ key = "DataSet\\Calibration\\Scanhead"
225
+ if key in header:
226
+ sens = from_array(key, "In5")
227
+ cantilever["Sensitivity"] = {"Value": sens / 10, "Unit": "m"}
228
+
229
+ mapTable = {}
230
+ key = "DataSet\\SpecInfos"
231
+ if key in header:
232
+ n = int(header[key]["SubSectionCount"])
233
+ secNames = [header[key]["SubSection" + str(i)] for i in range(n)]
234
+
235
+ specMode = header[key + "\\" + secNames[0]]["SpecMode"]
236
+
237
+ count = int(header[key + "\\" + secNames[1]]["Count"])
238
+
239
+ mapTable = [
240
+ header[key + "\\" + secNames[1]][specMode[:3] + str(i)].split(
241
+ ";"
242
+ )
243
+ for i in range(count)
244
+ ]
245
+ mapTable = np.array(mapTable).astype(float)[0]
246
+
247
+ specParam = {}
248
+ modFw, modBw, pauseFw, pauseBw, rangeFw, rangeBw, stopFw = (
249
+ [] for i in range(7)
250
+ )
251
+ key = "DataSet\\Parameters\\Spectroscopy"
252
+ if key in header:
253
+ modFw = get_values(key, "FwModTime")
254
+ modBw = get_values(key, "BwModTime")
255
+ pauseFw = get_values(key, "FwPauseTime")
256
+ pauseBw = get_values(key, "BwPauseTime")
257
+ rangeFw = get_values(key, "FwModRange")
258
+ rangeBw = get_values(key, "BwModRange")
259
+ stopFw = get_values(key, "FwModStopValue")
260
+
261
+ scanParam = {}
262
+ scanRange, scanTime, scanOffset, scanRotation = ([] for i in range(4))
263
+ key = "DataSet\\Parameters\\Imaging"
264
+ if key in header:
265
+ scanRange = get_values(key, "ScanRange")
266
+ scanTime = get_values(key, "ScanTime")
267
+ scanOffset = get_values(key, "ScanOffset")
268
+ scanRotation = get_values(key, "ScanRotation")
269
+
270
+ thermal = {}
271
+ key = "DataSet-Info"
272
+ if "-- Thermal Tuning --" in header[key]:
273
+ if "k" in header[key]["Q Factor:"]:
274
+ Q = float(header[key]["Q Factor:"][:-1]) * 1e3
275
+ else:
276
+ Q = float(header[key]["Q Factor:"])
277
+ Freq = header[key]["Frequency:"]
278
+ SpringK = header[key]["Spring Constant:"]
279
+ Peak = header[key]["Peak Value:"]
280
+
281
+ gr = re.search(r"(\d+\.\d+)(\S*)", Freq).groups()
282
+ Freq = {"Value": gr[0], "Unit": gr[1]}
283
+ try:
284
+ gr = re.search(r"(\d+\.\d+)\s(\S*)", SpringK).groups()
285
+ except:
286
+ gr = re.search(r"(\d)\s(\S*)", SpringK).groups()
287
+ SpringK = {"Value": gr[0], "Unit": gr[1]}
288
+
289
+ try:
290
+ gr = re.search(r"(\d+\.\d+)(\S*)", Peak).groups()
291
+ except:
292
+ gr = re.search(r"(\d)(\S*)", Peak).groups()
293
+ Peak = {"Value": gr[0], "Unit": gr[1]}
294
+
295
+ thermal = {
296
+ "Frequency": Freq,
297
+ "Q Factor": Q,
298
+ "Spring Constant": SpringK,
299
+ "Peak": Peak,
300
+ }
301
+
302
+ required_size = int(
303
+ sum(
304
+ [
305
+ a * b * c / 8
306
+ for a, b, c in zip(
307
+ param["Points"], param["Lines"], param["SaveBits"]
308
+ )
309
+ ]
310
+ )
311
+ )
312
+
313
+ q = float(2 ** param["SaveBits"][0])
314
+ z0 = float(q / 2)
315
+
316
+ if param["SaveBits"][0] == 16:
317
+ dt = np.int16
318
+ elif param["SaveBits"][0] == 32:
319
+ dt = np.int32
320
+
321
+ if self.verbose:
322
+ print("Reading Data")
323
+
324
+ fid = open(self.filename, "rb")
325
+ fid.seek(-required_size, 2)
326
+ data_in = np.fromfile(fid, count=required_size, dtype=dt).astype(float)
327
+ data_in = (data_in + z0) / q
328
+ fid.close()
329
+
330
+ data_in = np.split(
331
+ data_in,
332
+ np.cumsum(
333
+ [a * b for a, b in zip(param["Points"], param["Lines"])]
334
+ ),
335
+ )
336
+ data_in.pop()
337
+
338
+ data = []
339
+ # reshape and rescale data
340
+ for datain, pts, lns, zran, zmin in zip(
341
+ data_in,
342
+ param["Points"],
343
+ param["Lines"],
344
+ param["Dim2Range"],
345
+ param["Dim2Min"],
346
+ ):
347
+
348
+ data.append(datain.reshape((lns, pts)).__mul__(zran).__add__(zmin))
349
+
350
+ data_crop = []
351
+ for numP, dSet in zip(param["LinePoints"], data):
352
+ if numP.any():
353
+ temp = []
354
+ for n, d in zip(numP, dSet):
355
+ temp.append(d[:n])
356
+ data_crop.append(temp)
357
+ else:
358
+ data_crop.append(dSet)
359
+ data = np.asarray(data_crop, dtype=object)
360
+
361
+ # this is the index of the channels that will be output.
362
+ idx = [
363
+ idx
364
+ for idx, frame in enumerate(param["Frame"])
365
+ if frame in self.data_names
366
+ ]
367
+
368
+ # only take data from approved list in name
369
+ data = data[idx]
370
+ frames = np.array(param["Frame"])[idx]
371
+ channel = np.array(param["Dim2Name"])[idx]
372
+
373
+ frame_chan = [i + ";" + j for i, j in zip(frames, channel)]
374
+
375
+ seen = set()
376
+ new_channel = []
377
+ for x in frame_chan:
378
+ if x not in seen:
379
+ new_channel.append(x)
380
+ seen.add(x)
381
+ else:
382
+ new_channel.append(x + "2")
383
+ channel = [x.split(";")[1] for x in new_channel]
384
+
385
+ out = {}
386
+ for frame, chan, dat in zip(frames, channel, data):
387
+ if frame not in out:
388
+ out[frame] = {}
389
+ if chan not in out[frame]:
390
+ out[frame][chan] = {}
391
+ if isinstance(dat, list):
392
+ out[frame][chan] = dat
393
+ else:
394
+ out[frame][chan] = dat.astype(float)
395
+
396
+ image = {}
397
+ spec = {}
398
+ spectrum = {}
399
+
400
+ for name, value in out.items():
401
+ dt = self.data_types[self.data_names.index(name)]
402
+ if dt == 0:
403
+ if name == "Scan forward":
404
+ image["Forward"] = value
405
+ elif name == "Scan backward":
406
+ image["Backward"] = value
407
+ elif name == "2nd scan forward":
408
+ image["2nd Forward"] = value
409
+ elif name == "2nd scan backward":
410
+ image["2nd Backward"] = value
411
+ else:
412
+ pass
413
+ if dt == 1:
414
+ if name == "Spec forward":
415
+ spec["Forward"] = value
416
+ elif name == "Spec backward":
417
+ spec["Backward"] = value
418
+ elif name == "Spec fwd pause":
419
+ spec["Pause Forward"] = value
420
+ elif name == "Spec bwd pause":
421
+ spec["Pause Backward"] = value
422
+ else:
423
+ pass
424
+ if dt == 2:
425
+ if name == "Spectrum FFT":
426
+ spectrum["FFT"] = value
427
+ elif name == "Spectrum Fit":
428
+ spectrum["Fit"] = value
429
+ elif name == "Frequency sweep":
430
+ spectrum["Sweep"] = value
431
+ elif name == "Frequency sweep SHO":
432
+ spectrum["SHO"] = value
433
+ else:
434
+ pass
435
+
436
+ x = dict(
437
+ zip(
438
+ ["min", "range", "units"],
439
+ [param["Dim0Min"], param["Dim0Range"], param["Dim0Unit"]],
440
+ )
441
+ )
442
+ y = dict(
443
+ zip(
444
+ ["min", "range", "units"],
445
+ [param["Dim1Min"], param["Dim1Range"], param["Dim1Unit"]],
446
+ )
447
+ )
448
+ z = dict(
449
+ zip(
450
+ ["min", "range", "units"],
451
+ [param["Dim2Min"], param["Dim2Range"], param["Dim2Unit"]],
452
+ )
453
+ )
454
+ scanParam = dict(
455
+ zip(
456
+ ["range", "time/line", "offset", "rotation"],
457
+ [scanRange, scanTime, scanOffset, scanRotation],
458
+ )
459
+ )
460
+ specParam = dict(
461
+ zip(
462
+ [
463
+ "modFw",
464
+ "modBw",
465
+ "pauseFw",
466
+ "pauseBw",
467
+ "rangeFw",
468
+ "rangeBw",
469
+ "stop-by-value",
470
+ "maps",
471
+ ],
472
+ [
473
+ modFw,
474
+ modBw,
475
+ pauseFw,
476
+ pauseBw,
477
+ rangeFw,
478
+ rangeBw,
479
+ stopFw,
480
+ mapTable,
481
+ ],
482
+ )
483
+ )
484
+
485
+ parameters = dict(
486
+ zip(
487
+ ["Tip", "X", "Y", "Z", "Scan", "Spec", "Tune", "HeaderDump"],
488
+ [cantilever, x, y, z, scanParam, specParam, thermal, header],
489
+ )
490
+ )
491
+
492
+ dataout = [image, spec, spectrum]
493
+ datanames = ["Image", "Spec", "Sweep"]
494
+
495
+ valid_data = [val for num, val in enumerate(dataout) if val]
496
+ valid_names = [
497
+ datanames[num] for num, val in enumerate(dataout) if val
498
+ ]
499
+
500
+ dataout = dict(zip(valid_names, valid_data))
501
+ t_end = time.time() - t
502
+
503
+ if self.verbose:
504
+ print("Elapsed Time: %3.2f sec\n" % t_end)
505
+
506
+ if self.__dataframe:
507
+ # import pandas as pd
508
+ self.data = toPandaDF(dataout).unstack(level=0)
509
+ self.data.dropna(inplace=True)
510
+ # self.specunits = pd.DataFrame(specUnits)
511
+ self.param = toPandaSeries(parameters)
512
+ else:
513
+ self.data = dataout
514
+ self.param = parameters
515
+
516
+
517
+ class nhf_read:
518
+ def __init__(self, filename=None):
519
+ self.filename = filename
520
+ self.data = None
521
+ self.param = None
522
+ self.read()
523
+
524
+ def read(self):
525
+ # measurement
526
+ fopen = h5py.File(self.filename, "r")
527
+
528
+ group_name = list(fopen.keys())
529
+ # forward/backward
530
+ segment = fopen[group_name[0]]
531
+ seg_names = list(segment.keys())
532
+
533
+ s_prop = segment.attrs
534
+ prop_s = {name: s_prop[name] for name in list(s_prop)}
535
+
536
+ DAC_max = 2**31 - 1
537
+
538
+ # DAC_max: dict = {0: [-(2.0**31), 2.0**31, 'dt_int32'],
539
+ # 1: [-(2.0**8), 2.0**8, 'dt_uint8'],
540
+ # 2: [-(2.0**16), 2.0**16, 'dt_uint16'],
541
+ # 3: [-(2.0**32), 2.0**32, 'dt_uint32'],
542
+ # 4: [-(2.0**64), 2.0**64, 'dt_uint64'],
543
+ # 5: [-(2.0**15), 2.0**15, 'dt_int16'],
544
+ # 6: [-(2.0**64), 2.0**64, 'dt_int64'],
545
+ # 7: [0.0, 0.0, 'dt_double']
546
+ # }
547
+
548
+ data_out = {}
549
+ prop = []
550
+
551
+ for s in seg_names:
552
+ meas = segment[s]
553
+
554
+ if fopen.attrs["nsf_file_version_major"] == 1:
555
+ direction = meas.attrs["name"]
556
+ Nx = prop_s["image_points_per_line"]
557
+ Ny = prop_s["image_number_of_lines"]
558
+ else:
559
+ direction = meas.attrs["segment_name"]
560
+ Nx, Ny = meas.attrs["rect_axis_size"]
561
+
562
+ data_out[direction] = {}
563
+
564
+ for m in list(meas.keys()):
565
+ data = meas[m]
566
+ d_prop = data.attrs
567
+
568
+ if fopen.attrs["nsf_file_version_major"] == 1:
569
+ prop.append({name: d_prop[name] for name in list(d_prop)})
570
+ cal_max = d_prop["base_calibration_max"]
571
+ cal_min = d_prop["base_calibration_min"]
572
+ channel = d_prop["name"]
573
+
574
+ scale = (cal_max - cal_min) / DAC_max / 2
575
+
576
+ data_out[direction][channel] = (
577
+ np.reshape(data[:], [Nx, Ny]) * scale
578
+ )
579
+
580
+ elif fopen.attrs["nsf_file_version_major"] == 2:
581
+ if "signal_name" in list(d_prop):
582
+ prop.append(
583
+ {name: d_prop[name] for name in list(d_prop)}
584
+ )
585
+ cal_max = d_prop["signal_calibration_max"]
586
+ cal_min = d_prop["signal_calibration_min"]
587
+ channel = d_prop["signal_name"]
588
+
589
+ scale = (cal_max - cal_min) / DAC_max / 2
590
+
591
+ data_out[direction][channel] = (
592
+ np.reshape(data[:], [Nx, Ny]) * scale
593
+ )
594
+
595
+ _data_out = {}
596
+ _data_out["Image"] = data_out
597
+
598
+ self.data = toPandaDF(_data_out).unstack(level=0)
599
+ self.param = pd.Series(prop_s)
600
+ fopen.close()
601
+
602
+
603
+ def toPandaDF(user_dict):
604
+ df = pd.DataFrame.from_dict(
605
+ {
606
+ (i, j): user_dict[i][j]
607
+ for i in user_dict.keys()
608
+ for j in user_dict[i].keys()
609
+ },
610
+ orient="index",
611
+ ).transpose()
612
+ return df
613
+
614
+
615
+ def toPandaSeries(user_dict):
616
+ df = pd.Series(
617
+ {
618
+ (i, j): user_dict[i][j]
619
+ for i in user_dict.keys()
620
+ for j in user_dict[i].keys()
621
+ }
622
+ )
623
+ return df
624
+
625
+
626
+ def checkFileType(filename, cla):
627
+ import sys, os
628
+
629
+ switch = {"nid": "nhf_read", "nhf": "nid_read"}
630
+
631
+ _, ext = os.path.splitext(filename)
632
+ if ext[-3:] != cla:
633
+ print(f'\nWrong file type detected, use "%s" instead' % switch[cla])
634
+ sys.exit()
635
+ elif ext[-3:] == cla:
636
+ return filename
637
+ else:
638
+ print("\nNot a valid filetype")
639
+ exit()
640
+
641
+
642
+ if __name__ == "__main__":
643
+ # filename='..//example//Plane_Removal//circles.nid'
644
+ filename = "image_test.nhf"
645
+ afm = read(filename, verbose=True)
646
+ print(afm.param)
647
+
648
+ filename = "new.nhf"
649
+ afm = read(filename, verbose=True)
650
+ print(afm.param)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: NSFopen
3
- Version: 2.2.1
3
+ Version: 2.2.2
4
4
  Summary: Python module to open Nanosurf NID and NHF files
5
5
  Author: Nanosurf AG
6
6
  Author-email: scripting@nanosurf.com
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: NSFopen
3
- Version: 2.2.1
3
+ Version: 2.2.2
4
4
  Summary: Python module to open Nanosurf NID and NHF files
5
5
  Author: Nanosurf AG
6
6
  Author-email: scripting@nanosurf.com
@@ -1 +0,0 @@
1
- __version__ = "2.2.1"