Skip to content

Integrations API

AnnData and Scanpy integration modules.

AnnData Integration

slaf.integrations.anndata

Classes

LazyExpressionMatrix

Bases: LazySparseMixin

Lazy expression matrix backed by SLAF with scipy.sparse interface.

LazyExpressionMatrix provides a scipy.sparse-compatible interface for accessing single-cell expression data stored in SLAF format. It implements lazy evaluation to avoid loading all data into memory, making it suitable for large datasets.

Key Features
  • scipy.sparse-compatible interface
  • Lazy evaluation for memory efficiency
  • Caching for repeated queries
  • Support for cell and gene subsetting
  • Integration with AnnData objects

Examples:

>>> # Basic usage
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> lazy_matrix = LazyExpressionMatrix(slaf_array)
>>> print(f"Matrix shape: {lazy_matrix.shape}")
Matrix shape: (1000, 20000)
>>> # With AnnData integration
>>> adata = LazyAnnData(slaf_array)
>>> matrix = adata.X
>>> print(f"Expression matrix shape: {matrix.shape}")
Expression matrix shape: (1000, 20000)
>>> # Subsetting operations
>>> subset_matrix = matrix[:100, :5000]  # First 100 cells, first 5000 genes
>>> print(f"Subset shape: {subset_matrix.shape}")
Subset shape: (100, 5000)
Source code in slaf/integrations/anndata.py
 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
class LazyExpressionMatrix(LazySparseMixin):
    """
    Lazy expression matrix backed by SLAF with scipy.sparse interface.

    LazyExpressionMatrix provides a scipy.sparse-compatible interface for accessing
    single-cell expression data stored in SLAF format. It implements lazy evaluation
    to avoid loading all data into memory, making it suitable for large datasets.

    Key Features:
        - scipy.sparse-compatible interface
        - Lazy evaluation for memory efficiency
        - Caching for repeated queries
        - Support for cell and gene subsetting
        - Integration with AnnData objects

    Examples:
        >>> # Basic usage
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> lazy_matrix = LazyExpressionMatrix(slaf_array)
        >>> print(f"Matrix shape: {lazy_matrix.shape}")
        Matrix shape: (1000, 20000)

        >>> # With AnnData integration
        >>> adata = LazyAnnData(slaf_array)
        >>> matrix = adata.X
        >>> print(f"Expression matrix shape: {matrix.shape}")
        Expression matrix shape: (1000, 20000)

        >>> # Subsetting operations
        >>> subset_matrix = matrix[:100, :5000]  # First 100 cells, first 5000 genes
        >>> print(f"Subset shape: {subset_matrix.shape}")
        Subset shape: (100, 5000)
    """

    def __init__(self, slaf_array: SLAFArray):
        """
        Initialize lazy expression matrix with SLAF array.

        Args:
            slaf_array: SLAFArray instance containing the single-cell data.
                       Used for database queries and metadata access.

        Examples:
            >>> # Basic initialization
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> matrix = LazyExpressionMatrix(slaf_array)
            >>> print(f"Initialized with shape: {matrix.shape}")
            Initialized with shape: (1000, 20000)

            >>> # Check parent reference
            >>> print(f"Parent adata: {matrix.parent_adata}")
            Parent adata: None
        """
        super().__init__()
        self.slaf_array = slaf_array
        self.parent_adata: LazyAnnData | None = None
        # Store slicing selectors
        self._cell_selector: Any = None
        self._gene_selector: Any = None
        # Initialize shape attribute (required by LazySparseMixin)
        self._shape = self.slaf_array.shape
        self._cache: dict[str, Any] = {}  # Simple caching for repeated queries

    @property
    def shape(self) -> tuple[int, int]:
        """
        Shape of the expression matrix.

        Returns:
            Tuple of (n_cells, n_genes) representing the matrix dimensions.

        Examples:
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> matrix = LazyExpressionMatrix(slaf_array)
            >>> print(f"Matrix shape: {matrix.shape}")
            Matrix shape: (1000, 20000)
        """
        return self._shape

    @property
    def obs_names(self) -> pd.Index | None:
        """
        Cell names (observations).

        Returns:
            pandas.Index of cell names if parent AnnData is available, None otherwise.

        Examples:
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> matrix = adata.X
            >>> print(f"Cell names: {len(matrix.obs_names)}")
            Cell names: 1000
        """
        if hasattr(self, "parent_adata") and self.parent_adata is not None:
            return self.parent_adata.obs_names
        return None

    @property
    def var_names(self) -> pd.Index | None:
        """
        Gene names (variables).

        Returns:
            pandas.Index of gene names if parent AnnData is available, None otherwise.

        Examples:
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> matrix = adata.X
            >>> print(f"Gene names: {len(matrix.var_names)}")
            Gene names: 20000
        """
        if hasattr(self, "parent_adata") and self.parent_adata is not None:
            return self.parent_adata.var_names
        return None

    def _update_shape(self):
        """Update the shape attribute based on current selectors"""
        if self._cell_selector is not None or self._gene_selector is not None:
            # Calculate the shape based on selectors
            cell_selector = (
                self._cell_selector if self._cell_selector is not None else slice(None)
            )
            gene_selector = (
                self._gene_selector if self._gene_selector is not None else slice(None)
            )

            # Use the same logic as _get_result_shape in LazySparseMixin
            cell_selector = self._compose_selectors(cell_selector, None, axis=0)
            gene_selector = self._compose_selectors(gene_selector, None, axis=1)

            n_cells = self._calculate_selected_count(cell_selector, axis=0)
            n_genes = self._calculate_selected_count(gene_selector, axis=1)

            self._shape = (n_cells, n_genes)
        else:
            # No selectors applied, return original shape
            self._shape = self.slaf_array.shape

    def _calculate_selected_count(self, selector, axis: int) -> int:
        """Calculate the number of selected entities for a given selector"""
        if selector is None or (
            isinstance(selector, slice) and selector == slice(None)
        ):
            return self.slaf_array.shape[axis]

        if isinstance(selector, slice):
            start = selector.start or 0
            stop = selector.stop or self.slaf_array.shape[axis]
            step = selector.step or 1

            # Clamp bounds to actual data size
            start = max(0, min(start, self.slaf_array.shape[axis]))
            stop = max(0, min(stop, self.slaf_array.shape[axis]))

            return len(range(start, stop, step))
        elif isinstance(selector, list | np.ndarray):
            if isinstance(selector, np.ndarray) and selector.dtype == bool:
                return np.sum(selector)
            return len(selector)
        elif isinstance(selector, int | np.integer):
            return 1
        else:
            return self.slaf_array.shape[axis]

    def __getitem__(self, key) -> "LazyExpressionMatrix":
        """
        Lazy slicing - returns a new LazyExpressionMatrix with composed selectors
        No computation happens until .compute() is called
        """
        cell_selector, gene_selector = self._parse_key(key)

        # Handle selectors directly as integer indices
        # For slices, lists, ints - these are already relative to the current view
        # We need to compose them with existing selectors

        # Create a new LazyExpressionMatrix with composed selectors
        new_matrix = LazyExpressionMatrix(self.slaf_array)
        new_matrix.parent_adata = self.parent_adata

        # Compose selectors (these are relative to current view)
        new_matrix._cell_selector = self._compose_selectors(
            self._cell_selector, cell_selector, axis=0
        )
        new_matrix._gene_selector = self._compose_selectors(
            self._gene_selector, gene_selector, axis=1
        )

        # Update shape based on new selectors
        new_matrix._update_shape()

        return new_matrix

    def _compose_selectors(self, old, new, axis):
        """Compose two selectors (helper method)"""
        if old is None:
            return new
        if new is None or (isinstance(new, slice) and new == slice(None)):
            return old

        # If old is a slice, we need to apply new to the range defined by old
        if isinstance(old, slice):
            # Get the range from the old slice
            old_start = old.start or 0
            old_stop = old.stop or self.slaf_array.shape[axis]
            old_step = old.step or 1

            # Handle negative indices in old slice
            if old_start < 0:
                old_start = self.slaf_array.shape[axis] + old_start
            if old_stop < 0:
                old_stop = self.slaf_array.shape[axis] + old_stop

            # Clamp old slice bounds
            old_start = max(0, min(old_start, self.slaf_array.shape[axis]))
            old_stop = max(0, min(old_stop, self.slaf_array.shape[axis]))

            # Create the range from the old slice
            old_range = list(range(old_start, old_stop, old_step))

            # Now apply the new selector to this range
            if isinstance(new, slice):
                # Apply new slice to the old range
                new_start = new.start or 0
                new_stop = new.stop or len(old_range)
                new_step = new.step or 1

                # Handle negative indices in new slice
                if new_start < 0:
                    new_start = len(old_range) + new_start
                if new_stop < 0:
                    new_stop = len(old_range) + new_stop

                # Clamp new slice bounds
                new_start = max(0, min(new_start, len(old_range)))
                new_stop = max(0, min(new_stop, len(old_range)))

                # Apply the new slice to the old range
                result_indices = old_range[new_start:new_stop:new_step]
                return result_indices
            elif isinstance(new, int | np.integer):
                # Single index into the old range
                if 0 <= new < len(old_range):
                    return [old_range[new]]
                else:
                    return []
            elif isinstance(new, list | np.ndarray):
                # List of indices into the old range
                result = []
                for idx in new:
                    if 0 <= idx < len(old_range):
                        result.append(old_range[idx])
                return result
            else:
                return new

        # If old is a list of indices, apply new to those indices
        elif isinstance(old, list | np.ndarray):
            if isinstance(new, slice):
                # Apply slice to the old list
                new_start = new.start or 0
                new_stop = new.stop or len(old)
                new_step = new.step or 1

                # Handle negative indices
                if new_start < 0:
                    new_start = len(old) + new_start
                if new_stop < 0:
                    new_stop = len(old) + new_stop

                # Clamp bounds
                new_start = max(0, min(new_start, len(old)))
                new_stop = max(0, min(new_stop, len(old)))

                return old[new_start:new_stop:new_step]
            elif isinstance(new, int | np.integer):
                # Single index into the old list
                if 0 <= new < len(old):
                    return [old[new]]
                else:
                    return []
            elif isinstance(new, list | np.ndarray):
                # List of indices into the old list
                result = []
                for idx in new:
                    if 0 <= idx < len(old):
                        result.append(old[idx])
                return result
            else:
                return new

        # For other cases, return the new selector as fallback
        return new

    def _estimate_slice_size(self, cell_selector, gene_selector) -> int:
        """Estimate the size of the slice for strategy selection"""
        cell_count = self._estimate_selected_count(cell_selector, axis=0)
        gene_count = self._estimate_selected_count(gene_selector, axis=1)
        return cell_count * gene_count

    def _apply_transformations(
        self,
        matrix: scipy.sparse.csr_matrix,
        cell_selector,
        gene_selector,
    ) -> scipy.sparse.csr_matrix:
        """Apply any stored transformations to the matrix"""
        # Get transformations from the parent LazyAnnData if available
        if self.parent_adata is not None and hasattr(
            self.parent_adata, "_transformations"
        ):
            transformations = self.parent_adata._transformations
        else:
            return matrix

        # Avoid copying if no transformations
        if not transformations:
            return matrix

        # Try to apply transformations at SQL level first
        sql_transformed = self._apply_sql_transformations(
            cell_selector, gene_selector, transformations
        )

        if sql_transformed is not None:
            # SQL transformations were applied, reconstruct matrix
            return self._reconstruct_sparse_matrix(
                sql_transformed, cell_selector, gene_selector
            )

        # Fall back to numpy transformations
        return self._apply_numpy_transformations(
            matrix, cell_selector, gene_selector, transformations
        )

    def _apply_sql_transformations(
        self, cell_selector, gene_selector, transformations
    ) -> pd.DataFrame | None:
        """Apply transformations at SQL level when possible"""
        # Check if we can apply all transformations in SQL
        sql_applicable = []
        numpy_needed = []

        for transform_name, transform_data in transformations.items():
            if transform_name == "normalize_total":
                # normalize_total can be applied in SQL
                sql_applicable.append((transform_name, transform_data))
            elif transform_name == "log1p":
                # log1p can be applied in SQL
                sql_applicable.append((transform_name, transform_data))
            else:
                # Unknown transformation, needs numpy
                numpy_needed.append((transform_name, transform_data))

        # If we have numpy-only transformations, don't use SQL
        if numpy_needed:
            return None

        # Build SQL query with transformations
        # Convert list of tuples to dictionary for _build_transformed_query
        sql_transformations = dict(sql_applicable)
        query = self._build_transformed_query(
            cell_selector, gene_selector, sql_transformations
        )

        try:
            # Execute the transformed query
            return self.slaf_array.query(query)
        except Exception:
            # If SQL transformation fails, fall back to numpy
            return None

    def _build_transformed_query(
        self, cell_selector, gene_selector, transformations
    ) -> str:
        """Build SQL query with transformations applied"""
        # Build base SQL query string
        base_query = self._build_submatrix_sql(cell_selector, gene_selector)

        # Apply transformations in order
        transformed_query = base_query
        for transform_name, transform_data in transformations.items():
            if transform_name == "normalize_total":
                transformed_query = self._apply_sql_normalize_total(
                    transformed_query, transform_data
                )
            elif transform_name == "log1p":
                transformed_query = self._apply_sql_log1p(transformed_query)

        return transformed_query

    def _build_submatrix_sql(self, cell_selector, gene_selector) -> str:
        """Build SQL query string for submatrix selection"""
        # Use the QueryOptimizer to build the SQL string
        from slaf.core.query_optimizer import QueryOptimizer

        return QueryOptimizer.build_submatrix_query(
            cell_selector=cell_selector,
            gene_selector=gene_selector,
            cell_count=self.slaf_array.shape[0],  # Use original dataset dimensions
            gene_count=self.slaf_array.shape[1],  # Use original dataset dimensions
        )

    def _apply_sql_normalize_total(self, query: str, transform_data: dict) -> str:
        """Apply normalize_total transformation in SQL"""
        cell_factors = transform_data["cell_factors"]
        # target_sum = transform_data["target_sum"]  # Removed unused variable

        # Create a CASE statement for cell factors
        case_statements = []
        for cell_id, factor in cell_factors.items():
            # Convert scientific notation to regular decimal format for SQL compatibility
            factor_str = (
                f"{factor:.10f}".rstrip("0").rstrip(".") if factor != 0 else "0"
            )

            # Handle both integer and string cell IDs
            if isinstance(cell_id, str) and cell_id.startswith("cell_"):
                # Extract integer from string like "cell_0" -> 0
                try:
                    cell_integer_id_int = int(cell_id.split("_")[1])
                except (ValueError, IndexError):
                    # Fallback: skip this cell if we can't parse it
                    continue
            elif isinstance(cell_id, int | np.integer):
                cell_integer_id_int = int(cell_id)
            else:
                # Skip if we can't handle this cell ID type
                continue

            case_statements.append(
                f"WHEN e.cell_integer_id = {cell_integer_id_int} THEN {factor_str}"
            )

        factor_case = "CASE " + " ".join(case_statements) + " ELSE 1.0 END"

        # Wrap the query to apply normalization
        return f"""
        SELECT
            e.cell_integer_id,
            e.gene_integer_id,
            e.value * {factor_case} as value
        FROM ({query}) as base_data e
        """

    def _apply_sql_log1p(self, query: str) -> str:
        """Apply log1p transformation in SQL, only to nonzero values (sparse semantics)"""
        return f"""
        SELECT
            e.cell_integer_id,
            e.gene_integer_id,
            CASE WHEN e.value != 0 THEN LN(1 + e.value) ELSE 0 END as value
        FROM ({query}) as base_data e
        """

    def _apply_numpy_transformations(
        self,
        matrix: scipy.sparse.csr_matrix,
        cell_selector,
        gene_selector,
        transformations,
    ) -> scipy.sparse.csr_matrix:
        """Apply transformations using numpy operations"""
        # Apply transformations in the order they were added (preserves order)
        result = matrix
        for transform_name, transform_data in transformations.items():
            if transform_name == "normalize_total":
                result = self._apply_normalize_total(
                    result, cell_selector, transform_data
                )
            elif transform_name == "log1p":
                result = self._apply_log1p(result)

        return result

    def _apply_normalize_total(
        self,
        matrix: scipy.sparse.csr_matrix,
        cell_selector,
        transform_data,
    ) -> scipy.sparse.csr_matrix:
        """Apply normalize_total transformation using vectorized operations"""
        cell_factors = transform_data.get("cell_factors", {})
        obs_names_local = []  # Always a list
        obs_names = None
        if hasattr(self, "parent_adata") and self.parent_adata is not None:
            try:
                obs_names = self.parent_adata.obs_names
            except (AttributeError, TypeError):
                obs_names = None
        if obs_names is None or not isinstance(obs_names, list | np.ndarray | pd.Index):
            if (
                matrix is not None
                and hasattr(matrix, "shape")
                and matrix.shape is not None
            ):
                obs_names_local = [f"cell_{i}" for i in range(matrix.shape[0])]
            else:
                obs_names_local = []
        else:
            obs_names_local = list(obs_names)
        # Now obs_names_local is always a list
        # Determine selected_cell_names based on cell_selector
        if cell_selector is None or (
            isinstance(cell_selector, slice) and cell_selector == slice(None)
        ):
            selected_cell_names = obs_names_local
        elif isinstance(cell_selector, slice):
            start = cell_selector.start or 0
            stop = cell_selector.stop or len(obs_names_local)
            step = cell_selector.step or 1
            # Clamp bounds
            start = max(0, min(start, len(obs_names_local)))
            stop = max(0, min(stop, len(obs_names_local)))
            selected_cell_names = obs_names_local[start:stop:step]
        elif isinstance(cell_selector, list | np.ndarray):
            if len(obs_names_local) > 0:
                if (
                    isinstance(cell_selector, np.ndarray)
                    and cell_selector.dtype == bool
                ):
                    selected_cell_names = [
                        obs_names_local[i]
                        for i, keep in enumerate(cell_selector)
                        if keep and 0 <= i < len(obs_names_local)
                    ]
                else:
                    selected_cell_names = [
                        obs_names_local[i]
                        for i in cell_selector
                        if isinstance(i, int | np.integer)
                        and 0 <= i < len(obs_names_local)
                    ]
            else:
                selected_cell_names = []
        elif isinstance(cell_selector, int | np.integer):
            if 0 <= cell_selector < len(obs_names_local):
                selected_cell_names = [obs_names_local[cell_selector]]
            else:
                selected_cell_names = []
        else:
            selected_cell_names = obs_names_local
        # Create a vector of factors for all cells at once
        cell_factors_vector = np.array(
            [cell_factors.get(name, 1.0) for name in selected_cell_names]
        )
        # Apply vectorized scaling using CSR matrix properties
        # Create a copy only if we need to modify the data
        if not np.allclose(cell_factors_vector, 1.0):
            result = matrix.copy()
            # Apply scaling to each row using vectorized operations
            for i in range(result.shape[0]):
                if i < len(cell_factors_vector):
                    factor = cell_factors_vector[i]
                    if factor != 1.0:
                        # Scale the non-zero elements in this row
                        start_idx = result.indptr[i]
                        end_idx = result.indptr[i + 1]
                        result.data[start_idx:end_idx] *= factor
            return result
        else:
            # No scaling needed, return original matrix
            return matrix

    def _apply_log1p(self, matrix: scipy.sparse.csr_matrix) -> scipy.sparse.csr_matrix:
        """Apply log1p transformation using vectorized operations"""
        # Create a copy only if we need to modify the data
        result = matrix.copy()
        # Apply log1p to all non-zero values using vectorized operation
        result.data = np.log1p(result.data)
        return result

    def __array_function__(self, func, types, args, kwargs):
        """Intercept numpy functions for lazy evaluation"""
        if func == np.mean:
            axis = kwargs.get("axis", None)
            return self.mean(axis=axis)
        elif func == np.sum:
            axis = kwargs.get("axis", None)
            return self.sum(axis=axis)
        elif func == np.var:
            axis = kwargs.get("axis", None)
            return self.var(axis=axis)
        elif func == np.std:
            axis = kwargs.get("axis", None)
            return self.std(axis=axis)
        else:
            # Fall back to materializing the matrix
            matrix = self.compute()
            return func(matrix, *args[1:], **kwargs)

    def mean(
        self, axis: int | None = None, fragments: bool | None = None
    ) -> float | np.ndarray:
        """Compute mean along axis via SQL aggregation"""
        return self._aggregation_with_fragments("mean", fragments, axis=axis)

    def sum(
        self, axis: int | None = None, fragments: bool | None = None
    ) -> float | np.ndarray:
        """Compute sum along axis via SQL aggregation"""
        return self._aggregation_with_fragments("sum", fragments, axis=axis)

    def var(self, axis: int | None = None) -> float | np.ndarray:
        """Compute variance along axis via SQL aggregation"""
        return self._sql_aggregation("variance", axis)

    def std(self, axis: int | None = None) -> float | np.ndarray:
        """Compute standard deviation along axis"""
        return self._sql_aggregation("stddev", axis)

    def toarray(self) -> np.ndarray:
        """Convert to dense numpy array"""
        matrix = self.compute()
        return matrix.toarray()

    def compute(self, fragments: bool | None = None) -> scipy.sparse.csr_matrix:
        """
        Explicitly compute the matrix with all transformations applied.
        This is where the actual SQL query and materialization happens.

        Args:
            fragments: Whether to use fragment processing (None for automatic)

        Returns:
            Sparse matrix with transformations applied
        """
        # Determine processing strategy
        if fragments is not None:
            use_fragments = fragments
        else:
            # Check if dataset has multiple fragments
            try:
                fragments_list = self.slaf_array.expression.get_fragments()
                use_fragments = len(fragments_list) > 1
            except Exception:
                use_fragments = False

        if use_fragments:
            processor = FragmentProcessor(
                self.slaf_array,
                cell_selector=self._cell_selector,
                gene_selector=self._gene_selector,
                max_workers=4,
                enable_caching=True,
            )
            # Use smart strategy selection for optimal performance
            lazy_pipeline = processor.build_lazy_pipeline_smart("compute_matrix")
            result = processor.compute(lazy_pipeline)
            return self._convert_to_sparse_matrix(result)
        else:
            return self._compute_global()

    def _compute_global(self) -> scipy.sparse.csr_matrix:
        """Compute the matrix globally (original implementation)"""
        # Build the SQL query with transformations
        if self.parent_adata is not None and hasattr(
            self.parent_adata, "_transformations"
        ):
            transformations = self.parent_adata._transformations
        else:
            transformations = {}

        # Try SQL-level transformations first
        if transformations:
            sql_result = self._apply_sql_transformations(
                self._cell_selector, self._gene_selector, transformations
            )
            if sql_result is not None:
                return self._reconstruct_sparse_matrix(
                    sql_result, self._cell_selector, self._gene_selector
                )

        # Fall back to base query + numpy transformations
        base_query = self._build_submatrix_sql(self._cell_selector, self._gene_selector)
        base_result = self.slaf_array.query(base_query)

        # Reconstruct base matrix
        base_matrix = self._reconstruct_sparse_matrix(
            base_result, self._cell_selector, self._gene_selector
        )

        # Apply transformations in numpy if needed
        if transformations:
            return self._apply_numpy_transformations(
                base_matrix,
                self._cell_selector,
                self._gene_selector,
                transformations,
            )

        return base_matrix

    def _convert_to_sparse_matrix(
        self, result_df: pl.DataFrame
    ) -> scipy.sparse.csr_matrix:
        """
        Convert fragment processing result to sparse matrix.

        Args:
            result_df: Polars DataFrame from fragment processing

        Returns:
            Sparse matrix representation
        """
        if len(result_df) == 0:
            # Return empty matrix with appropriate shape
            return scipy.sparse.csr_matrix(self.shape)

        # Convert to COO format for efficient sparse matrix construction
        rows = result_df["cell_integer_id"].to_numpy()
        cols = result_df["gene_integer_id"].to_numpy()
        data = result_df["value"].to_numpy()

        # Create sparse matrix
        return scipy.sparse.coo_matrix((data, (rows, cols)), shape=self.shape).tocsr()
Attributes
shape: tuple[int, int] property

Shape of the expression matrix.

Returns:

Type Description
tuple[int, int]

Tuple of (n_cells, n_genes) representing the matrix dimensions.

Examples:

>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> matrix = LazyExpressionMatrix(slaf_array)
>>> print(f"Matrix shape: {matrix.shape}")
Matrix shape: (1000, 20000)
obs_names: pd.Index | None property

Cell names (observations).

Returns:

Type Description
Index | None

pandas.Index of cell names if parent AnnData is available, None otherwise.

Examples:

>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> matrix = adata.X
>>> print(f"Cell names: {len(matrix.obs_names)}")
Cell names: 1000
var_names: pd.Index | None property

Gene names (variables).

Returns:

Type Description
Index | None

pandas.Index of gene names if parent AnnData is available, None otherwise.

Examples:

>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> matrix = adata.X
>>> print(f"Gene names: {len(matrix.var_names)}")
Gene names: 20000
Functions
__init__(slaf_array: SLAFArray)

Initialize lazy expression matrix with SLAF array.

Parameters:

Name Type Description Default
slaf_array SLAFArray

SLAFArray instance containing the single-cell data. Used for database queries and metadata access.

required

Examples:

>>> # Basic initialization
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> matrix = LazyExpressionMatrix(slaf_array)
>>> print(f"Initialized with shape: {matrix.shape}")
Initialized with shape: (1000, 20000)
>>> # Check parent reference
>>> print(f"Parent adata: {matrix.parent_adata}")
Parent adata: None
Source code in slaf/integrations/anndata.py
def __init__(self, slaf_array: SLAFArray):
    """
    Initialize lazy expression matrix with SLAF array.

    Args:
        slaf_array: SLAFArray instance containing the single-cell data.
                   Used for database queries and metadata access.

    Examples:
        >>> # Basic initialization
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> matrix = LazyExpressionMatrix(slaf_array)
        >>> print(f"Initialized with shape: {matrix.shape}")
        Initialized with shape: (1000, 20000)

        >>> # Check parent reference
        >>> print(f"Parent adata: {matrix.parent_adata}")
        Parent adata: None
    """
    super().__init__()
    self.slaf_array = slaf_array
    self.parent_adata: LazyAnnData | None = None
    # Store slicing selectors
    self._cell_selector: Any = None
    self._gene_selector: Any = None
    # Initialize shape attribute (required by LazySparseMixin)
    self._shape = self.slaf_array.shape
    self._cache: dict[str, Any] = {}  # Simple caching for repeated queries
mean(axis: int | None = None, fragments: bool | None = None) -> float | np.ndarray

Compute mean along axis via SQL aggregation

Source code in slaf/integrations/anndata.py
def mean(
    self, axis: int | None = None, fragments: bool | None = None
) -> float | np.ndarray:
    """Compute mean along axis via SQL aggregation"""
    return self._aggregation_with_fragments("mean", fragments, axis=axis)
sum(axis: int | None = None, fragments: bool | None = None) -> float | np.ndarray

Compute sum along axis via SQL aggregation

Source code in slaf/integrations/anndata.py
def sum(
    self, axis: int | None = None, fragments: bool | None = None
) -> float | np.ndarray:
    """Compute sum along axis via SQL aggregation"""
    return self._aggregation_with_fragments("sum", fragments, axis=axis)
var(axis: int | None = None) -> float | np.ndarray

Compute variance along axis via SQL aggregation

Source code in slaf/integrations/anndata.py
def var(self, axis: int | None = None) -> float | np.ndarray:
    """Compute variance along axis via SQL aggregation"""
    return self._sql_aggregation("variance", axis)
std(axis: int | None = None) -> float | np.ndarray

Compute standard deviation along axis

Source code in slaf/integrations/anndata.py
def std(self, axis: int | None = None) -> float | np.ndarray:
    """Compute standard deviation along axis"""
    return self._sql_aggregation("stddev", axis)
toarray() -> np.ndarray

Convert to dense numpy array

Source code in slaf/integrations/anndata.py
def toarray(self) -> np.ndarray:
    """Convert to dense numpy array"""
    matrix = self.compute()
    return matrix.toarray()
compute(fragments: bool | None = None) -> scipy.sparse.csr_matrix

Explicitly compute the matrix with all transformations applied. This is where the actual SQL query and materialization happens.

Parameters:

Name Type Description Default
fragments bool | None

Whether to use fragment processing (None for automatic)

None

Returns:

Type Description
csr_matrix

Sparse matrix with transformations applied

Source code in slaf/integrations/anndata.py
def compute(self, fragments: bool | None = None) -> scipy.sparse.csr_matrix:
    """
    Explicitly compute the matrix with all transformations applied.
    This is where the actual SQL query and materialization happens.

    Args:
        fragments: Whether to use fragment processing (None for automatic)

    Returns:
        Sparse matrix with transformations applied
    """
    # Determine processing strategy
    if fragments is not None:
        use_fragments = fragments
    else:
        # Check if dataset has multiple fragments
        try:
            fragments_list = self.slaf_array.expression.get_fragments()
            use_fragments = len(fragments_list) > 1
        except Exception:
            use_fragments = False

    if use_fragments:
        processor = FragmentProcessor(
            self.slaf_array,
            cell_selector=self._cell_selector,
            gene_selector=self._gene_selector,
            max_workers=4,
            enable_caching=True,
        )
        # Use smart strategy selection for optimal performance
        lazy_pipeline = processor.build_lazy_pipeline_smart("compute_matrix")
        result = processor.compute(lazy_pipeline)
        return self._convert_to_sparse_matrix(result)
    else:
        return self._compute_global()

LazyAnnData

Bases: LazySparseMixin

AnnData-compatible interface for SLAF data with lazy evaluation.

LazyAnnData provides a drop-in replacement for AnnData objects that works with SLAF datasets. It implements lazy evaluation to avoid loading all data into memory, making it suitable for large single-cell datasets.

Key Features
  • AnnData-compatible interface
  • Lazy evaluation for memory efficiency
  • Support for cell and gene subsetting
  • Integration with scanpy workflows
  • Automatic metadata loading
  • Transformation caching

Examples:

>>> # Basic usage
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> print(f"AnnData shape: {adata.shape}")
AnnData shape: (1000, 20000)
>>> # Access expression data
>>> print(f"Expression matrix shape: {adata.X.shape}")
Expression matrix shape: (1000, 20000)
>>> # Access metadata
>>> print(f"Cell metadata columns: {list(adata.obs.columns)}")
Cell metadata columns: ['cell_type', 'total_counts', 'batch']
>>> print(f"Gene metadata columns: {list(adata.var.columns)}")
Gene metadata columns: ['gene_type', 'chromosome']
>>> # Subsetting operations
>>> subset = adata[:100, :5000]  # First 100 cells, first 5000 genes
>>> print(f"Subset shape: {subset.shape}")
Subset shape: (100, 5000)
Source code in slaf/integrations/anndata.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
class LazyAnnData(LazySparseMixin):
    """
    AnnData-compatible interface for SLAF data with lazy evaluation.

    LazyAnnData provides a drop-in replacement for AnnData objects that works with
    SLAF datasets. It implements lazy evaluation to avoid loading all data into memory,
    making it suitable for large single-cell datasets.

    Key Features:
        - AnnData-compatible interface
        - Lazy evaluation for memory efficiency
        - Support for cell and gene subsetting
        - Integration with scanpy workflows
        - Automatic metadata loading
        - Transformation caching

    Examples:
        >>> # Basic usage
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> print(f"AnnData shape: {adata.shape}")
        AnnData shape: (1000, 20000)

        >>> # Access expression data
        >>> print(f"Expression matrix shape: {adata.X.shape}")
        Expression matrix shape: (1000, 20000)

        >>> # Access metadata
        >>> print(f"Cell metadata columns: {list(adata.obs.columns)}")
        Cell metadata columns: ['cell_type', 'total_counts', 'batch']
        >>> print(f"Gene metadata columns: {list(adata.var.columns)}")
        Gene metadata columns: ['gene_type', 'chromosome']

        >>> # Subsetting operations
        >>> subset = adata[:100, :5000]  # First 100 cells, first 5000 genes
        >>> print(f"Subset shape: {subset.shape}")
        Subset shape: (100, 5000)
    """

    def __init__(
        self,
        slaf_array: SLAFArray,
        backend: str = "auto",
    ):
        """
        Initialize LazyAnnData with SLAF array.

        Args:
            slaf_array: SLAFArray instance containing the single-cell data.
                       Used for database queries and metadata access.
            backend: Backend for expression matrix. Currently supports "scipy" and "auto".
                    "auto" defaults to "scipy" for sparse matrix operations.

        Raises:
            ValueError: If the backend is not supported.
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Basic initialization
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> print(f"Backend: {adata.backend}")
            Backend: auto

            >>> # With explicit backend
            >>> adata = LazyAnnData(slaf_array, backend="scipy")
            >>> print(f"Backend: {adata.backend}")
            Backend: scipy

            >>> # Error handling for unsupported backend
            >>> try:
            ...     adata = LazyAnnData(slaf_array, backend="unsupported")
            ... except ValueError as e:
            ...     print(f"Error: {e}")
            Error: Unknown backend: unsupported
        """
        super().__init__()
        self.slaf = slaf_array
        self.backend = backend

        # Initialize expression matrix
        if backend == "scipy" or backend == "auto":
            self._X = LazyExpressionMatrix(slaf_array)
            self._X.parent_adata = self  # Set parent reference for transformations
        else:
            raise ValueError(f"Unknown backend: {backend}")

        # Lazy-loaded metadata
        self._obs = None
        self._var = None
        self._cached_obs_names: pd.Index | None = None
        self._cached_var_names: pd.Index | None = None

        # Filter selectors for subsetting
        self._cell_selector: Any = None
        self._gene_selector: Any = None
        self._filtered_obs: Callable[[], pd.DataFrame] | None = None
        self._filtered_var: Callable[[], pd.DataFrame] | None = None

        # Transformations for lazy evaluation
        self._transformations: dict[str, Any] = {}

    @property
    def X(self) -> LazyExpressionMatrix:
        """
        Access to expression data.

        Returns the lazy expression matrix that provides scipy.sparse-compatible
        access to the single-cell expression data. The matrix is lazily evaluated
        to avoid loading all data into memory.

        Returns:
            LazyExpressionMatrix providing scipy.sparse-compatible interface.

        Examples:
            >>> # Access expression data
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> print(f"Expression matrix shape: {adata.X.shape}")
            Expression matrix shape: (1000, 20000)

            >>> # Subsetting expression data
            >>> subset_X = adata.X[:100, :5000]
            >>> print(f"Subset expression shape: {subset_X.shape}")
            Subset expression shape: (100, 5000)

            >>> # Check matrix type
            >>> print(f"Matrix type: {type(adata.X)}")
            Matrix type: <class 'slaf.integrations.anndata.LazyExpressionMatrix'>
        """
        return self._X

    @property
    def obs(self) -> pd.DataFrame:
        """
        Cell metadata (observations).

        This property triggers computation of metadata when accessed.
        For lazy access to metadata structure only, use obs.columns, obs.index, etc.
        """
        if self._filtered_obs is not None:
            result = self._filtered_obs()
            if isinstance(result, pd.DataFrame):
                return result
            return pd.DataFrame()
        if self._obs is None:
            # Use the obs from SLAFArray (now polars DataFrame)
            obs_df = getattr(self.slaf, "obs", None)
            if obs_df is not None:
                # Work with polars DataFrame internally
                obs_pl = obs_df
                # Drop cell_integer_id column if present to match AnnData expectations
                if "cell_integer_id" in obs_pl.columns:
                    obs_pl = obs_pl.drop("cell_integer_id")
                # Convert to pandas DataFrame for AnnData compatibility at API boundary
                obs_copy = obs_pl.to_pandas()
                # Set cell_id as index if present, otherwise use default index
                if "cell_id" in obs_copy.columns:
                    obs_copy = obs_copy.set_index("cell_id")
                # Set index name to match AnnData format
                if hasattr(obs_copy, "index"):
                    obs_copy.index.name = "cell_id"
                self._obs = obs_copy
            else:
                self._obs = pd.DataFrame()
        return self._obs

    @property
    def var(self) -> pd.DataFrame:
        """
        Gene metadata (variables).

        This property triggers computation of metadata when accessed.
        For lazy access to metadata structure only, use var.columns, var.index, etc.
        """
        if self._filtered_var is not None:
            result = self._filtered_var()
            if isinstance(result, pd.DataFrame):
                return result
            return pd.DataFrame()
        if self._var is None:
            var_df = getattr(self.slaf, "var", None)
            if var_df is not None:
                # Work with polars DataFrame internally
                var_pl = var_df
                # Drop gene_integer_id column if present to match AnnData expectations
                if "gene_integer_id" in var_pl.columns:
                    var_pl = var_pl.drop("gene_integer_id")
                # Convert to pandas DataFrame for AnnData compatibility at API boundary
                var_copy = var_pl.to_pandas()
                # Set gene_id as index if present, otherwise use default index
                if "gene_id" in var_copy.columns:
                    var_copy = var_copy.set_index("gene_id")
                # Set index name to match AnnData format
                if hasattr(var_copy, "index"):
                    var_copy.index.name = "gene_id"
                self._var = var_copy
            else:
                self._var = pd.DataFrame()
        return self._var

    @property
    def obs_names(self) -> pd.Index:
        """Cell names"""
        if self._cached_obs_names is None:
            self._cached_obs_names = self.obs.index
        return self._cached_obs_names

    @property
    def var_names(self) -> pd.Index:
        """Gene names"""
        if self._cached_var_names is None:
            self._cached_var_names = self.var.index
        return self._cached_var_names

    @property
    def n_obs(self) -> int:
        """Number of observations (cells)"""
        return self.shape[0]

    @property
    def n_vars(self) -> int:
        """Number of variables (genes)"""
        return self.shape[1]

    @property
    def shape(self) -> tuple[int, int]:
        """Get the shape of the data, accounting for any applied filters"""
        if (
            getattr(self, "_cell_selector", None) is not None
            or getattr(self, "_gene_selector", None) is not None
        ):
            # Calculate the shape based on selectors
            cell_selector = (
                self._cell_selector
                if getattr(self, "_cell_selector", None) is not None
                else slice(None)
            )
            gene_selector = (
                self._gene_selector
                if getattr(self, "_gene_selector", None) is not None
                else slice(None)
            )

            # Use the same logic as _get_result_shape in LazySparseMixin
            n_cells = self._calculate_selected_count(cell_selector, axis=0)
            n_genes = self._calculate_selected_count(gene_selector, axis=1)

            return (n_cells, n_genes)
        else:
            # No filters applied, return original shape
            return self.slaf.shape

    def _calculate_selected_count(self, selector, axis: int) -> int:
        """Calculate the number of selected entities for a given selector"""
        if selector is None or (
            isinstance(selector, slice) and selector == slice(None)
        ):
            return self.slaf.shape[axis]

        if isinstance(selector, slice):
            start = selector.start or 0
            stop = selector.stop or self.slaf.shape[axis]
            step = selector.step or 1

            # Handle negative indices
            if start < 0:
                start = self.slaf.shape[axis] + start
            if stop < 0:
                stop = self.slaf.shape[axis] + stop

            # Clamp bounds to actual data size
            start = max(0, min(start, self.slaf.shape[axis]))
            stop = max(0, min(stop, self.slaf.shape[axis]))

            return len(range(start, stop, step))
        elif isinstance(selector, list | np.ndarray):
            if isinstance(selector, np.ndarray) and selector.dtype == bool:
                return np.sum(selector)
            return len(selector)
        elif isinstance(selector, int | np.integer):
            return 1
        else:
            return self.slaf.shape[axis]

    def __getitem__(self, key) -> "LazyAnnData":
        """Subset the data, composing selectors if already sliced"""
        # Disallow chained slicing on LazyAnnData objects
        if self._cell_selector is not None or self._gene_selector is not None:
            raise NotImplementedError(
                "Chained slicing on LazyAnnData objects is not supported. "
                "Please use adata[rows, cols] for single-step slicing instead of "
                "adata[rows][:, cols]. For chained slicing on the expression matrix, "
                "use adata.X[rows][:, cols]."
            )

        # Parse indexing key using the same logic as LazyExpressionMatrix
        cell_selector, gene_selector = self._parse_key(key)

        # Create a new LazyAnnData with the same backend
        new_adata = LazyAnnData(self.slaf, backend=self.backend)

        # Store the selectors for lazy filtering
        new_adata._cell_selector = cell_selector
        new_adata._gene_selector = gene_selector

        # Update the LazyExpressionMatrix to know about the slicing
        if isinstance(new_adata._X, LazyExpressionMatrix):
            new_adata._X.parent_adata = new_adata
            # Store the selectors in the LazyExpressionMatrix so it can use them
            new_adata._X._cell_selector = cell_selector
            new_adata._X._gene_selector = gene_selector
            # Update the shape to reflect the slicing
            new_adata._X._update_shape()

        # Override obs and var properties to apply filtering
        def filtered_obs() -> pd.DataFrame:
            # Always apply the composed selector to the original obs
            obs_df = self.obs
            if cell_selector is None or (
                isinstance(cell_selector, slice) and cell_selector == slice(None)
            ):
                pass
            else:
                obs_df = obs_df.copy()
                if isinstance(cell_selector, slice):
                    start = cell_selector.start or 0
                    stop = cell_selector.stop or len(obs_df)
                    step = cell_selector.step or 1

                    # Handle negative indices
                    if start < 0:
                        start = len(obs_df) + start
                    if stop < 0:
                        stop = len(obs_df) + stop

                    # Clamp bounds to valid range
                    start = max(0, min(start, len(obs_df)))
                    stop = max(0, min(stop, len(obs_df)))
                    obs_df = obs_df.iloc[start:stop:step]
                elif (
                    isinstance(cell_selector, np.ndarray)
                    and cell_selector.dtype == bool
                ):
                    # Boolean mask - ensure it matches the length
                    if len(cell_selector) == len(obs_df):
                        obs_df = obs_df[cell_selector]
                    else:
                        # Pad or truncate the mask to match
                        if len(cell_selector) < len(obs_df):
                            mask: np.ndarray = np.zeros(len(obs_df), dtype=bool)
                            mask[: len(cell_selector)] = cell_selector
                        else:
                            mask = cell_selector[: len(obs_df)]
                        obs_df = obs_df[mask]
                elif isinstance(cell_selector, list | np.ndarray):
                    # Integer indices
                    obs_df = obs_df.iloc[cell_selector]
                elif isinstance(cell_selector, int | np.integer):
                    obs_df = obs_df.iloc[[int(cell_selector)]]
                # else: leave as is
            # Remove unused categories for all categorical columns if not empty
            if obs_df is not None and not obs_df.empty:
                for col in obs_df.select_dtypes(include="category").columns:
                    col_data = obs_df[col]
                    # Type-safe check for pandas categorical data
                    if isinstance(col_data, pd.Series) and hasattr(col_data, "cat"):
                        obs_df[col] = col_data.cat.remove_unused_categories()
            if isinstance(obs_df, pd.DataFrame):
                return obs_df
            return pd.DataFrame()

        def filtered_var() -> pd.DataFrame:
            # Always apply the composed selector to the original var
            var_df = self.var
            if gene_selector is None or (
                isinstance(gene_selector, slice) and gene_selector == slice(None)
            ):
                pass
            else:
                var_df = var_df.copy()
                if isinstance(gene_selector, slice):
                    start = gene_selector.start or 0
                    stop = gene_selector.stop or len(var_df)
                    step = gene_selector.step or 1

                    # Handle negative indices
                    if start < 0:
                        start = len(var_df) + start
                    if stop < 0:
                        stop = len(var_df) + stop

                    # Clamp bounds to valid range
                    start = max(0, min(start, len(var_df)))
                    stop = max(0, min(stop, len(var_df)))
                    var_df = var_df.iloc[start:stop:step]
                elif (
                    isinstance(gene_selector, np.ndarray)
                    and gene_selector.dtype == bool
                ):
                    # Boolean mask - ensure it matches the length
                    if len(gene_selector) == len(var_df):
                        var_df = var_df[gene_selector]
                    else:
                        # Pad or truncate the mask to match
                        if len(gene_selector) < len(var_df):
                            mask: np.ndarray = np.zeros(len(var_df), dtype=bool)
                            mask[: len(gene_selector)] = gene_selector
                        else:
                            mask = gene_selector[: len(var_df)]
                        var_df = var_df[mask]
                elif isinstance(gene_selector, list | np.ndarray):
                    # Integer indices
                    var_df = var_df.iloc[gene_selector]
                elif isinstance(gene_selector, int | np.integer):
                    var_df = var_df.iloc[[int(gene_selector)]]
                # else: leave as is
            # Remove unused categories for all categorical columns if not empty
            if var_df is not None and not var_df.empty:
                for col in var_df.select_dtypes(include="category").columns:
                    col_data = var_df[col]
                    # Type-safe check for pandas categorical data
                    if isinstance(col_data, pd.Series) and hasattr(col_data, "cat"):
                        var_df[col] = col_data.cat.remove_unused_categories()
            if isinstance(var_df, pd.DataFrame):
                return var_df
            return pd.DataFrame()

        # Store the filter functions
        new_adata._filtered_obs = filtered_obs
        new_adata._filtered_var = filtered_var

        # Ensure obs_names and var_names match the filtered DataFrames
        new_adata._cached_obs_names = new_adata._filtered_obs().index
        new_adata._cached_var_names = new_adata._filtered_var().index

        # Copy transformations
        new_adata._transformations = self._transformations.copy()

        return new_adata

    def copy(self) -> "LazyAnnData":
        """Create a copy"""
        new_adata = LazyAnnData(self.slaf, backend=self.backend)

        # Copy selectors
        new_adata._cell_selector = self._cell_selector
        new_adata._gene_selector = self._gene_selector

        # Copy filtered metadata functions
        new_adata._filtered_obs = self._filtered_obs
        new_adata._filtered_var = self._filtered_var

        # Copy transformations
        new_adata._transformations = self._transformations.copy()

        # Set up parent reference for the expression matrix
        if isinstance(new_adata._X, LazyExpressionMatrix):
            new_adata._X.parent_adata = new_adata

        return new_adata

    def to_memory(self) -> scipy.sparse.spmatrix:
        """Load entire matrix into memory"""
        return self.get_expression_data()

    def write(self, filename: str):
        """Write to h5ad format (would need implementation)"""
        raise NotImplementedError("Writing LazyAnnData not yet implemented")

    def get_expression_data(self) -> scipy.sparse.csr_matrix:
        """Get expression data with any applied filters"""
        if isinstance(self._X, LazyExpressionMatrix):
            # If the LazyExpressionMatrix already has selectors stored, just get the data
            # without passing additional selectors to avoid double-composition
            if self._X._cell_selector is not None or self._X._gene_selector is not None:
                return self._X[:, :].compute()
            elif self._cell_selector is not None or self._gene_selector is not None:
                cell_sel = (
                    self._cell_selector
                    if self._cell_selector is not None
                    else slice(None)
                )
                gene_sel = (
                    self._gene_selector
                    if self._gene_selector is not None
                    else slice(None)
                )
                return self._X[cell_sel, gene_sel].compute()
            else:
                return self._X[:, :].compute()
        else:
            raise NotImplementedError(
                "Dask backend not yet implemented for get_expression_data"
            )

    def compute(self) -> "sc.AnnData":
        """Explicitly compute and return a native AnnData object"""
        import scanpy as sc

        # Create native AnnData object
        adata = sc.AnnData(X=self._X.compute(), obs=self.obs, var=self.var)

        return adata

    def _update_with_normalized_data(
        self, result_df: pl.DataFrame, target_sum: float, inplace: bool
    ) -> "LazyAnnData | None":
        """
        Update AnnData with normalized data from fragment processing.

        Args:
            result_df: Polars DataFrame with normalized values
            target_sum: Target sum used for normalization
            inplace: Whether to modify in place

        Returns:
            Updated LazyAnnData or None if inplace=True
        """
        if inplace:
            # Store normalization transformation
            if not hasattr(self, "_transformations"):
                self._transformations = {}

            self._transformations["normalize_total"] = {
                "type": "normalize_total",
                "target_sum": target_sum,
                "fragment_processed": True,
                "result_df": result_df,
            }

            print(
                f"Applied normalize_total with target_sum={target_sum} (fragment processing)"
            )
            return None
        else:
            # Create a copy with the transformation
            new_adata = self.copy()
            if not hasattr(new_adata, "_transformations"):
                new_adata._transformations = {}

            new_adata._transformations["normalize_total"] = {
                "type": "normalize_total",
                "target_sum": target_sum,
                "fragment_processed": True,
                "result_df": result_df,
            }

            return new_adata

    def _update_with_log1p_data(
        self, result_df: pl.DataFrame, inplace: bool
    ) -> "LazyAnnData | None":
        """
        Update AnnData with log1p data from fragment processing.

        Args:
            result_df: Polars DataFrame with log1p values
            inplace: Whether to modify in place

        Returns:
            Updated LazyAnnData or None if inplace=True
        """
        if inplace:
            # Store log1p transformation
            if not hasattr(self, "_transformations"):
                self._transformations = {}

            self._transformations["log1p"] = {
                "type": "log1p",
                "fragment_processed": True,
                "result_df": result_df,
            }

            print("Applied log1p transformation (fragment processing)")
            return None
        else:
            # Create a copy with the transformation
            new_adata = self.copy()
            if not hasattr(new_adata, "_transformations"):
                new_adata._transformations = {}

            new_adata._transformations["log1p"] = {
                "type": "log1p",
                "fragment_processed": True,
                "result_df": result_df,
            }

            return new_adata

    def _get_processing_strategy(self, fragments: bool | None = None) -> bool:
        """Determine the processing strategy based on fragments and dataset size"""
        if fragments is not None:
            return fragments
        try:
            fragments_list = self.slaf.expression.get_fragments()
            return len(fragments_list) > 1
        except Exception:
            return False
Attributes
X: LazyExpressionMatrix property

Access to expression data.

Returns the lazy expression matrix that provides scipy.sparse-compatible access to the single-cell expression data. The matrix is lazily evaluated to avoid loading all data into memory.

Returns:

Type Description
LazyExpressionMatrix

LazyExpressionMatrix providing scipy.sparse-compatible interface.

Examples:

>>> # Access expression data
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> print(f"Expression matrix shape: {adata.X.shape}")
Expression matrix shape: (1000, 20000)
>>> # Subsetting expression data
>>> subset_X = adata.X[:100, :5000]
>>> print(f"Subset expression shape: {subset_X.shape}")
Subset expression shape: (100, 5000)
>>> # Check matrix type
>>> print(f"Matrix type: {type(adata.X)}")
Matrix type: <class 'slaf.integrations.anndata.LazyExpressionMatrix'>
obs: pd.DataFrame property

Cell metadata (observations).

This property triggers computation of metadata when accessed. For lazy access to metadata structure only, use obs.columns, obs.index, etc.

var: pd.DataFrame property

Gene metadata (variables).

This property triggers computation of metadata when accessed. For lazy access to metadata structure only, use var.columns, var.index, etc.

obs_names: pd.Index property

Cell names

var_names: pd.Index property

Gene names

n_obs: int property

Number of observations (cells)

n_vars: int property

Number of variables (genes)

shape: tuple[int, int] property

Get the shape of the data, accounting for any applied filters

Functions
__init__(slaf_array: SLAFArray, backend: str = 'auto')

Initialize LazyAnnData with SLAF array.

Parameters:

Name Type Description Default
slaf_array SLAFArray

SLAFArray instance containing the single-cell data. Used for database queries and metadata access.

required
backend str

Backend for expression matrix. Currently supports "scipy" and "auto". "auto" defaults to "scipy" for sparse matrix operations.

'auto'

Raises:

Type Description
ValueError

If the backend is not supported.

RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Basic initialization
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> print(f"Backend: {adata.backend}")
Backend: auto
>>> # With explicit backend
>>> adata = LazyAnnData(slaf_array, backend="scipy")
>>> print(f"Backend: {adata.backend}")
Backend: scipy
>>> # Error handling for unsupported backend
>>> try:
...     adata = LazyAnnData(slaf_array, backend="unsupported")
... except ValueError as e:
...     print(f"Error: {e}")
Error: Unknown backend: unsupported
Source code in slaf/integrations/anndata.py
def __init__(
    self,
    slaf_array: SLAFArray,
    backend: str = "auto",
):
    """
    Initialize LazyAnnData with SLAF array.

    Args:
        slaf_array: SLAFArray instance containing the single-cell data.
                   Used for database queries and metadata access.
        backend: Backend for expression matrix. Currently supports "scipy" and "auto".
                "auto" defaults to "scipy" for sparse matrix operations.

    Raises:
        ValueError: If the backend is not supported.
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Basic initialization
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> print(f"Backend: {adata.backend}")
        Backend: auto

        >>> # With explicit backend
        >>> adata = LazyAnnData(slaf_array, backend="scipy")
        >>> print(f"Backend: {adata.backend}")
        Backend: scipy

        >>> # Error handling for unsupported backend
        >>> try:
        ...     adata = LazyAnnData(slaf_array, backend="unsupported")
        ... except ValueError as e:
        ...     print(f"Error: {e}")
        Error: Unknown backend: unsupported
    """
    super().__init__()
    self.slaf = slaf_array
    self.backend = backend

    # Initialize expression matrix
    if backend == "scipy" or backend == "auto":
        self._X = LazyExpressionMatrix(slaf_array)
        self._X.parent_adata = self  # Set parent reference for transformations
    else:
        raise ValueError(f"Unknown backend: {backend}")

    # Lazy-loaded metadata
    self._obs = None
    self._var = None
    self._cached_obs_names: pd.Index | None = None
    self._cached_var_names: pd.Index | None = None

    # Filter selectors for subsetting
    self._cell_selector: Any = None
    self._gene_selector: Any = None
    self._filtered_obs: Callable[[], pd.DataFrame] | None = None
    self._filtered_var: Callable[[], pd.DataFrame] | None = None

    # Transformations for lazy evaluation
    self._transformations: dict[str, Any] = {}
copy() -> LazyAnnData

Create a copy

Source code in slaf/integrations/anndata.py
def copy(self) -> "LazyAnnData":
    """Create a copy"""
    new_adata = LazyAnnData(self.slaf, backend=self.backend)

    # Copy selectors
    new_adata._cell_selector = self._cell_selector
    new_adata._gene_selector = self._gene_selector

    # Copy filtered metadata functions
    new_adata._filtered_obs = self._filtered_obs
    new_adata._filtered_var = self._filtered_var

    # Copy transformations
    new_adata._transformations = self._transformations.copy()

    # Set up parent reference for the expression matrix
    if isinstance(new_adata._X, LazyExpressionMatrix):
        new_adata._X.parent_adata = new_adata

    return new_adata
to_memory() -> scipy.sparse.spmatrix

Load entire matrix into memory

Source code in slaf/integrations/anndata.py
def to_memory(self) -> scipy.sparse.spmatrix:
    """Load entire matrix into memory"""
    return self.get_expression_data()
write(filename: str)

Write to h5ad format (would need implementation)

Source code in slaf/integrations/anndata.py
def write(self, filename: str):
    """Write to h5ad format (would need implementation)"""
    raise NotImplementedError("Writing LazyAnnData not yet implemented")
get_expression_data() -> scipy.sparse.csr_matrix

Get expression data with any applied filters

Source code in slaf/integrations/anndata.py
def get_expression_data(self) -> scipy.sparse.csr_matrix:
    """Get expression data with any applied filters"""
    if isinstance(self._X, LazyExpressionMatrix):
        # If the LazyExpressionMatrix already has selectors stored, just get the data
        # without passing additional selectors to avoid double-composition
        if self._X._cell_selector is not None or self._X._gene_selector is not None:
            return self._X[:, :].compute()
        elif self._cell_selector is not None or self._gene_selector is not None:
            cell_sel = (
                self._cell_selector
                if self._cell_selector is not None
                else slice(None)
            )
            gene_sel = (
                self._gene_selector
                if self._gene_selector is not None
                else slice(None)
            )
            return self._X[cell_sel, gene_sel].compute()
        else:
            return self._X[:, :].compute()
    else:
        raise NotImplementedError(
            "Dask backend not yet implemented for get_expression_data"
        )
compute() -> sc.AnnData

Explicitly compute and return a native AnnData object

Source code in slaf/integrations/anndata.py
def compute(self) -> "sc.AnnData":
    """Explicitly compute and return a native AnnData object"""
    import scanpy as sc

    # Create native AnnData object
    adata = sc.AnnData(X=self._X.compute(), obs=self.obs, var=self.var)

    return adata

Functions

read_slaf(filename: str, backend: str = 'auto') -> LazyAnnData

Read SLAF file as LazyAnnData object

Source code in slaf/integrations/anndata.py
def read_slaf(filename: str, backend: str = "auto") -> LazyAnnData:
    """Read SLAF file as LazyAnnData object"""
    slaf_array = SLAFArray(filename)
    return LazyAnnData(slaf_array, backend=backend)

Scanpy Integration

slaf.integrations.scanpy

Classes

LazyPreprocessing

Scanpy preprocessing functions with lazy evaluation

Source code in slaf/integrations/scanpy.py
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
class LazyPreprocessing:
    """Scanpy preprocessing functions with lazy evaluation"""

    @staticmethod
    def calculate_qc_metrics(
        adata: LazyAnnData,
        percent_top: int | list | None = None,
        log1p: bool = True,
        inplace: bool = True,
    ) -> tuple | None:
        """
        Calculate quality control metrics for cells and genes using lazy evaluation.

        This function computes cell and gene-level QC metrics using SQL aggregation
        for memory efficiency. It calculates metrics like total counts, number of
        genes per cell, and number of cells per gene.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            percent_top: Number of top genes to consider for percent_top calculation.
                        Currently not implemented in lazy version.
            log1p: Whether to compute log1p-transformed versions of count metrics.
                   Adds log1p_total_counts and log1p_n_genes_by_counts to cell metrics,
                   and log1p_total_counts and log1p_n_cells_by_counts to gene metrics.
            inplace: Whether to modify the adata object in place. Currently not fully
                    implemented in lazy version - returns None when True.

        Returns:
            tuple | None: If inplace=False, returns (cell_qc, gene_qc) where:
                - cell_qc: DataFrame with cell-level QC metrics
                - gene_qc: DataFrame with gene-level QC metrics
                If inplace=True, returns None.

        Raises:
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Calculate QC metrics
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
            ...     adata, inplace=False
            ... )
            >>> print(f"Cell QC shape: {cell_qc.shape}")
            Cell QC shape: (1000, 4)
            >>> print(f"Gene QC shape: {gene_qc.shape}")
            Gene QC shape: (20000, 4)

            >>> # With log1p transformation
            >>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
            ...     adata, log1p=True, inplace=False
            ... )
            >>> print(f"Cell QC columns: {list(cell_qc.columns)}")
            Cell QC columns: ['cell_id', 'n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'log1p_n_genes_by_counts']
        """

        # Calculate cell-level metrics via SQL using simple aggregation (no JOINs)
        cell_qc_sql = """
        SELECT
            e.cell_integer_id,
            COUNT(DISTINCT e.gene_integer_id) as n_genes_by_counts,
            SUM(e.value) as total_counts
        FROM expression e
        GROUP BY e.cell_integer_id
        ORDER BY e.cell_integer_id
        """

        cell_qc = adata.slaf.query(cell_qc_sql)

        # Work with polars DataFrame internally
        cell_qc_pl = cell_qc

        # Map cell_integer_id to cell_id for scanpy compatibility
        if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
            # Create mapping from cell_integer_id to cell names
            # Use polars DataFrame to get cell names
            obs_df = adata.slaf.obs
            if "cell_id" in obs_df.columns:
                cell_id_to_name = dict(
                    zip(
                        obs_df["cell_integer_id"].to_list(),
                        obs_df["cell_id"].to_list(),
                        strict=False,
                    )
                )
            else:
                # Fallback: create cell names from integer IDs
                cell_id_to_name = {i: f"cell_{i}" for i in range(len(obs_df))}
            # Use vectorized polars operations for mapping
            # Create mapping DataFrame
            cell_map_df = pl.DataFrame(
                {
                    "cell_integer_id": list(cell_id_to_name.keys()),
                    "cell_id": list(cell_id_to_name.values()),
                }
            )
            # Join with mapping DataFrame
            cell_qc_pl = cell_qc_pl.join(cell_map_df, on="cell_integer_id", how="left")
            # Fill any missing values with default format
            cell_qc_pl = cell_qc_pl.with_columns(
                pl.col("cell_id").fill_null(
                    pl.col("cell_integer_id")
                    .cast(pl.Utf8)
                    .map_elements(lambda x: f"cell_{x}", return_dtype=pl.Utf8)
                )
            )
        else:
            # Fallback: use cell_integer_id as cell_id
            cell_qc_pl = cell_qc_pl.with_columns(
                pl.col("cell_integer_id").cast(pl.Utf8).alias("cell_id")
            )

        # Add log1p transformed counts if requested
        if log1p:
            cell_qc_pl = cell_qc_pl.with_columns(
                [
                    pl.col("total_counts").log1p().alias("log1p_total_counts"),
                    pl.col("n_genes_by_counts")
                    .log1p()
                    .alias("log1p_n_genes_by_counts"),
                ]
            )

        # Convert to pandas for return compatibility
        cell_qc = cell_qc_pl.to_pandas()

        # Calculate gene-level metrics via SQL using simple aggregation (no JOINs)
        gene_qc_sql = """
        SELECT
            e.gene_integer_id,
            COUNT(DISTINCT e.cell_integer_id) AS n_cells_by_counts,
            SUM(e.value) AS total_counts
        FROM expression e
        GROUP BY e.gene_integer_id
        ORDER BY e.gene_integer_id
        """

        gene_qc = adata.slaf.query(gene_qc_sql)

        # Work with polars DataFrames internally
        gene_qc_pl = gene_qc

        # For scanpy compatibility, we need to ensure all genes are present
        # Use in-memory var if available, otherwise fall back to SQL
        if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
            # Use the materialized var metadata directly
            expected_genes_pl = pl.DataFrame(
                {"gene_integer_id": range(len(adata.slaf.var))}
            )
        else:
            expected_genes_sql = """
            SELECT gene_integer_id
            FROM genes
            ORDER BY gene_integer_id
            """
            expected_genes = adata.slaf.query(expected_genes_sql)
            expected_genes_pl = expected_genes

        # Create a complete gene_qc DataFrame with all expected genes using polars
        gene_qc_complete_pl = expected_genes_pl.join(
            gene_qc_pl, on="gene_integer_id", how="left"
        ).fill_null(0)

        # Ensure proper data types
        gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
            [
                pl.col("n_cells_by_counts").cast(pl.Int64),
                pl.col("total_counts").cast(pl.Float64),
            ]
        )

        # Map gene_integer_id to gene names for scanpy compatibility
        if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
            # Create mapping from gene_integer_id to gene names
            # Use polars DataFrame to get gene names
            var_df = adata.slaf.var
            if "gene_id" in var_df.columns:
                gene_id_to_name = dict(
                    zip(
                        var_df["gene_integer_id"].to_list(),
                        var_df["gene_id"].to_list(),
                        strict=False,
                    )
                )
            else:
                # Fallback: create gene names from integer IDs
                gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
            # Use vectorized polars operations for mapping
            # Create mapping DataFrame
            gene_map_df = pl.DataFrame(
                {
                    "gene_integer_id": list(gene_id_to_name.keys()),
                    "gene_id": list(gene_id_to_name.values()),
                }
            )
            # Join with mapping DataFrame
            gene_qc_complete_pl = gene_qc_complete_pl.join(
                gene_map_df, on="gene_integer_id", how="left"
            )
            # Fill any missing values with default format
            gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
                pl.col("gene_id").fill_null(
                    pl.col("gene_integer_id")
                    .cast(pl.Utf8)
                    .map_elements(lambda x: f"gene_{x}", return_dtype=pl.Utf8)
                )
            )
        else:
            # Fallback: use gene_integer_id as gene_id
            gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
                pl.col("gene_integer_id").cast(pl.Utf8).alias("gene_id")
            )

        # Convert to pandas and set gene_id as index
        gene_qc_complete = gene_qc_complete_pl.to_pandas().set_index("gene_id")

        if log1p:
            gene_qc_complete["log1p_total_counts"] = np.log1p(
                gene_qc_complete["total_counts"]
            )
            gene_qc_complete["log1p_n_cells_by_counts"] = np.log1p(
                gene_qc_complete["n_cells_by_counts"]
            )

        if inplace:
            # Update the metadata tables in SLAF
            # This would require implementing metadata updates in SLAF
            # For now, just update the cached obs/var

            # Update obs
            adata._obs = None  # Clear cache
            for _ in cell_qc.iterrows():
                # Would need to implement metadata updates
                pass

            # Update var
            adata._var = None  # Clear cache
            for _ in gene_qc_complete.iterrows():
                # Would need to implement metadata updates
                pass

            return None
        else:
            return cell_qc, gene_qc_complete

    @staticmethod
    def filter_cells(
        adata: LazyAnnData,
        min_counts: int | None = None,
        min_genes: int | None = None,
        max_counts: int | None = None,
        max_genes: int | None = None,
        inplace: bool = True,
    ) -> LazyAnnData | None:
        """
        Filter cells based on quality control metrics using lazy evaluation.

        This function filters cells based on their total counts and number of genes
        using SQL aggregation for memory efficiency. It supports both minimum and
        maximum thresholds for each metric.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            min_counts: Minimum total counts per cell. Cells with fewer counts are filtered.
            min_genes: Minimum number of genes per cell. Cells with fewer genes are filtered.
            max_counts: Maximum total counts per cell. Cells with more counts are filtered.
            max_genes: Maximum number of genes per cell. Cells with more genes are filtered.
            inplace: Whether to modify the adata object in place. Currently not fully
                    implemented in lazy version - returns None when True.

        Returns:
            LazyAnnData | None: If inplace=False, returns filtered LazyAnnData.
                               If inplace=True, returns None.

        Raises:
            ValueError: If all cells are filtered out by the criteria.
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Filter cells with basic criteria
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> filtered = LazyPreprocessing.filter_cells(
            ...     adata, min_counts=100, min_genes=50, inplace=False
            ... )
            >>> print(f"Original cells: {adata.n_obs}")
            Original cells: 1000
            >>> print(f"Filtered cells: {filtered.n_obs}")
            Filtered cells: 850

            >>> # Filter with maximum thresholds
            >>> filtered = LazyPreprocessing.filter_cells(
            ...     adata, max_counts=10000, max_genes=5000, inplace=False
            ... )
            >>> print(f"Cells after max filtering: {filtered.n_obs}")
            Cells after max filtering: 920

            >>> # Error when all cells filtered out
            >>> try:
            ...     LazyPreprocessing.filter_cells(adata, min_counts=1000000)
            ... except ValueError as e:
            ...     print(f"Error: {e}")
            Error: All cells were filtered out
        """

        # Build filter conditions
        conditions = []

        if min_counts is not None:
            conditions.append(f"cell_stats.total_counts >= {min_counts}")
        if max_counts is not None:
            conditions.append(f"cell_stats.total_counts <= {max_counts}")
        if min_genes is not None:
            conditions.append(f"cell_stats.n_genes_by_counts >= {min_genes}")
        if max_genes is not None:
            conditions.append(f"cell_stats.n_genes_by_counts <= {max_genes}")

        if not conditions:
            return adata if not inplace else None

        where_clause = " AND ".join(conditions)

        # Get filtered cell IDs using simple aggregation (no JOINs)
        filter_sql = f"""
        SELECT cell_stats.cell_integer_id
        FROM (
            SELECT
                e.cell_integer_id,
                COUNT(DISTINCT e.gene_integer_id) as n_genes_by_counts,
                SUM(e.value) as total_counts
            FROM expression e
            GROUP BY e.cell_integer_id
        ) cell_stats
        WHERE ({where_clause})
        ORDER BY cell_stats.cell_integer_id
        """

        filtered_cells = adata.slaf.query(filter_sql)

        if len(filtered_cells) == 0:
            raise ValueError("All cells were filtered out")

        # Create boolean mask from the filtered cell IDs
        # Use the materialized obs metadata to map cell_integer_id to cell names
        if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
            # Get all cell integer IDs that pass the filter
            filtered_cell_ids = set(filtered_cells["cell_integer_id"].to_list())

            # Create boolean mask for all cells
            all_cell_ids = adata.slaf.obs["cell_integer_id"].to_list()
            boolean_mask = [cell_id in filtered_cell_ids for cell_id in all_cell_ids]

            # Actually subset the LazyAnnData object (like scanpy does)
            if inplace:
                # Set up the filtered obs function to apply the boolean mask
                def filtered_obs() -> pd.DataFrame:
                    obs_df = adata.slaf.obs
                    if obs_df is not None:
                        # Work with polars DataFrame internally
                        obs_pl = obs_df
                        # Drop cell_integer_id column if present
                        if "cell_integer_id" in obs_pl.columns:
                            obs_pl = obs_pl.drop("cell_integer_id")
                        # Apply boolean mask
                        obs_pl = obs_pl.filter(pl.Series(boolean_mask))
                        # Convert to pandas DataFrame for AnnData compatibility
                        obs_copy = obs_pl.to_pandas()
                        # Set cell_id as index if present
                        if "cell_id" in obs_copy.columns:
                            obs_copy = obs_copy.set_index("cell_id")
                        # Set index name to match AnnData format
                        if hasattr(obs_copy, "index"):
                            obs_copy.index.name = "cell_id"
                        return obs_copy
                    return pd.DataFrame()

                # Set the filtered functions
                adata._filtered_obs = filtered_obs
                adata._filtered_var = None  # No gene filtering
                adata._cell_selector = boolean_mask
                adata._gene_selector = None

                # Clear cached names to force recalculation
                adata._cached_obs_names = None
                adata._cached_var_names = None

                return None
            else:
                # Create a new filtered LazyAnnData
                filtered_adata = LazyAnnData(adata.slaf, backend=adata.backend)

                # Set up the filtered obs function
                def filtered_obs() -> pd.DataFrame:
                    obs_df = adata.slaf.obs
                    if obs_df is not None:
                        # Work with polars DataFrame internally
                        obs_pl = obs_df
                        # Drop cell_integer_id column if present
                        if "cell_integer_id" in obs_pl.columns:
                            obs_pl = obs_pl.drop("cell_integer_id")
                        # Apply boolean mask
                        obs_pl = obs_pl.filter(pl.Series(boolean_mask))
                        # Convert to pandas DataFrame for AnnData compatibility
                        obs_copy = obs_pl.to_pandas()
                        # Set cell_id as index if present
                        if "cell_id" in obs_copy.columns:
                            obs_copy = obs_copy.set_index("cell_id")
                        # Set index name to match AnnData format
                        if hasattr(obs_copy, "index"):
                            obs_copy.index.name = "cell_id"
                        return obs_copy
                    return pd.DataFrame()

                # Set the filtered functions
                filtered_adata._filtered_obs = filtered_obs
                filtered_adata._filtered_var = None  # No gene filtering
                filtered_adata._cell_selector = boolean_mask
                filtered_adata._gene_selector = None

                return filtered_adata
        else:
            # Fallback to using cell_integer_id directly
            cell_mask = adata.obs_names.isin(filtered_cells["cell_integer_id"])

        if inplace:
            # Apply filter to adata (would need proper implementation)
            # For now, just return the original adata
            print(
                f"Filtered out {np.sum(~cell_mask)} cells, {np.sum(cell_mask)} remaining"
            )
            return None
        else:
            # Create new filtered LazyAnnData
            filtered_adata = adata.copy()
            # Apply mask (would need proper implementation)
            return filtered_adata

    @staticmethod
    def filter_genes(
        adata: LazyAnnData,
        min_counts: int | None = None,
        min_cells: int | None = None,
        max_counts: int | None = None,
        max_cells: int | None = None,
        inplace: bool = True,
    ) -> LazyAnnData | None:
        """
        Filter genes based on quality control metrics using lazy evaluation.

        This function filters genes based on their total counts and number of cells
        using SQL aggregation for memory efficiency. It supports both minimum and
        maximum thresholds for each metric.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            min_counts: Minimum total counts per gene. Genes with fewer counts are filtered.
            min_cells: Minimum number of cells per gene. Genes expressed in fewer cells are filtered.
            max_counts: Maximum total counts per gene. Genes with more counts are filtered.
            max_cells: Maximum number of cells per gene. Genes expressed in more cells are filtered.
            inplace: Whether to modify the adata object in place. Currently not fully
                    implemented in lazy version - returns None when True.

        Returns:
            LazyAnnData | None: If inplace=False, returns filtered LazyAnnData.
                               If inplace=True, returns None.

        Raises:
            ValueError: If all genes are filtered out by the criteria.
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Filter genes with basic criteria
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> filtered = LazyPreprocessing.filter_genes(
            ...     adata, min_counts=10, min_cells=5, inplace=False
            ... )
            >>> print(f"Original genes: {adata.n_vars}")
            Original genes: 20000
            >>> print(f"Filtered genes: {filtered.n_vars}")
            Filtered genes: 15000

            >>> # Filter with maximum thresholds
            >>> filtered = LazyPreprocessing.filter_genes(
            ...     adata, max_counts=100000, max_cells=1000, inplace=False
            ... )
            >>> print(f"Genes after max filtering: {filtered.n_vars}")
            Genes after max filtering: 18000

            >>> # Error when all genes filtered out
            >>> try:
            ...     LazyPreprocessing.filter_genes(adata, min_counts=1000000)
            ... except ValueError as e:
            ...     print(f"Error: {e}")
            Error: All genes were filtered out
        """

        # Build filter conditions for genes
        conditions = []

        if min_counts is not None:
            conditions.append(f"gene_stats.total_counts >= {min_counts}")
        if max_counts is not None:
            conditions.append(f"gene_stats.total_counts <= {max_counts}")
        if min_cells is not None:
            conditions.append(f"gene_stats.n_cells_by_counts >= {min_cells}")
        if max_cells is not None:
            conditions.append(f"gene_stats.n_cells_by_counts <= {max_cells}")

        if not conditions:
            return adata if not inplace else None

        where_clause = " AND ".join(conditions)

        # Get filtered gene IDs using simple aggregation (no JOINs)
        filter_sql = f"""
        SELECT gene_stats.gene_integer_id
        FROM (
            SELECT
                e.gene_integer_id,
                COUNT(DISTINCT e.cell_integer_id) AS n_cells_by_counts,
                SUM(e.value) AS total_counts
            FROM expression e
            GROUP BY e.gene_integer_id
        ) gene_stats
        WHERE {where_clause}
        ORDER BY gene_stats.gene_integer_id
        """

        filtered_genes = adata.slaf.query(filter_sql)

        if len(filtered_genes) == 0:
            raise ValueError("All genes were filtered out")

        # Create boolean mask from the filtered gene IDs
        # Use the materialized var metadata to map gene_integer_id to gene names
        if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
            # Create a mapping from gene_integer_id to gene names
            # Use polars DataFrame to get gene names
            var_df = adata.slaf.var
            if "gene_id" in var_df.columns:
                gene_id_to_name = dict(
                    zip(
                        var_df["gene_integer_id"].to_list(),
                        var_df["gene_id"].to_list(),
                        strict=False,
                    )
                )
            else:
                # Fallback: create gene names from integer IDs
                gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
            filtered_gene_names = [
                gene_id_to_name.get(gid, f"gene_{gid}")
                for gid in filtered_genes["gene_integer_id"]
            ]
            gene_mask = adata.var_names.isin(filtered_gene_names)
        else:
            # Fallback to using gene_integer_id directly
            gene_mask = adata.var_names.isin(filtered_genes["gene_integer_id"])

        if inplace:
            # Apply filter to adata (would need proper implementation)
            print(
                f"Filtered out {np.sum(~gene_mask)} genes, {np.sum(gene_mask)} remaining"
            )
            return None
        else:
            # Create new filtered LazyAnnData
            filtered_adata = adata.copy()
            # Apply mask (would need proper implementation)
            return filtered_adata

    @staticmethod
    def normalize_total(
        adata: LazyAnnData,
        target_sum: float | None = 1e4,
        inplace: bool = True,
        fragments: bool | None = None,
    ) -> LazyAnnData | None:
        """
        Normalize counts per cell to target sum using lazy evaluation.

        This function normalizes the expression data so that each cell has a total
        count equal to target_sum. The normalization is applied lazily and stored
        as a transformation that will be computed when the data is accessed.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            target_sum: Target sum for normalization. Default is 10,000.
            inplace: Whether to modify the adata object in place. If False, returns
                    a copy with the transformation applied.
            fragments: Whether to use fragment-based processing. If None, automatically
                      selects based on dataset characteristics.

        Returns:
            LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation.
                               If inplace=True, returns None.

        Raises:
            ValueError: If target_sum is not positive.
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Basic normalization
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> LazyPreprocessing.normalize_total(adata, target_sum=10000)
            Applied normalize_total with target_sum=10000

            >>> # Custom target sum
            >>> adata_copy = adata.copy()
            >>> LazyPreprocessing.normalize_total(
            ...     adata_copy, target_sum=5000, inplace=False
            ... )
            >>> print("Normalization applied to copy")

            >>> # Error with invalid target_sum
            >>> try:
            ...     LazyPreprocessing.normalize_total(adata, target_sum=0)
            ... except ValueError as e:
            ...     print(f"Error: {e}")
            Error: target_sum must be positive
        """
        if target_sum is None:
            target_sum = 1e4

        # Validate target_sum
        if target_sum <= 0:
            raise ValueError("target_sum must be positive")

        # Determine processing strategy
        if fragments is not None:
            use_fragments = fragments
        else:
            # Check if dataset has multiple fragments
            try:
                fragments_list = adata.slaf.expression.get_fragments()
                use_fragments = len(fragments_list) > 1
            except Exception:
                use_fragments = False

        if use_fragments:
            # Use fragment-based processing
            try:
                from slaf.core.fragment_processor import FragmentProcessor

                # Get selectors from the LazyAnnData if it's sliced
                cell_selector = getattr(adata, "_cell_selector", None)
                gene_selector = getattr(adata, "_gene_selector", None)

                processor = FragmentProcessor(
                    adata.slaf,
                    cell_selector=cell_selector,
                    gene_selector=gene_selector,
                    max_workers=4,
                    enable_caching=True,
                )
                # Use smart strategy selection for optimal performance
                lazy_pipeline = processor.build_lazy_pipeline_smart(
                    "normalize_total", target_sum=target_sum
                )
                result_df = processor.compute(lazy_pipeline)

                # Update adata with normalized values
                return adata._update_with_normalized_data(
                    result_df, target_sum, inplace
                )

            except Exception as e:
                print(
                    f"Fragment processing failed, falling back to global processing: {e}"
                )
                # Fall back to global processing
                use_fragments = False

        if not use_fragments:
            # Use global processing (original implementation)
            # Get cell totals for normalization using only the expression table
            cell_totals_sql = """
            SELECT
                e.cell_integer_id,
                SUM(e.value) as total_counts
            FROM expression e
            GROUP BY e.cell_integer_id
            ORDER BY e.cell_integer_id
            """

            cell_totals = adata.slaf.query(cell_totals_sql)

        # Work with polars DataFrame internally
        cell_totals_pl = cell_totals

        # Create normalization factors using polars
        # Map cell_integer_id to cell names for compatibility with anndata.py
        if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
            # Create mapping from cell_integer_id to cell names
            # Use polars DataFrame to get cell names
            obs_df = adata.slaf.obs
            if "cell_id" in obs_df.columns:
                cell_id_to_name = dict(
                    zip(
                        obs_df["cell_integer_id"].to_list(),
                        obs_df["cell_id"].to_list(),
                        strict=False,
                    )
                )
            else:
                # Fallback: create cell names from integer IDs
                cell_id_to_name = {i: f"cell_{i}" for i in range(len(obs_df))}
            # Use vectorized polars operations for mapping
            # Create mapping DataFrame
            cell_map_df = pl.DataFrame(
                {
                    "cell_integer_id": list(cell_id_to_name.keys()),
                    "cell_id": list(cell_id_to_name.values()),
                }
            )
            # Join with mapping DataFrame
            cell_totals_pl = cell_totals_pl.join(
                cell_map_df, on="cell_integer_id", how="left"
            )
            # Fill any missing values with default format
            cell_totals_pl = cell_totals_pl.with_columns(
                [
                    pl.col("cell_id").fill_null(
                        pl.col("cell_integer_id")
                        .cast(pl.Utf8)
                        .map_elements(lambda x: f"cell_{x}", return_dtype=pl.Utf8)
                    ),
                    (target_sum / pl.col("total_counts")).alias("normalization_factor"),
                ]
            )
            # Convert to dictionary for compatibility
            normalization_dict = dict(
                zip(
                    cell_totals_pl["cell_id"].to_list(),
                    cell_totals_pl["normalization_factor"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: use cell_integer_id as string keys
            cell_totals_pl = cell_totals_pl.with_columns(
                [
                    pl.col("cell_integer_id").cast(pl.Utf8).alias("cell_id"),
                    (target_sum / pl.col("total_counts")).alias("normalization_factor"),
                ]
            )
            # Convert to dictionary for compatibility
            normalization_dict = dict(
                zip(
                    cell_totals_pl["cell_id"].to_list(),
                    cell_totals_pl["normalization_factor"].to_list(),
                    strict=False,
                )
            )

        if inplace:
            # Store normalization factors for lazy application
            if not hasattr(adata, "_transformations"):
                adata._transformations = {}

            adata._transformations["normalize_total"] = {
                "type": "normalize_total",
                "target_sum": float(
                    f"{target_sum:.10f}"
                ),  # Convert to regular decimal format
                "cell_factors": normalization_dict,
            }

            print(f"Applied normalize_total with target_sum={target_sum}")
            return None
        else:
            # Create a copy with the transformation (copy-on-write)
            new_adata = adata.copy()
            if not hasattr(new_adata, "_transformations"):
                new_adata._transformations = {}

            new_adata._transformations["normalize_total"] = {
                "type": "normalize_total",
                "target_sum": float(
                    f"{target_sum:.10f}"
                ),  # Convert to regular decimal format
                "cell_factors": normalization_dict,
            }

            return new_adata

    @staticmethod
    def log1p(
        adata: LazyAnnData, inplace: bool = True, fragments: bool | None = None
    ) -> LazyAnnData | None:
        """
        Apply log1p transformation to expression data using lazy evaluation.

        This function applies log(1 + x) transformation to the expression data.
        The transformation is stored lazily and will be computed when the data
        is accessed, avoiding memory-intensive operations on large datasets.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            inplace: Whether to modify the adata object in place. If False, returns
                    a copy with the transformation applied.

        Returns:
            LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation.
                               If inplace=True, returns None.

        Raises:
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Apply log1p transformation
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> LazyPreprocessing.log1p(adata)
            Applied log1p transformation

            >>> # Apply to copy
            >>> adata_copy = adata.copy()
            >>> LazyPreprocessing.log1p(adata_copy, inplace=False)
            >>> print("Log1p transformation applied to copy")

            >>> # Check transformation was stored
            >>> print("log1p" in adata._transformations)
            True
        """
        # Determine processing strategy
        if fragments is not None:
            use_fragments = fragments
        else:
            # Check if dataset has multiple fragments
            try:
                fragments_list = adata.slaf.expression.get_fragments()
                use_fragments = len(fragments_list) > 1
            except Exception:
                use_fragments = False

        if use_fragments:
            # Use fragment-based processing
            try:
                from slaf.core.fragment_processor import FragmentProcessor

                # Get selectors from the LazyAnnData if it's sliced
                cell_selector = getattr(adata, "_cell_selector", None)
                gene_selector = getattr(adata, "_gene_selector", None)

                processor = FragmentProcessor(
                    adata.slaf,
                    cell_selector=cell_selector,
                    gene_selector=gene_selector,
                    max_workers=4,
                    enable_caching=True,
                )
                # Use smart strategy selection for optimal performance
                lazy_pipeline = processor.build_lazy_pipeline_smart("log1p")
                result_df = processor.compute(lazy_pipeline)

                # Update adata with log1p values
                return adata._update_with_log1p_data(result_df, inplace)

            except Exception as e:
                print(
                    f"Fragment processing failed, falling back to global processing: {e}"
                )
                # Fall back to global processing
                use_fragments = False

        if not use_fragments:
            # Use global processing (original implementation)
            if inplace:
                # Store log1p transformation for lazy application
                if not hasattr(adata, "_transformations"):
                    adata._transformations = {}

                adata._transformations["log1p"] = {"type": "log1p", "applied": True}

                print("Applied log1p transformation")
                return None
            else:
                # Create a copy with the transformation (copy-on-write)
                new_adata = adata.copy()
                if not hasattr(new_adata, "_transformations"):
                    new_adata._transformations = {}

                new_adata._transformations["log1p"] = {"type": "log1p", "applied": True}

                return new_adata

    @staticmethod
    def highly_variable_genes(
        adata: LazyAnnData,
        min_mean: float = 0.0125,
        max_mean: float = 3,
        min_disp: float = 0.5,
        max_disp: float = np.inf,
        n_top_genes: int | None = None,
        inplace: bool = True,
    ) -> pd.DataFrame | None:
        """
        Identify highly variable genes using lazy evaluation.

        This function identifies genes with high cell-to-cell variation in expression
        using SQL aggregation for memory efficiency. It calculates mean expression
        and dispersion for each gene and applies filtering criteria.

        Args:
            adata: LazyAnnData instance containing the single-cell data.
            min_mean: Minimum mean expression for genes to be considered.
            max_mean: Maximum mean expression for genes to be considered.
            min_disp: Minimum dispersion for genes to be considered.
            max_disp: Maximum dispersion for genes to be considered.
            n_top_genes: Number of top genes to select by dispersion.
                        If specified, overrides min_disp and max_disp criteria.
            inplace: Whether to modify the adata object in place. Currently not
                    fully implemented - returns None when True.

        Returns:
            pd.DataFrame | None: If inplace=False, returns DataFrame with gene statistics
                                and highly_variable column. If inplace=True, returns None.

        Raises:
            RuntimeError: If the SLAF array is not properly initialized.

        Examples:
            >>> # Find highly variable genes
            >>> slaf_array = SLAFArray("path/to/data.slaf")
            >>> adata = LazyAnnData(slaf_array)
            >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
            ...     adata, inplace=False
            ... )
            >>> print(f"Highly variable genes: {hvg_stats['highly_variable'].sum()}")
            Highly variable genes: 1500

            >>> # With custom criteria
            >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
            ...     adata, min_mean=0.1, max_mean=5, min_disp=1.0, inplace=False
            ... )
            >>> print(f"Genes meeting criteria: {hvg_stats['highly_variable'].sum()}")
            Genes meeting criteria: 800

            >>> # Select top N genes
            >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
            ...     adata, n_top_genes=1000, inplace=False
            ... )
            >>> print(f"Top genes selected: {hvg_stats['highly_variable'].sum()}")
            Top genes selected: 1000
        """

        # Calculate gene statistics via SQL using simple aggregation (no JOINs)
        stats_sql = """
        SELECT
            e.gene_integer_id,
            COUNT(DISTINCT e.cell_integer_id) AS n_cells,
            AVG(e.value) AS mean_expr,
            VARIANCE(e.value) AS variance,
            CASE WHEN AVG(e.value) > 0 THEN VARIANCE(e.value) / AVG(e.value) ELSE 0 END as dispersion
        FROM expression e
        GROUP BY e.gene_integer_id
        ORDER BY e.gene_integer_id
        """

        gene_stats = adata.slaf.query(stats_sql)

        # Work with polars DataFrames internally
        gene_stats_pl = gene_stats

        # Get the expected gene_integer_ids from the materialized var metadata
        # Use in-memory var if available, otherwise fall back to SQL
        if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
            # Use the materialized var metadata directly
            expected_genes_pl = pl.DataFrame(
                {"gene_integer_id": range(len(adata.slaf.var))}
            )
        else:
            # Fallback to SQL if var is not available
            expected_genes_sql = """
            SELECT gene_integer_id
            FROM genes
            ORDER BY gene_integer_id
            """
            expected_genes = adata.slaf.query(expected_genes_sql)
            expected_genes_pl = expected_genes

        # Create a complete gene_stats DataFrame with all expected genes using polars
        gene_stats_complete_pl = expected_genes_pl.join(
            gene_stats_pl, on="gene_integer_id", how="left"
        ).fill_null(0)

        # Ensure proper data types
        gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
            [
                pl.col("n_cells").cast(pl.Int64),
                pl.col("mean_expr").cast(pl.Float64),
                pl.col("variance").cast(pl.Float64),
                pl.col("dispersion").cast(pl.Float64),
            ]
        )

        # Map gene_integer_id to gene_id for scanpy compatibility
        if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
            # Create mapping from gene_integer_id to gene names
            # Use polars DataFrame to get gene names
            var_df = adata.slaf.var
            if "gene_id" in var_df.columns:
                gene_id_to_name = dict(
                    zip(
                        var_df["gene_integer_id"].to_list(),
                        var_df["gene_id"].to_list(),
                        strict=False,
                    )
                )
            else:
                # Fallback: create gene names from integer IDs
                gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
            # Use vectorized polars operations for mapping
            # Create mapping DataFrame
            gene_map_df = pl.DataFrame(
                {
                    "gene_integer_id": list(gene_id_to_name.keys()),
                    "gene_id": list(gene_id_to_name.values()),
                }
            )
            # Join with mapping DataFrame
            gene_stats_complete_pl = gene_stats_complete_pl.join(
                gene_map_df, on="gene_integer_id", how="left"
            )
            # Fill any missing values with default format
            gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
                pl.col("gene_id").fill_null(
                    pl.col("gene_integer_id")
                    .cast(pl.Utf8)
                    .map_elements(lambda x: f"gene_{x}", return_dtype=pl.Utf8)
                )
            )
        else:
            # Fallback: use gene_integer_id as gene_id
            gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
                pl.col("gene_integer_id").cast(pl.Utf8).alias("gene_id")
            )

        # Convert to pandas and set gene_id as index for scanpy compatibility
        gene_stats_complete = gene_stats_complete_pl.to_pandas().set_index("gene_id")

        # Apply HVG criteria
        hvg_mask = (
            (gene_stats_complete["mean_expr"] >= min_mean)
            & (gene_stats_complete["mean_expr"] <= max_mean)
            & (gene_stats_complete["dispersion"] >= min_disp)
            & (gene_stats_complete["dispersion"] <= max_disp)
        )

        gene_stats_complete["highly_variable"] = hvg_mask

        if n_top_genes is not None:
            # Select top N genes by dispersion
            top_genes = gene_stats_complete.nlargest(n_top_genes, "dispersion")
            gene_stats_complete["highly_variable"] = gene_stats_complete.index.isin(
                top_genes.index
            )

        if inplace:
            # Update var metadata (would need implementation)
            print(f"Identified {hvg_mask.sum()} highly variable genes")
            return None
        else:
            return gene_stats_complete
Functions
calculate_qc_metrics(adata: LazyAnnData, percent_top: int | list | None = None, log1p: bool = True, inplace: bool = True) -> tuple | None staticmethod

Calculate quality control metrics for cells and genes using lazy evaluation.

This function computes cell and gene-level QC metrics using SQL aggregation for memory efficiency. It calculates metrics like total counts, number of genes per cell, and number of cells per gene.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
percent_top int | list | None

Number of top genes to consider for percent_top calculation. Currently not implemented in lazy version.

None
log1p bool

Whether to compute log1p-transformed versions of count metrics. Adds log1p_total_counts and log1p_n_genes_by_counts to cell metrics, and log1p_total_counts and log1p_n_cells_by_counts to gene metrics.

True
inplace bool

Whether to modify the adata object in place. Currently not fully implemented in lazy version - returns None when True.

True

Returns:

Type Description
tuple | None

tuple | None: If inplace=False, returns (cell_qc, gene_qc) where: - cell_qc: DataFrame with cell-level QC metrics - gene_qc: DataFrame with gene-level QC metrics If inplace=True, returns None.

Raises:

Type Description
RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Calculate QC metrics
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
...     adata, inplace=False
... )
>>> print(f"Cell QC shape: {cell_qc.shape}")
Cell QC shape: (1000, 4)
>>> print(f"Gene QC shape: {gene_qc.shape}")
Gene QC shape: (20000, 4)
>>> # With log1p transformation
>>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
...     adata, log1p=True, inplace=False
... )
>>> print(f"Cell QC columns: {list(cell_qc.columns)}")
Cell QC columns: ['cell_id', 'n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'log1p_n_genes_by_counts']
Source code in slaf/integrations/scanpy.py
@staticmethod
def calculate_qc_metrics(
    adata: LazyAnnData,
    percent_top: int | list | None = None,
    log1p: bool = True,
    inplace: bool = True,
) -> tuple | None:
    """
    Calculate quality control metrics for cells and genes using lazy evaluation.

    This function computes cell and gene-level QC metrics using SQL aggregation
    for memory efficiency. It calculates metrics like total counts, number of
    genes per cell, and number of cells per gene.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        percent_top: Number of top genes to consider for percent_top calculation.
                    Currently not implemented in lazy version.
        log1p: Whether to compute log1p-transformed versions of count metrics.
               Adds log1p_total_counts and log1p_n_genes_by_counts to cell metrics,
               and log1p_total_counts and log1p_n_cells_by_counts to gene metrics.
        inplace: Whether to modify the adata object in place. Currently not fully
                implemented in lazy version - returns None when True.

    Returns:
        tuple | None: If inplace=False, returns (cell_qc, gene_qc) where:
            - cell_qc: DataFrame with cell-level QC metrics
            - gene_qc: DataFrame with gene-level QC metrics
            If inplace=True, returns None.

    Raises:
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Calculate QC metrics
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
        ...     adata, inplace=False
        ... )
        >>> print(f"Cell QC shape: {cell_qc.shape}")
        Cell QC shape: (1000, 4)
        >>> print(f"Gene QC shape: {gene_qc.shape}")
        Gene QC shape: (20000, 4)

        >>> # With log1p transformation
        >>> cell_qc, gene_qc = LazyPreprocessing.calculate_qc_metrics(
        ...     adata, log1p=True, inplace=False
        ... )
        >>> print(f"Cell QC columns: {list(cell_qc.columns)}")
        Cell QC columns: ['cell_id', 'n_genes_by_counts', 'total_counts', 'log1p_total_counts', 'log1p_n_genes_by_counts']
    """

    # Calculate cell-level metrics via SQL using simple aggregation (no JOINs)
    cell_qc_sql = """
    SELECT
        e.cell_integer_id,
        COUNT(DISTINCT e.gene_integer_id) as n_genes_by_counts,
        SUM(e.value) as total_counts
    FROM expression e
    GROUP BY e.cell_integer_id
    ORDER BY e.cell_integer_id
    """

    cell_qc = adata.slaf.query(cell_qc_sql)

    # Work with polars DataFrame internally
    cell_qc_pl = cell_qc

    # Map cell_integer_id to cell_id for scanpy compatibility
    if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
        # Create mapping from cell_integer_id to cell names
        # Use polars DataFrame to get cell names
        obs_df = adata.slaf.obs
        if "cell_id" in obs_df.columns:
            cell_id_to_name = dict(
                zip(
                    obs_df["cell_integer_id"].to_list(),
                    obs_df["cell_id"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: create cell names from integer IDs
            cell_id_to_name = {i: f"cell_{i}" for i in range(len(obs_df))}
        # Use vectorized polars operations for mapping
        # Create mapping DataFrame
        cell_map_df = pl.DataFrame(
            {
                "cell_integer_id": list(cell_id_to_name.keys()),
                "cell_id": list(cell_id_to_name.values()),
            }
        )
        # Join with mapping DataFrame
        cell_qc_pl = cell_qc_pl.join(cell_map_df, on="cell_integer_id", how="left")
        # Fill any missing values with default format
        cell_qc_pl = cell_qc_pl.with_columns(
            pl.col("cell_id").fill_null(
                pl.col("cell_integer_id")
                .cast(pl.Utf8)
                .map_elements(lambda x: f"cell_{x}", return_dtype=pl.Utf8)
            )
        )
    else:
        # Fallback: use cell_integer_id as cell_id
        cell_qc_pl = cell_qc_pl.with_columns(
            pl.col("cell_integer_id").cast(pl.Utf8).alias("cell_id")
        )

    # Add log1p transformed counts if requested
    if log1p:
        cell_qc_pl = cell_qc_pl.with_columns(
            [
                pl.col("total_counts").log1p().alias("log1p_total_counts"),
                pl.col("n_genes_by_counts")
                .log1p()
                .alias("log1p_n_genes_by_counts"),
            ]
        )

    # Convert to pandas for return compatibility
    cell_qc = cell_qc_pl.to_pandas()

    # Calculate gene-level metrics via SQL using simple aggregation (no JOINs)
    gene_qc_sql = """
    SELECT
        e.gene_integer_id,
        COUNT(DISTINCT e.cell_integer_id) AS n_cells_by_counts,
        SUM(e.value) AS total_counts
    FROM expression e
    GROUP BY e.gene_integer_id
    ORDER BY e.gene_integer_id
    """

    gene_qc = adata.slaf.query(gene_qc_sql)

    # Work with polars DataFrames internally
    gene_qc_pl = gene_qc

    # For scanpy compatibility, we need to ensure all genes are present
    # Use in-memory var if available, otherwise fall back to SQL
    if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
        # Use the materialized var metadata directly
        expected_genes_pl = pl.DataFrame(
            {"gene_integer_id": range(len(adata.slaf.var))}
        )
    else:
        expected_genes_sql = """
        SELECT gene_integer_id
        FROM genes
        ORDER BY gene_integer_id
        """
        expected_genes = adata.slaf.query(expected_genes_sql)
        expected_genes_pl = expected_genes

    # Create a complete gene_qc DataFrame with all expected genes using polars
    gene_qc_complete_pl = expected_genes_pl.join(
        gene_qc_pl, on="gene_integer_id", how="left"
    ).fill_null(0)

    # Ensure proper data types
    gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
        [
            pl.col("n_cells_by_counts").cast(pl.Int64),
            pl.col("total_counts").cast(pl.Float64),
        ]
    )

    # Map gene_integer_id to gene names for scanpy compatibility
    if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
        # Create mapping from gene_integer_id to gene names
        # Use polars DataFrame to get gene names
        var_df = adata.slaf.var
        if "gene_id" in var_df.columns:
            gene_id_to_name = dict(
                zip(
                    var_df["gene_integer_id"].to_list(),
                    var_df["gene_id"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: create gene names from integer IDs
            gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
        # Use vectorized polars operations for mapping
        # Create mapping DataFrame
        gene_map_df = pl.DataFrame(
            {
                "gene_integer_id": list(gene_id_to_name.keys()),
                "gene_id": list(gene_id_to_name.values()),
            }
        )
        # Join with mapping DataFrame
        gene_qc_complete_pl = gene_qc_complete_pl.join(
            gene_map_df, on="gene_integer_id", how="left"
        )
        # Fill any missing values with default format
        gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
            pl.col("gene_id").fill_null(
                pl.col("gene_integer_id")
                .cast(pl.Utf8)
                .map_elements(lambda x: f"gene_{x}", return_dtype=pl.Utf8)
            )
        )
    else:
        # Fallback: use gene_integer_id as gene_id
        gene_qc_complete_pl = gene_qc_complete_pl.with_columns(
            pl.col("gene_integer_id").cast(pl.Utf8).alias("gene_id")
        )

    # Convert to pandas and set gene_id as index
    gene_qc_complete = gene_qc_complete_pl.to_pandas().set_index("gene_id")

    if log1p:
        gene_qc_complete["log1p_total_counts"] = np.log1p(
            gene_qc_complete["total_counts"]
        )
        gene_qc_complete["log1p_n_cells_by_counts"] = np.log1p(
            gene_qc_complete["n_cells_by_counts"]
        )

    if inplace:
        # Update the metadata tables in SLAF
        # This would require implementing metadata updates in SLAF
        # For now, just update the cached obs/var

        # Update obs
        adata._obs = None  # Clear cache
        for _ in cell_qc.iterrows():
            # Would need to implement metadata updates
            pass

        # Update var
        adata._var = None  # Clear cache
        for _ in gene_qc_complete.iterrows():
            # Would need to implement metadata updates
            pass

        return None
    else:
        return cell_qc, gene_qc_complete
filter_cells(adata: LazyAnnData, min_counts: int | None = None, min_genes: int | None = None, max_counts: int | None = None, max_genes: int | None = None, inplace: bool = True) -> LazyAnnData | None staticmethod

Filter cells based on quality control metrics using lazy evaluation.

This function filters cells based on their total counts and number of genes using SQL aggregation for memory efficiency. It supports both minimum and maximum thresholds for each metric.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
min_counts int | None

Minimum total counts per cell. Cells with fewer counts are filtered.

None
min_genes int | None

Minimum number of genes per cell. Cells with fewer genes are filtered.

None
max_counts int | None

Maximum total counts per cell. Cells with more counts are filtered.

None
max_genes int | None

Maximum number of genes per cell. Cells with more genes are filtered.

None
inplace bool

Whether to modify the adata object in place. Currently not fully implemented in lazy version - returns None when True.

True

Returns:

Type Description
LazyAnnData | None

LazyAnnData | None: If inplace=False, returns filtered LazyAnnData. If inplace=True, returns None.

Raises:

Type Description
ValueError

If all cells are filtered out by the criteria.

RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Filter cells with basic criteria
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> filtered = LazyPreprocessing.filter_cells(
...     adata, min_counts=100, min_genes=50, inplace=False
... )
>>> print(f"Original cells: {adata.n_obs}")
Original cells: 1000
>>> print(f"Filtered cells: {filtered.n_obs}")
Filtered cells: 850
>>> # Filter with maximum thresholds
>>> filtered = LazyPreprocessing.filter_cells(
...     adata, max_counts=10000, max_genes=5000, inplace=False
... )
>>> print(f"Cells after max filtering: {filtered.n_obs}")
Cells after max filtering: 920
>>> # Error when all cells filtered out
>>> try:
...     LazyPreprocessing.filter_cells(adata, min_counts=1000000)
... except ValueError as e:
...     print(f"Error: {e}")
Error: All cells were filtered out
Source code in slaf/integrations/scanpy.py
@staticmethod
def filter_cells(
    adata: LazyAnnData,
    min_counts: int | None = None,
    min_genes: int | None = None,
    max_counts: int | None = None,
    max_genes: int | None = None,
    inplace: bool = True,
) -> LazyAnnData | None:
    """
    Filter cells based on quality control metrics using lazy evaluation.

    This function filters cells based on their total counts and number of genes
    using SQL aggregation for memory efficiency. It supports both minimum and
    maximum thresholds for each metric.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        min_counts: Minimum total counts per cell. Cells with fewer counts are filtered.
        min_genes: Minimum number of genes per cell. Cells with fewer genes are filtered.
        max_counts: Maximum total counts per cell. Cells with more counts are filtered.
        max_genes: Maximum number of genes per cell. Cells with more genes are filtered.
        inplace: Whether to modify the adata object in place. Currently not fully
                implemented in lazy version - returns None when True.

    Returns:
        LazyAnnData | None: If inplace=False, returns filtered LazyAnnData.
                           If inplace=True, returns None.

    Raises:
        ValueError: If all cells are filtered out by the criteria.
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Filter cells with basic criteria
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> filtered = LazyPreprocessing.filter_cells(
        ...     adata, min_counts=100, min_genes=50, inplace=False
        ... )
        >>> print(f"Original cells: {adata.n_obs}")
        Original cells: 1000
        >>> print(f"Filtered cells: {filtered.n_obs}")
        Filtered cells: 850

        >>> # Filter with maximum thresholds
        >>> filtered = LazyPreprocessing.filter_cells(
        ...     adata, max_counts=10000, max_genes=5000, inplace=False
        ... )
        >>> print(f"Cells after max filtering: {filtered.n_obs}")
        Cells after max filtering: 920

        >>> # Error when all cells filtered out
        >>> try:
        ...     LazyPreprocessing.filter_cells(adata, min_counts=1000000)
        ... except ValueError as e:
        ...     print(f"Error: {e}")
        Error: All cells were filtered out
    """

    # Build filter conditions
    conditions = []

    if min_counts is not None:
        conditions.append(f"cell_stats.total_counts >= {min_counts}")
    if max_counts is not None:
        conditions.append(f"cell_stats.total_counts <= {max_counts}")
    if min_genes is not None:
        conditions.append(f"cell_stats.n_genes_by_counts >= {min_genes}")
    if max_genes is not None:
        conditions.append(f"cell_stats.n_genes_by_counts <= {max_genes}")

    if not conditions:
        return adata if not inplace else None

    where_clause = " AND ".join(conditions)

    # Get filtered cell IDs using simple aggregation (no JOINs)
    filter_sql = f"""
    SELECT cell_stats.cell_integer_id
    FROM (
        SELECT
            e.cell_integer_id,
            COUNT(DISTINCT e.gene_integer_id) as n_genes_by_counts,
            SUM(e.value) as total_counts
        FROM expression e
        GROUP BY e.cell_integer_id
    ) cell_stats
    WHERE ({where_clause})
    ORDER BY cell_stats.cell_integer_id
    """

    filtered_cells = adata.slaf.query(filter_sql)

    if len(filtered_cells) == 0:
        raise ValueError("All cells were filtered out")

    # Create boolean mask from the filtered cell IDs
    # Use the materialized obs metadata to map cell_integer_id to cell names
    if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
        # Get all cell integer IDs that pass the filter
        filtered_cell_ids = set(filtered_cells["cell_integer_id"].to_list())

        # Create boolean mask for all cells
        all_cell_ids = adata.slaf.obs["cell_integer_id"].to_list()
        boolean_mask = [cell_id in filtered_cell_ids for cell_id in all_cell_ids]

        # Actually subset the LazyAnnData object (like scanpy does)
        if inplace:
            # Set up the filtered obs function to apply the boolean mask
            def filtered_obs() -> pd.DataFrame:
                obs_df = adata.slaf.obs
                if obs_df is not None:
                    # Work with polars DataFrame internally
                    obs_pl = obs_df
                    # Drop cell_integer_id column if present
                    if "cell_integer_id" in obs_pl.columns:
                        obs_pl = obs_pl.drop("cell_integer_id")
                    # Apply boolean mask
                    obs_pl = obs_pl.filter(pl.Series(boolean_mask))
                    # Convert to pandas DataFrame for AnnData compatibility
                    obs_copy = obs_pl.to_pandas()
                    # Set cell_id as index if present
                    if "cell_id" in obs_copy.columns:
                        obs_copy = obs_copy.set_index("cell_id")
                    # Set index name to match AnnData format
                    if hasattr(obs_copy, "index"):
                        obs_copy.index.name = "cell_id"
                    return obs_copy
                return pd.DataFrame()

            # Set the filtered functions
            adata._filtered_obs = filtered_obs
            adata._filtered_var = None  # No gene filtering
            adata._cell_selector = boolean_mask
            adata._gene_selector = None

            # Clear cached names to force recalculation
            adata._cached_obs_names = None
            adata._cached_var_names = None

            return None
        else:
            # Create a new filtered LazyAnnData
            filtered_adata = LazyAnnData(adata.slaf, backend=adata.backend)

            # Set up the filtered obs function
            def filtered_obs() -> pd.DataFrame:
                obs_df = adata.slaf.obs
                if obs_df is not None:
                    # Work with polars DataFrame internally
                    obs_pl = obs_df
                    # Drop cell_integer_id column if present
                    if "cell_integer_id" in obs_pl.columns:
                        obs_pl = obs_pl.drop("cell_integer_id")
                    # Apply boolean mask
                    obs_pl = obs_pl.filter(pl.Series(boolean_mask))
                    # Convert to pandas DataFrame for AnnData compatibility
                    obs_copy = obs_pl.to_pandas()
                    # Set cell_id as index if present
                    if "cell_id" in obs_copy.columns:
                        obs_copy = obs_copy.set_index("cell_id")
                    # Set index name to match AnnData format
                    if hasattr(obs_copy, "index"):
                        obs_copy.index.name = "cell_id"
                    return obs_copy
                return pd.DataFrame()

            # Set the filtered functions
            filtered_adata._filtered_obs = filtered_obs
            filtered_adata._filtered_var = None  # No gene filtering
            filtered_adata._cell_selector = boolean_mask
            filtered_adata._gene_selector = None

            return filtered_adata
    else:
        # Fallback to using cell_integer_id directly
        cell_mask = adata.obs_names.isin(filtered_cells["cell_integer_id"])

    if inplace:
        # Apply filter to adata (would need proper implementation)
        # For now, just return the original adata
        print(
            f"Filtered out {np.sum(~cell_mask)} cells, {np.sum(cell_mask)} remaining"
        )
        return None
    else:
        # Create new filtered LazyAnnData
        filtered_adata = adata.copy()
        # Apply mask (would need proper implementation)
        return filtered_adata
filter_genes(adata: LazyAnnData, min_counts: int | None = None, min_cells: int | None = None, max_counts: int | None = None, max_cells: int | None = None, inplace: bool = True) -> LazyAnnData | None staticmethod

Filter genes based on quality control metrics using lazy evaluation.

This function filters genes based on their total counts and number of cells using SQL aggregation for memory efficiency. It supports both minimum and maximum thresholds for each metric.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
min_counts int | None

Minimum total counts per gene. Genes with fewer counts are filtered.

None
min_cells int | None

Minimum number of cells per gene. Genes expressed in fewer cells are filtered.

None
max_counts int | None

Maximum total counts per gene. Genes with more counts are filtered.

None
max_cells int | None

Maximum number of cells per gene. Genes expressed in more cells are filtered.

None
inplace bool

Whether to modify the adata object in place. Currently not fully implemented in lazy version - returns None when True.

True

Returns:

Type Description
LazyAnnData | None

LazyAnnData | None: If inplace=False, returns filtered LazyAnnData. If inplace=True, returns None.

Raises:

Type Description
ValueError

If all genes are filtered out by the criteria.

RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Filter genes with basic criteria
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> filtered = LazyPreprocessing.filter_genes(
...     adata, min_counts=10, min_cells=5, inplace=False
... )
>>> print(f"Original genes: {adata.n_vars}")
Original genes: 20000
>>> print(f"Filtered genes: {filtered.n_vars}")
Filtered genes: 15000
>>> # Filter with maximum thresholds
>>> filtered = LazyPreprocessing.filter_genes(
...     adata, max_counts=100000, max_cells=1000, inplace=False
... )
>>> print(f"Genes after max filtering: {filtered.n_vars}")
Genes after max filtering: 18000
>>> # Error when all genes filtered out
>>> try:
...     LazyPreprocessing.filter_genes(adata, min_counts=1000000)
... except ValueError as e:
...     print(f"Error: {e}")
Error: All genes were filtered out
Source code in slaf/integrations/scanpy.py
@staticmethod
def filter_genes(
    adata: LazyAnnData,
    min_counts: int | None = None,
    min_cells: int | None = None,
    max_counts: int | None = None,
    max_cells: int | None = None,
    inplace: bool = True,
) -> LazyAnnData | None:
    """
    Filter genes based on quality control metrics using lazy evaluation.

    This function filters genes based on their total counts and number of cells
    using SQL aggregation for memory efficiency. It supports both minimum and
    maximum thresholds for each metric.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        min_counts: Minimum total counts per gene. Genes with fewer counts are filtered.
        min_cells: Minimum number of cells per gene. Genes expressed in fewer cells are filtered.
        max_counts: Maximum total counts per gene. Genes with more counts are filtered.
        max_cells: Maximum number of cells per gene. Genes expressed in more cells are filtered.
        inplace: Whether to modify the adata object in place. Currently not fully
                implemented in lazy version - returns None when True.

    Returns:
        LazyAnnData | None: If inplace=False, returns filtered LazyAnnData.
                           If inplace=True, returns None.

    Raises:
        ValueError: If all genes are filtered out by the criteria.
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Filter genes with basic criteria
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> filtered = LazyPreprocessing.filter_genes(
        ...     adata, min_counts=10, min_cells=5, inplace=False
        ... )
        >>> print(f"Original genes: {adata.n_vars}")
        Original genes: 20000
        >>> print(f"Filtered genes: {filtered.n_vars}")
        Filtered genes: 15000

        >>> # Filter with maximum thresholds
        >>> filtered = LazyPreprocessing.filter_genes(
        ...     adata, max_counts=100000, max_cells=1000, inplace=False
        ... )
        >>> print(f"Genes after max filtering: {filtered.n_vars}")
        Genes after max filtering: 18000

        >>> # Error when all genes filtered out
        >>> try:
        ...     LazyPreprocessing.filter_genes(adata, min_counts=1000000)
        ... except ValueError as e:
        ...     print(f"Error: {e}")
        Error: All genes were filtered out
    """

    # Build filter conditions for genes
    conditions = []

    if min_counts is not None:
        conditions.append(f"gene_stats.total_counts >= {min_counts}")
    if max_counts is not None:
        conditions.append(f"gene_stats.total_counts <= {max_counts}")
    if min_cells is not None:
        conditions.append(f"gene_stats.n_cells_by_counts >= {min_cells}")
    if max_cells is not None:
        conditions.append(f"gene_stats.n_cells_by_counts <= {max_cells}")

    if not conditions:
        return adata if not inplace else None

    where_clause = " AND ".join(conditions)

    # Get filtered gene IDs using simple aggregation (no JOINs)
    filter_sql = f"""
    SELECT gene_stats.gene_integer_id
    FROM (
        SELECT
            e.gene_integer_id,
            COUNT(DISTINCT e.cell_integer_id) AS n_cells_by_counts,
            SUM(e.value) AS total_counts
        FROM expression e
        GROUP BY e.gene_integer_id
    ) gene_stats
    WHERE {where_clause}
    ORDER BY gene_stats.gene_integer_id
    """

    filtered_genes = adata.slaf.query(filter_sql)

    if len(filtered_genes) == 0:
        raise ValueError("All genes were filtered out")

    # Create boolean mask from the filtered gene IDs
    # Use the materialized var metadata to map gene_integer_id to gene names
    if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
        # Create a mapping from gene_integer_id to gene names
        # Use polars DataFrame to get gene names
        var_df = adata.slaf.var
        if "gene_id" in var_df.columns:
            gene_id_to_name = dict(
                zip(
                    var_df["gene_integer_id"].to_list(),
                    var_df["gene_id"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: create gene names from integer IDs
            gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
        filtered_gene_names = [
            gene_id_to_name.get(gid, f"gene_{gid}")
            for gid in filtered_genes["gene_integer_id"]
        ]
        gene_mask = adata.var_names.isin(filtered_gene_names)
    else:
        # Fallback to using gene_integer_id directly
        gene_mask = adata.var_names.isin(filtered_genes["gene_integer_id"])

    if inplace:
        # Apply filter to adata (would need proper implementation)
        print(
            f"Filtered out {np.sum(~gene_mask)} genes, {np.sum(gene_mask)} remaining"
        )
        return None
    else:
        # Create new filtered LazyAnnData
        filtered_adata = adata.copy()
        # Apply mask (would need proper implementation)
        return filtered_adata
normalize_total(adata: LazyAnnData, target_sum: float | None = 10000.0, inplace: bool = True, fragments: bool | None = None) -> LazyAnnData | None staticmethod

Normalize counts per cell to target sum using lazy evaluation.

This function normalizes the expression data so that each cell has a total count equal to target_sum. The normalization is applied lazily and stored as a transformation that will be computed when the data is accessed.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
target_sum float | None

Target sum for normalization. Default is 10,000.

10000.0
inplace bool

Whether to modify the adata object in place. If False, returns a copy with the transformation applied.

True
fragments bool | None

Whether to use fragment-based processing. If None, automatically selects based on dataset characteristics.

None

Returns:

Type Description
LazyAnnData | None

LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation. If inplace=True, returns None.

Raises:

Type Description
ValueError

If target_sum is not positive.

RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Basic normalization
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> LazyPreprocessing.normalize_total(adata, target_sum=10000)
Applied normalize_total with target_sum=10000
>>> # Custom target sum
>>> adata_copy = adata.copy()
>>> LazyPreprocessing.normalize_total(
...     adata_copy, target_sum=5000, inplace=False
... )
>>> print("Normalization applied to copy")
>>> # Error with invalid target_sum
>>> try:
...     LazyPreprocessing.normalize_total(adata, target_sum=0)
... except ValueError as e:
...     print(f"Error: {e}")
Error: target_sum must be positive
Source code in slaf/integrations/scanpy.py
@staticmethod
def normalize_total(
    adata: LazyAnnData,
    target_sum: float | None = 1e4,
    inplace: bool = True,
    fragments: bool | None = None,
) -> LazyAnnData | None:
    """
    Normalize counts per cell to target sum using lazy evaluation.

    This function normalizes the expression data so that each cell has a total
    count equal to target_sum. The normalization is applied lazily and stored
    as a transformation that will be computed when the data is accessed.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        target_sum: Target sum for normalization. Default is 10,000.
        inplace: Whether to modify the adata object in place. If False, returns
                a copy with the transformation applied.
        fragments: Whether to use fragment-based processing. If None, automatically
                  selects based on dataset characteristics.

    Returns:
        LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation.
                           If inplace=True, returns None.

    Raises:
        ValueError: If target_sum is not positive.
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Basic normalization
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> LazyPreprocessing.normalize_total(adata, target_sum=10000)
        Applied normalize_total with target_sum=10000

        >>> # Custom target sum
        >>> adata_copy = adata.copy()
        >>> LazyPreprocessing.normalize_total(
        ...     adata_copy, target_sum=5000, inplace=False
        ... )
        >>> print("Normalization applied to copy")

        >>> # Error with invalid target_sum
        >>> try:
        ...     LazyPreprocessing.normalize_total(adata, target_sum=0)
        ... except ValueError as e:
        ...     print(f"Error: {e}")
        Error: target_sum must be positive
    """
    if target_sum is None:
        target_sum = 1e4

    # Validate target_sum
    if target_sum <= 0:
        raise ValueError("target_sum must be positive")

    # Determine processing strategy
    if fragments is not None:
        use_fragments = fragments
    else:
        # Check if dataset has multiple fragments
        try:
            fragments_list = adata.slaf.expression.get_fragments()
            use_fragments = len(fragments_list) > 1
        except Exception:
            use_fragments = False

    if use_fragments:
        # Use fragment-based processing
        try:
            from slaf.core.fragment_processor import FragmentProcessor

            # Get selectors from the LazyAnnData if it's sliced
            cell_selector = getattr(adata, "_cell_selector", None)
            gene_selector = getattr(adata, "_gene_selector", None)

            processor = FragmentProcessor(
                adata.slaf,
                cell_selector=cell_selector,
                gene_selector=gene_selector,
                max_workers=4,
                enable_caching=True,
            )
            # Use smart strategy selection for optimal performance
            lazy_pipeline = processor.build_lazy_pipeline_smart(
                "normalize_total", target_sum=target_sum
            )
            result_df = processor.compute(lazy_pipeline)

            # Update adata with normalized values
            return adata._update_with_normalized_data(
                result_df, target_sum, inplace
            )

        except Exception as e:
            print(
                f"Fragment processing failed, falling back to global processing: {e}"
            )
            # Fall back to global processing
            use_fragments = False

    if not use_fragments:
        # Use global processing (original implementation)
        # Get cell totals for normalization using only the expression table
        cell_totals_sql = """
        SELECT
            e.cell_integer_id,
            SUM(e.value) as total_counts
        FROM expression e
        GROUP BY e.cell_integer_id
        ORDER BY e.cell_integer_id
        """

        cell_totals = adata.slaf.query(cell_totals_sql)

    # Work with polars DataFrame internally
    cell_totals_pl = cell_totals

    # Create normalization factors using polars
    # Map cell_integer_id to cell names for compatibility with anndata.py
    if hasattr(adata.slaf, "obs") and adata.slaf.obs is not None:
        # Create mapping from cell_integer_id to cell names
        # Use polars DataFrame to get cell names
        obs_df = adata.slaf.obs
        if "cell_id" in obs_df.columns:
            cell_id_to_name = dict(
                zip(
                    obs_df["cell_integer_id"].to_list(),
                    obs_df["cell_id"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: create cell names from integer IDs
            cell_id_to_name = {i: f"cell_{i}" for i in range(len(obs_df))}
        # Use vectorized polars operations for mapping
        # Create mapping DataFrame
        cell_map_df = pl.DataFrame(
            {
                "cell_integer_id": list(cell_id_to_name.keys()),
                "cell_id": list(cell_id_to_name.values()),
            }
        )
        # Join with mapping DataFrame
        cell_totals_pl = cell_totals_pl.join(
            cell_map_df, on="cell_integer_id", how="left"
        )
        # Fill any missing values with default format
        cell_totals_pl = cell_totals_pl.with_columns(
            [
                pl.col("cell_id").fill_null(
                    pl.col("cell_integer_id")
                    .cast(pl.Utf8)
                    .map_elements(lambda x: f"cell_{x}", return_dtype=pl.Utf8)
                ),
                (target_sum / pl.col("total_counts")).alias("normalization_factor"),
            ]
        )
        # Convert to dictionary for compatibility
        normalization_dict = dict(
            zip(
                cell_totals_pl["cell_id"].to_list(),
                cell_totals_pl["normalization_factor"].to_list(),
                strict=False,
            )
        )
    else:
        # Fallback: use cell_integer_id as string keys
        cell_totals_pl = cell_totals_pl.with_columns(
            [
                pl.col("cell_integer_id").cast(pl.Utf8).alias("cell_id"),
                (target_sum / pl.col("total_counts")).alias("normalization_factor"),
            ]
        )
        # Convert to dictionary for compatibility
        normalization_dict = dict(
            zip(
                cell_totals_pl["cell_id"].to_list(),
                cell_totals_pl["normalization_factor"].to_list(),
                strict=False,
            )
        )

    if inplace:
        # Store normalization factors for lazy application
        if not hasattr(adata, "_transformations"):
            adata._transformations = {}

        adata._transformations["normalize_total"] = {
            "type": "normalize_total",
            "target_sum": float(
                f"{target_sum:.10f}"
            ),  # Convert to regular decimal format
            "cell_factors": normalization_dict,
        }

        print(f"Applied normalize_total with target_sum={target_sum}")
        return None
    else:
        # Create a copy with the transformation (copy-on-write)
        new_adata = adata.copy()
        if not hasattr(new_adata, "_transformations"):
            new_adata._transformations = {}

        new_adata._transformations["normalize_total"] = {
            "type": "normalize_total",
            "target_sum": float(
                f"{target_sum:.10f}"
            ),  # Convert to regular decimal format
            "cell_factors": normalization_dict,
        }

        return new_adata
log1p(adata: LazyAnnData, inplace: bool = True, fragments: bool | None = None) -> LazyAnnData | None staticmethod

Apply log1p transformation to expression data using lazy evaluation.

This function applies log(1 + x) transformation to the expression data. The transformation is stored lazily and will be computed when the data is accessed, avoiding memory-intensive operations on large datasets.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
inplace bool

Whether to modify the adata object in place. If False, returns a copy with the transformation applied.

True

Returns:

Type Description
LazyAnnData | None

LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation. If inplace=True, returns None.

Raises:

Type Description
RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Apply log1p transformation
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> LazyPreprocessing.log1p(adata)
Applied log1p transformation
>>> # Apply to copy
>>> adata_copy = adata.copy()
>>> LazyPreprocessing.log1p(adata_copy, inplace=False)
>>> print("Log1p transformation applied to copy")
>>> # Check transformation was stored
>>> print("log1p" in adata._transformations)
True
Source code in slaf/integrations/scanpy.py
@staticmethod
def log1p(
    adata: LazyAnnData, inplace: bool = True, fragments: bool | None = None
) -> LazyAnnData | None:
    """
    Apply log1p transformation to expression data using lazy evaluation.

    This function applies log(1 + x) transformation to the expression data.
    The transformation is stored lazily and will be computed when the data
    is accessed, avoiding memory-intensive operations on large datasets.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        inplace: Whether to modify the adata object in place. If False, returns
                a copy with the transformation applied.

    Returns:
        LazyAnnData | None: If inplace=False, returns LazyAnnData with transformation.
                           If inplace=True, returns None.

    Raises:
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Apply log1p transformation
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> LazyPreprocessing.log1p(adata)
        Applied log1p transformation

        >>> # Apply to copy
        >>> adata_copy = adata.copy()
        >>> LazyPreprocessing.log1p(adata_copy, inplace=False)
        >>> print("Log1p transformation applied to copy")

        >>> # Check transformation was stored
        >>> print("log1p" in adata._transformations)
        True
    """
    # Determine processing strategy
    if fragments is not None:
        use_fragments = fragments
    else:
        # Check if dataset has multiple fragments
        try:
            fragments_list = adata.slaf.expression.get_fragments()
            use_fragments = len(fragments_list) > 1
        except Exception:
            use_fragments = False

    if use_fragments:
        # Use fragment-based processing
        try:
            from slaf.core.fragment_processor import FragmentProcessor

            # Get selectors from the LazyAnnData if it's sliced
            cell_selector = getattr(adata, "_cell_selector", None)
            gene_selector = getattr(adata, "_gene_selector", None)

            processor = FragmentProcessor(
                adata.slaf,
                cell_selector=cell_selector,
                gene_selector=gene_selector,
                max_workers=4,
                enable_caching=True,
            )
            # Use smart strategy selection for optimal performance
            lazy_pipeline = processor.build_lazy_pipeline_smart("log1p")
            result_df = processor.compute(lazy_pipeline)

            # Update adata with log1p values
            return adata._update_with_log1p_data(result_df, inplace)

        except Exception as e:
            print(
                f"Fragment processing failed, falling back to global processing: {e}"
            )
            # Fall back to global processing
            use_fragments = False

    if not use_fragments:
        # Use global processing (original implementation)
        if inplace:
            # Store log1p transformation for lazy application
            if not hasattr(adata, "_transformations"):
                adata._transformations = {}

            adata._transformations["log1p"] = {"type": "log1p", "applied": True}

            print("Applied log1p transformation")
            return None
        else:
            # Create a copy with the transformation (copy-on-write)
            new_adata = adata.copy()
            if not hasattr(new_adata, "_transformations"):
                new_adata._transformations = {}

            new_adata._transformations["log1p"] = {"type": "log1p", "applied": True}

            return new_adata
highly_variable_genes(adata: LazyAnnData, min_mean: float = 0.0125, max_mean: float = 3, min_disp: float = 0.5, max_disp: float = np.inf, n_top_genes: int | None = None, inplace: bool = True) -> pd.DataFrame | None staticmethod

Identify highly variable genes using lazy evaluation.

This function identifies genes with high cell-to-cell variation in expression using SQL aggregation for memory efficiency. It calculates mean expression and dispersion for each gene and applies filtering criteria.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
min_mean float

Minimum mean expression for genes to be considered.

0.0125
max_mean float

Maximum mean expression for genes to be considered.

3
min_disp float

Minimum dispersion for genes to be considered.

0.5
max_disp float

Maximum dispersion for genes to be considered.

inf
n_top_genes int | None

Number of top genes to select by dispersion. If specified, overrides min_disp and max_disp criteria.

None
inplace bool

Whether to modify the adata object in place. Currently not fully implemented - returns None when True.

True

Returns:

Type Description
DataFrame | None

pd.DataFrame | None: If inplace=False, returns DataFrame with gene statistics and highly_variable column. If inplace=True, returns None.

Raises:

Type Description
RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Find highly variable genes
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> hvg_stats = LazyPreprocessing.highly_variable_genes(
...     adata, inplace=False
... )
>>> print(f"Highly variable genes: {hvg_stats['highly_variable'].sum()}")
Highly variable genes: 1500
>>> # With custom criteria
>>> hvg_stats = LazyPreprocessing.highly_variable_genes(
...     adata, min_mean=0.1, max_mean=5, min_disp=1.0, inplace=False
... )
>>> print(f"Genes meeting criteria: {hvg_stats['highly_variable'].sum()}")
Genes meeting criteria: 800
>>> # Select top N genes
>>> hvg_stats = LazyPreprocessing.highly_variable_genes(
...     adata, n_top_genes=1000, inplace=False
... )
>>> print(f"Top genes selected: {hvg_stats['highly_variable'].sum()}")
Top genes selected: 1000
Source code in slaf/integrations/scanpy.py
@staticmethod
def highly_variable_genes(
    adata: LazyAnnData,
    min_mean: float = 0.0125,
    max_mean: float = 3,
    min_disp: float = 0.5,
    max_disp: float = np.inf,
    n_top_genes: int | None = None,
    inplace: bool = True,
) -> pd.DataFrame | None:
    """
    Identify highly variable genes using lazy evaluation.

    This function identifies genes with high cell-to-cell variation in expression
    using SQL aggregation for memory efficiency. It calculates mean expression
    and dispersion for each gene and applies filtering criteria.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        min_mean: Minimum mean expression for genes to be considered.
        max_mean: Maximum mean expression for genes to be considered.
        min_disp: Minimum dispersion for genes to be considered.
        max_disp: Maximum dispersion for genes to be considered.
        n_top_genes: Number of top genes to select by dispersion.
                    If specified, overrides min_disp and max_disp criteria.
        inplace: Whether to modify the adata object in place. Currently not
                fully implemented - returns None when True.

    Returns:
        pd.DataFrame | None: If inplace=False, returns DataFrame with gene statistics
                            and highly_variable column. If inplace=True, returns None.

    Raises:
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Find highly variable genes
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
        ...     adata, inplace=False
        ... )
        >>> print(f"Highly variable genes: {hvg_stats['highly_variable'].sum()}")
        Highly variable genes: 1500

        >>> # With custom criteria
        >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
        ...     adata, min_mean=0.1, max_mean=5, min_disp=1.0, inplace=False
        ... )
        >>> print(f"Genes meeting criteria: {hvg_stats['highly_variable'].sum()}")
        Genes meeting criteria: 800

        >>> # Select top N genes
        >>> hvg_stats = LazyPreprocessing.highly_variable_genes(
        ...     adata, n_top_genes=1000, inplace=False
        ... )
        >>> print(f"Top genes selected: {hvg_stats['highly_variable'].sum()}")
        Top genes selected: 1000
    """

    # Calculate gene statistics via SQL using simple aggregation (no JOINs)
    stats_sql = """
    SELECT
        e.gene_integer_id,
        COUNT(DISTINCT e.cell_integer_id) AS n_cells,
        AVG(e.value) AS mean_expr,
        VARIANCE(e.value) AS variance,
        CASE WHEN AVG(e.value) > 0 THEN VARIANCE(e.value) / AVG(e.value) ELSE 0 END as dispersion
    FROM expression e
    GROUP BY e.gene_integer_id
    ORDER BY e.gene_integer_id
    """

    gene_stats = adata.slaf.query(stats_sql)

    # Work with polars DataFrames internally
    gene_stats_pl = gene_stats

    # Get the expected gene_integer_ids from the materialized var metadata
    # Use in-memory var if available, otherwise fall back to SQL
    if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
        # Use the materialized var metadata directly
        expected_genes_pl = pl.DataFrame(
            {"gene_integer_id": range(len(adata.slaf.var))}
        )
    else:
        # Fallback to SQL if var is not available
        expected_genes_sql = """
        SELECT gene_integer_id
        FROM genes
        ORDER BY gene_integer_id
        """
        expected_genes = adata.slaf.query(expected_genes_sql)
        expected_genes_pl = expected_genes

    # Create a complete gene_stats DataFrame with all expected genes using polars
    gene_stats_complete_pl = expected_genes_pl.join(
        gene_stats_pl, on="gene_integer_id", how="left"
    ).fill_null(0)

    # Ensure proper data types
    gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
        [
            pl.col("n_cells").cast(pl.Int64),
            pl.col("mean_expr").cast(pl.Float64),
            pl.col("variance").cast(pl.Float64),
            pl.col("dispersion").cast(pl.Float64),
        ]
    )

    # Map gene_integer_id to gene_id for scanpy compatibility
    if hasattr(adata.slaf, "var") and adata.slaf.var is not None:
        # Create mapping from gene_integer_id to gene names
        # Use polars DataFrame to get gene names
        var_df = adata.slaf.var
        if "gene_id" in var_df.columns:
            gene_id_to_name = dict(
                zip(
                    var_df["gene_integer_id"].to_list(),
                    var_df["gene_id"].to_list(),
                    strict=False,
                )
            )
        else:
            # Fallback: create gene names from integer IDs
            gene_id_to_name = {i: f"gene_{i}" for i in range(len(var_df))}
        # Use vectorized polars operations for mapping
        # Create mapping DataFrame
        gene_map_df = pl.DataFrame(
            {
                "gene_integer_id": list(gene_id_to_name.keys()),
                "gene_id": list(gene_id_to_name.values()),
            }
        )
        # Join with mapping DataFrame
        gene_stats_complete_pl = gene_stats_complete_pl.join(
            gene_map_df, on="gene_integer_id", how="left"
        )
        # Fill any missing values with default format
        gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
            pl.col("gene_id").fill_null(
                pl.col("gene_integer_id")
                .cast(pl.Utf8)
                .map_elements(lambda x: f"gene_{x}", return_dtype=pl.Utf8)
            )
        )
    else:
        # Fallback: use gene_integer_id as gene_id
        gene_stats_complete_pl = gene_stats_complete_pl.with_columns(
            pl.col("gene_integer_id").cast(pl.Utf8).alias("gene_id")
        )

    # Convert to pandas and set gene_id as index for scanpy compatibility
    gene_stats_complete = gene_stats_complete_pl.to_pandas().set_index("gene_id")

    # Apply HVG criteria
    hvg_mask = (
        (gene_stats_complete["mean_expr"] >= min_mean)
        & (gene_stats_complete["mean_expr"] <= max_mean)
        & (gene_stats_complete["dispersion"] >= min_disp)
        & (gene_stats_complete["dispersion"] <= max_disp)
    )

    gene_stats_complete["highly_variable"] = hvg_mask

    if n_top_genes is not None:
        # Select top N genes by dispersion
        top_genes = gene_stats_complete.nlargest(n_top_genes, "dispersion")
        gene_stats_complete["highly_variable"] = gene_stats_complete.index.isin(
            top_genes.index
        )

    if inplace:
        # Update var metadata (would need implementation)
        print(f"Identified {hvg_mask.sum()} highly variable genes")
        return None
    else:
        return gene_stats_complete

Functions

apply_transformations(adata: LazyAnnData, transformations: list | None = None) -> LazyAnnData

Apply a list of transformations to the data.

This function provides explicit control over when transformations are applied. It creates a copy of the LazyAnnData with only the specified transformations stored for lazy evaluation.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
transformations list | None

List of transformation names to apply. If None, applies all available transformations.

None

Returns:

Name Type Description
LazyAnnData LazyAnnData

New LazyAnnData with specified transformations applied.

Raises:

Type Description
RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Apply all transformations
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> LazyPreprocessing.normalize_total(adata)
>>> LazyPreprocessing.log1p(adata)
>>> adata_with_transforms = apply_transformations(adata)
>>> print("Transformations applied")
>>> # Apply specific transformations
>>> adata_copy = adata.copy()
>>> adata_with_norm = apply_transformations(
...     adata_copy, transformations=["normalize_total"]
... )
>>> print("Only normalization applied")
Source code in slaf/integrations/scanpy.py
def apply_transformations(
    adata: LazyAnnData, transformations: list | None = None
) -> LazyAnnData:
    """
    Apply a list of transformations to the data.

    This function provides explicit control over when transformations are applied.
    It creates a copy of the LazyAnnData with only the specified transformations
    stored for lazy evaluation.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        transformations: List of transformation names to apply. If None, applies all
                       available transformations.

    Returns:
        LazyAnnData: New LazyAnnData with specified transformations applied.

    Raises:
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Apply all transformations
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> LazyPreprocessing.normalize_total(adata)
        >>> LazyPreprocessing.log1p(adata)
        >>> adata_with_transforms = apply_transformations(adata)
        >>> print("Transformations applied")

        >>> # Apply specific transformations
        >>> adata_copy = adata.copy()
        >>> adata_with_norm = apply_transformations(
        ...     adata_copy, transformations=["normalize_total"]
        ... )
        >>> print("Only normalization applied")
    """
    if transformations is None:
        # Apply all transformations
        transformations = list(adata._transformations.keys())

    # Create a copy to avoid modifying the original
    new_adata = adata.copy()

    # Apply only the specified transformations
    new_adata._transformations = {
        name: adata._transformations[name]
        for name in transformations
        if name in adata._transformations
    }

    return new_adata

clear_transformations(adata: LazyAnnData, inplace: bool = False) -> LazyAnnData | None

Clear all transformations from the data.

This function removes all stored transformations from the LazyAnnData object, effectively resetting it to its original state without any preprocessing.

Parameters:

Name Type Description Default
adata LazyAnnData

LazyAnnData instance containing the single-cell data.

required
inplace bool

Whether to modify the adata object in place. If False, returns a copy with transformations cleared.

False

Returns:

Type Description
LazyAnnData | None

LazyAnnData | None: If inplace=False, returns LazyAnnData with transformations cleared. If inplace=True, returns None.

Raises:

Type Description
RuntimeError

If the SLAF array is not properly initialized.

Examples:

>>> # Clear transformations in place
>>> slaf_array = SLAFArray("path/to/data.slaf")
>>> adata = LazyAnnData(slaf_array)
>>> LazyPreprocessing.normalize_total(adata)
>>> LazyPreprocessing.log1p(adata)
>>> clear_transformations(adata, inplace=True)
>>> print("Transformations cleared")
>>> # Clear transformations to copy
>>> adata_copy = adata.copy()
>>> LazyPreprocessing.normalize_total(adata_copy)
>>> adata_clean = clear_transformations(adata_copy, inplace=False)
>>> print("Clean copy created")
Source code in slaf/integrations/scanpy.py
def clear_transformations(
    adata: LazyAnnData, inplace: bool = False
) -> LazyAnnData | None:
    """
    Clear all transformations from the data.

    This function removes all stored transformations from the LazyAnnData object,
    effectively resetting it to its original state without any preprocessing.

    Args:
        adata: LazyAnnData instance containing the single-cell data.
        inplace: Whether to modify the adata object in place. If False, returns
                a copy with transformations cleared.

    Returns:
        LazyAnnData | None: If inplace=False, returns LazyAnnData with transformations
                           cleared. If inplace=True, returns None.

    Raises:
        RuntimeError: If the SLAF array is not properly initialized.

    Examples:
        >>> # Clear transformations in place
        >>> slaf_array = SLAFArray("path/to/data.slaf")
        >>> adata = LazyAnnData(slaf_array)
        >>> LazyPreprocessing.normalize_total(adata)
        >>> LazyPreprocessing.log1p(adata)
        >>> clear_transformations(adata, inplace=True)
        >>> print("Transformations cleared")

        >>> # Clear transformations to copy
        >>> adata_copy = adata.copy()
        >>> LazyPreprocessing.normalize_total(adata_copy)
        >>> adata_clean = clear_transformations(adata_copy, inplace=False)
        >>> print("Clean copy created")
    """
    if inplace:
        adata._transformations = {}
        return None
    else:
        new_adata = adata.copy()
        new_adata._transformations = {}
        return new_adata