Preprocessing¶
Counts to something you can do statistics on. Two routes, both of Seurat's:
log-normalize → find variable features → scale, or sctransform in one call.
find_variable_features has two selectors and they honour different arguments —
"vst" and "disp" take nfeatures, "mvp" takes the mean and dispersion
cutoffs. That is Seurat's behaviour, not a quirk of the port; the docstring says
which is which.
Verified against Seurat in PBMC 3k and, for the regularized-NB route, per fitted gene in SCTransform.
Log-normalize workflow¶
normalize_data
¶
normalize_data(seurat, normalization_method: str = 'LogNormalize', scale_factor: float = 10000.0, assay: Optional[str] = None, margin: int = 1) -> None
Log-normalize counts.
Mirrors R's NormalizeData(pbmc, normalization.method = "LogNormalize", scale.factor = 10000). Modifies the assay in-place by adding / updating the 'data' layer.
Parameters:
-
normalization_method(str, default:'LogNormalize') –'LogNormalize', 'CLR', or 'RC'
-
margin(int, default:1) –for CLR only, and matching Seurat's flag exactly — normalize each feature across cells (1, Seurat's default) or each cell across its features (2). ADT/CITE-seq panels typically use margin=2.
Source code in truecell/preprocessing.py
find_variable_features
¶
find_variable_features(seurat, selection_method: str = 'vst', nfeatures: int = 2000, assay: Optional[str] = None, layer: Optional[str] = None, mean_cutoff: tuple = (0.1, 8), dispersion_cutoff: tuple = (1, float('inf')), num_bin: int = 20, binning_method: str = 'equal_width') -> None
Select highly variable features.
Mirrors R's FindVariableFeatures(pbmc, selection.method = "vst", nfeatures = 2000). Modifies the assay in-place by setting var_features (Assay) or highly_variable in meta_data (Assay5).
On an Assay5 the per-feature statistics land in assay.meta_data under
the names HVFInfo() uses, so a column reads the same in either language:
selection_method="vst"—mean,variance,variance.expected,variance.standardized"mvp"/"mean.var.plot"/"dispersion"/"disp"—mvp.mean,mvp.dispersion,mvp.dispersion.scaled
plus highly_variable, a boolean flag that has no Seurat counterpart of
its own (HVFInfo(status = TRUE) spells it variable); it is the
fallback Assay5.variable_features reads when the ordered list is empty.
The two dispersion spellings are not synonyms, however much they share.
Seurat routes them to different selectors — MVP for "mvp" /
"mean.var.plot", DISP for "dispersion" / "disp" — and only
the second honours nfeatures. mean_cutoff and dispersion_cutoff
apply to the first, and to nothing else; they were accepted and discarded
before, so mean.var.plot returned a top-nfeatures list under a name
that promises a cutoff.
Source code in truecell/preprocessing.py
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 | |
scale_data
¶
scale_data(seurat, features: Optional[list[str]] = None, vars_to_regress: Optional[list[str]] = None, assay: Optional[str] = None, do_scale: bool = True, do_center: bool = True, scale_max: float = 10.0, layer: str = 'data') -> None
Scale and optionally center expression data.
Mirrors R's ScaleData(). Stores result in the 'scale.data' layer (Assay5) or scale_data slot (Assay v3).
Parameters:
-
features(Optional[list[str]], default:None) –genes to scale (defaults to variable features)
-
vars_to_regress(Optional[list[str]], default:None) –metadata columns to regress out before scaling
-
do_scale(bool, default:True) –standardize variance to 1
-
do_center(bool, default:True) –subtract mean
-
scale_max(float, default:10.0) –clip scaled values at this magnitude
Source code in truecell/preprocessing.py
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 | |
percentage_feature_set
¶
percentage_feature_set(seurat, pattern: str, col_name: Optional[str] = None, assay: Optional[str] = None, layer: str = 'counts') -> None
Add a metadata column with % of counts matching a gene name pattern.
Mirrors R's PercentageFeatureSet(pbmc, pattern = "^MT-"). Modifies seurat.meta_data in-place.
Source code in truecell/preprocessing.py
Regularized negative binomial¶
sctransform
¶
sctransform(seurat, assay: Optional[str] = None, new_assay_name: str = 'SCT', n_cells: int = 5000, n_genes: int = 2000, n_features: int = 3000, min_cells: int = 5, vars_to_regress: Optional[list[str]] = None, clip_range: Optional[tuple] = None, gene_chunk: int = 500, seed: int = 42, set_default: bool = True, vst_flavor: str = 'v2', bw_adjust: float = 3.0, verbose: bool = False) -> 'object'
Run SCTransform and attach a normalized assay.
Mirrors R's SCTransform(object). Fits the regularized NB model on the
active assay's counts and stores the result as new_assay_name ("SCT").
Parameters:
-
n_cells(int, default:5000) –cells subsampled for parameter estimation (Seurat default 5000).
-
n_genes(int, default:2000) –genes used for step-1 estimation, sampled to spread evenly over expression (Seurat default 2000).
Noneuses every gene. -
n_features(int, default:3000) –number of variable features by residual variance (default 3000).
-
min_cells(int, default:5) –drop genes detected in fewer than this many cells (default 5).
-
vars_to_regress(Optional[list[str]], default:None) –metadata columns (e.g. 'percent.mt') regressed out of the Pearson residuals, mirroring SCTransform's vars.to.regress.
-
clip_range(Optional[tuple], default:None) –residual clip for
scale.data; default (-√(N/30), √(N/30)). Note this is not the clip used when ranking variable features — see below. -
vst_flavor(str, default:'v2') –"v2" (default, as Seurat 5) or "v1". See the module docstring.
-
bw_adjust(float, default:3.0) –multiplier on the Sheather-Jones smoothing bandwidth (R's 3).
-
set_default(bool, default:True) –make the new assay the active assay.
Returns:
-
``seurat``, with the new assay added.–
Source code in truecell/sctransform.py
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 | |
Run prep_sct_find_markers before differential expression on an object
that carries more than one SCT model — the state you get by SCTransforming
several objects separately and merging them. Without it, a fold change
across the merge partly measures how deeply each batch was sequenced.
prep_sct_find_markers
¶
prep_sct_find_markers(seurat, assay: str = 'SCT', umi_assay: Optional[str] = None, verbose: bool = True)
Put a merged object's SCT counts on one scale, before differential expression.
Mirrors R's PrepSCTFindMarkers(object). Run it once on an object that
carries more than one SCT model — the state you get by SCTransforming
several objects separately and merging them — and before any
find_markers call on the SCT assay.
Why it is needed
sctransform corrects each object's counts to that object's median
sequencing depth. Merge two such objects and the two halves of the SCT
counts layer are expressed at two different depths, so a fold change
across them partly measures how deeply each batch happened to be
sequenced. This re-corrects every cell to the minimum median UMI across
the models, which is the deepest common scale all of them can reach without
extrapolating.
What it does
For each model, the Pearson residual is taken at each cell's own depth from
the raw UMI counts (never from the already-corrected ones, so the
operation is idempotent) and read back out at log10(min_median_umi).
counts becomes the recorrected matrix and data its log1p.
It returns early, unchanged, in the two cases R does: when only one model is
stored, and when every model's recorded median_umi already sits above
the minimum observed one.
Parameters:
-
assay(str, default:'SCT') –the SCT assay to re-correct (default
"SCT"). -
umi_assay(Optional[str], default:None) –assay holding the raw counts. Defaults to the one each model recorded at fit time, and raises if the models disagree — as R does, since a single corrected matrix cannot come from two different count matrices.
Returns:
-
``seurat``, with the SCT assay's ``counts`` and ``data`` layers replaced.–
Notes
Scale factor. The target depth is log10(median(umi)) — the median on
the count scale — where an ordinary sctransform call uses
median(log10(umi)). That asymmetry is R's, not a slip: correct_counts
takes the median of the latent variable when no scale_factor is passed
and log10 of the supplied one when there is. The two differ whenever a
model has an even number of cells.
Source code in truecell/sctransform.py
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 | |