prsmfile 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.
- prsmfile/__init__.py +15 -0
- prsmfile/__main__.py +5 -0
- prsmfile/archive.py +341 -0
- prsmfile/cli.py +146 -0
- prsmfile/errors.py +5 -0
- prsmfile/py.typed +0 -0
- prsmfile/readers/__init__.py +101 -0
- prsmfile/readers/auc.py +55 -0
- prsmfile/readers/common.py +236 -0
- prsmfile/readers/generic.py +78 -0
- prsmfile/readers/nonlinear.py +129 -0
- prsmfile/readers/oneway.py +128 -0
- prsmfile/readers/ttest.py +295 -0
- prsmfile/readers/twoway.py +154 -0
- prsmfile/render.py +245 -0
- prsmfile/report.py +78 -0
- prsmfile/tables.py +180 -0
- prsmfile/values.py +173 -0
- prsmfile-0.1.0.dist-info/METADATA +217 -0
- prsmfile-0.1.0.dist-info/RECORD +24 -0
- prsmfile-0.1.0.dist-info/WHEEL +5 -0
- prsmfile-0.1.0.dist-info/entry_points.txt +2 -0
- prsmfile-0.1.0.dist-info/licenses/LICENSE +21 -0
- prsmfile-0.1.0.dist-info/top_level.txt +1 -0
prsmfile/__init__.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .archive import Analysis, PrismFile, open
|
|
4
|
+
from .errors import PrismFormatError
|
|
5
|
+
from .readers import read_analysis
|
|
6
|
+
from .report import Report, Section
|
|
7
|
+
from .tables import Table, read_table
|
|
8
|
+
from .values import PValue
|
|
9
|
+
|
|
10
|
+
__version__ = "0.1.0"
|
|
11
|
+
|
|
12
|
+
__all__ = [
|
|
13
|
+
"open", "PrismFile", "Analysis", "PrismFormatError", "PValue",
|
|
14
|
+
"Report", "Section", "read_analysis", "Table", "read_table", "__version__",
|
|
15
|
+
]
|
prsmfile/__main__.py
ADDED
prsmfile/archive.py
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import math
|
|
5
|
+
import re
|
|
6
|
+
import zipfile
|
|
7
|
+
import zlib
|
|
8
|
+
import copy
|
|
9
|
+
from dataclasses import dataclass, field, replace
|
|
10
|
+
|
|
11
|
+
from .errors import PrismFormatError
|
|
12
|
+
from .values import letter
|
|
13
|
+
|
|
14
|
+
_SHEET_RE = re.compile(r"analyses/([^/]+)/sheet\.json")
|
|
15
|
+
_READ_ERRORS = (
|
|
16
|
+
zipfile.BadZipFile,
|
|
17
|
+
zlib.error,
|
|
18
|
+
OSError,
|
|
19
|
+
EOFError,
|
|
20
|
+
NotImplementedError,
|
|
21
|
+
RuntimeError,
|
|
22
|
+
UnicodeDecodeError,
|
|
23
|
+
)
|
|
24
|
+
_JSON_ERRORS = (ValueError, RecursionError)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _is_opaque(name: str) -> bool:
|
|
28
|
+
"""Members that are never read: media, binary graph and layout data."""
|
|
29
|
+
return name.startswith("media/") or name.endswith(".bin")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _text(x) -> str | None:
|
|
33
|
+
if isinstance(x, str) and x.strip():
|
|
34
|
+
return x
|
|
35
|
+
return None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _norm(s: str) -> str:
|
|
39
|
+
return " ".join(s.split())
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _squash(s: str) -> str:
|
|
43
|
+
"""All whitespace removed: Prism stores alertText without the separators of the note."""
|
|
44
|
+
return "".join(s.split())
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
_LINE_SEP = re.compile(r"(\r\n|\r|\n)")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _drop_link_text(s: str) -> str:
|
|
51
|
+
"""Remove the UI link text "Learn more" that Prism appends to a note paragraph."""
|
|
52
|
+
parts = _LINE_SEP.split(s) # text, sep, text, sep, ...
|
|
53
|
+
out: list[str] = []
|
|
54
|
+
i = 0
|
|
55
|
+
while i < len(parts):
|
|
56
|
+
if i % 2 == 0 and parts[i].strip() == "Learn more":
|
|
57
|
+
i += 2 # the text and the separator after it
|
|
58
|
+
continue
|
|
59
|
+
out.append(parts[i])
|
|
60
|
+
i += 1
|
|
61
|
+
return "".join(out).strip()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parse_version(raw) -> tuple[int, ...]:
|
|
65
|
+
if not isinstance(raw, str):
|
|
66
|
+
return ()
|
|
67
|
+
try:
|
|
68
|
+
return tuple(int(p) for p in raw.split("-"))
|
|
69
|
+
except ValueError:
|
|
70
|
+
return ()
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@dataclass
|
|
74
|
+
class Analysis:
|
|
75
|
+
id: str
|
|
76
|
+
title: str
|
|
77
|
+
analysis_class: str
|
|
78
|
+
is_calculated: bool | None
|
|
79
|
+
parameters: dict = field(default_factory=dict)
|
|
80
|
+
results: dict | None = None
|
|
81
|
+
inputs: list[tuple[str, str]] = field(default_factory=list) # (letter, title or letter)
|
|
82
|
+
views: list[tuple[str, str | None]] = field(default_factory=list)
|
|
83
|
+
alerts: list[str] = field(default_factory=list)
|
|
84
|
+
input_titles: list[str | None] = field(default_factory=list) # title as stored, None if blank; parallel to inputs
|
|
85
|
+
|
|
86
|
+
@property
|
|
87
|
+
def has_results(self) -> bool:
|
|
88
|
+
return self.results is not None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
class PrismFile:
|
|
92
|
+
def __init__(self, path):
|
|
93
|
+
self.path = path
|
|
94
|
+
self.warnings: list[str] = []
|
|
95
|
+
self._analyses: list[Analysis] | None = None
|
|
96
|
+
self._view_ids: frozenset[str] | None = None
|
|
97
|
+
try:
|
|
98
|
+
self._zip = zipfile.ZipFile(path)
|
|
99
|
+
except zipfile.BadZipFile:
|
|
100
|
+
raise PrismFormatError(f"{path}: not a zip archive (not a .prism file)") from None
|
|
101
|
+
except OSError as e:
|
|
102
|
+
raise PrismFormatError(f"{path}: {e.strerror or e}") from None
|
|
103
|
+
except (UnicodeDecodeError, NotImplementedError, EOFError, zlib.error, RuntimeError) as e:
|
|
104
|
+
raise PrismFormatError(f"{path}: unsupported or damaged zip archive ({e})") from None
|
|
105
|
+
try:
|
|
106
|
+
self._names = set(self._zip.namelist())
|
|
107
|
+
if "document.json" not in self._names:
|
|
108
|
+
raise PrismFormatError(f"{path}: document.json missing (not a .prism file)")
|
|
109
|
+
try:
|
|
110
|
+
raw = self._zip.read("document.json")
|
|
111
|
+
doc = json.loads(raw.decode("utf-8"))
|
|
112
|
+
except _READ_ERRORS + _JSON_ERRORS as e:
|
|
113
|
+
raise PrismFormatError(f"{path}: document.json unreadable ({e})") from None
|
|
114
|
+
if not isinstance(doc, dict):
|
|
115
|
+
raise PrismFormatError(f"{path}: document.json root is not an object")
|
|
116
|
+
except BaseException:
|
|
117
|
+
self._zip.close()
|
|
118
|
+
raise
|
|
119
|
+
self._doc = doc
|
|
120
|
+
raw_v = doc.get("formatVersion")
|
|
121
|
+
self.format_version_raw: str | None = raw_v if isinstance(raw_v, str) else None
|
|
122
|
+
self.format_version: tuple[int, ...] = _parse_version(raw_v)
|
|
123
|
+
if not self.format_version or self.format_version[0] != 1:
|
|
124
|
+
raw = self.format_version_raw if self.format_version_raw is not None else "missing"
|
|
125
|
+
self.warnings.append(f"Unknown format version {raw}; structured readers skipped.")
|
|
126
|
+
self.prism_version = self._version_of("createdBy")
|
|
127
|
+
self.saved_with = self._version_of("modifiedBy")
|
|
128
|
+
|
|
129
|
+
def _version_of(self, key: str) -> str | None:
|
|
130
|
+
v = self._doc.get(key)
|
|
131
|
+
v = v.get("version") if isinstance(v, dict) else None
|
|
132
|
+
return v if isinstance(v, str) else None
|
|
133
|
+
|
|
134
|
+
def __enter__(self) -> "PrismFile":
|
|
135
|
+
return self
|
|
136
|
+
|
|
137
|
+
def __exit__(self, *exc) -> None:
|
|
138
|
+
self.close()
|
|
139
|
+
|
|
140
|
+
def close(self) -> None:
|
|
141
|
+
self._zip.close()
|
|
142
|
+
|
|
143
|
+
def _warn(self, msg: str) -> None:
|
|
144
|
+
if msg not in self.warnings: # members may be read by several indexes
|
|
145
|
+
self.warnings.append(msg)
|
|
146
|
+
|
|
147
|
+
def read_text(self, name: str) -> str | None:
|
|
148
|
+
if _is_opaque(name) or name not in self._names:
|
|
149
|
+
return None
|
|
150
|
+
try:
|
|
151
|
+
return self._zip.read(name).decode("utf-8")
|
|
152
|
+
except UnicodeDecodeError:
|
|
153
|
+
self._warn(f"Could not decode {name}")
|
|
154
|
+
except _READ_ERRORS:
|
|
155
|
+
self._warn(f"Could not read {name}")
|
|
156
|
+
return None
|
|
157
|
+
|
|
158
|
+
def read_json(self, name: str) -> dict | None:
|
|
159
|
+
text = self.read_text(name)
|
|
160
|
+
if text is None:
|
|
161
|
+
return None
|
|
162
|
+
try:
|
|
163
|
+
obj = json.loads(text)
|
|
164
|
+
except _JSON_ERRORS:
|
|
165
|
+
self._warn(f"Could not parse {name}")
|
|
166
|
+
return None
|
|
167
|
+
if not isinstance(obj, dict):
|
|
168
|
+
self._warn(f"{name} is not a JSON object")
|
|
169
|
+
return None
|
|
170
|
+
return obj
|
|
171
|
+
|
|
172
|
+
def data_tables(self) -> list[str]:
|
|
173
|
+
"""Sheet ids of the raw data tables, in the listed order."""
|
|
174
|
+
sheets = self._doc.get("sheets")
|
|
175
|
+
lst = sheets.get("data") if isinstance(sheets, dict) else None
|
|
176
|
+
out: list[str] = []
|
|
177
|
+
for sid in lst if isinstance(lst, list) else []:
|
|
178
|
+
if isinstance(sid, str) and sid not in out:
|
|
179
|
+
out.append(sid)
|
|
180
|
+
return out
|
|
181
|
+
|
|
182
|
+
def result_table(self, sheet_id: str):
|
|
183
|
+
"""The data table behind a view's result sheet id, or None."""
|
|
184
|
+
from .tables import read_table
|
|
185
|
+
|
|
186
|
+
if not isinstance(sheet_id, str) or sheet_id not in self._view_sheet_ids():
|
|
187
|
+
return None
|
|
188
|
+
return read_table(self, sheet_id)
|
|
189
|
+
|
|
190
|
+
def _view_sheet_ids(self) -> frozenset[str]:
|
|
191
|
+
"""Data-sheet ids of all result views, indexed once from sheet.json
|
|
192
|
+
resultSheets and the result_sheets members (no parameters or results)."""
|
|
193
|
+
if self._view_ids is None:
|
|
194
|
+
ids: set[str] = set()
|
|
195
|
+
for n in sorted(self._names):
|
|
196
|
+
m = _SHEET_RE.fullmatch(n)
|
|
197
|
+
if not m:
|
|
198
|
+
continue
|
|
199
|
+
sheet = self.read_json(n)
|
|
200
|
+
refs = sheet.get("resultSheets") if sheet else None
|
|
201
|
+
for r in refs if isinstance(refs, list) else []:
|
|
202
|
+
uid = r.get("uid") if isinstance(r, dict) else None
|
|
203
|
+
if not isinstance(uid, str) or "/" in uid:
|
|
204
|
+
continue
|
|
205
|
+
v = self.read_json(f"analyses/{m.group(1)}/result_sheets/{uid}.json")
|
|
206
|
+
ds = v.get("dataSheet") if v else None
|
|
207
|
+
if isinstance(ds, str):
|
|
208
|
+
ids.add(ds)
|
|
209
|
+
self._view_ids = frozenset(ids)
|
|
210
|
+
return self._view_ids
|
|
211
|
+
|
|
212
|
+
def analyses(self) -> list[Analysis]:
|
|
213
|
+
if self._analyses is None:
|
|
214
|
+
self._analyses = self._discover()
|
|
215
|
+
# copies: callers cannot change the cached state
|
|
216
|
+
return [
|
|
217
|
+
replace(
|
|
218
|
+
a,
|
|
219
|
+
parameters=copy.deepcopy(a.parameters),
|
|
220
|
+
results=copy.deepcopy(a.results),
|
|
221
|
+
inputs=list(a.inputs),
|
|
222
|
+
input_titles=list(a.input_titles),
|
|
223
|
+
views=list(a.views),
|
|
224
|
+
alerts=list(a.alerts),
|
|
225
|
+
)
|
|
226
|
+
for a in self._analyses
|
|
227
|
+
]
|
|
228
|
+
|
|
229
|
+
def _discover(self) -> list[Analysis]:
|
|
230
|
+
ids = []
|
|
231
|
+
for n in self._zip.namelist():
|
|
232
|
+
m = _SHEET_RE.fullmatch(n)
|
|
233
|
+
if m:
|
|
234
|
+
ids.append(m.group(1))
|
|
235
|
+
found: dict[str, Analysis] = {}
|
|
236
|
+
for aid in ids:
|
|
237
|
+
a = self._load(aid)
|
|
238
|
+
if a is not None:
|
|
239
|
+
found[aid] = a
|
|
240
|
+
listed = []
|
|
241
|
+
sheets = self._doc.get("sheets")
|
|
242
|
+
lst = sheets.get("analyses") if isinstance(sheets, dict) else None
|
|
243
|
+
if isinstance(lst, list):
|
|
244
|
+
for aid in lst:
|
|
245
|
+
if isinstance(aid, str) and aid in found and aid not in listed:
|
|
246
|
+
listed.append(aid)
|
|
247
|
+
rest = sorted((a for k, a in found.items() if k not in listed), key=lambda a: a.title)
|
|
248
|
+
return [found[k] for k in listed] + rest
|
|
249
|
+
|
|
250
|
+
def _load(self, aid: str) -> Analysis | None:
|
|
251
|
+
base = f"analyses/{aid}/"
|
|
252
|
+
sheet = self.read_json(base + "sheet.json")
|
|
253
|
+
if sheet is None:
|
|
254
|
+
self.warnings.append(f"Skipped analysis {aid}: unreadable sheet.json")
|
|
255
|
+
return None
|
|
256
|
+
calc = sheet.get("isCalculated")
|
|
257
|
+
a = Analysis(
|
|
258
|
+
id=aid,
|
|
259
|
+
title=_text(sheet.get("title")) or "(untitled)",
|
|
260
|
+
analysis_class=_text(sheet.get("analysisClass")) or "UNKNOWN",
|
|
261
|
+
is_calculated=calc if isinstance(calc, bool) else None,
|
|
262
|
+
)
|
|
263
|
+
params = self.read_json(base + "parameters.json")
|
|
264
|
+
content = params.get("content") if params else None
|
|
265
|
+
a.parameters = content if isinstance(content, dict) else {}
|
|
266
|
+
res = self.read_json(base + "results.json")
|
|
267
|
+
content = res.get("content") if res else None
|
|
268
|
+
a.results = content if isinstance(content, dict) else None
|
|
269
|
+
items = sheet.get("inputDataSets")
|
|
270
|
+
for i, item in enumerate(items if isinstance(items, list) else []):
|
|
271
|
+
if not isinstance(item, dict):
|
|
272
|
+
continue
|
|
273
|
+
idx = item.get("idx")
|
|
274
|
+
ltr = idx if isinstance(idx, str) and idx.strip() else letter(i)
|
|
275
|
+
title = _text(item.get("title"))
|
|
276
|
+
a.inputs.append((ltr, title or ltr))
|
|
277
|
+
a.input_titles.append(title)
|
|
278
|
+
a.views = self._views(base, sheet)
|
|
279
|
+
a.alerts = self._alerts(base, sheet)
|
|
280
|
+
return a
|
|
281
|
+
|
|
282
|
+
def _views(self, base: str, sheet: dict) -> list[tuple[str, str | None]]:
|
|
283
|
+
refs = sheet.get("resultSheets")
|
|
284
|
+
uids: list[str] = []
|
|
285
|
+
for r in refs if isinstance(refs, list) else []:
|
|
286
|
+
uid = r.get("uid") if isinstance(r, dict) else None
|
|
287
|
+
if isinstance(uid, str) and "/" not in uid and uid not in uids:
|
|
288
|
+
uids.append(uid)
|
|
289
|
+
out = []
|
|
290
|
+
for uid in uids:
|
|
291
|
+
v = self.read_json(f"{base}result_sheets/{uid}.json")
|
|
292
|
+
if v is None:
|
|
293
|
+
continue
|
|
294
|
+
key = v.get("viewIdx")
|
|
295
|
+
ok = (isinstance(key, int) and not isinstance(key, bool)) or (
|
|
296
|
+
isinstance(key, float) and math.isfinite(key)
|
|
297
|
+
)
|
|
298
|
+
name = v.get("name")
|
|
299
|
+
ds = v.get("dataSheet")
|
|
300
|
+
out.append((
|
|
301
|
+
(0, key) if ok else (1, 0), # ints stay exact; missing last
|
|
302
|
+
(name if _text(name) else "", ds if isinstance(ds, str) else None),
|
|
303
|
+
))
|
|
304
|
+
out.sort(key=lambda p: p[0]) # stable
|
|
305
|
+
return [p[1] for p in out]
|
|
306
|
+
|
|
307
|
+
def _alerts(self, base: str, sheet: dict) -> list[str]:
|
|
308
|
+
head = _text(sheet.get("alertText"))
|
|
309
|
+
notes = []
|
|
310
|
+
pattern = re.compile(re.escape(base) + r"floating_notes/[^/]+\.json")
|
|
311
|
+
for n in self._zip.namelist(): # archive member order
|
|
312
|
+
if not pattern.fullmatch(n):
|
|
313
|
+
continue
|
|
314
|
+
note = self.read_json(n)
|
|
315
|
+
if not note or note.get("isAuto") is not True:
|
|
316
|
+
continue
|
|
317
|
+
s = note.get("text")
|
|
318
|
+
s = s.get("string") if isinstance(s, dict) else None
|
|
319
|
+
s = _drop_link_text(s) if _text(s) else None
|
|
320
|
+
if s:
|
|
321
|
+
notes.append(s)
|
|
322
|
+
texts = []
|
|
323
|
+
if head:
|
|
324
|
+
head = _drop_link_text(head)
|
|
325
|
+
# alertText is often the first characters of a note without its separators
|
|
326
|
+
sq = _squash(head)
|
|
327
|
+
if head and not any(_squash(s).startswith(sq) and _squash(s) != sq for s in notes):
|
|
328
|
+
texts.append(head)
|
|
329
|
+
texts.extend(notes)
|
|
330
|
+
seen: set[str] = set()
|
|
331
|
+
out = []
|
|
332
|
+
for s in texts:
|
|
333
|
+
k = _norm(s)
|
|
334
|
+
if k not in seen:
|
|
335
|
+
seen.add(k)
|
|
336
|
+
out.append(s)
|
|
337
|
+
return out
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def open(path) -> PrismFile: # noqa: A001
|
|
341
|
+
return PrismFile(path)
|
prsmfile/cli.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
"""Command line interface."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import os
|
|
6
|
+
import re
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from . import __version__
|
|
11
|
+
from . import open as open_prism
|
|
12
|
+
from .errors import PrismFormatError
|
|
13
|
+
from .readers import read_analysis
|
|
14
|
+
from .render import flat, to_json_obj, to_text, write_csv
|
|
15
|
+
from .tables import read_table
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _parser() -> argparse.ArgumentParser:
|
|
19
|
+
p = argparse.ArgumentParser(
|
|
20
|
+
prog="prsmfile",
|
|
21
|
+
description="Read analysis results and data tables from GraphPad Prism .prism files.",
|
|
22
|
+
)
|
|
23
|
+
p.add_argument("file", metavar="FILE", help="a .prism file")
|
|
24
|
+
mode = p.add_mutually_exclusive_group()
|
|
25
|
+
mode.add_argument("--list", action="store_true", help="list the analyses and their state")
|
|
26
|
+
mode.add_argument("--json", action="store_true", help="print JSON instead of text tables")
|
|
27
|
+
mode.add_argument("--csv", metavar="DIR", help="write CSV files into a new or empty directory")
|
|
28
|
+
p.add_argument("--data", action="store_true", help="include the raw data tables")
|
|
29
|
+
p.add_argument("--analysis", metavar="TEXT",
|
|
30
|
+
help="only the analysis with this number (as in --list) or id, "
|
|
31
|
+
"else the analyses whose title contains TEXT (case-insensitive); "
|
|
32
|
+
"a pure number never falls back to the title")
|
|
33
|
+
p.add_argument("--version", action="version", version=f"prsmfile {__version__}")
|
|
34
|
+
return p
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_ASCII_NUMBER = re.compile(r"[0-9]+")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _status_error(a) -> str | None:
|
|
41
|
+
"""The Prism error code of an analysis whose results hold nothing but a failed status."""
|
|
42
|
+
res = a.results
|
|
43
|
+
if not isinstance(res, dict) or any(k != "status" for k in res):
|
|
44
|
+
return None
|
|
45
|
+
status = res.get("status")
|
|
46
|
+
err = status.get("error") if isinstance(status, dict) else None
|
|
47
|
+
return err if isinstance(err, str) and err != "VALID" else None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _state(a) -> str:
|
|
51
|
+
err = _status_error(a)
|
|
52
|
+
if err is not None:
|
|
53
|
+
return f"Prism error {err}"
|
|
54
|
+
if a.has_results:
|
|
55
|
+
return "calculated"
|
|
56
|
+
if a.is_calculated is False:
|
|
57
|
+
return "not calculated"
|
|
58
|
+
return "no stored results"
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _warn_file(pf) -> None:
|
|
62
|
+
for w in pf.warnings:
|
|
63
|
+
print(f"Warning: {flat(w)}", file=sys.stderr)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _run(args) -> int:
|
|
67
|
+
with open_prism(args.file) as pf:
|
|
68
|
+
numbered = list(enumerate(pf.analyses(), 1))
|
|
69
|
+
if args.analysis is not None:
|
|
70
|
+
needle = args.analysis.strip().casefold()
|
|
71
|
+
exact = [(n, a) for n, a in numbered
|
|
72
|
+
if a.id.casefold() == needle or (_ASCII_NUMBER.fullmatch(needle) and int(needle) == n)]
|
|
73
|
+
if not exact and _ASCII_NUMBER.fullmatch(needle):
|
|
74
|
+
print(f"no analysis numbered {int(needle)}", file=sys.stderr)
|
|
75
|
+
return 1
|
|
76
|
+
numbered = exact or [(n, a) for n, a in numbered if needle in flat(a.title).casefold()]
|
|
77
|
+
if not numbered:
|
|
78
|
+
print(f'no analysis matches "{args.analysis}"', file=sys.stderr)
|
|
79
|
+
return 1
|
|
80
|
+
if args.list:
|
|
81
|
+
for n, a in numbered:
|
|
82
|
+
print(f"{n:02d} {a.analysis_class} {_state(a)} {flat(a.title)}")
|
|
83
|
+
_warn_file(pf)
|
|
84
|
+
return 0
|
|
85
|
+
analyses = [a for _, a in numbered]
|
|
86
|
+
numbers = [n for n, _ in numbered]
|
|
87
|
+
reports = [read_analysis(pf, a) for a in analyses]
|
|
88
|
+
tables = []
|
|
89
|
+
if args.data:
|
|
90
|
+
tables = [t for t in (read_table(pf, sid) for sid in pf.data_tables()) if t is not None]
|
|
91
|
+
if args.csv is not None:
|
|
92
|
+
print(len(write_csv(Path(args.csv), reports, tables, numbers)))
|
|
93
|
+
_warn_file(pf)
|
|
94
|
+
elif args.json:
|
|
95
|
+
import json
|
|
96
|
+
|
|
97
|
+
print(json.dumps(to_json_obj(pf, reports, tables, numbers), ensure_ascii=False, indent=2,
|
|
98
|
+
allow_nan=False))
|
|
99
|
+
else:
|
|
100
|
+
sys.stdout.write(to_text(pf, reports, tables, numbers))
|
|
101
|
+
return 0
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _quiet_stdout() -> None:
|
|
105
|
+
"""The reader of our stdout went away: stop the exit-time flush from complaining."""
|
|
106
|
+
try:
|
|
107
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
108
|
+
os.dup2(devnull, sys.stdout.fileno())
|
|
109
|
+
except (OSError, ValueError, AttributeError):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def main(argv=None) -> int:
|
|
114
|
+
parser = _parser()
|
|
115
|
+
try:
|
|
116
|
+
args = parser.parse_args(argv)
|
|
117
|
+
if args.list and args.data:
|
|
118
|
+
parser.error("--data cannot be combined with --list")
|
|
119
|
+
except SystemExit as e: # --help / --version print, then exit; the pipe may be closed
|
|
120
|
+
try:
|
|
121
|
+
sys.stdout.flush()
|
|
122
|
+
except BrokenPipeError:
|
|
123
|
+
_quiet_stdout()
|
|
124
|
+
raise SystemExit(1) from None
|
|
125
|
+
raise e
|
|
126
|
+
for stream in (sys.stdout, sys.stderr):
|
|
127
|
+
reconf = getattr(stream, "reconfigure", None)
|
|
128
|
+
if reconf is not None:
|
|
129
|
+
reconf(encoding="utf-8", errors="replace")
|
|
130
|
+
try:
|
|
131
|
+
code = _run(args)
|
|
132
|
+
sys.stdout.flush()
|
|
133
|
+
return code
|
|
134
|
+
except BrokenPipeError:
|
|
135
|
+
# the reader went away (e.g. `| head`): silence the flush at exit
|
|
136
|
+
_quiet_stdout()
|
|
137
|
+
return 1
|
|
138
|
+
except PrismFormatError as e:
|
|
139
|
+
msg = str(e)
|
|
140
|
+
if args.file.lower().endswith(".pzf"):
|
|
141
|
+
msg += " (.pzf files are not supported, save the project as .prism)"
|
|
142
|
+
print(f"prsmfile: {msg}", file=sys.stderr)
|
|
143
|
+
return 1
|
|
144
|
+
except OSError as e:
|
|
145
|
+
print(f"prsmfile: {e.filename or args.csv or args.file}: {e.strerror or e}", file=sys.stderr)
|
|
146
|
+
return 1
|
prsmfile/errors.py
ADDED
prsmfile/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Reader registry: analysisClass to a typed reader, with a generic fallback."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from typing import Callable
|
|
5
|
+
|
|
6
|
+
from ..report import Report, Section, is_empty_rows
|
|
7
|
+
from .generic import flatten, generic_sections
|
|
8
|
+
|
|
9
|
+
Reader = Callable[..., "list[Section]"]
|
|
10
|
+
REGISTRY: dict[str, Reader] = {}
|
|
11
|
+
_NOTE = "Rounded values from Prism's rendered table."
|
|
12
|
+
_READER_ERRORS = (KeyError, TypeError, ValueError, IndexError, AttributeError)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def register(analysis_class: str):
|
|
16
|
+
def deco(fn: Reader) -> Reader:
|
|
17
|
+
REGISTRY[analysis_class] = fn
|
|
18
|
+
return fn
|
|
19
|
+
|
|
20
|
+
return deco
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _status(a) -> tuple[str | None, list[str]]:
|
|
24
|
+
status = a.results.get("status") if isinstance(a.results, dict) else None
|
|
25
|
+
if not isinstance(status, dict):
|
|
26
|
+
return None, []
|
|
27
|
+
err = status.get("error")
|
|
28
|
+
warns = status.get("warning")
|
|
29
|
+
return (
|
|
30
|
+
err if isinstance(err, str) else None,
|
|
31
|
+
[w for w in warns if isinstance(w, str)] if isinstance(warns, list) else [],
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _coded(codes: list[str]) -> list[str]:
|
|
36
|
+
return [f"Prism reported {c}" for c in codes]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _rendered_sections(pf, a) -> list[Section]:
|
|
40
|
+
out = []
|
|
41
|
+
for name, ds in a.views:
|
|
42
|
+
if ds is None:
|
|
43
|
+
continue
|
|
44
|
+
t = pf.result_table(ds)
|
|
45
|
+
if t is None or is_empty_rows(t.rows):
|
|
46
|
+
continue
|
|
47
|
+
n = len(t.columns)
|
|
48
|
+
rows = [list(r) + [""] * (n - len(r)) for r in t.rows]
|
|
49
|
+
out.append(Section(
|
|
50
|
+
title=name if name.strip() else t.title,
|
|
51
|
+
columns=list(t.columns),
|
|
52
|
+
rows=rows,
|
|
53
|
+
note=_NOTE if t.data_format == "text" else None,
|
|
54
|
+
))
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _major_unknown(pf) -> bool:
|
|
59
|
+
return not pf.format_version or pf.format_version[0] != 1
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def read_analysis(pf, a) -> Report:
|
|
63
|
+
warnings: list[str] = list(a.alerts)
|
|
64
|
+
warn = warnings.append
|
|
65
|
+
if a.is_calculated is False and not a.has_results:
|
|
66
|
+
warn(
|
|
67
|
+
"Not calculated when saved: open the file in Prism, "
|
|
68
|
+
"view this analysis's results and save again."
|
|
69
|
+
)
|
|
70
|
+
return Report(a, "not_calculated", [], warnings)
|
|
71
|
+
err, codes = _status(a)
|
|
72
|
+
if a.results is None or all(k == "status" for k in a.results):
|
|
73
|
+
if a.results is None:
|
|
74
|
+
warn(f"No stored results (file saved by Prism {pf.saved_with or 'unknown'}).")
|
|
75
|
+
warnings.extend(_coded(codes))
|
|
76
|
+
if err is not None and err != "VALID":
|
|
77
|
+
warn(f"Prism reported {err}")
|
|
78
|
+
return Report(a, "generic", _rendered_sections(pf, a), warnings)
|
|
79
|
+
kind, sections = "generic", None
|
|
80
|
+
if _major_unknown(pf):
|
|
81
|
+
sections = generic_sections(pf, a)
|
|
82
|
+
else:
|
|
83
|
+
reader = REGISTRY.get(a.analysis_class)
|
|
84
|
+
if reader is not None:
|
|
85
|
+
try:
|
|
86
|
+
sections = reader(pf, a, warn) or None # no section at all: use the generic reader
|
|
87
|
+
kind = "structured" if sections else "generic"
|
|
88
|
+
except _READER_ERRORS as e:
|
|
89
|
+
warn(f"Structured reader failed ({type(e).__name__}), showing generic values.")
|
|
90
|
+
if sections is None:
|
|
91
|
+
sections = generic_sections(pf, a)
|
|
92
|
+
warnings.extend(_coded(codes))
|
|
93
|
+
if err is not None and err != "VALID":
|
|
94
|
+
warn(f"Prism reported {err}")
|
|
95
|
+
return Report(a, kind, sections, warnings)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
__all__ = ["REGISTRY", "register", "read_analysis", "flatten", "generic_sections"]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
from . import auc, nonlinear, oneway, ttest, twoway # noqa: E402,F401 (registers the readers)
|
prsmfile/readers/auc.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""AREA_UNDER_CURVE (docs/format.md 2.6)."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import re
|
|
5
|
+
|
|
6
|
+
from ..report import Section
|
|
7
|
+
from ..values import entries, num
|
|
8
|
+
from . import register
|
|
9
|
+
from .common import other_rows, other_section
|
|
10
|
+
from .nonlinear import dataset_label
|
|
11
|
+
|
|
12
|
+
_READ = [("samples", "summary", n) for n in ("baseline", "totalArea", "totalPeakArea", "peakCount")]
|
|
13
|
+
_PEAK_FIELDS = ("firstX", "lastX", "peakX", "peakY", "area", "areaPercentage")
|
|
14
|
+
_SUMMARY_COLUMNS = ["Data set", "Baseline", "Total area", "Total peak area", "Peaks"]
|
|
15
|
+
_PEAK_COLUMNS = ["Data set", "Peak", "First X", "Last X", "Peak X", "Peak Y", "Area", "Area %"]
|
|
16
|
+
_PEAK_RE = re.compile(r"(\d+)")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _dict(x) -> dict:
|
|
20
|
+
return x if isinstance(x, dict) else {}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _peak_order(name) -> tuple:
|
|
24
|
+
m = _PEAK_RE.search(name) if isinstance(name, str) else None
|
|
25
|
+
return (0, int(m.group(1)), "") if m else (1, 0, str(name))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@register("AREA_UNDER_CURVE")
|
|
29
|
+
def read_auc(pf, a, warn):
|
|
30
|
+
samples = a.results.get("samples")
|
|
31
|
+
if not isinstance(samples, dict):
|
|
32
|
+
raise KeyError("samples")
|
|
33
|
+
summary_rows, peak_rows, read = [], [], list(_READ)
|
|
34
|
+
for id_, value in entries(samples):
|
|
35
|
+
v = _dict(value)
|
|
36
|
+
ds = dataset_label(id_)
|
|
37
|
+
s = _dict(v.get("summary"))
|
|
38
|
+
summary_rows.append([ds, num(s.get("baseline")), num(s.get("totalArea")),
|
|
39
|
+
num(s.get("totalPeakArea")), num(s.get("peakCount"))])
|
|
40
|
+
peaks = _dict(v.get("peaks"))
|
|
41
|
+
read += [("samples", "peaks", name, f) for name in peaks for f in _PEAK_FIELDS]
|
|
42
|
+
for name in sorted(peaks, key=_peak_order):
|
|
43
|
+
p = _dict(peaks[name])
|
|
44
|
+
peak_rows.append([ds, str(name), num(p.get("firstX")), num(p.get("lastX")),
|
|
45
|
+
num(p.get("peakX")), num(p.get("peakY")), num(p.get("area")),
|
|
46
|
+
num(p.get("areaPercentage"))])
|
|
47
|
+
sections = []
|
|
48
|
+
if summary_rows:
|
|
49
|
+
sections.append(Section("Area under curve", list(_SUMMARY_COLUMNS), summary_rows))
|
|
50
|
+
if peak_rows:
|
|
51
|
+
sections.append(Section("Peaks", list(_PEAK_COLUMNS), peak_rows))
|
|
52
|
+
extra = other_section(other_rows(a.results, read))
|
|
53
|
+
if extra is not None:
|
|
54
|
+
sections.append(extra)
|
|
55
|
+
return sections
|