-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.v8.py
More file actions
executable file
·2553 lines (2117 loc) · 116 KB
/
parse.v8.py
File metadata and controls
executable file
·2553 lines (2117 loc) · 116 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 dataclasses
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Optional, Set, Tuple, Any, Final
from contextlib import contextmanager
import psycopg2 # Postgresql adapter
from psycopg2.extensions import connection as PGConnection # Postgresql adapter
from psycopg2.extras import RealDictCursor # Postgresql adapter
from urllib.parse import urlparse # For parsing host string
import argparse # Needed to parse arguments
import sys # Needed for ErrorJSON
import os # Needed for pathjoin and path/create dirs
import h5py # Needed for parsing hdf5 files
import json # For writing output files
import numpy as np # For diverse array calculations
import re # Regex for gene to db comparison
from pathlib import Path # Needed for file extension manipulation
from collections import Counter # To count categories occurrences
import scipy.sparse as sp # For handling sparse matrices
import polars as pl # For fast-reading text matrices (csv, tsv, ...)
import rpy2.robjects as ro # For reading RDS files
from rpy2.robjects.packages import importr # For reading RDS files
from rpy2.robjects import pandas2ri
import pandas as pd # For handling dataframes (especially used with RDS files)
## Constants
# For defining variable as categorical (arbitrary thresholds)
CATEGORICAL_NMIN: Final[int] = 10 # Less than 10 unique values = categorical
CATEGORICAL_NMAX: Final[int] = 500 # More than 500 unique values = non-categorical
CATEGORICAL_PC_UNIQUE: Final[float] = 0.10 # Else, categorical only if unique values < 10% of all values
DEFAULT_BLOCK_CELLS: Final[int] = 1024 # For reading in chunks
LOOM_FILENAME: Final[str] = "output.loom" # Output LOOM file name
LOOM_CHUNK_GENES: Final[int] = 1024 # Output LOOM chunked policy (rows)
LOOM_CHUNK_CELLS: Final[int] = 1024 # Output LOOM chunked policy (cols)
LOOM_COMPRESSION: Final[str] = "gzip" # Output LOOM compression
LOOM_COMPRESSION_LEVEL: Final[int] = 4 # Output LOOM compression level
LOOM_DTYPE: Final[str] = "float32" # Output LOOM numeric format
DEFAULT_DB_PORT: Final[int] = 5432 # Default DB port for PostgreSQL
DEFAULT_CONNECT_TIMEOUT: Final[int] = 10 # Default DB connection timeout for PostgreSQL
DEFAULT_RIBO_GO_TERM: Final[str] = "GO:0003735" # GO Term used for inferring ribo genes for QC
DEFAULT_TEXT_DELIM: Final[str] = "\t" # For TextHandler, default delim
DEFAULT_NP_DTYPE = np.float64 # Keeping internal best precision
## Format Handlers
# Helper
def _is_compound_dataset(node: h5py.HLObject) -> bool:
return isinstance(node, h5py.Dataset) and node.dtype.fields is not None
class H5ADHandler:
@staticmethod
def get_size(f: h5py.File, path: str) -> tuple[int, int]:
node = f[path]
shape = node.attrs.get("shape", None)
if shape is None:
shape = node.attrs.get("h5sparse_shape", None)
if shape is not None:
return tuple(int(x) for x in shape)
if isinstance(node, h5py.Dataset):
return tuple(int(x) for x in node.shape)
if isinstance(node, h5py.Group) and all(k in node for k in ("data", "indices", "indptr")):
enc = node.attrs.get("encoding-type", "csr_matrix")
if isinstance(enc, bytes): enc = enc.decode()
enc = str(enc)
major = int(node["indptr"].shape[0] - 1)
max_idx = int(np.max(node["indices"][:])) if int(node["indices"].shape[0]) else -1
minor = int(max_idx + 1) if max_idx >= 0 else 0
if enc == "csr_matrix":
return (major, minor) # (cells, genes)
if enc == "csc_matrix":
return (minor, major) # (genes, cells) - swapped because H5AD CSC has genes as columns
ErrorJSON(f"Unsupported encoding-type={enc!r} at {path}")
ErrorJSON(f"Could not determine shape for {path}")
@staticmethod
def extract_index(f: h5py.File, path: str) -> list[str]:
node = f[path]
if isinstance(node, h5py.Group):
raw = node.attrs.get("_index", "index")
index_col_name = raw.decode() if isinstance(raw, bytes) else raw
full_path = f"{path.rstrip('/')}/{index_col_name.lstrip('/')}"
if full_path not in f:
full_path = f"{path.rstrip('/')}/_index"
return [v.decode() if isinstance(v, bytes) else str(v) for v in f[full_path][:]]
if _is_compound_dataset(node):
raw = node.attrs.get("_index", None)
index_field = raw.decode() if isinstance(raw, bytes) else raw
candidates = ([index_field] if index_field else []) + ["_index", "index", "obs_names", "var_names"]
for c in candidates:
if c in (node.dtype.names or ()):
vals = node[c]
if getattr(vals, "dtype", None) is not None and vals.dtype.kind in ("S", "O", "U"):
return [v.decode() if isinstance(v, (bytes, np.bytes_)) else str(v) for v in vals]
return [str(v) for v in vals]
ErrorJSON(f"Could not find index field in compound table {path}.")
ErrorJSON(f"Unsupported obs/var node at {path}")
@staticmethod
def _table_columns(f, table_path: str):
"""Extract column names from obs/var table."""
if table_path not in f:
return []
node = f[table_path]
if isinstance(node, h5py.Group):
cols = node.attrs.get('_column_names', list(node.keys()))
if isinstance(cols, np.ndarray):
cols = cols.tolist()
return cols
elif _is_compound_dataset(node):
return list(node.dtype.names or [])
else:
return []
@staticmethod
def _find_categories_for_column(f, table_path: str, col: str):
"""
Returns list[str] categories if found, else None.
Looks in old-style __categories, cat, raw/cat, and uns locations.
"""
candidates = []
# Categories attached to table
candidates.append(f"{table_path.rstrip('/')}/__categories/{col}")
candidates.append(f"{table_path.rstrip('/')}/cat/{col}")
# Raw-specific category store
if table_path.startswith("raw/") or table_path.startswith("/raw/"):
candidates.append("raw/cat/" + col)
candidates.append("/raw/cat/" + col)
# Top-level /cat
candidates.append("cat/" + col)
candidates.append("/cat/" + col)
for p in candidates:
if p in f and isinstance(f[p], h5py.Dataset):
cats = f[p][:]
return [v.decode() if isinstance(v, (bytes, np.bytes_)) else str(v) for v in cats]
# Fallback: categories stored in uns as "<col>_categories"
for p in (f"uns/{col}_categories", f"/uns/{col}_categories"):
if p in f and isinstance(f[p], h5py.Dataset):
cats = f[p][:]
return [v.decode() if isinstance(v, (bytes, np.bytes_)) else str(v) for v in cats]
return None
@staticmethod
def _decode_enum_if_needed(item: h5py.Dataset) -> np.ndarray | None:
"""If dataset is H5T_ENUM, decode integer codes to string labels. Returns None if not enum."""
enum_dict = h5py.check_enum_dtype(item.dtype)
if enum_dict is None:
return None
# Invert {label: code} -> {code: label}
code_to_label = {v: k for k, v in enum_dict.items()}
codes = item[:]
return np.array([code_to_label.get(int(c), "nan") for c in codes.flat], dtype=object).reshape(codes.shape)
@staticmethod
def _detect_sparse_encoding(node: h5py.Group, n_cells: int, n_genes: int) -> str:
enc = node.attrs.get("encoding-type", None)
if isinstance(enc, bytes): enc = enc.decode()
enc = str(enc) if enc is not None else None
indptr_len = int(node["indptr"].shape[0])
if indptr_len == n_cells + 1: inferred = "csr_matrix"
elif indptr_len == n_genes + 1: inferred = "csc_matrix"
else:
ErrorJSON(f"Cannot infer sparse encoding: len(indptr)={indptr_len}, expected {n_cells+1} or {n_genes+1}")
return inferred
@staticmethod
def _create_h5ad_block_reader(f: h5py.File, src_path: str, n_cells: int, n_genes: int):
"""
Creates a block reader function for H5AD matrices.
Returns: get_block(start, end) -> ndarray(cells x genes)
"""
node = f[src_path]
is_sparse = isinstance(node, h5py.Group) and all(k in node for k in ("data", "indices", "indptr"))
is_dense = isinstance(node, h5py.Dataset)
if not (is_sparse or is_dense):
ErrorJSON(f"Unsupported matrix layout at {src_path}")
if is_dense:
def get_block(start, end): return node[start:end, :] # cells x genes
return get_block
# Detect sparse encoding
enc = H5ADHandler._detect_sparse_encoding(node, n_cells, n_genes)
if enc == "csr_matrix":
# Hybrid loading - pre-load pointers, lazy-load data
indptr_full = node["indptr"][:] # Small array (~200 KB)
ds_indices = node["indices"] # Keep as HDF5 reference (lazy)
ds_data = node["data"] # Keep as HDF5 reference (lazy)
def get_block(start, end):
ptr = indptr_full[start:end + 1].astype(np.int64)
p0, p1 = int(ptr[0]), int(ptr[-1])
# Empty block optimization
if p0 == p1: return sp.csr_matrix((end - start, n_genes), dtype=DEFAULT_NP_DTYPE)
# Load only needed data from disk
indptr_local = (ptr - p0).astype(np.int64, copy=False)
block_indices = ds_indices[p0:p1]
block_data = ds_data[p0:p1]
# Return sparse CSR directly (no .toarray())
return sp.csr_matrix((block_data.astype(DEFAULT_NP_DTYPE, copy=False), block_indices.astype(np.int64, copy=False), indptr_local), shape=(end - start, n_genes))
return get_block
elif enc == "csc_matrix":
# CSC: Loading entire matrix and converting to CSR...
X_csc = sp.csc_matrix((node["data"][:], node["indices"][:], node["indptr"][:]), shape=(n_cells, n_genes), dtype=DEFAULT_NP_DTYPE)
csr_view = X_csc.tocsr()
def get_block(start, end):
# Extract rows (cells) start:end from the CSR view
return csr_view[start:end, :]
return get_block
else:
ErrorJSON(f"Unsupported sparse encoding: {enc}")
@staticmethod
def _transfer_metadata(f, group_path, loom, result, n_cells, n_genes, orientation, existing_paths):
"""
Transfer obs (CELL) or var (GENE) metadata from H5AD to Loom.
Handles categorical decoding (codes→categories).
"""
if group_path not in f:
return
cols = H5ADHandler._table_columns(f, group_path)
if not cols:
return
# Skip these internal columns
skip_cols = {"_index", "categories", "codes", "__categories", "cat"}
# Identify index column name if available
node = f[group_path]
index_col = None
if isinstance(node, h5py.Group):
index_col = node.attrs.get('_index', '_index')
if isinstance(index_col, bytes):
index_col = index_col.decode()
for col in cols:
if col in skip_cols or (index_col and col == index_col):
continue
loom_path = f"/{'col' if orientation == 'CELL' else 'row'}_attrs/{col}"
if loom_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {group_path}/{col} -> {loom_path} transfer: already exists.")
continue
values = None
# ---- CASE 1: Group-based column ----
if isinstance(node, h5py.Group):
item = node[col]
# New-style categorical group: {categories, codes}
if isinstance(item, h5py.Group) and 'categories' in item and 'codes' in item:
cats = [v.decode() if isinstance(v, bytes) else str(v) for v in item['categories'][:]]
codes = item['codes'][:]
values = np.array([cats[c] if c != -1 else "nan" for c in codes], dtype=object)
# Old-style categorical: codes in dataset, categories elsewhere
elif isinstance(item, h5py.Dataset) and np.issubdtype(item.dtype, np.integer):
cats = H5ADHandler._find_categories_for_column(f, group_path, col)
if cats is not None:
codes = item[:]
def map_code(c):
if c == -1: return "nan"
c = int(c)
return cats[c] if 0 <= c < len(cats) else "nan"
values = np.array([map_code(c) for c in codes], dtype=object)
else:
values = item[:]
else:
decoded = H5ADHandler._decode_enum_if_needed(item)
if decoded is not None:
values = decoded
else:
raw_values = item[:]
if raw_values.dtype.kind in ('S', 'U', 'O'):
values = np.array([v.decode() if isinstance(v, bytes) else str(v) for v in raw_values], dtype=object)
else:
values = raw_values
# ---- CASE 2: Compound dataset ----
else:
raw_values = node[col]
# If integer codes and categories exist, decode them
if np.issubdtype(np.array(raw_values).dtype, np.integer):
cats = H5ADHandler._find_categories_for_column(f, group_path, col)
if cats is not None:
def map_code(c):
if c == -1: return "nan"
c = int(c)
return cats[c] if 0 <= c < len(cats) else "nan"
values = np.array([map_code(c) for c in raw_values], dtype=object)
else:
values = raw_values
else:
if np.array(raw_values).dtype.kind in ('S', 'U', 'O'):
values = np.array([v.decode() if isinstance(v, (bytes, np.bytes_)) else str(v) for v in raw_values], dtype=object)
else:
values = raw_values
if values is None:
continue
# ASAP.jar ExtractMetadata does not handle boolean metadata arrays reliably.
# Normalize booleans to string categories so they behave like standard discrete metadata.
values_array = np.asarray(values)
if np.issubdtype(values_array.dtype, np.bool_):
values = np.where(values_array, "True", "False").astype(object)
# Dimension check
expected_len = n_cells if orientation == "CELL" else n_genes
if len(values) != expected_len:
entity = "cells" if orientation == "CELL" else "genes"
result.setdefault("warnings", []).append(f"Skipping {col} from {group_path}: length mismatch. Expected {expected_len} {entity}, but found {len(values)}.")
continue
# Write using LoomFile's write_metadata
meta = loom.write_metadata(values, loom_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(loom_path)
@staticmethod
def _transfer_multidimensional_metadata(f, group_path, loom, result, n_cells, n_genes, orientation, existing_paths):
"""
Transfer obsm (CELL) or varm (GENE) multidimensional matrices.
Examples: PCA, UMAP, tSNE embeddings.
"""
if group_path not in f:
return
group = f[group_path]
if not isinstance(group, h5py.Group):
return
prefix = "col" if orientation == "CELL" else "row"
for key in group.keys():
loom_path = f"/{prefix}_attrs/{key}"
if loom_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {group_path}/{key} -> {loom_path} transfer: already exists.")
continue
try:
item = group[key]
if not isinstance(item, h5py.Dataset):
result.setdefault("warnings", []).append(f"Skipping {group_path}/{key}: not a dataset.")
continue
# Dimension check
expected_n = n_cells if orientation == "CELL" else n_genes
actual_shape = item.shape
if actual_shape[0] != expected_n:
result.setdefault("warnings", []).append(f"Skipping {group_path}/{key}: dimension mismatch. Expected {expected_n} {orientation.lower()}s, but found {actual_shape[0]}.")
continue
# Handle compound datasets
if _is_compound_dataset(item):
H5ADHandler._write_compound_and_register(item, loom, result, n_cells, n_genes, orientation, loom_path, existing_paths)
continue
# Normal multidim write
data = item[:]
meta = loom.write_metadata(data, loom_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(loom_path)
except Exception as e:
result.setdefault("warnings", []).append(f"Could not transfer {group_path}/{key}: {str(e)}")
@staticmethod
def _transfer_layers(f, loom, result, n_cells, n_genes, existing_paths, input_group):
"""
Transfer H5AD /layers/* and alternative main matrices to Loom /layers.
"""
# 1. Transfer explicit /layers/* (spliced/unspliced, normalized, etc.)
if "/layers" in f:
for layer_name in f["/layers"].keys():
layer_path = f"/layers/{layer_name}"
dest_path = f"/layers/{layer_name}"
if dest_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {layer_path} -> {dest_path} transfer: already exists.")
continue
try:
l_cells, l_genes = H5ADHandler.get_size(f, layer_path)
if l_cells != n_cells or l_genes != n_genes:
result.setdefault("warnings", []).append(f"Skipping layer {layer_name}: dimension mismatch (expected {n_cells}x{n_genes}, found {l_cells}x{l_genes})")
continue
# Write layer without heavy stats (gene_metadata=None)
block_reader = H5ADHandler._create_h5ad_block_reader(f=f, src_path=layer_path, n_cells=n_cells, n_genes=n_genes)
layer_stats = loom.write_expression_matrix(get_block=block_reader, n_cells=n_cells, n_genes=n_genes, gene_metadata=None, dest_path=dest_path)
# Register metadata
meta = Metadata(name=dest_path, on="EXPRESSION_MATRIX", type="NUMERIC", nber_rows=n_genes, nber_cols=n_cells, dataset_size=loom.get_dataset_size(dest_path), nber_zeros=layer_stats["total_zeros"], is_count_table=layer_stats["is_count_table"], imported=1)
result["metadata"].append(meta)
existing_paths.add(dest_path)
except Exception as e:
result.setdefault("warnings", []).append(f"Failed to transfer layer {layer_name}: {str(e)}")
# 2. Transfer alternative main matrices to /layers
# (e.g., if /X was selected as primary, save /raw/X and /raw.X as layers)
candidates = ["/X", "/raw/X", "/raw.X"]
for candidate in candidates:
# Skip if not present or is the primary matrix
if candidate not in f or candidate == input_group:
continue
try:
c_cells, c_genes = H5ADHandler.get_size(f, candidate)
if c_cells != n_cells or c_genes != n_genes:
result.setdefault("warnings", []).append(f"Skipping alternative matrix {candidate}: dimension mismatch (expected {n_cells}x{n_genes}, found {c_cells}x{c_genes})")
continue
# Create safe layer name (e.g., "/raw/X" → "raw_X")
layer_name = candidate.strip("/").replace("/", "_")
dest_path = f"/layers/{layer_name}"
if dest_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {candidate} -> {dest_path} transfer: already exists.")
continue
# Write alternative matrix as a layer without heavy stats (gene_metadata=None)
block_reader = H5ADHandler._create_h5ad_block_reader(f=f, src_path=candidate, n_cells=n_cells, n_genes=n_genes)
alt_stats = loom.write_expression_matrix(get_block=block_reader, n_cells=n_cells, n_genes=n_genes, gene_metadata=None, dest_path=dest_path)
# Register metadata
meta = Metadata(name=dest_path, on="EXPRESSION_MATRIX", type="NUMERIC", nber_rows=n_genes, nber_cols=n_cells, dataset_size=loom.get_dataset_size(dest_path), nber_zeros=alt_stats["total_zeros"], is_count_table=alt_stats["is_count_table"], imported=1)
result["metadata"].append(meta)
existing_paths.add(dest_path)
except Exception as e:
result.setdefault("warnings", []).append(f"Could not transfer alternative matrix {candidate}: {str(e)}")
@staticmethod
def _transfer_unstructured_metadata(f, loom, result, n_cells, n_genes, existing_paths):
"""
Transfer uns (unstructured global metadata) from H5AD to Loom /attrs.
Skips categorical lookup tables (*_categories, *_levels, *_codes).
"""
if "uns" not in f:
return
def should_skip_uns_key(key: str) -> bool:
"""Skip categorical lookup tables."""
k = key.lower()
return k.endswith("_categories") or k.endswith("_levels") or k.endswith("_codes")
def walk(group, prefix=""):
for key in group.keys():
item = group[key]
attr_name = f"{prefix}{key}"
if should_skip_uns_key(attr_name):
continue
loom_path = f"/attrs/{attr_name}"
if isinstance(item, h5py.Group):
walk(item, prefix=f"{attr_name}_")
continue
if not isinstance(item, h5py.Dataset):
continue
if loom_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping /uns/{attr_name} -> {loom_path} transfer: already exists.")
continue
# Handle compound datasets
if _is_compound_dataset(item):
H5ADHandler._write_compound_and_register(item, loom, result, n_cells, n_genes, "GLOBAL", loom_path, existing_paths)
continue
try:
decoded = H5ADHandler._decode_enum_if_needed(item)
if decoded is not None:
val = decoded
else:
val = item[()]
if isinstance(val, (bytes, np.bytes_)):
val = val.decode("utf-8")
elif isinstance(val, np.ndarray) and val.dtype.kind in ("S", "U"):
val = np.array([v.decode("utf-8") if isinstance(v, bytes) else str(v) for v in val.flatten()]).reshape(val.shape)
meta = loom.write_metadata(val, loom_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(loom_path)
except Exception as e:
result.setdefault("warnings", []).append(f"Skipping uns item {attr_name}: {str(e)}")
walk(f["uns"])
@staticmethod
def _write_compound_and_register(src_obj: h5py.Dataset, loom, result: dict, n_cells: int, n_genes: int, orientation: str, loom_path: str, existing_paths: set[str]) -> None:
"""Write a compound/structured HDF5 dataset into Loom as a regular (non-compound) dataset.
- If the compound dtype has 1 field, writes it as a 1D vector.
- If it has multiple fields, writes it as a 2D matrix (n_rows × n_fields).
"""
if loom_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {src_obj.name} -> {loom_path} transfer: already exists.")
return
try:
fields = list(src_obj.dtype.names or [])
if not fields:
result.setdefault("warnings", []).append(f"Skipping compound dataset {loom_path}: no fields.")
return
data = src_obj[()] # structured ndarray (possibly >1D)
arr = np.asarray(data)
data_flat = arr.reshape(-1) if arr.ndim > 1 else arr
n_rows = int(data_flat.shape[0])
def field_is_numeric(fname: str) -> bool:
dt = src_obj.dtype.fields[fname][0]
return np.issubdtype(dt, np.number) or np.issubdtype(dt, np.bool_)
all_numeric = all(field_is_numeric(f) for f in fields)
if len(fields) == 1:
col = np.asarray(data_flat[fields[0]]).reshape(-1)
if col.dtype.kind in ("S", "O", "U"):
col = np.array([v.decode(errors="ignore") if isinstance(v, (bytes, np.bytes_)) else str(v) for v in col], dtype=object)
meta = loom.write_metadata(col, loom_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(loom_path)
return
if all_numeric:
mat = np.empty((n_rows, len(fields)), dtype=DEFAULT_NP_DTYPE)
for j, f_ in enumerate(fields):
mat[:, j] = np.asarray(data_flat[f_], dtype=DEFAULT_NP_DTYPE)
else:
mat = np.empty((n_rows, len(fields)), dtype=object)
for j, f_ in enumerate(fields):
col = np.asarray(data_flat[f_]).reshape(-1)
mat[:, j] = [v.decode(errors="ignore") if isinstance(v, (bytes, np.bytes_)) else str(v) for v in col]
meta = loom.write_metadata(mat, loom_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(loom_path)
except Exception as e:
result.setdefault("warnings", []).append(f"Could not write compound dataset {loom_path}: {e}")
@staticmethod
def parse(args, file_path: str, out_dir: Path, gene_db: MapGene, loom, result):
with h5py.File(file_path, "r") as f:
if args.sel is not None:
if args.sel not in f:
ErrorJSON(f"--sel path {args.sel!r} not found")
input_group = args.sel
else:
candidates = ["/X", "/raw/X", "/raw.X"]
matches = [g for g in candidates if g in f]
if len(matches) == 0:
ErrorJSON(f"No candidate matrix found in {candidates}. Provide --sel.")
if len(matches) > 1:
ErrorJSON(f"Multiple candidate matrices found {matches}. Provide --sel.")
input_group = matches[0]
result["input_group"] = input_group
n_cells, n_genes = H5ADHandler.get_size(f, input_group)
result["nber_cols"] = int(n_cells)
result["nber_rows"] = int(n_genes)
var_path = "/var"
obs_path = "/obs"
obsm_path = "/obsm"
varm_path = "/varm"
if input_group == "/raw.X":
var_path = "/raw.var" if "/raw.var" in f else var_path
obs_path = "/raw.obs" if "/raw.obs" in f else obs_path
obsm_path = "/raw.obsm" if "/raw.obsm" in f else obsm_path
varm_path = "/raw.varm" if "/raw.varm" in f else varm_path
elif input_group == "/raw/X":
var_path = "/raw/var" if "/raw/var" in f else var_path
obs_path = "/raw/obs" if "/raw/obs" in f else obs_path
obsm_path = "/raw/obsm" if "/raw/obsm" in f else obsm_path
varm_path = "/raw/varm" if "/raw/varm" in f else varm_path
gene_names = H5ADHandler.extract_index(f, var_path)
cell_ids = H5ADHandler.extract_index(f, obs_path)
parsed_genes, _ = loom.write_names_and_gene_db(cell_ids=cell_ids, original_gene_names=gene_names, gene_db=gene_db, output_dir=out_dir, result=result, n_cells=n_cells, n_genes=n_genes)
# Write Expression Matrix
block_reader = H5ADHandler._create_h5ad_block_reader(f=f, src_path=input_group, n_cells=n_cells, n_genes=n_genes)
stats = loom.write_expression_matrix(get_block=block_reader, n_cells=n_cells, n_genes=n_genes, gene_metadata=parsed_genes, dest_path="/matrix")
## Transfer Metadata
existing_paths = (input_group | {m.name for m in result["metadata"]} | LoomFile._reserved_paths())
# Transfer OBS (Cells)
H5ADHandler._transfer_metadata(f, obs_path, loom, result, n_cells, n_genes, "CELL", existing_paths)
if obs_path != "/obs":
H5ADHandler._transfer_metadata(f, "/obs", loom, result, n_cells, n_genes, "CELL", existing_paths) # Because I still want to copy everything from there if correct size.
# Transfer VAR (Genes)
H5ADHandler._transfer_metadata(f, var_path, loom, result, n_cells, n_genes, "GENE", existing_paths)
if var_path != "/var":
H5ADHandler._transfer_metadata(f, "/var", loom, result, n_cells, n_genes, "GENE", existing_paths) # Because I still want to copy everything from there if correct size.
# Transfer OBSM (Cell Embeddings)
H5ADHandler._transfer_multidimensional_metadata(f, obsm_path, loom, result, n_cells, n_genes, "CELL", existing_paths)
if obsm_path != "/obsm":
H5ADHandler._transfer_multidimensional_metadata(f, "/obsm", loom, result, n_cells, n_genes, "CELL", existing_paths) # Because I still want to copy everything from there if correct size.
# Transfer VARM (Gene Embeddings)
H5ADHandler._transfer_multidimensional_metadata(f, varm_path, loom, result, n_cells, n_genes, "GENE", existing_paths)
if varm_path != "/varm":
H5ADHandler._transfer_multidimensional_metadata(f, "/varm", loom, result, n_cells, n_genes, "GENE", existing_paths) # Because I still want to copy everything from there if correct size.
# Transfer uns (unstructured global metadata)
H5ADHandler._transfer_unstructured_metadata(f, loom, result, n_cells, n_genes, existing_paths)
# Transfer Layers + Alternative matrices like 'spliced'/'unspliced' or 'transformed'
H5ADHandler._transfer_layers(f, loom, result, n_cells, n_genes, existing_paths, input_group)
return stats
class LoomHandler:
@staticmethod
def _find_first_existing(f: h5py.File, paths: list[str]) -> str | None:
for p in paths:
if p in f:
return p
return None
@staticmethod
def _as_str_list(arr) -> list[str]:
"""
Convert HDF5 array to list of strings, handling bytes/numpy types.
Used for reading cell IDs and gene names from Loom files.
"""
flat = arr.ravel() if isinstance(arr, np.ndarray) else arr
out = []
for v in flat:
if isinstance(v, (bytes, np.bytes_, np.void)):
out.append(v.decode(errors="ignore"))
else:
out.append(str(v))
return out
@staticmethod
def _infer_cell_ids(f: h5py.File, n_cells: int) -> list[str]:
candidates = [
"/col_attrs/CellID", "/col_attrs/cell_id", "/col_attrs/cell_ids",
"/col_attrs/barcode", "/col_attrs/barcodes", "/col_attrs/Barcode",
"/col_attrs/obs_names", "/col_attrs/index", "/col_attrs/_index",
]
p = LoomHandler._find_first_existing(f, candidates)
if p and isinstance(f[p], h5py.Dataset):
vals = f[p][:]
cell_ids = LoomHandler._as_str_list(vals)
if len(cell_ids) == n_cells:
return cell_ids
return [f"Cell_{i+1}" for i in range(n_cells)]
@staticmethod
def _infer_gene_names(f: h5py.File, n_genes: int) -> list[str]:
"""
Per-gene fallback across multiple candidate row_attrs vectors:
for each gene i, take the first non-empty value from the ordered candidates.
If all candidates are empty/missing for a gene, fall back to "Gene_{i+1}".
"""
candidates = [
"/row_attrs/Accession", "/row_attrs/Name", "/row_attrs/Gene", "/row_attrs/Original_Gene",
"/row_attrs/gene", "/row_attrs/gene_name", "/row_attrs/var_names",
"/row_attrs/index", "/row_attrs/_index",
]
# Load all usable candidate vectors (must exist, be dataset, and have correct length)
loaded: list[tuple[str, list[str]]] = []
for p in candidates:
if p in f and isinstance(f[p], h5py.Dataset):
try:
vals = f[p][:]
vec = LoomHandler._as_str_list(vals)
except Exception:
continue
if len(vec) == n_genes:
loaded.append((p, vec))
if not loaded:
return [f"Gene_{i+1}" for i in range(n_genes)]
def is_empty(s: str) -> bool:
if s is None:
return True
ss = str(s).strip()
return (ss == "" or ss.lower() in {"nan", "null", "0"})
# Per-gene fallback: first non-empty across loaded candidates
out: list[str] = []
for i in range(n_genes):
chosen = None
for p, vec in loaded:
v = vec[i]
if not is_empty(v):
chosen = str(v).strip()
break
if chosen is None:
out.append(f"Gene_{i+1}")
else:
out.append(chosen)
return out
@staticmethod
def _create_loom_block_reader(f: h5py.File, src_path: str, n_cells: int, n_genes: int):
"""
Creates a block reader for Loom matrices.
Returns: get_block(start, end) -> ndarray(cells x genes)
"""
node = f[src_path]
if not isinstance(node, h5py.Dataset):
ErrorJSON(f"Unsupported Loom matrix layout at {src_path}: expected dataset")
if tuple(node.shape) != (n_genes, n_cells):
ErrorJSON(f"Matrix dimension mismatch at {src_path}: expected {(n_genes, n_cells)}, got {tuple(node.shape)}")
def get_block(start, end):
block_gxc = np.array(node[:, start:end], copy=False) # genes x cells
return block_gxc.T # cells x genes
return get_block
@staticmethod
def _transfer_other_datasets(src_f: h5py.File, loom: LoomFile, result: dict, n_cells: int, n_genes: int, existing_paths: set[str]):
"""
Transfer all other datasets from source Loom file to output Loom file.
"""
skip_prefixes = ("/matrix",)
def should_skip(full_path: str) -> bool:
if full_path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {full_path} -> {full_path} transfer: already exists.")
return True
for spx in skip_prefixes:
if full_path == spx or full_path.startswith(spx + "/"):
return True
return False
def write_compound_as_regular(obj: h5py.Dataset, full_path: str) -> None:
fields = list(obj.dtype.names or [])
if not fields:
result["warnings"].append(f"Skipping compound dataset {full_path}: no fields.")
return
data = obj[:] # structured ndarray
data_flat = data.reshape(-1) if data.ndim > 1 else data
n_rows = int(data_flat.shape[0])
def field_is_numeric(fname: str) -> bool:
dt = obj.dtype.fields[fname][0]
return np.issubdtype(dt, np.number) or np.issubdtype(dt, np.bool_)
all_numeric = all(field_is_numeric(f) for f in fields)
if len(fields) == 1:
col = np.asarray(data_flat[fields[0]]).reshape(-1)
if col.dtype.kind in ("S", "O", "U"):
col = np.array([v.decode(errors="ignore") if isinstance(v, (bytes, np.bytes_)) else str(v) for v in col], dtype=object)
meta = loom.write_metadata(col, full_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(full_path)
return
if all_numeric:
mat = np.empty((n_rows, len(fields)), dtype=DEFAULT_NP_DTYPE)
for j, f_ in enumerate(fields):
mat[:, j] = np.asarray(data_flat[f_], dtype=DEFAULT_NP_DTYPE)
else:
mat = np.empty((n_rows, len(fields)), dtype=object)
for j, f_ in enumerate(fields):
col = np.asarray(data_flat[f_]).reshape(-1)
mat[:, j] = [v.decode(errors="ignore") if isinstance(v, (bytes, np.bytes_)) else str(v) for v in col]
meta = loom.write_metadata(mat, full_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(full_path)
def visitor(name: str, obj):
full_path = "/" + name if not name.startswith("/") else name
if not isinstance(obj, h5py.Dataset):
return
if should_skip(full_path):
return
try:
if _is_compound_dataset(obj):
write_compound_as_regular(obj, full_path)
return
val = obj[()]
meta = loom.write_metadata(val, full_path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)
existing_paths.add(full_path)
except Exception as e:
result["warnings"].append(f"Could not copy dataset {full_path}: {e}")
src_f.visititems(visitor)
@staticmethod
def parse(args, file_path: str, out_dir: Path, gene_db: MapGene, loom, result):
with h5py.File(file_path, "r") as f:
matrix_path = args.sel or LoomHandler._find_first_existing(f, ["/matrix"])
if not matrix_path or matrix_path not in f:
ErrorJSON("Could not find Loom main matrix. Provide --sel or ensure /matrix exists.")
node = f[matrix_path]
if not isinstance(node, h5py.Dataset) or len(node.shape) != 2:
ErrorJSON(f"Unsupported Loom main matrix at {matrix_path}")
n_genes, n_cells = int(node.shape[0]), int(node.shape[1])
result["nber_rows"] = n_genes
result["nber_cols"] = n_cells
result["input_group"] = matrix_path
cell_ids = LoomHandler._infer_cell_ids(f, n_cells)
gene_names = LoomHandler._infer_gene_names(f, n_genes)
parsed_genes, _ = loom.write_names_and_gene_db(cell_ids=cell_ids, original_gene_names=gene_names, gene_db=gene_db, output_dir=out_dir, result=result, n_cells=n_cells, n_genes=n_genes)
block_reader = LoomHandler._create_loom_block_reader(f=f, src_path=matrix_path, n_cells=n_cells, n_genes=n_genes)
stats = loom.write_expression_matrix(get_block=block_reader, n_cells=n_cells, n_genes=n_genes, gene_metadata=parsed_genes, dest_path="/matrix")
## Transfer Metadata
existing_paths = ({m.name for m in result["metadata"]} | LoomFile._reserved_paths())
LoomHandler._transfer_other_datasets(src_f=f, loom=loom, result=result, n_cells=n_cells, n_genes=n_genes, existing_paths=existing_paths)
return stats
class H510xHandler:
@staticmethod
def _find_10x_groups(f: h5py.File) -> list[str]:
out = []
for key in f.keys():
if isinstance(f[key], h5py.Group):
grp = f[key]
if {"barcodes", "data", "indices", "indptr", "shape"}.issubset(grp.keys()):
out.append(key)
return out
@staticmethod
def _pick_group(f: h5py.File, sel: str | None) -> str:
candidates = H510xHandler._find_10x_groups(f)
if sel is not None:
if sel in f and isinstance(f[sel], h5py.Group):
grp = f[sel]
if {"barcodes", "data", "indices", "indptr", "shape"}.issubset(grp.keys()):
return sel
ErrorJSON(f"--sel {sel!r} is not a valid 10x group.")
ErrorJSON(f"--sel {sel!r} not found.")
if len(candidates) == 0:
ErrorJSON("No valid 10x matrix group found.")
if len(candidates) > 1:
ErrorJSON(f"Multiple 10x groups found: {candidates}. Use --sel.")
return candidates[0]
@staticmethod
def _decode_list(arr) -> list[str]:
out = []
for v in arr:
if isinstance(v, (bytes, np.bytes_, np.void)):
try:
out.append(v.decode(errors="ignore"))
except Exception:
out.append(str(v))
else:
out.append(str(v))
return out
@staticmethod
def _read_feature_names(grp: h5py.Group, n_genes: int) -> list[str]:
if "gene_names" in grp:
vec = H510xHandler._decode_list(grp["gene_names"][:])
return (vec + [f"Gene_{i+1}" for i in range(len(vec), n_genes)])[:n_genes]
if "genes" in grp:
vec = H510xHandler._decode_list(grp["genes"][:])
return (vec + [f"Gene_{i+1}" for i in range(len(vec), n_genes)])[:n_genes]
if "features" in grp and isinstance(grp["features"], h5py.Group):
fg = grp["features"]
if "name" in fg:
vec = H510xHandler._decode_list(fg["name"][:])
elif "id" in fg:
vec = H510xHandler._decode_list(fg["id"][:])
else:
vec = []
return (vec + [f"Gene_{i+1}" for i in range(len(vec), n_genes)])[:n_genes]
return [f"Gene_{i+1}" for i in range(n_genes)]
@staticmethod
def _create_10x_block_reader(grp: h5py.Group, n_cells: int, n_genes: int):
"""
Creates a block reader for 10x CSC sparse matrices.
Returns: get_block(start, end) -> ndarray(cells x genes)
"""
for k in ("data", "indices", "indptr", "shape"):
if k not in grp:
ErrorJSON(f"10x group missing '{k}'")
shape = tuple(int(x) for x in grp["shape"][:])
if shape != (n_genes, n_cells):
ErrorJSON(f"10x shape mismatch: expected {(n_genes, n_cells)}, got {shape}")
# Hybrid loading - pre-load pointers, lazy-load data
indptr_full = grp["indptr"][:] # Small array (~200 KB)
ds_indices = grp["indices"] # Keep as HDF5 reference (lazy)
ds_data = grp["data"] # Keep as HDF5 reference (lazy)
if int(indptr_full.shape[0]) != n_cells + 1: ErrorJSON("Unexpected 10x indptr length (expected CSC with columns=cells).")
def get_block(start, end):
ptr = indptr_full[start:end + 1]
ptr0, ptrN = int(ptr[0]), int(ptr[-1])
# Empty block optimization
if ptr0 == ptrN: return sp.csr_matrix((end - start, n_genes), dtype=DEFAULT_NP_DTYPE)
# Calculate relative pointers for CSR construction
indptr_local = (ptr - ptr0).astype(np.int64, copy=False)
# Load only the data/indices required for this block from HDF5
block_indices = ds_indices[ptr0:ptrN]
block_data = ds_data[ptr0:ptrN]
# Return sparse CSR directly (no .toarray(), no transpose)
# Note: 10x is stored as CSC (genes × cells), we build CSR (cells × genes)
return sp.csr_matrix((block_data.astype(DEFAULT_NP_DTYPE, copy=False), block_indices.astype(np.int64, copy=False), indptr_local), shape=(end - start, n_genes))
return get_block
@staticmethod
def _transfer_10x_feature_extras(grp: h5py.Group, loom, result: dict, n_genes: int, n_cells: int, existing_paths: set[str]):
"""
Write extra 10x features/* vectors into /row_attrs/<key>.
"""
if "features" not in grp: return
fg = grp["features"]
# Make sure it's a group (not a dataset)
if not hasattr(fg, "keys"): return
for k in fg.keys():
if k in {"name", "id"}: continue
node = fg[k]
if not hasattr(node, "shape"): continue # only datasets
# must be feature-length vector
try:
if len(node.shape) != 1 or node.shape[0] != n_genes:
continue
except Exception:
continue
path = f"/row_attrs/{k}"
if path in existing_paths:
result.setdefault("warnings", []).append(f"Skipping {grp}/features/{node} -> {path} transfer: already exists.")
continue
try:
arr = node[:]
except Exception:
continue
if hasattr(arr, "dtype") and arr.dtype.kind in ("S", "O", "U"):
arr = np.array([v.decode(errors="ignore") if isinstance(v, (bytes, np.bytes_)) else str(v) for v in arr], dtype=object)
meta = loom.write_metadata(arr, path, n_cells=n_cells, n_genes=n_genes, imported=1)
result["metadata"].append(meta)