|
18 | 18 | infer_obs_schema, |
19 | 19 | list_obs_columns_from_file, |
20 | 20 | list_obs_columns_from_group, |
| 21 | + preload_complex_obs_fields, |
21 | 22 | ) |
22 | 23 |
|
23 | 24 | app = typer.Typer(help="Extract metadata fields from h5ad AnnData files") |
24 | 25 |
|
25 | 26 |
|
| 27 | +MAX_LOG_VALUE_LENGTH = 200 |
| 28 | +MAX_SAMPLE_ROWS = 5 |
| 29 | +MAX_NESTED_ITEMS = 8 |
| 30 | + |
| 31 | + |
| 32 | +def _coerce_all_null_object_columns( |
| 33 | + df: pl.DataFrame, |
| 34 | + obs_schema: dict[str, pl.DataType] |
| 35 | +) -> pl.DataFrame: |
| 36 | + if not df.columns: |
| 37 | + return df |
| 38 | + replacements: list[pl.Expr] = [] |
| 39 | + for column_name, dtype in df.schema.items(): |
| 40 | + if dtype != pl.Object: |
| 41 | + continue |
| 42 | + if column_name not in obs_schema: |
| 43 | + continue |
| 44 | + series = df[column_name] |
| 45 | + if series.is_null().all(): |
| 46 | + target_dtype = obs_schema[column_name] |
| 47 | + replacements.append(pl.lit(None, dtype=target_dtype).alias(column_name)) |
| 48 | + if not replacements: |
| 49 | + return df |
| 50 | + return df.with_columns(replacements) |
| 51 | + |
| 52 | + |
| 53 | +def _truncate_for_log(value: str) -> str: |
| 54 | + if len(value) <= MAX_LOG_VALUE_LENGTH: |
| 55 | + return value |
| 56 | + return f"{value[:MAX_LOG_VALUE_LENGTH]}...[truncated]" |
| 57 | + |
| 58 | + |
| 59 | +def _safe_serialize_for_log(value: Any, *, max_items: int = MAX_NESTED_ITEMS) -> Any: |
| 60 | + if value is None: |
| 61 | + return None |
| 62 | + if isinstance(value, (bool, int, float)): |
| 63 | + return value |
| 64 | + if isinstance(value, str): |
| 65 | + return _truncate_for_log(value) |
| 66 | + if isinstance(value, (bytes, bytearray)): |
| 67 | + decoded = value.decode("utf-8", errors="replace") |
| 68 | + return _truncate_for_log(decoded) |
| 69 | + if isinstance(value, dict): |
| 70 | + limited_items = list(value.items())[:max_items] |
| 71 | + return { |
| 72 | + str(k): _safe_serialize_for_log(v, max_items=max_items) |
| 73 | + for k, v in limited_items |
| 74 | + } |
| 75 | + if isinstance(value, (list, tuple, set)): |
| 76 | + limited_values = list(value)[:max_items] |
| 77 | + return [_safe_serialize_for_log(v, max_items=max_items) for v in limited_values] |
| 78 | + if hasattr(value, "tolist"): |
| 79 | + try: |
| 80 | + data_list = value.tolist() |
| 81 | + return _safe_serialize_for_log(data_list, max_items=max_items) |
| 82 | + except Exception: |
| 83 | + pass |
| 84 | + if hasattr(value, "item"): |
| 85 | + try: |
| 86 | + return value.item() |
| 87 | + except Exception: |
| 88 | + pass |
| 89 | + representation = repr(value) |
| 90 | + return _truncate_for_log(representation) |
| 91 | + |
| 92 | + |
| 93 | +def _collect_sample_rows(df: pl.DataFrame, max_rows: int = MAX_SAMPLE_ROWS) -> list[dict[str, Any]]: |
| 94 | + if df.height == 0: |
| 95 | + return [] |
| 96 | + sample_rows: list[dict[str, Any]] = [] |
| 97 | + for row in df.head(max_rows).iter_rows(named=True): |
| 98 | + serialized_row = {column: _safe_serialize_for_log(value) for column, value in row.items()} |
| 99 | + sample_rows.append(serialized_row) |
| 100 | + return sample_rows |
| 101 | + |
| 102 | + |
26 | 103 | def extract_fields_from_h5ad( |
27 | 104 | h5ad_path: Path, |
28 | 105 | fields: Optional[list[str]], |
@@ -63,6 +140,15 @@ def extract_fields_from_h5ad( |
63 | 140 | obs_schema = infer_obs_schema(obs_group) |
64 | 141 | string_fields = {col for col, dtype in obs_schema.items() if dtype == pl.String} |
65 | 142 | requested_fields = fields if fields is not None else obs_columns |
| 143 | + preloaded_fields = preload_complex_obs_fields( |
| 144 | + obs_group=obs_group, |
| 145 | + fields=[field for field in requested_fields if field in obs_columns] |
| 146 | + ) |
| 147 | + if preloaded_fields: |
| 148 | + action.log( |
| 149 | + message_type="preloaded_complex_obs_fields", |
| 150 | + fields=list(preloaded_fields.keys()) |
| 151 | + ) |
66 | 152 |
|
67 | 153 | action.log( |
68 | 154 | message_type="h5ad_loaded", |
@@ -109,55 +195,85 @@ def extract_fields_from_h5ad( |
109 | 195 | start_idx = chunk_idx * chunk_size |
110 | 196 | end_idx = min(start_idx + chunk_size, n_cells) |
111 | 197 |
|
112 | | - chunk_df = build_obs_chunk_dataframe( |
113 | | - obs_group=obs_group, |
114 | | - fields=valid_fields, |
115 | | - start_idx=start_idx, |
116 | | - end_idx=end_idx, |
117 | | - categorical_cache=categorical_cache, |
118 | | - string_fields=string_fields, |
119 | | - string_fill_value=None |
120 | | - ) |
| 198 | + chunk_df: pl.DataFrame | None = None |
| 199 | + chunk_columns: list[str] = [] |
121 | 200 |
|
122 | | - cast_exprs = [ |
123 | | - pl.col(col).cast(dtype, strict=False) |
124 | | - for col, dtype in obs_schema.items() |
125 | | - if col in chunk_df.columns |
126 | | - ] |
127 | | - if cast_exprs: |
128 | | - chunk_df = chunk_df.with_columns(cast_exprs) |
129 | | - fill_exprs = [ |
130 | | - pl.col(col).fill_null("nan") |
131 | | - for col, dtype in obs_schema.items() |
132 | | - if dtype == pl.String and col in chunk_df.columns |
133 | | - ] |
134 | | - if fill_exprs: |
135 | | - chunk_df = chunk_df.with_columns(fill_exprs) |
136 | | - |
137 | | - if extract_age: |
138 | | - chunk_df = extract_age_columns( |
139 | | - chunk_df, |
140 | | - development_stage_col=age_source_col |
| 201 | + try: |
| 202 | + chunk_df = build_obs_chunk_dataframe( |
| 203 | + obs_group=obs_group, |
| 204 | + fields=valid_fields, |
| 205 | + start_idx=start_idx, |
| 206 | + end_idx=end_idx, |
| 207 | + categorical_cache=categorical_cache, |
| 208 | + string_fields=string_fields, |
| 209 | + string_fill_value=None, |
| 210 | + preloaded_fields=preloaded_fields |
141 | 211 | ) |
142 | | - |
143 | | - # Write chunk to temp file |
144 | | - chunk_file = temp_dir / f"chunk_{chunk_idx:04d}.parquet" |
145 | | - chunk_df.write_parquet( |
146 | | - chunk_file, |
147 | | - compression=compression, |
148 | | - compression_level=compression_level, |
149 | | - use_pyarrow=use_pyarrow |
150 | | - ) |
151 | | - |
152 | | - # Clean up chunk data immediately |
153 | | - del chunk_df |
154 | | - |
155 | | - chunk_action.log( |
156 | | - message_type="chunk_processed", |
157 | | - rows=end_idx - start_idx, |
158 | | - start_idx=start_idx, |
159 | | - end_idx=end_idx |
160 | | - ) |
| 212 | + chunk_df = _coerce_all_null_object_columns(chunk_df, obs_schema) |
| 213 | + |
| 214 | + chunk_columns = list(chunk_df.columns) |
| 215 | + |
| 216 | + cast_exprs = [ |
| 217 | + pl.col(col).cast(dtype, strict=False) |
| 218 | + for col, dtype in obs_schema.items() |
| 219 | + if col in chunk_columns |
| 220 | + ] |
| 221 | + if cast_exprs: |
| 222 | + chunk_df = chunk_df.with_columns(cast_exprs) |
| 223 | + fill_exprs = [ |
| 224 | + pl.col(col).fill_null("nan") |
| 225 | + for col, dtype in obs_schema.items() |
| 226 | + if dtype == pl.String and col in chunk_columns |
| 227 | + ] |
| 228 | + if fill_exprs: |
| 229 | + chunk_df = chunk_df.with_columns(fill_exprs) |
| 230 | + |
| 231 | + if extract_age: |
| 232 | + chunk_df = extract_age_columns( |
| 233 | + chunk_df, |
| 234 | + development_stage_col=age_source_col |
| 235 | + ) |
| 236 | + |
| 237 | + # Write chunk to temp file |
| 238 | + chunk_file = temp_dir / f"chunk_{chunk_idx:04d}.parquet" |
| 239 | + chunk_df.write_parquet( |
| 240 | + chunk_file, |
| 241 | + compression=compression, |
| 242 | + compression_level=compression_level, |
| 243 | + use_pyarrow=use_pyarrow |
| 244 | + ) |
| 245 | + |
| 246 | + chunk_action.log( |
| 247 | + message_type="chunk_processed", |
| 248 | + rows=end_idx - start_idx, |
| 249 | + start_idx=start_idx, |
| 250 | + end_idx=end_idx |
| 251 | + ) |
| 252 | + |
| 253 | + chunk_df = None |
| 254 | + except Exception as exc: |
| 255 | + sample_rows: list[dict[str, Any]] = [] |
| 256 | + if chunk_df is not None: |
| 257 | + try: |
| 258 | + sample_rows = _collect_sample_rows(chunk_df) |
| 259 | + except Exception as sample_exc: |
| 260 | + sample_rows = [ |
| 261 | + { |
| 262 | + "_error": f"Failed to serialize sample rows: {sample_exc}" |
| 263 | + } |
| 264 | + ] |
| 265 | + chunk_action.log( |
| 266 | + message_type="chunk_failure_sample", |
| 267 | + error=str(exc), |
| 268 | + start_idx=start_idx, |
| 269 | + end_idx=end_idx, |
| 270 | + columns=chunk_columns, |
| 271 | + sample_rows=sample_rows |
| 272 | + ) |
| 273 | + raise |
| 274 | + finally: |
| 275 | + if chunk_df is not None: |
| 276 | + del chunk_df |
161 | 277 |
|
162 | 278 | # Read all chunks lazily without materializing full dataset |
163 | 279 | action.log(message_type="building_lazy_dataframe", n_chunks=n_chunks) |
|
0 commit comments