-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgui.py
More file actions
1318 lines (1109 loc) · 55.8 KB
/
Copy pathgui.py
File metadata and controls
1318 lines (1109 loc) · 55.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import csv
import json
import os
import re
import signal
import sys
import threading
from datetime import datetime
from pathlib import Path
import traceback
from PySide6.QtCore import QObject, Signal, Slot, QThread, Qt, QTimer
from PySide6.QtGui import QFont
from PySide6.QtWidgets import (
QApplication,
QCheckBox,
QDialog,
QFileDialog,
QGroupBox,
QHBoxLayout,
QLabel,
QLineEdit,
QMainWindow,
QMessageBox,
QPushButton,
QProgressBar,
QScrollArea,
QSizePolicy,
QSpacerItem,
QTextEdit,
QVBoxLayout,
QWidget,
QListWidget,
QListWidgetItem
)
from raw_parser import MetaXtract
from plotly_visualizer import (
PlotlyMS1Visualizer,
PlotlyMS2Visualizer,
write_comparison_html,
write_comparison_html_multi,
write_comparison_html_with_boxplots,
)
from anndata_export import export_ms2_to_h5ad
class MS1Visualizer:
def __init__(self, single_file_name: str, output_dir: str):
self.single_file_name = single_file_name
self.output_dir = Path(output_dir)
self.ms1_scans = []
self.ms1_data = {
"Scan Start Time (min)": [],
"Elapsed Scan Time (sec)": [],
"Total Ion Current": [],
"Total Number of Peaks": [],
"Base Peak Intensity": [],
"Base Peak m/z": [],
"Ion Injection Time (ms)": [],
}
def generate_pdf_report(self, output_pdf_report: str):
pass
class MS2Visualizer:
def __init__(self, single_file_name: str, output_dir: str):
self.single_file_name = single_file_name
self.output_dir = Path(output_dir)
self.ms2_scans = []
self.ms2_data = {
"Scan Start Time (min)": [],
"Elapsed Scan Time (sec)": [],
"Total Ion Current": [],
"Total Number of Peaks": [],
"Selected Ion Intensity": [],
"Charge State": [],
"Ion Injection Time (ms)": [],
}
def generate_pdf_report(self, output_pdf_report: str):
pass
_NUM_RE = re.compile(r"[-+]?\d+(?:[.,]\d+)?(?:[eE][-+]?\d+)?")
def _tsv_safe(v):
if v is None:
return ""
if isinstance(v, (dict, list, tuple)):
return json.dumps(v, ensure_ascii=False)
s = str(v)
return s.replace("\r\n", " ").replace("\n", " ").replace("\r", " ")
def write_info_tsv(raw_parser, out_tsv_path: str, should_stop=None):
raw_parser.CountMS2(should_stop=should_stop)
instrument_details = raw_parser.GetInstrumentDetails() or {}
sample_information = raw_parser.GetSampleInformation() or {}
rows = []
rows += [
("File", "RAW File Name", raw_parser.GetRAWFileName()),
("File", "User ID", raw_parser.GetUserID()),
("File", "File Creation Date", raw_parser.GetFileCreationDate()),
("Instrument", "Instrument Name", raw_parser.GetInstrumentName()),
("Counts", "Number of MS2 Scans (centroid)", raw_parser.NumMS2Centroid),
("Counts", "Number of MS2 Scans (profile)", raw_parser.NumMS2Profile),
("Counts", "Number of MS1 Scans", raw_parser.NumMS1),
("Counts", "Total Number of Scans", raw_parser.NumSpectra),
("Run", "Start Time", raw_parser.StartTime),
("Run", "End Time", raw_parser.EndTime),
("Run", "Lowest Mass", raw_parser.LowMass),
("Run", "Highest Mass", raw_parser.HighMass),
("Run", "Mass Resolution", raw_parser.MassResolution),
("Run", "Highest Integrated Intensity", raw_parser.GetMaxIntegratedIntensity()),
("Run", "Highest Base Peak", raw_parser.GetHighestBasePeakOfRawFile()),
]
for k, v in instrument_details.items():
rows.append(("Instrument Details", k, v))
for k, v in sample_information.items():
rows.append(("Sample", k, v))
with open(out_tsv_path, "w", newline="", encoding="utf-8") as f:
w = csv.writer(f, delimiter="\t")
w.writerow(["Section", "Key", "Value"])
for sec, key, val in rows:
w.writerow([_tsv_safe(sec), _tsv_safe(key), _tsv_safe(val)])
def to_float(x):
if x is None:
return None
if isinstance(x, (int, float)):
return float(x)
s = str(x).strip()
if not s:
return None
s = s.replace("\u00a0", " ").strip()
m = _NUM_RE.search(s)
if not m:
return None
token = m.group(0).replace(",", ".")
try:
return float(token)
except Exception:
return None
def to_int(x):
v = to_float(x)
return int(v) if v is not None else None
def safe_call(fn, default=None):
try:
return fn()
except Exception:
return default
def td_get(trailer_data, key):
if not trailer_data:
return None
#print(trailer_data)
return trailer_data.get(key, None)
COLUMN_SOURCE_ALIASES = {
"Scan Start Time (min)": ("Retention Time (min)", "Retention Time (s)"),
"Base Peak m/z": ("Base Peak Mass",),
"Selected Ion Intensity": ("Precursor Intensity",),
"Scan Window m/z Range": ("Mass Ranges",),
"Filter String": ("Scan Description",),
"Dissociation Method": ("Activation Type",),
"Sampling Frequency": ("Frequency",),
"Experimental Precursor Monoisotopic m/z": ("Monoisotopic M/Z",),
"Isolation Window Width (m/z)": ("MS2 Isolation Width",),
"Normalized Collision Energy (%)": ("HCD Energy",),
"Collision Energy (eV)": ("HCD Energy eV",),
"FAIMS Compensation Voltage": ("FAIMS CV",),
"thermo_Number of Channels": ("Number of Channels",),
"thermo_AGC": ("AGC",),
"thermo_Micro Scan Count": ("Micro Scan Count",),
"thermo_Elapsed Scan Time (sec)": ("Elapsed Scan Time (sec)",),
"thermo_Average Scan by Inst": ("Average Scan by Inst",),
"thermo_Orbitrap Resolution": ("Orbitrap Resolution",),
"thermo_API Process Delay": ("API Process Delay",),
"thermo_Dependency Type": ("Dependency Type",),
"thermo_Multi Inject Info": ("Multi Inject Info",),
"thermo_Master Scan Number": ("Master Scan Number",),
"thermo_Access ID": ("Access ID",),
"thermo_Conversion Parameter I": ("Conversion Parameter I",),
"thermo_Conversion Parameter A": ("Conversion Parameter A",),
"thermo_Conversion Parameter B": ("Conversion Parameter B",),
"thermo_Conversion Parameter C": ("Conversion Parameter C",),
"thermo_Conversion Parameter D": ("Conversion Parameter D",),
"thermo_Conversion Parameter E": ("Conversion Parameter E",),
"thermo_Temperature Comp. (ppm)": ("Temperature Comp. (ppm)",),
"thermo_RF Comp. (ppm)": ("RF Comp. (ppm)",),
"thermo_Space Charge Comp. (ppm)": ("Space Charge Comp. (ppm)",),
"thermo_Resolution Comp. (ppm)": ("Resolution Comp. (ppm)",),
"thermo_Number of LM Found": ("Number of LM Found",),
"thermo_LM Correction (ppm)": ("LM Correction (ppm)",),
"thermo_RawOvFtT": ("RawOvFtT",),
"thermo_Injection t0": ("Injection t0",),
"thermo_Reagent Ion Injection Time (ms)": ("Reagent Ion Injection Time (ms)",),
"thermo_FAIMS Voltage On": ("FAIMS Voltage On",),
"thermo_Multiple Injection": ("Multiple Injection",),
}
def trailer_value(trailer_data, output_label: str):
if not trailer_data:
return None
for key in (output_label, *COLUMN_SOURCE_ALIASES.get(output_label, ())):
value = trailer_data.get(key, None)
if value not in (None, ""):
return value
return None
class LogWindow(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("MetaXtract Log")
self.setMinimumSize(820, 520)
lay = QVBoxLayout(self)
self.text = QTextEdit(self)
self.text.setReadOnly(True)
lay.addWidget(self.text)
@Slot(str)
def append_log(self, msg: str):
self.text.append(str(msg))
class _ExtractionWorker(QObject):
progress = Signal(int)
log = Signal(str)
finished = Signal()
failed = Signal(str)
def __init__(
self,
selected_files: list[str],
output_dir_raw: str,
selected_options: list[str],
selected_header_options_ms2: list[str],
selected_header_options_ms1: list[str],
plotly_enabled: bool,
export_fmt: str | None,
multi_cmp: bool,
cmp_files: list[str] | None,
hdf5_export: bool = False,
ms2_peaklist_export: bool = False,
ms1_peaklist_export: bool = False,
ms2_technical_details_export: bool = False,
ms1_technical_details_export: bool = False
):
super().__init__()
self.selected_files = selected_files
self.output_dir_raw = output_dir_raw
self.selected_options = selected_options
self.selected_header_options_ms2 = selected_header_options_ms2
self.selected_header_options_ms1 = selected_header_options_ms1
self.plotly_enabled = plotly_enabled
self.export_fmt = export_fmt
self.multi_cmp = bool(multi_cmp)
self.hdf5_export = bool(hdf5_export)
self.ms2_peaklist_export = bool(ms2_peaklist_export)
self.ms1_peaklist_export = bool(ms1_peaklist_export)
self.ms2_technical_details_export = bool(ms2_technical_details_export)
self.ms1_technical_details_export = bool(ms1_technical_details_export)
self.cmp_files = (cmp_files or [])
self._stop_event = threading.Event()
self._current_raw_parser = None
@Slot()
def stop(self):
self._stop_event.set()
def should_stop(self) -> bool:
return self._stop_event.is_set() or QThread.currentThread().isInterruptionRequested()
def _close_current_raw_file(self) -> None:
raw_parser = self._current_raw_parser
self._current_raw_parser = None
if raw_parser is not None:
safe_call(lambda: raw_parser.CloseRAWFile(), None)
def _remove_empty_lines(self, input_file: str) -> None:
try:
with open(input_file, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
with open(input_file, "w", encoding="utf-8", errors="replace") as f:
for line in lines:
if line.strip():
f.write(line)
except Exception:
return
def _write_plotly(self, ms1_vis: PlotlyMS1Visualizer | None, ms2_vis: PlotlyMS2Visualizer | None) -> None:
if not self.plotly_enabled:
return
try:
if ms1_vis is not None:
idx = ms1_vis.write_html_report()
self.log.emit(f"[VIS] MS1 report: {idx}")
if self.export_fmt:
outs = ms1_vis.export_images(self.export_fmt)
self.log.emit(f"[VIS] MS1 exported {len(outs)} images as {self.export_fmt}")
if ms2_vis is not None:
idx = ms2_vis.write_html_report()
self.log.emit(f"[VIS] MS2 report: {idx}")
if self.export_fmt:
outs = ms2_vis.export_images(self.export_fmt)
self.log.emit(f"[VIS] MS2 exported {len(outs)} images as {self.export_fmt}")
except Exception as e:
self.log.emit(f"[VIS][WARN] {e}")
def _extract_ms2_scan_header(
self,
raw_parser,
out_dir: Path,
selected_options: list[str],
base: str,
plotly_vis: PlotlyMS2Visualizer | None,
):
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_path = out_dir / f"{base}_scan_header_ms2_{ts}.csv"
with open(csv_path, "w", newline="", encoding="utf-8", errors="replace") as f:
w = csv.writer(f)
w.writerow(["Scan Number", "RAW File"] + selected_options)
num_scans = int(getattr(raw_parser, "NumSpectra", 0) or 0)
last_ui = 0
for scan_number in range(1, num_scans + 1):
if self.should_stop():
break
ms_order = safe_call(lambda: int(raw_parser.GetMSOrder(scan_number)), 0)
if ms_order != 2:
continue
#if not safe_call(lambda: raw_parser.CheckMS2Centroid(scan_number), False):
# continue
trailer_data = safe_call(lambda: raw_parser.GetTrailerExtraInformaionEdited(scan_number), {}) or {}
def opt_value(opt: str):
v = trailer_value(trailer_data, opt)
if v is not None:
return v
if opt in ("Scan Start Time (min)", "Retention Time (min)", "Retention Time (s)"):
v = safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Total Ion Current":
v = safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Total Number of Peaks":
v = safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt in ("Base Peak m/z", "Base Peak Mass"):
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), (None, None))
return bp[0] if isinstance(bp, (list, tuple)) and len(bp) >= 2 and bp[0] not in (None, "") else "N/A"
if opt == "Base Peak Intensity":
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), (None, None))
return bp[1] if isinstance(bp, (list, tuple)) and len(bp) >= 2 and bp[1] not in (None, "") else "N/A"
if opt in ("Selected Ion Intensity", "Precursor Intensity"):
v = safe_call(lambda: raw_parser.GetPrecursorIntensityFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt in ("Scan Window m/z Range", "Mass Ranges"):
n = safe_call(lambda: raw_parser.GetNumberOfMassRangesFromScanNumber(scan_number), 0) or 0
ranges = []
for i in range(n):
lo, hi = safe_call(lambda i=i: raw_parser.GetMassRangeFromScanNumber(scan_number, i), (None, None))
if lo is None or hi is None:
continue
ranges.append(f"{lo}-{hi}")
return "; ".join(ranges) if ranges else "N/A"
if opt in ("Filter String", "Scan Description"):
v = safe_call(lambda: raw_parser.GetScanEventStringForScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Scan Mode":
v = safe_call(lambda: raw_parser.GetScanModeFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Detector Type":
return safe_call(lambda: raw_parser.GetDetectorTypeFromScanNumber(scan_number), "N/A")
if opt == "Mass Analyzer Type":
return safe_call(lambda: raw_parser.GetMassAnalyzerTypeFromScanNumber(scan_number), "N/A")
if opt in ("Dissociation Method", "Activation Type"):
return safe_call(lambda: raw_parser.GetActivationTypeForScanNumber(scan_number), "N/A")
if opt == "Collision Energy":
return safe_call(lambda: raw_parser.GetCollisionEnergyForScanNumber(scan_number), "N/A")
if opt in ("Sampling Frequency", "Frequency"):
return safe_call(lambda: raw_parser.GetFrequencyForScanNumber(scan_number), "N/A")
if opt in ("thermo_Number of Channels", "Number of Channels"):
return safe_call(lambda: raw_parser.GetNumChannelsForScanNumber(scan_number), "N/A")
return "N/A"
w.writerow([scan_number, base] + [opt_value(o) for o in selected_options])
if plotly_vis is not None:
#rt = to_float(td_get(trailer_data, "Retention Time (s)"))
rt = to_float(safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number)))
est = to_float(td_get(trailer_data, "Elapsed Scan Time (sec)"))
#tic = to_float(td_get(trailer_data, "Total Ion Current"))
tic = to_float(safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number)))
#tnp = to_int(td_get(trailer_data, "Total Number of Peaks"))
#prec_i = to_float(td_get(trailer_data, "Precursor Intensity"))
tnp = to_int(safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number)))
cs = to_int(td_get(trailer_data, "Charge State"))
iit = to_float(td_get(trailer_data, "Ion Injection Time (ms)"))
prec_i = to_float(safe_call(lambda: raw_parser.GetPrecursorIntensityFromScanNumber(scan_number)))
if rt is None:
rt = to_float(safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number)))
if est is None:
est = to_float(safe_call(lambda: raw_parser.GetElaspedScanTimeFromScanNumber(scan_number)))
if tic is None:
tic = to_float(safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number)))
if tnp is None:
tnp = to_int(safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number)))
if prec_i is None:
prec_i = to_float(safe_call(lambda: raw_parser.GetPrecursorIntensityFromScanNumber(scan_number)))
if cs is None:
cs = to_int(safe_call(lambda: raw_parser.GetMS2ChargeFromScanNumber(scan_number)))
if iit is None:
iit = to_float(safe_call(lambda: raw_parser.GetIonInjectionTimeFromScanNumber(scan_number)))
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), None)
bp_int = to_float(bp[1]) if isinstance(bp, (list, tuple)) and len(bp) >= 2 else 0.0
plotly_vis.ms2_data["Base Peak Intensity"].append(bp_int or 0.0)
plotly_vis.ms2_scans.append(scan_number)
plotly_vis.ms2_data["Scan Start Time (min)"].append(rt if rt is not None else 0.0)
plotly_vis.ms2_data["Elapsed Scan Time (sec)"].append(est or 0.0)
plotly_vis.ms2_data["Total Ion Current"].append(tic or 0.0)
plotly_vis.ms2_data["Total Number of Peaks"].append(tnp or 0)
plotly_vis.ms2_data["Selected Ion Intensity"].append(prec_i or 0.0)
plotly_vis.ms2_data["Charge State"].append(cs or 0)
plotly_vis.ms2_data["Ion Injection Time (ms)"].append(iit or 0.0)
if scan_number - last_ui >= 300:
last_ui = scan_number
self.progress.emit(int((scan_number / max(1, num_scans)) * 100))
self.log.emit(f"[INFO] MS2 scan header CSV: {csv_path}")
def _extract_ms1_scan_header(
self,
raw_parser,
out_dir: Path,
selected_options: list[str],
base: str,
plotly_vis: PlotlyMS1Visualizer | None,
):
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
csv_path = out_dir / f"{base}_scan_header_ms1_{ts}.csv"
with open(csv_path, "w", newline="", encoding="utf-8", errors="replace") as f:
w = csv.writer(f)
w.writerow(["Scan Number", "RAW File"] + selected_options)
num_scans = int(getattr(raw_parser, "NumSpectra", 0) or 0)
last_ui = 0
for scan_number in range(1, num_scans + 1):
if self.should_stop():
break
ms_order = safe_call(lambda: int(raw_parser.GetMSOrder(scan_number)), 0)
if ms_order != 1:
continue
trailer_data = safe_call(lambda: raw_parser.GetTrailerExtraInformaionEdited(scan_number), {}) or {}
def opt_value(opt: str):
v = trailer_value(trailer_data, opt)
if v is not None:
return v
if opt in ("Scan Start Time (min)", "Retention Time (min)", "Retention Time (s)"):
v = safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Total Ion Current":
v = safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Total Number of Peaks":
v = safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt in ("Base Peak m/z", "Base Peak Mass"):
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), (None, None))
return bp[0] if isinstance(bp, (list, tuple)) and len(bp) >= 2 and bp[0] not in (None, "") else "N/A"
if opt == "Base Peak Intensity":
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), (None, None))
return bp[1] if isinstance(bp, (list, tuple)) and len(bp) >= 2 and bp[1] not in (None, "") else "N/A"
if opt == "Ion Injection Time (ms)":
v = safe_call(lambda: raw_parser.GetIonInjectionTimeFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
if opt == "Scan Mode":
v = safe_call(lambda: raw_parser.GetScanModeFromScanNumber(scan_number))
return v if v not in (None, "") else "N/A"
return "N/A"
w.writerow([scan_number, base] + [opt_value(o) for o in selected_options])
if plotly_vis is not None:
#rt = to_float(td_get(trailer_data, "Retention Time (s)"))
rt = to_float(safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number)))
est = to_float(td_get(trailer_data, "Elapsed Scan Time (sec)"))
#tic = to_float(td_get(trailer_data, "Total Ion Current"))
tic = to_float(safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number)))
#tnp = to_int(td_get(trailer_data, "Total Number of Peaks"))
tnp = to_int(safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number)))
#print(tnp)
iit = to_float(td_get(trailer_data, "Ion Injection Time (ms)"))
if rt is None:
rt = to_float(safe_call(lambda: raw_parser.GetRetentionTimeFromScanNumber(scan_number)))
if est is None:
est = to_float(safe_call(lambda: raw_parser.GetElaspedScanTimeFromScanNumber(scan_number)))
if tic is None:
tic = to_float(safe_call(lambda: raw_parser.GetTICForScanNumber(scan_number)))
if tnp is None:
tnp = to_int(safe_call(lambda: raw_parser.GetNumPeaksForScanNumber(scan_number)))
# print(tnp)
if iit is None:
iit = to_float(safe_call(lambda: raw_parser.GetIonInjectionTimeFromScanNumber(scan_number)))
bp = safe_call(lambda: raw_parser.GetBasePeakForScanNumber(scan_number), None)
bp_mass = to_float(bp[0]) if isinstance(bp, (list, tuple)) and len(bp) >= 2 else 0.0
bp_int = to_float(bp[1]) if isinstance(bp, (list, tuple)) and len(bp) >= 2 else 0.0
plotly_vis.ms1_scans.append(scan_number)
plotly_vis.ms1_data["Scan Start Time (min)"].append(rt if rt is not None else 0.0)
plotly_vis.ms1_data["Elapsed Scan Time (sec)"].append(est or 0.0)
plotly_vis.ms1_data["Total Ion Current"].append(tic or 0.0)
plotly_vis.ms1_data["Total Number of Peaks"].append(tnp or 0)
plotly_vis.ms1_data["Base Peak m/z"].append(bp_mass or 0.0)
plotly_vis.ms1_data["Base Peak Intensity"].append(bp_int or 0.0)
plotly_vis.ms1_data["Ion Injection Time (ms)"].append(iit or 0.0)
if scan_number - last_ui >= 300:
last_ui = scan_number
self.progress.emit(int((scan_number / max(1, num_scans)) * 100))
self.log.emit(f"[INFO] MS1 scan header CSV: {csv_path}")
def _extract_technical_details(
self,
raw_parser,
out_dir: Path,
base: str,
ms_order: int,
):
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
ms_label = f"ms{ms_order}"
csv_path = out_dir / f"{base}_technical_details_{ms_label}_{ts}.csv"
rows = []
columns = ["Scan Number", "RAW File"]
seen_columns = set(columns)
num_scans = int(getattr(raw_parser, "NumSpectra", 0) or 0)
last_ui = 0
for scan_number in range(1, num_scans + 1):
if self.should_stop():
break
scan_ms_order = safe_call(lambda: int(raw_parser.GetMSOrder(scan_number)), 0)
if scan_ms_order != ms_order:
continue
info = safe_call(lambda: raw_parser.GetMoreMSInfos(scan_number), {}) or {}
if not isinstance(info, dict):
info = {}
row = {"Scan Number": scan_number, "RAW File": base}
for key, value in info.items():
if key in ("Scan Number", "RAW File"):
continue
if key not in seen_columns:
seen_columns.add(key)
columns.append(key)
row[key] = value
rows.append(row)
if scan_number - last_ui >= 300:
last_ui = scan_number
self.progress.emit(int((scan_number / max(1, num_scans)) * 100))
with open(csv_path, "w", newline="", encoding="utf-8", errors="replace") as f:
w = csv.writer(f)
w.writerow(columns)
for row in rows:
w.writerow([_tsv_safe(row.get(col, "N/A")) for col in columns])
self.log.emit(f"[INFO] MS{ms_order} technical details CSV: {csv_path}")
@Slot()
def run(self):
try:
all_ms1_tic = []
all_ms1_bpi = []
all_ms1_tnp = []
all_ms2_tic = []
all_ms2_tnp = []
all_ms2_prec = []
ms1_box_tic, ms1_box_bpi, ms1_box_tnp = {}, {}, {}
ms2_box_tic, ms2_box_bpi, ms2_box_tnp = {}, {}, {}
global_out = Path(self.output_dir_raw)
global_out.mkdir(parents=True, exist_ok=True)
cmp_set = set(self.cmp_files) if (self.multi_cmp and self.cmp_files) else None
for selected_file in self.selected_files:
if cmp_set is not None and selected_file not in cmp_set:
continue
if self.should_stop():
break
self.log.emit(f"[INFO] Processing: {selected_file}")
raw_parser = MetaXtract(selected_file)
self._current_raw_parser = raw_parser
base = os.path.splitext(os.path.basename(selected_file))[0]
out_dir = Path(self.output_dir_raw) / base
out_dir.mkdir(parents=True, exist_ok=True)
plotly_ms1 = PlotlyMS1Visualizer(base, str(out_dir)) if self.plotly_enabled else None
plotly_ms2 = PlotlyMS2Visualizer(base, str(out_dir)) if self.plotly_enabled else None
if self.plotly_enabled and not self.selected_header_options_ms2:
self.selected_header_options_ms2 = ["Scan Start Time (min)"]
if self.plotly_enabled and not self.selected_header_options_ms1:
self.selected_header_options_ms1 = ["Scan Start Time (min)"]
info_tsv_path = None
if "File-based Details" in self.selected_options:
info_tsv = out_dir / f"{base}_info_{datetime.now().strftime('%Y%m%d_%H%M%S')}.tsv"
write_info_tsv(raw_parser, info_tsv, should_stop=self.should_stop)
info_tsv_path = str(info_tsv)
self.log.emit(f"[INFO] Wrote: {info_tsv}")
# info_file = out_dir / f"{base}_info_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
# safe_call(lambda: raw_parser.CountMS2(), None)
# sample_information = safe_call(lambda: raw_parser.GetSampleInformation(), {}) or {}
# instrument_details = safe_call(lambda: raw_parser.GetInstrumentDetails(), {}) or {}
# with open(info_file, "w", encoding="utf-8", errors="replace") as f:
# f.write(f"- RAW File Name: {safe_call(lambda: raw_parser.GetRAWFileName(), 'N/A')}\n")
# f.write("- Instrument Details:\n")
# for k, v in instrument_details.items():
# f.write(f"{k}: {v}\n")
# f.write("\n")
# f.write(f"- User ID: {safe_call(lambda: raw_parser.GetUserID(), 'N/A')}\n")
# f.write(f"- File Creation Date: {safe_call(lambda: raw_parser.GetFileCreationDate(), 'N/A')}\n")
# f.write(f"- Instrument Name: {safe_call(lambda: raw_parser.GetInstrumentName(), 'N/A')}\n")
# f.write(f"- Number of MS2 Scans (centroid): {getattr(raw_parser, 'NumMS2Centroid', 'N/A')}\n")
# f.write(f"- Number of MS2 Scans (profile): {getattr(raw_parser, 'NumMS2Profile', 'N/A')}\n")
# f.write(f"- Number of MS1 Scans: {getattr(raw_parser, 'NumMS1', 'N/A')}\n")
# f.write(f"- Total Number of Scans: {getattr(raw_parser, 'NumSpectra', 'N/A')}\n")
# f.write(f"- Start Time: {getattr(raw_parser, 'StartTime', 'N/A')}\n")
# f.write(f"- End Time: {getattr(raw_parser, 'EndTime', 'N/A')}\n")
# f.write(f"- Lowest Mass: {getattr(raw_parser, 'LowMass', 'N/A')}\n")
# f.write(f"- Highest Mass: {getattr(raw_parser, 'HighMass', 'N/A')}\n")
# f.write(f"- Mass Resolution: {getattr(raw_parser, 'MassResolution', 'N/A')}\n")
# f.write(f"- Highest Integrated Intensity: {safe_call(lambda: raw_parser.GetMaxIntegratedIntensity(), 'N/A')}\n")
# f.write(f"- Highest Base Peak: {safe_call(lambda: raw_parser.GetHighestBasePeakOfRawFile(), 'N/A')}\n\n")
# f.write("Sample Information\n")
# for k, v in sample_information.items():
# f.write(f"{k}: {v}\n")
# self.log.emit(f"[INFO] Wrote: {info_file}")
if self.should_stop():
break
if "MS-Method" in self.selected_options:
ms_method_file = out_dir / f"{base}_MS_method_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(ms_method_file, "w", encoding="utf-8", errors="replace") as f:
f.write(f"{safe_call(lambda: raw_parser.GetMSMethod(), '')}\n")
self._remove_empty_lines(str(ms_method_file))
self.log.emit(f"[INFO] Wrote: {ms_method_file}")
if self.should_stop():
break
if "LC-Method" in self.selected_options:
lc_method_file = out_dir / f"{base}_LC_method_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
with open(lc_method_file, "w", encoding="utf-8", errors="replace") as f:
f.write(f"{safe_call(lambda: raw_parser.GetLCMethod(), '')}\n")
self._remove_empty_lines(str(lc_method_file))
self.log.emit(f"[INFO] Wrote: {lc_method_file}")
if self.should_stop():
break
if self.selected_header_options_ms2:
self._extract_ms2_scan_header(raw_parser, out_dir, self.selected_header_options_ms2, base, plotly_ms2)
if self.should_stop():
break
if self.ms2_technical_details_export:
self._extract_technical_details(raw_parser, out_dir, base, 2)
if self.should_stop():
break
if self.hdf5_export:
out_h5ad = out_dir / f"{base}_MS2.h5ad"
export_ms2_to_h5ad(raw_parser, out_h5ad, info_tsv_path=info_tsv_path, should_stop=self.should_stop)
self.log.emit(f"[INFO] Wrote: {out_h5ad}")
if self.should_stop():
break
if self.ms2_peaklist_export:
out_pq = out_dir / f"{base}_ms2_peaklist.parquet"
raw_parser.ExportPeakList(str(out_pq), should_stop=self.should_stop)
self.log.emit(f"[INFO] Wrote: {out_pq}")
if self.should_stop():
break
if self.ms1_peaklist_export:
out_pq = out_dir / f"{base}_ms1_peaklist.parquet"
raw_parser.ExportMS1PeakList(str(out_pq), should_stop=self.should_stop)
self.log.emit(f"[INFO] Wrote: {out_pq}")
if self.should_stop():
break
if self.selected_header_options_ms1:
self._extract_ms1_scan_header(raw_parser, out_dir, self.selected_header_options_ms1, base, plotly_ms1)
if self.should_stop():
break
if self.ms1_technical_details_export:
self._extract_technical_details(raw_parser, out_dir, base, 1)
if self.should_stop():
break
self._write_plotly(plotly_ms1, plotly_ms2)
if self.should_stop():
break
if plotly_ms1 is not None:
ms1_box_tic[base] = list(plotly_ms1.ms1_data.get("Total Ion Current", []))
ms1_box_bpi[base] = list(plotly_ms1.ms1_data.get("Base Peak Intensity", []))
ms1_box_tnp[base] = list(plotly_ms1.ms1_data.get("Total Number of Peaks", []))
if plotly_ms2 is not None:
ms2_box_tic[base] = list(plotly_ms2.ms2_data.get("Total Ion Current", []))
ms2_box_tnp[base] = list(plotly_ms2.ms2_data.get("Total Number of Peaks", []))
ms2_box_bpi[base] = list(plotly_ms2.ms2_data.get("Base Peak Intensity", []))
if plotly_ms1 is not None:
x, y = plotly_ms1.tic_trace()
all_ms1_tic.append((base, x, y))
x, y = plotly_ms1.bpi_trace()
all_ms1_bpi.append((base, x, y))
x, y = plotly_ms1.tnp_trace()
all_ms1_tnp.append((base, x, y))
if plotly_ms2 is not None:
x, y = plotly_ms2.tic_trace()
all_ms2_tic.append((base, x, y))
x, y = plotly_ms2.tnp_trace()
all_ms2_tnp.append((base, x, y))
x, y = plotly_ms2.prec_trace()
all_ms2_prec.append((base, x, y))
safe_call(lambda: raw_parser.CloseRAWFile(), None)
self._current_raw_parser = None
self.progress.emit(100)
self.log.emit(f"[INFO] Finished: {selected_file}\n")
if self.should_stop():
self._close_current_raw_file()
self.log.emit("[INFO] Processing stopped.")
if not self.should_stop() and self.plotly_enabled and len(all_ms1_tic) >= 2:
out = global_out / "MS1_compare.html"
write_comparison_html_with_boxplots(
out,
"MS1 Comparison",
overlay_panels=[
("Overlay TIC (MS1)", "TIC", all_ms1_tic),
("Overlay BPI (MS1)", "BPI", all_ms1_bpi),
("Overlay Total Peaks (MS1)", "Total Peaks", all_ms1_tnp),
],
box_panels=[
("MS1 TIC Boxplot (across samples)", "log10(TIC+1)", ms1_box_tic, True),
("MS1 BPI Boxplot (across samples)", "log10(BPI+1)", ms1_box_bpi, True),
("MS1 TNP Boxplot (across samples)", "Total Peaks", ms1_box_tnp, False),
],
)
self.log.emit(f"[VIS] MS1 comparison: {out}")
if not self.should_stop() and self.plotly_enabled and len(all_ms2_tic) >= 2:
out = global_out / "MS2_compare.html"
write_comparison_html_with_boxplots(
out,
"MS2 Comparison",
overlay_panels=[
("Overlay TIC (MS2)", "TIC", all_ms2_tic),
("Overlay Total Peaks (MS2)", "Total Peaks", all_ms2_tnp),
("Overlay Selected Ion Intensity (MS2)", "Selected Ion Intensity", all_ms2_prec),
],
box_panels=[
("MS2 TIC Boxplot (across samples)", "log10(TIC+1)", ms2_box_tic, True),
("MS2 TNP Boxplot (across samples)", "Total Peaks", ms2_box_tnp, False),
("MS2 BPI Boxplot (across samples)", "log10(BPI+1)", ms2_box_bpi, True),
],
)
self.log.emit(f"[VIS] MS2 comparison: {out}")
self.finished.emit()
except InterruptedError:
self._close_current_raw_file()
self.log.emit("[INFO] Processing stopped.")
self.finished.emit()
except Exception as e:
self._close_current_raw_file()
#self.failed.emit(str(e))
tb = traceback.format_exc()
try:
self.log.emit(tb)
except Exception:
pass
self.failed.emit(f"{e}\n\n{tb}")
class TwoFilePickerDialog(QDialog):
def __init__(self, files: list[str], parent=None):
super().__init__(parent)
self.setWindowTitle("Select 2 files to compare")
self.setMinimumSize(760, 420)
self._files = files
self.selected: list[str] = []
lay = QVBoxLayout(self)
lay.addWidget(QLabel("Pick exactly 2 files:", self))
self.listw = QListWidget(self)
self.listw.setSelectionMode(QListWidget.MultiSelection)
for fp in files:
it = QListWidgetItem(fp)
self.listw.addItem(it)
lay.addWidget(self.listw, 1)
btns = QHBoxLayout()
btn_cancel = QPushButton("Cancel", self)
btn_ok = QPushButton("OK", self)
btns.addStretch(1)
btns.addWidget(btn_cancel)
btns.addWidget(btn_ok)
lay.addLayout(btns)
btn_cancel.clicked.connect(self.reject)
btn_ok.clicked.connect(self._accept_checked)
def _accept_checked(self):
picked = [it.text() for it in self.listw.selectedItems()]
if len(picked) != 2:
QMessageBox.critical(self, "Error", "Select exactly 2 files.")
return
self.selected = picked
self.accept()
class MetaXtract_GUI(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("MetaXtract")
self.setMinimumSize(1020, 760)
self._thread: QThread | None = None
self._worker: _ExtractionWorker | None = None
self.selected_files: list[str] = []
self.setStyleSheet( #https://doc.qt.io/qt-6/stylesheet-examples.html
"""
QMainWindow { background: #0f1115; }
QLabel, QCheckBox { color: #e9eef5; font-size: 12px; }
QLineEdit {
background: #161a22; color: #e9eef5; border: 1px solid #2a3242;
border-radius: 10px; padding: 7px 10px;
}
QPushButton {
background: #7a001a; color: #ffffff; border: 1px solid #a00023;
border-radius: 12px; padding: 9px 14px; font-weight: 700;
}
QPushButton:hover { background: #920020; }
QPushButton:disabled { background: #2a3242; border: 1px solid #2a3242; color: #8fa0b6; }
QGroupBox {
border: 1px solid #2a3242; border-radius: 14px; margin-top: 10px;
padding: 10px;
}
QGroupBox::title {
subcontrol-origin: margin;
left: 12px;
padding: 0 6px;
color: #ffffff;
font-weight: 900;
}
QProgressBar {
border: 1px solid #2a3242; border-radius: 10px;
text-align: center; color: #e9eef5; background: #161a22; height: 18px;
}
QProgressBar::chunk { background: #7a001a; border-radius: 10px; }
QScrollArea { border: none; background: transparent; }
QScrollArea QWidget { background: transparent; }
QScrollArea QWidget#qt_scrollarea_viewport { background: #0b0d12; border-radius: 12px; }
QGroupBox { background: #0b0d12; }
QCheckBox { spacing: 10px; }
QCheckBox::indicator { width: 16px; height: 16px; }
QCheckBox::indicator:unchecked { border: 1px solid #2a3242; background: #161a22; border-radius: 4px; }
QCheckBox::indicator:checked { border: 1px solid #a00023; background: #7a001a; border-radius: 4px; }
QTextEdit {
background: #0b0d12; color: #e9eef5; border: 1px solid #2a3242;
border-radius: 12px; padding: 8px;
}
"""
)
root = QWidget(self)
self.setCentralWidget(root)
main = QVBoxLayout(root)
main.setContentsMargins(16, 16, 16, 16)
main.setSpacing(12)
gb_io = QGroupBox("Inputs", self)
io = QVBoxLayout(gb_io)
r1 = QHBoxLayout()
self.file_field = QLineEdit(self)
self.file_field.setReadOnly(True)
btn_files = QPushButton("Select RAW files", self)
btn_files.clicked.connect(self.select_files)
r1.addWidget(QLabel("RAW files", self))
r1.addWidget(self.file_field, 1)
r1.addWidget(btn_files)
io.addLayout(r1)
r2 = QHBoxLayout()
self.output_field = QLineEdit(self)
btn_out = QPushButton("Select output dir", self)
btn_out.clicked.connect(self.select_output_dir)
r2.addWidget(QLabel("Output dir", self))
r2.addWidget(self.output_field, 1)
r2.addWidget(btn_out)
io.addLayout(r2)
main.addWidget(gb_io)
gb_opt = QGroupBox("Outputs", self)
opt = QVBoxLayout(gb_opt)
self.cb_file_details = QCheckBox("File-based Details", self)
self.cb_ms_method = QCheckBox("MS-Method", self)
self.cb_lc_method = QCheckBox("LC-Method", self)
self.cb_plotly = QCheckBox("Visualisations", self)
self.cb_ms2_peaklist = QCheckBox("Export MS2 extended peak list (parquet)", self)
self.cb_ms1_peaklist = QCheckBox("Export MS1 peak list (parquet)", self)
self.cb_ms2_technical_details = QCheckBox("Export MS2 technical details", self)
self.cb_ms1_technical_details = QCheckBox("Export MS1 technical details", self)