PyATCLI 2026.10.10__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.
- PyATCLI/__init__.py +196 -0
- PyATCLI/__main__.py +7 -0
- PyATCLI/_version.py +47 -0
- PyATCLI/analyses.py +640 -0
- PyATCLI/analysis/__init__.py +81 -0
- PyATCLI/analysis/auc.py +79 -0
- PyATCLI/analysis/curve_fit.py +88 -0
- PyATCLI/analysis/event_peth.py +263 -0
- PyATCLI/analysis/fft.py +99 -0
- PyATCLI/analysis/group/__init__.py +318 -0
- PyATCLI/analysis/group/rebuild.py +59 -0
- PyATCLI/analysis/group/report.py +281 -0
- PyATCLI/analysis/group/run.py +164 -0
- PyATCLI/analysis/group/scan.py +92 -0
- PyATCLI/analysis/group/stats.py +451 -0
- PyATCLI/analysis/group/trials.py +188 -0
- PyATCLI/analysis/intervals.py +59 -0
- PyATCLI/analysis/peak_finder.py +155 -0
- PyATCLI/analysis/shared.py +100 -0
- PyATCLI/analysis/zscore_peth.py +107 -0
- PyATCLI/cli/__init__.py +105 -0
- PyATCLI/cli/commands.py +395 -0
- PyATCLI/cli/docs.py +246 -0
- PyATCLI/cli/parser.py +286 -0
- PyATCLI/cli/render.py +130 -0
- PyATCLI/engine/__init__.py +0 -0
- PyATCLI/engine/contract.py +124 -0
- PyATCLI/engine/server.py +169 -0
- PyATCLI/engine/session.py +40 -0
- PyATCLI/engine/store.py +222 -0
- PyATCLI/engine/wire.py +103 -0
- PyATCLI/fieldstudy/__init__.py +1 -0
- PyATCLI/fieldstudy/study.py +440 -0
- PyATCLI/fieldstudy/validation.py +443 -0
- PyATCLI/markers.py +71 -0
- PyATCLI/models.py +102 -0
- PyATCLI/numeric.py +35 -0
- PyATCLI/ops/__init__.py +274 -0
- PyATCLI/ops/analysis.py +136 -0
- PyATCLI/ops/common.py +93 -0
- PyATCLI/ops/compute.py +94 -0
- PyATCLI/ops/fieldstudy.py +52 -0
- PyATCLI/ops/files.py +42 -0
- PyATCLI/ops/group.py +144 -0
- PyATCLI/ops/recording.py +90 -0
- PyATCLI/ops/records.py +63 -0
- PyATCLI/ops/results.py +27 -0
- PyATCLI/ops/saved.py +98 -0
- PyATCLI/ops/system.py +31 -0
- PyATCLI/outputs.py +165 -0
- PyATCLI/progress.py +227 -0
- PyATCLI/provenance.py +336 -0
- PyATCLI/recording.py +602 -0
- PyATCLI/reproduce.py +278 -0
- PyATCLI/results.py +106 -0
- PyATCLI/saved_state.py +275 -0
- PyATCLI/sources/__init__.py +1 -0
- PyATCLI/sources/dataset.py +110 -0
- PyATCLI/sources/load.py +169 -0
- PyATCLI/sources/processing_TDT.py +810 -0
- PyATCLI/sources/processing_oxysoft.py +259 -0
- PyATCLI/sources/pt2.py +46 -0
- PyATCLI/sources/tables.py +306 -0
- PyATCLI/splice.py +196 -0
- PyATCLI/viewplan.py +181 -0
- pyatcli-2026.10.10.dist-info/METADATA +296 -0
- pyatcli-2026.10.10.dist-info/RECORD +71 -0
- pyatcli-2026.10.10.dist-info/WHEEL +5 -0
- pyatcli-2026.10.10.dist-info/entry_points.txt +2 -0
- pyatcli-2026.10.10.dist-info/licenses/LICENSE +661 -0
- pyatcli-2026.10.10.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
"""
|
|
2
|
+
sources/processing_oxysoft.py
|
|
3
|
+
-----------------------------
|
|
4
|
+
Reading Oxysoft / Artinis NIRS .txt exports (Oxymon, OctaMon, PortaMon, ...) into channel arrays:
|
|
5
|
+
the Legend-block parser for one file, and the folder / single-file readers built on it. The
|
|
6
|
+
counterpart of processing_TDT.py for the other supported recording format — load.py's load_oxysoft
|
|
7
|
+
only wraps the result into a Dataset, the same way its load_tdt wraps processing_TDT.
|
|
8
|
+
|
|
9
|
+
Unlike TDT there is no signal processing here (an Oxysoft export already holds delta-concentrations),
|
|
10
|
+
so "processing" is parsing: find the channels from the Legend, read the numeric rows, pull out the
|
|
11
|
+
event column, and (for a folder) concatenate the exports in alphabetical order.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
from typing import Optional
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from ..numeric import as_float64
|
|
23
|
+
from ..progress import Plan
|
|
24
|
+
|
|
25
|
+
_PROGRESS_CHUNK = 1 << 18 # bytes read between progress ticks (tqdm throttles the rest)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def process_oxysoft_folder(folder_path: str, progress=None) -> dict:
|
|
29
|
+
"""
|
|
30
|
+
Parse an Oxysoft TXT export folder.
|
|
31
|
+
Multiple .txt files are concatenated in alphabetical order.
|
|
32
|
+
|
|
33
|
+
`progress` (None, True or callable(fraction, message); see
|
|
34
|
+
PyATCLI.progress) is weighted by each file's size in bytes.
|
|
35
|
+
|
|
36
|
+
Returns
|
|
37
|
+
-------
|
|
38
|
+
dict
|
|
39
|
+
o2hb, hhb : np.ndarray, shape (n_channels, n_samples)
|
|
40
|
+
events : list of {'label': str, 'sample': int}
|
|
41
|
+
metadata : dict from the first file, plus "n_channels"
|
|
42
|
+
channel_labels : list[str], e.g. ['Tx1', 'Tx2', 'Tx3']
|
|
43
|
+
sample_rate : float (Hz), from the first file
|
|
44
|
+
"""
|
|
45
|
+
txt_files = sorted(
|
|
46
|
+
f for f in os.listdir(folder_path) if f.lower().endswith('.txt')
|
|
47
|
+
)
|
|
48
|
+
if not txt_files:
|
|
49
|
+
raise FileNotFoundError(f"No .txt files found in: {folder_path}")
|
|
50
|
+
|
|
51
|
+
sizes = {f: os.path.getsize(os.path.join(folder_path, f)) or 1 for f in txt_files}
|
|
52
|
+
plan = Plan(progress, [(f, sizes[f]) for f in txt_files] + [("Combining files", 0.02 * sum(sizes.values()))])
|
|
53
|
+
|
|
54
|
+
all_o2hb: list[np.ndarray] = []
|
|
55
|
+
all_hhb: list[np.ndarray] = []
|
|
56
|
+
all_events: list[dict] = []
|
|
57
|
+
metadata: dict = {}
|
|
58
|
+
ch_labels: list[str] = []
|
|
59
|
+
sample_rate: float = 0.0
|
|
60
|
+
first_file = True
|
|
61
|
+
|
|
62
|
+
for fname in txt_files:
|
|
63
|
+
fpath = os.path.join(folder_path, fname)
|
|
64
|
+
o2hb, hhb, events, meta, labels, fs = _parse_oxysoft_txt(fpath, progress=plan.sub(fname))
|
|
65
|
+
|
|
66
|
+
if first_file:
|
|
67
|
+
metadata = meta
|
|
68
|
+
ch_labels = labels
|
|
69
|
+
sample_rate = fs
|
|
70
|
+
first_file = False
|
|
71
|
+
|
|
72
|
+
all_o2hb.append(o2hb)
|
|
73
|
+
all_hhb.append(hhb)
|
|
74
|
+
all_events.extend(events)
|
|
75
|
+
|
|
76
|
+
plan.begin("Combining files")
|
|
77
|
+
# o2hb / hhb: shape (n_channels, n_samples)
|
|
78
|
+
o2hb_concat = np.concatenate(all_o2hb, axis=1)
|
|
79
|
+
hhb_concat = np.concatenate(all_hhb, axis=1)
|
|
80
|
+
plan.done()
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
"o2hb": o2hb_concat,
|
|
84
|
+
"hhb": hhb_concat,
|
|
85
|
+
"events": all_events,
|
|
86
|
+
"metadata": {**metadata, "n_channels": o2hb_concat.shape[0]}, # physical channels (not * 2)
|
|
87
|
+
"channel_labels": ch_labels,
|
|
88
|
+
"sample_rate": sample_rate,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def process_oxysoft_file(file_path: str, progress=None) -> dict:
|
|
93
|
+
"""Parse a single Oxysoft .txt export; returns the same dict as process_oxysoft_folder.
|
|
94
|
+
|
|
95
|
+
`progress` (None, True or callable(fraction, message); see
|
|
96
|
+
PyATCLI.progress) follows the file as it is read.
|
|
97
|
+
"""
|
|
98
|
+
o2hb, hhb, events, metadata, ch_labels, sample_rate = _parse_oxysoft_txt(file_path, progress=progress)
|
|
99
|
+
if o2hb.ndim < 2 or o2hb.shape[0] == 0:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
f"No O2Hb channels recognized in the Legend block of {os.path.basename(file_path)} — "
|
|
102
|
+
"this file's column labels don't match what this parser expects "
|
|
103
|
+
"(looks for 'O2Hb' in each Legend row's description). The file may use a "
|
|
104
|
+
"different Oxysoft export format/version than this parser was built against."
|
|
105
|
+
)
|
|
106
|
+
return {
|
|
107
|
+
"o2hb": o2hb,
|
|
108
|
+
"hhb": hhb,
|
|
109
|
+
"events": events,
|
|
110
|
+
"metadata": {**metadata, "n_channels": o2hb.shape[0]},
|
|
111
|
+
"channel_labels": ch_labels,
|
|
112
|
+
"sample_rate": sample_rate,
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _parse_oxysoft_txt(
|
|
117
|
+
filepath: str,
|
|
118
|
+
progress=None,
|
|
119
|
+
) -> tuple[np.ndarray, np.ndarray, list[dict], dict, list[str], float]:
|
|
120
|
+
"""
|
|
121
|
+
Parse a single Oxysoft .txt file.
|
|
122
|
+
|
|
123
|
+
The Oxysoft format has a Legend block that maps column numbers to
|
|
124
|
+
channel names, followed by a numeric header row (1 2 3 ...) and
|
|
125
|
+
then the data. Row 0 is absolute baseline and is skipped.
|
|
126
|
+
|
|
127
|
+
`progress` follows the bytes read (the total isn't known in lines
|
|
128
|
+
without a second pass over the file); see PyATCLI.progress.
|
|
129
|
+
|
|
130
|
+
Returns
|
|
131
|
+
-------
|
|
132
|
+
o2hb : np.ndarray shape (n_channels, n_samples)
|
|
133
|
+
hhb : np.ndarray shape (n_channels, n_samples)
|
|
134
|
+
events : list of {'label': str, 'sample': int}
|
|
135
|
+
metadata : dict
|
|
136
|
+
channel_labels: list[str] e.g. ['Tx1', 'Tx2', 'Tx3']
|
|
137
|
+
sample_rate : float (Hz)
|
|
138
|
+
"""
|
|
139
|
+
metadata: dict = {}
|
|
140
|
+
events: list = []
|
|
141
|
+
data_rows: list = []
|
|
142
|
+
sample_rate = 0.0
|
|
143
|
+
|
|
144
|
+
# Will be filled from the Legend block
|
|
145
|
+
# col_index → ('O2Hb' | 'HHb', channel_label)
|
|
146
|
+
col_map: dict[int, tuple[str, str]] = {}
|
|
147
|
+
event_col: Optional[int] = None
|
|
148
|
+
|
|
149
|
+
in_legend = False
|
|
150
|
+
in_data = False
|
|
151
|
+
fit_factor_col: Optional[int] = None
|
|
152
|
+
|
|
153
|
+
plan = Plan(progress, [("Reading file", 92), ("Building channels", 8)])
|
|
154
|
+
size = os.path.getsize(filepath)
|
|
155
|
+
unreported = 0
|
|
156
|
+
|
|
157
|
+
with plan.bar("Reading file", size) as bar, \
|
|
158
|
+
open(filepath, 'r', encoding='utf-8', errors='replace') as fh:
|
|
159
|
+
for raw_line in fh:
|
|
160
|
+
unreported += len(raw_line)
|
|
161
|
+
if unreported >= _PROGRESS_CHUNK:
|
|
162
|
+
bar.update(unreported)
|
|
163
|
+
unreported = 0
|
|
164
|
+
|
|
165
|
+
line = raw_line.rstrip('\n')
|
|
166
|
+
parts = line.split('\t')
|
|
167
|
+
|
|
168
|
+
# ---- metadata -----------------------------------------------
|
|
169
|
+
if not in_legend and not in_data:
|
|
170
|
+
if 'sample rate' in line.lower():
|
|
171
|
+
try:
|
|
172
|
+
sample_rate = float(parts[1].strip().split()[0])
|
|
173
|
+
except (IndexError, ValueError):
|
|
174
|
+
pass
|
|
175
|
+
|
|
176
|
+
if line.strip() == 'Legend:':
|
|
177
|
+
in_legend = True
|
|
178
|
+
continue
|
|
179
|
+
|
|
180
|
+
# ---- legend block -------------------------------------------
|
|
181
|
+
if in_legend:
|
|
182
|
+
# The column-number header row signals end of legend
|
|
183
|
+
stripped = [p.strip() for p in parts]
|
|
184
|
+
if all(p.isdigit() for p in stripped if p):
|
|
185
|
+
in_legend = False
|
|
186
|
+
in_data = True
|
|
187
|
+
continue
|
|
188
|
+
|
|
189
|
+
# Legend rows look like: "2\tRx1 - Tx1 O2Hb (filename)"
|
|
190
|
+
if len(parts) >= 2:
|
|
191
|
+
try:
|
|
192
|
+
col_idx = int(parts[0].strip())
|
|
193
|
+
col_desc = parts[1].strip()
|
|
194
|
+
except ValueError:
|
|
195
|
+
continue
|
|
196
|
+
|
|
197
|
+
if '(Event)' in col_desc or 'Event' in col_desc:
|
|
198
|
+
event_col = col_idx - 1 # convert to 0-based
|
|
199
|
+
elif 'O2Hb' in col_desc:
|
|
200
|
+
m = re.search(r'Tx\d+', col_desc)
|
|
201
|
+
label = m.group(0) if m else f"Ch{col_idx}"
|
|
202
|
+
col_map[col_idx - 1] = ('O2Hb', label)
|
|
203
|
+
elif 'HHb' in col_desc:
|
|
204
|
+
m = re.search(r'Tx\d+', col_desc)
|
|
205
|
+
label = m.group(0) if m else f"Ch{col_idx}"
|
|
206
|
+
col_map[col_idx - 1] = ('HHb', label)
|
|
207
|
+
elif 'Fit Factor' in col_desc:
|
|
208
|
+
fit_factor_col = col_idx - 1 # 0-based
|
|
209
|
+
# TSI%, sample number → ignored
|
|
210
|
+
continue
|
|
211
|
+
|
|
212
|
+
# ---- data section -------------------------------------------
|
|
213
|
+
if not in_data or len(parts) < 2:
|
|
214
|
+
continue
|
|
215
|
+
|
|
216
|
+
try:
|
|
217
|
+
row = [float(p) if p.strip() else 0.0 for p in parts]
|
|
218
|
+
except ValueError:
|
|
219
|
+
continue
|
|
220
|
+
|
|
221
|
+
# Skip row 0 — absolute baseline, not delta values
|
|
222
|
+
sample_num = int(row[0])
|
|
223
|
+
if sample_num == 0:
|
|
224
|
+
continue
|
|
225
|
+
|
|
226
|
+
data_rows.append(row)
|
|
227
|
+
|
|
228
|
+
# Events
|
|
229
|
+
if event_col is not None and event_col < len(row):
|
|
230
|
+
ev = parts[event_col].strip() if event_col < len(parts) else ''
|
|
231
|
+
if ev and ev != '0':
|
|
232
|
+
events.append({'label': ev, 'sample': len(data_rows) - 1})
|
|
233
|
+
|
|
234
|
+
if not data_rows:
|
|
235
|
+
raise ValueError(f"No data rows parsed from {filepath}")
|
|
236
|
+
|
|
237
|
+
plan.begin("Building channels")
|
|
238
|
+
data = np.array(data_rows, dtype=np.float64) # (n_samples, n_cols)
|
|
239
|
+
|
|
240
|
+
# Sort col_map into ordered O2Hb and HHb columns
|
|
241
|
+
o2hb_cols = sorted(
|
|
242
|
+
[(idx, label) for idx, (kind, label) in col_map.items() if kind == 'O2Hb'],
|
|
243
|
+
key=lambda x: x[1]
|
|
244
|
+
)
|
|
245
|
+
hhb_cols = sorted(
|
|
246
|
+
[(idx, label) for idx, (kind, label) in col_map.items() if kind == 'HHb'],
|
|
247
|
+
key=lambda x: x[1]
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
channel_labels = [label for _, label in o2hb_cols]
|
|
251
|
+
|
|
252
|
+
o2hb = as_float64(np.array([data[:, idx] for idx, _ in o2hb_cols])) # (n_ch, n_samp)
|
|
253
|
+
hhb = as_float64(np.array([data[:, idx] for idx, _ in hhb_cols])) # (n_ch, n_samp)
|
|
254
|
+
|
|
255
|
+
if fit_factor_col is not None and fit_factor_col < data.shape[1]:
|
|
256
|
+
metadata['fit_factor_mean'] = float(np.mean(data[:, fit_factor_col]))
|
|
257
|
+
|
|
258
|
+
plan.done()
|
|
259
|
+
return o2hb, hhb, events, metadata, channel_labels, sample_rate
|
PyATCLI/sources/pt2.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""
|
|
2
|
+
sources/pt2.py
|
|
3
|
+
----------------
|
|
4
|
+
Terranova / Prospa .pt2 EFNMR/MRI image parser.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import numpy as np
|
|
8
|
+
|
|
9
|
+
from ..numeric import as_float64
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def load_pt2(path: str) -> np.ndarray:
|
|
13
|
+
"""
|
|
14
|
+
Parse a Terranova Prospa .pt2 2D NMR/MRI image file.
|
|
15
|
+
|
|
16
|
+
The reconstructed magnitude image is stored after the 4-byte marker
|
|
17
|
+
b'LAER' ('REAL' reversed) as little-endian float32 values (widened to
|
|
18
|
+
float64 on the way out, like every load — see numeric.py).
|
|
19
|
+
|
|
20
|
+
Returns
|
|
21
|
+
-------
|
|
22
|
+
np.ndarray
|
|
23
|
+
2D float64 array shaped (n, n).
|
|
24
|
+
"""
|
|
25
|
+
with open(path, 'rb') as f:
|
|
26
|
+
raw = f.read()
|
|
27
|
+
|
|
28
|
+
pos = raw.find(b'LAER')
|
|
29
|
+
if pos == -1:
|
|
30
|
+
raise ValueError("Not a recognised .pt2 file — LAER image marker not found.")
|
|
31
|
+
pos += 4
|
|
32
|
+
|
|
33
|
+
arr = as_float64(np.frombuffer(raw[pos:], dtype='<f4'))
|
|
34
|
+
n_total = len(arr)
|
|
35
|
+
|
|
36
|
+
for n in [16, 32, 64, 128, 256]:
|
|
37
|
+
if n_total == n * n and np.isfinite(arr).all() and arr.max() > 0:
|
|
38
|
+
return arr.reshape(n, n)
|
|
39
|
+
|
|
40
|
+
sq = int(np.sqrt(n_total))
|
|
41
|
+
if sq * sq == n_total and np.isfinite(arr).all() and arr.max() > 0:
|
|
42
|
+
return arr.reshape(sq, sq)
|
|
43
|
+
|
|
44
|
+
raise ValueError(
|
|
45
|
+
f"Could not determine image dimensions ({n_total} floats after LAER)."
|
|
46
|
+
)
|
|
@@ -0,0 +1,306 @@
|
|
|
1
|
+
"""
|
|
2
|
+
sources/tables.py
|
|
3
|
+
-----------------
|
|
4
|
+
Best-effort parser for arbitrary tabular files.
|
|
5
|
+
|
|
6
|
+
Supports:
|
|
7
|
+
.xlsx / .xls — openpyxl required (pip install openpyxl)
|
|
8
|
+
.csv — comma-delimited
|
|
9
|
+
.tsv — tab-delimited
|
|
10
|
+
.txt / .dat / other — delimiter sniffed, then numpy genfromtxt fallback
|
|
11
|
+
|
|
12
|
+
The key feature is *sub-table detection*: a single sheet or file can contain
|
|
13
|
+
multiple independent tables laid out side-by-side (separated by empty columns)
|
|
14
|
+
or stacked (separated by empty rows). Each block is returned as a separate
|
|
15
|
+
GenericTable so the user can choose which one to plot.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
from __future__ import annotations
|
|
19
|
+
|
|
20
|
+
import csv
|
|
21
|
+
import os
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from typing import Optional
|
|
24
|
+
|
|
25
|
+
import numpy as np
|
|
26
|
+
|
|
27
|
+
from ..numeric import as_float64
|
|
28
|
+
from ..progress import Plan
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# ---------------------------------------------------------------------------
|
|
32
|
+
# Public data structure
|
|
33
|
+
# ---------------------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
@dataclass
|
|
36
|
+
class GenericTable:
|
|
37
|
+
name: str
|
|
38
|
+
headers: list[str]
|
|
39
|
+
data: np.ndarray # (n_rows, n_cols) float64; NaN for missing
|
|
40
|
+
metadata: dict = field(default_factory=dict)
|
|
41
|
+
|
|
42
|
+
def __post_init__(self):
|
|
43
|
+
self.data = as_float64(self.data) # every load is float64 — see numeric.py
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# ---------------------------------------------------------------------------
|
|
47
|
+
# Public entry point
|
|
48
|
+
# ---------------------------------------------------------------------------
|
|
49
|
+
|
|
50
|
+
def load_any_file(path: str, progress=None) -> list[GenericTable]:
|
|
51
|
+
"""
|
|
52
|
+
Parse *path* and return every detected table.
|
|
53
|
+
Raises ValueError if nothing useful is found.
|
|
54
|
+
|
|
55
|
+
progress : None, True or callable(fraction, message)
|
|
56
|
+
Progress reporting; see PyATCLI.progress. Excel reports per
|
|
57
|
+
sheet after opening the workbook; delimited text reports per row.
|
|
58
|
+
"""
|
|
59
|
+
ext = os.path.splitext(path)[1].lower()
|
|
60
|
+
if ext in ('.xlsx', '.xls'):
|
|
61
|
+
return _parse_excel(path, progress=progress)
|
|
62
|
+
elif ext == '.csv':
|
|
63
|
+
return _parse_delimited(path, delimiter=',', progress=progress)
|
|
64
|
+
elif ext == '.tsv':
|
|
65
|
+
return _parse_delimited(path, delimiter='\t', progress=progress)
|
|
66
|
+
else:
|
|
67
|
+
return _parse_text(path, progress=progress)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
# Excel
|
|
72
|
+
# ---------------------------------------------------------------------------
|
|
73
|
+
|
|
74
|
+
def _parse_excel(path: str, progress=None) -> list[GenericTable]:
|
|
75
|
+
try:
|
|
76
|
+
import openpyxl
|
|
77
|
+
except ImportError:
|
|
78
|
+
raise ImportError("Install openpyxl to read .xlsx files: pip install openpyxl")
|
|
79
|
+
|
|
80
|
+
plan = Plan(progress, [("Opening workbook", 45), ("Reading sheets", 55)])
|
|
81
|
+
plan.begin("Opening workbook")
|
|
82
|
+
wb = openpyxl.load_workbook(path, data_only=True)
|
|
83
|
+
tables: list[GenericTable] = []
|
|
84
|
+
|
|
85
|
+
for sheet_name in plan.track("Reading sheets", wb.sheetnames):
|
|
86
|
+
ws = wb[sheet_name]
|
|
87
|
+
# Load full sheet into a 2-D list, trim trailing all-None rows
|
|
88
|
+
grid: list[list] = [list(row) for row in ws.iter_rows(values_only=True)]
|
|
89
|
+
while grid and all(c is None for c in grid[-1]):
|
|
90
|
+
grid.pop()
|
|
91
|
+
if not grid:
|
|
92
|
+
continue
|
|
93
|
+
|
|
94
|
+
n_rows = len(grid)
|
|
95
|
+
n_cols = max(len(r) for r in grid)
|
|
96
|
+
for r in grid: # pad to uniform width
|
|
97
|
+
while len(r) < n_cols:
|
|
98
|
+
r.append(None)
|
|
99
|
+
|
|
100
|
+
# ── Find empty-column boundaries ──────────────────────────────────
|
|
101
|
+
empty_col = [
|
|
102
|
+
all(grid[r][c] is None for r in range(n_rows))
|
|
103
|
+
for c in range(n_cols)
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
# Collect contiguous non-empty column spans
|
|
107
|
+
col_groups: list[tuple[int, int]] = [] # (start_inclusive, end_exclusive)
|
|
108
|
+
c = 0
|
|
109
|
+
while c < n_cols:
|
|
110
|
+
if not empty_col[c]:
|
|
111
|
+
j = c
|
|
112
|
+
while j < n_cols and not empty_col[j]:
|
|
113
|
+
j += 1
|
|
114
|
+
col_groups.append((c, j))
|
|
115
|
+
c = j
|
|
116
|
+
else:
|
|
117
|
+
c += 1
|
|
118
|
+
|
|
119
|
+
for c_start, c_end in col_groups:
|
|
120
|
+
sub = _extract_block(grid, n_rows, c_start, c_end)
|
|
121
|
+
if sub is None:
|
|
122
|
+
continue
|
|
123
|
+
|
|
124
|
+
col_letter_range = f"cols {_col_letter(c_start)}-{_col_letter(c_end - 1)}"
|
|
125
|
+
tname = (sheet_name if len(col_groups) == 1
|
|
126
|
+
else f"{sheet_name} | {col_letter_range}")
|
|
127
|
+
t = _block_to_table(sub, tname, {'sheet': sheet_name, 'col_start': c_start})
|
|
128
|
+
if t is not None:
|
|
129
|
+
tables.append(t)
|
|
130
|
+
|
|
131
|
+
return tables
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _extract_block(grid: list[list], n_rows: int,
|
|
135
|
+
c_start: int, c_end: int) -> Optional[list[list]]:
|
|
136
|
+
"""Slice columns c_start..c_end-1 from grid; trim trailing all-None rows."""
|
|
137
|
+
sub = [[grid[r][c] for c in range(c_start, c_end)] for r in range(n_rows)]
|
|
138
|
+
while sub and all(c is None for c in sub[-1]):
|
|
139
|
+
sub.pop()
|
|
140
|
+
return sub if len(sub) >= 2 else None
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _block_to_table(sub: list[list], name: str, meta: dict) -> Optional[GenericTable]:
|
|
144
|
+
"""
|
|
145
|
+
Given a 2-D block of raw cells, find the header row, extract numeric data,
|
|
146
|
+
drop all-NaN rows and columns, and return a GenericTable.
|
|
147
|
+
"""
|
|
148
|
+
# ── Find header row ────────────────────────────────────────────────────
|
|
149
|
+
# The header row is the LAST row where >= 50 % of non-None values are strings.
|
|
150
|
+
header_row = 0
|
|
151
|
+
for ri, row in enumerate(sub):
|
|
152
|
+
non_none = [c for c in row if c is not None]
|
|
153
|
+
if not non_none:
|
|
154
|
+
continue
|
|
155
|
+
str_frac = sum(1 for c in non_none if isinstance(c, str)) / len(non_none)
|
|
156
|
+
if str_frac >= 0.5:
|
|
157
|
+
header_row = ri
|
|
158
|
+
|
|
159
|
+
# ── Build column headers ───────────────────────────────────────────────
|
|
160
|
+
headers: list[str] = []
|
|
161
|
+
for ci, val in enumerate(sub[header_row]):
|
|
162
|
+
if val is not None and str(val).strip():
|
|
163
|
+
headers.append(str(val).strip())
|
|
164
|
+
else:
|
|
165
|
+
# Fall back to nearest non-None value above in the same column
|
|
166
|
+
label = f"Col{ci + 1}"
|
|
167
|
+
for prev_ri in range(header_row - 1, -1, -1):
|
|
168
|
+
pv = sub[prev_ri][ci]
|
|
169
|
+
if pv is not None and str(pv).strip():
|
|
170
|
+
label = str(pv).strip()
|
|
171
|
+
break
|
|
172
|
+
headers.append(label)
|
|
173
|
+
|
|
174
|
+
# ── Convert data rows to float ─────────────────────────────────────────
|
|
175
|
+
data_rows = sub[header_row + 1:]
|
|
176
|
+
if not data_rows:
|
|
177
|
+
return None
|
|
178
|
+
|
|
179
|
+
float_grid: list[list[float]] = []
|
|
180
|
+
for row in data_rows:
|
|
181
|
+
converted = []
|
|
182
|
+
for v in row:
|
|
183
|
+
try:
|
|
184
|
+
converted.append(float(v)) # type: ignore[arg-type]
|
|
185
|
+
except (TypeError, ValueError):
|
|
186
|
+
converted.append(float('nan'))
|
|
187
|
+
float_grid.append(converted)
|
|
188
|
+
|
|
189
|
+
arr = np.array(float_grid, dtype=np.float64)
|
|
190
|
+
|
|
191
|
+
# Drop all-NaN columns, then all-NaN rows
|
|
192
|
+
valid_cols = [c for c in range(arr.shape[1]) if not np.all(np.isnan(arr[:, c]))]
|
|
193
|
+
if not valid_cols:
|
|
194
|
+
return None
|
|
195
|
+
arr = arr[:, valid_cols]
|
|
196
|
+
headers = [headers[c] if c < len(headers) else f"Col{c + 1}" for c in valid_cols]
|
|
197
|
+
|
|
198
|
+
valid_rows = [r for r in range(arr.shape[0]) if not np.all(np.isnan(arr[r, :]))]
|
|
199
|
+
if not valid_rows:
|
|
200
|
+
return None
|
|
201
|
+
arr = arr[valid_rows, :]
|
|
202
|
+
|
|
203
|
+
return GenericTable(name=name, headers=headers, data=arr, metadata=meta)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _col_letter(i: int) -> str:
|
|
207
|
+
"""0-based column index → Excel column letter (A, B, … Z, AA, AB, …)."""
|
|
208
|
+
s = ''
|
|
209
|
+
i += 1
|
|
210
|
+
while i > 0:
|
|
211
|
+
i, r = divmod(i - 1, 26)
|
|
212
|
+
s = chr(65 + r) + s
|
|
213
|
+
return s
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ---------------------------------------------------------------------------
|
|
217
|
+
# CSV / TSV
|
|
218
|
+
# ---------------------------------------------------------------------------
|
|
219
|
+
|
|
220
|
+
def _parse_delimited(path: str, delimiter: str, progress=None) -> list[GenericTable]:
|
|
221
|
+
plan = Plan(progress, [("Reading file", 15), ("Building table", 85)])
|
|
222
|
+
plan.begin("Reading file")
|
|
223
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as fh:
|
|
224
|
+
rows = [r for r in csv.reader(fh, delimiter=delimiter)]
|
|
225
|
+
if not rows:
|
|
226
|
+
return []
|
|
227
|
+
t = _rows_to_table(rows, os.path.basename(path), progress=plan.sub("Building table"))
|
|
228
|
+
plan.done()
|
|
229
|
+
return [t] if t is not None else []
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ---------------------------------------------------------------------------
|
|
233
|
+
# Plain text (sniff delimiter)
|
|
234
|
+
# ---------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
def _parse_text(path: str, progress=None) -> list[GenericTable]:
|
|
237
|
+
with open(path, 'r', encoding='utf-8', errors='replace') as fh:
|
|
238
|
+
sample = fh.read(8192)
|
|
239
|
+
|
|
240
|
+
# Pick the most-frequent candidate delimiter
|
|
241
|
+
counts = {'\t': sample.count('\t'), ',': sample.count(','), ';': sample.count(';')}
|
|
242
|
+
best = max(counts, key=counts.get)
|
|
243
|
+
if counts[best] > 0:
|
|
244
|
+
return _parse_delimited(path, best, progress=progress)
|
|
245
|
+
|
|
246
|
+
# Last resort: numpy whitespace splitting
|
|
247
|
+
try:
|
|
248
|
+
arr = np.genfromtxt(path, comments='#', filling_values=np.nan)
|
|
249
|
+
if arr.ndim == 1:
|
|
250
|
+
arr = arr[:, np.newaxis]
|
|
251
|
+
headers = [f"Col{i + 1}" for i in range(arr.shape[1])]
|
|
252
|
+
return [GenericTable(name=os.path.basename(path), headers=headers, data=arr)]
|
|
253
|
+
except Exception:
|
|
254
|
+
return []
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
# ---------------------------------------------------------------------------
|
|
258
|
+
# Helpers shared by CSV / text paths
|
|
259
|
+
# ---------------------------------------------------------------------------
|
|
260
|
+
|
|
261
|
+
def _rows_to_table(rows: list[list[str]], name: str, progress=None) -> Optional[GenericTable]:
|
|
262
|
+
if not rows:
|
|
263
|
+
return None
|
|
264
|
+
|
|
265
|
+
# Both passes below touch every cell in Python, so on a large file they are
|
|
266
|
+
# what takes the time: they are the two stages the progress follows.
|
|
267
|
+
plan = Plan(progress, [("Finding the header row", 40), ("Converting to numbers", 60)])
|
|
268
|
+
|
|
269
|
+
# Find header row: last row where >= 50 % of non-empty cells are non-numeric
|
|
270
|
+
header_row = 0
|
|
271
|
+
for ri, row in plan.track("Finding the header row", enumerate(rows), total=len(rows)):
|
|
272
|
+
non_empty = [c for c in row if c.strip()]
|
|
273
|
+
if not non_empty:
|
|
274
|
+
continue
|
|
275
|
+
non_numeric = sum(1 for c in non_empty if not _is_numeric(c))
|
|
276
|
+
if non_numeric / len(non_empty) >= 0.5:
|
|
277
|
+
header_row = ri
|
|
278
|
+
|
|
279
|
+
headers = [c.strip() or f"Col{i + 1}" for i, c in enumerate(rows[header_row])]
|
|
280
|
+
|
|
281
|
+
float_grid: list[list[float]] = []
|
|
282
|
+
for row in plan.track("Converting to numbers", rows[header_row + 1:]):
|
|
283
|
+
if not any(c.strip() for c in row):
|
|
284
|
+
continue
|
|
285
|
+
converted = []
|
|
286
|
+
for c in row:
|
|
287
|
+
try:
|
|
288
|
+
converted.append(float(c))
|
|
289
|
+
except ValueError:
|
|
290
|
+
converted.append(float('nan'))
|
|
291
|
+
float_grid.append(converted)
|
|
292
|
+
|
|
293
|
+
if not float_grid:
|
|
294
|
+
return None
|
|
295
|
+
|
|
296
|
+
arr = np.array(float_grid, dtype=np.float64)
|
|
297
|
+
return GenericTable(name=name, headers=headers, data=arr)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _is_numeric(s: str) -> bool:
|
|
301
|
+
try:
|
|
302
|
+
float(s)
|
|
303
|
+
return True
|
|
304
|
+
except ValueError:
|
|
305
|
+
return False
|
|
306
|
+
|