Changelog
Version 0.6.2#
Fixed — multi-gene blend rendering:
spatial_cellnow draws a raw per-cell colour column as onePatchCollectioninstead of one collection per unique colour. A typicaltl.multigene_blendresult has one colour per cell, so 600 cells meant 600 collections (~49 s) and 5,000 cells effectively never finished; a single collection draws 5,000 cells in ~1.1 s. The render-smoke test now asserts one collection with many facecolors instead of one collection per colour.tl.multigene_blendfalls back to the observed range when a gene’svmax_percentileis zero. A gene expressed in fewer cells than the upper percentile tail (e.g. 3 of 1,000 at 99th percentile) used to be zeroed entirely, so its cells were painted as background — exactly the rare markers a co-expression map is often used to find.pl.multigene_blendreadsuns['<key>_params']through the same_as_uns_mappinghelper as palettes, so an AnnData that packs the dict into a 0-d object array during subset/copy no longer raisesAttributeError.tl.multigene_blendvalidates duplicate gene names, negative/non-finite expression values,gamma, percentile order and colour arguments, and normalises matplotlib colour names to hex before storing them. The docstring and the usage page now state explicitly that the blend encodes relative composition, not absolute expression intensity.
Infrastructure:
The release workflow prefers GitHub OIDC Trusted Publishing when
PYPI_API_TOKENis absent, and keeps the token path while the secret exists. Deleting the secret switches the next tag to attestation-enabled Trusted Publishing without another workflow change.
Version 0.6.1#
Fixed — physical units:
tl.hd_labeldistnow resolves the coordinate unit throughpl.resolve_microns_per_unitinstead of maintaining a second resolver. Xenium and Atera centroid coordinates are already µm; the old fallback multiplied them by the morphologypixel_size(0.2125 on a typical Xenium run), so every{label}_distwas 4.7× too small with no warning. Atera’s own documentation andREADMEalready said not to apply that factor.coordinate_system='auto'now resolves to'data'for physical coordinates;'fullres'is ignored with a warning and'hires'raises.pl.resolve_microns_per_unitreadsmetadata['pixel_size_um']andmetadata['resolution_nm']. STOmics GEF coordinates are resolution units (500 nm by default), socells_in_radius, scale bars andmark_circlewere 2× wrong on those objects, andhd_labeldistraised for lack of amicrons_per_pixel. The coordinate unit is now explicit inread_xenium_cellsegmetadata (coord_unit='um').
Fixed — geometry and rendering:
read_hd_cellsegdrops the falseEPSG:4326thatgpd.read_fileassigns to GeoJSON. The coordinates are full-resolution image pixels. The false CRS madespatial_cellemit an “Aspect calculation failed” warning on every plot, madegeometries.areareturn square degrees, and was persisted bysave_h5ad.Compact boundary tables now carry a
layoutmarker. Xenium writeslayout='offset'with a row-alignedn_vertices; Atera writeslayout='index'.tl.split_by_slicesupports both and also reindexesnucleus_boundaries. Previously an Atera object was decoded with vertex offsets and silently got the wrong cells’ vertices, while a Xenium object with any cell lacking a boundary raisedIndexError.An empty
uns['classification_colors']is no longer treated as a palette.spatial_cellused to warn about every category and paint them all grey when the vendor GeoJSON omitted colours.read_hd_cellsegnow publishes the palette only when at least one colour was found.tl.multigene_blendcasts integer expression matrices to float before percentile normalisation. AnnData’s denseArrayViewexposestoarray(), so the oldhasattrsparse check skipped the cast andnp.zeros_like(int_array)truncated most cells to the background colour.
Changed — maintenance:
add_geometries_to_annohdcell_outputinstalls the bin-coordinate array once per worker instead of shipping it in every task tuple. On a 10⁵-cell × 10⁶-bin dataset that reduced per-task pickling from the whole array to two small integers; an empty cell set no longer tries to start a zero-process pool.RegionSelector.to_adata()preserves labels from a previous session for cells outside the new ROIs, matching_save_to_adata().tl.spatial_slice_clusterinterpretsepsin micrometres by default and converts throughpl.resolve_microns_per_unit. The sameeps=80now means 80 µm on Visium HD (266.7 px at 0.3 µm/px) and STOmics (160 units), not 80 raw coordinate units. Passeps_unit='data'to keep the previous raw-unit behaviour.uns['slice_id_params']recordseps_data.io.save_h5adno longer removes a pre-existing<key>__crssidecar; only the temporary value written for the file is cleaned up.
Testing:
New
tests/data/sct_golden(40 genes × 120 cells) plustests/test_sct_r_golden_small.py: the Pythonvstis compared against Rsctransformstep-1 parameters, regularised parameters, gene means and Pearson residuals in ~2 s. This is the first SCT parity check that runs on every PR; the external benchmark suite is still skipped whenTRACKCELL_BENCHMARK_ROOTis absent.convert_annohdcellserial/parallel tests; CI ratchet 12% → 45%.Docs: public-function counts (74), the mypy command in
CONTRIBUTING, the unit-resolution order (STOmics), the boundarylayoutcontract and the deprecation-free categorical check inpl.plot.
Version 0.6.0#
Internal — no behaviour change:
spatial_cell(884 lines) loses two stages and two dead functions. The extraction is verified byscripts/render_snapshots.py, which fingerprints what 15 scenarios actually draw — collection count, face colours, collection alpha, edge colours, linewidths, z-order, path counts, axis limits, labels, legend entries, image alpha — and which was checked to detect a0.8 -> 0.79alpha change in 12 of 15 scenarios before being trusted._finish_background_paneland_finish_panel_axesnow name what was inline;spatial_cellis 837 lines andpl/plot.pycoverage went from 68% to 71%.Two dead functions removed.
_draw_background_onlywas not reusable: it callsinvert_yaxis()while the live path carries a comment that it must not, becauseset_ylim(h, 0)withorigin='upper'already gives image convention — reusing it would have flipped every background-only panel._is_hex_color_seriesbecame unreferenced when the two colour predicates were unified; keeping it “for callers” when there are none is how a module grows two answers to one question again.The remaining C-1 work — splitting the per-panel core into fill / edges / legend — is not done. Those stages are interdependent through ~20 locals and are the risky half; see
docs/backlog-0.5.0.mdC-1 for the plan and the measured starting point.tests/test_render_smoke.pyasserts the structural facts of every rendering path, so a refactor that drops a branch or loses the legend fails in CI. The fingerprint script stays a local tool: its hashes depend on the matplotlib and freetype builds, so storing them in the repository would fail on any environment change.
Breaking — one module path again:
trackcell/tl/spatial_cluster.py→trackcell/tl/_cluster.py. This is the same defect 0.5.0 fixed forsctransformandread_atera, and it survived that round because eager binding masked it:tl/__init__.pyimported thespatial_clusterfunction after the submodule, so the function won and the collision was invisible. PEP 562 lazy resolution removed the mask — importing the submodule from anywhere sets it as an attribute on the package, the import system bypasses__getattr__, and callers received a module where a function was promised.Public API unchanged:
tcl.tl.spatial_cluster(...)is still the function.import trackcell.tl.spatial_clusterandfrom trackcell.tl.spatial_cluster import spatial_clusternow raiseModuleNotFoundError. Migration:from trackcell.tl import spatial_clusterorfrom trackcell.tl._cluster import spatial_cluster.tests/test_module_paths.pynow covers all three retired paths.
Changed — import time:
import trackcellwent from 2.43 s to ~0 s.io/pl/tlare resolved on first access (PEP 562) instead of at import, andio/tldo the same for their own public names.import trackcell.tlandimport trackcell.ioalso drop to ~0 s;trackcell.plstays at ~0.7 s because plotting genuinely needsmatplotlib.pyplotandgeopandas.Beyond speed, this fixes a real trap:
matplotlib.pyplotlocks the backend when imported, somatplotlib.use("Agg")had to run beforeimport trackcellto take effect. On a headless machine the wrong order surfaced as a hang or an X11 error rather than as a message.Enforced by
scripts/measure_import.py --check(a CI step) andtests/test_lazy_imports.py, which imports the core package in a fresh interpreter and asserts neitherscanpynormatplotlib.pyplotwas loaded. Both were verified to fail when an eager import is restored.
Documentation — behavior unchanged:
tl.select_integration_featuresnow states that its twomethodvalues answer different questions and are not comparable.'seurat'(default) selects genes that vary reproducibly within batches;'xgboost'selects genes that separate batches. The docstring previously opened with “SeuratSelectIntegrationFeatures” and offered'xgboost'as an “optional enhancement”, which reads as two implementations of one method. They are not: on a synthetic pair of batches, a gene whose only variance is a batch shift is ranked first by'xgboost'and not selected at all by'seurat', and the two 10-gene sets overlap by 2. That is now asserted by a test rather than described in prose.'xgboost'is documented as an experiment: importances are in-sample (no held-out fold, no cross-validation), and anchors found on batch-discriminating features can match cells by batch structure rather than cell identity.'seurat'remains the supported path for reciprocal PCA.select_integration_features(..., return_importance=True)returns(genes, table)formethod='xgboost', wheretablehasgeneandimportancesorted descending — the manual review the ranking previously gave no access to. Ignored with a warning for'seurat', which has no single importance score. When fewer than two batches are present no classifier is fitted and the table carriesNaNimportances.
Version 0.5.1#
Fixed:
read_sto_cellbinfaked a 10x10 polygon for cells whose GEF border cannot form one (all-sentinel, or fewer than three vertices). The fabrication itself is deliberate — aNonegeometry would put a null check into every downstream area /intersects/ ROI path — but it was only visible as anINFOlog line, so area statistics and region selections silently used boxes that do not exist in the data. It is now disclosed three ways:obs['geometry_is_fallback'](per cell),uns['spatial'][sample]['metadata']['n_fallback_polygons'](per sample), and aRuntimeWarningnaming the affected count.The flag covers every fabrication path, which is more than the box it started as: fewer than three usable vertices gives a 10x10 box, a self-intersecting border gives a buffered convex hull, and fully coincident vertices give a small disc. All three are valid, non-empty polygons that a caller cannot tell from stored geometry, so the extractor reports which one it used rather than the caller inferring it.
(An earlier draft of this entry claimed it also fixed a latent
wkt.dumps(None)crash. It did not: that branch is unreachable —MultiPoint(...).convex_hullalways has.buffer, and 3000 fuzzed border arrays never producedNone. The substitution is kept as belt-and-braces, but it fixes nothing and the claim is withdrawn.)tl.remove_long_linksexempted the wrong edges from trimming. Self loops were identified by weight (data >= 1 - 1e-12), on the assumption that only a self loop can normalise to 1.0. Butbuild_spatial_weightsemits no self loops at all, and a row with exactly one neighbour normalises that genuine edge to 1.0 too — so degree-1 cells (tissue edges, anything isolated by an earlier trim) had their single, usually longest, edge kept out of the percentile sample and exempt from trimming. Self loops are now identified by position (row == col). Verified on a graph where the old test let a 100-unit edge from a degree-1 cell survive.Consequence worth knowing: an isolated cell’s long edge is now trimmed, which leaves a zero-degree row.
remove_long_linksnow gives such a row a self loop of weight 1.0 (see below), so the two changes are consistent.tl.nhood_enrichment/tl.diff_nhood_enrichmentno longer count self loops as spatial links. The diagonal of a spatial graph holds repair entries (build_spatial_weightsfor a neighbour-less cell,remove_long_linksfor a cell whose edges were all trimmed), and those were added to the observed same-cluster count while the configuration-model null halves the diagonal for the undirected convention — one self loop counted once, then halved as though it had been counted twice. On a 4-cell example theA,Aenrichment moved from-0.167to+0.5: the sign flipped.tl.remove_long_linkshonours its documented “every row sums to 1” on the early-return paths too. An all-empty graph used to come back with every row at zero — the exact zero-context state the repair exists to remove.pl.multigene_blendno longer fails quietly. Auns['<key>_params']whosecolorsandgenesdisagree now raises instead of lettingziptruncate the legend; a missing params dict now warns instead of drawing the unlabelled composite it was written to eliminate (anndata.concatdropsuns, so that is reachable without hand-editing). Thebackgroundcolour becomes a legend entry, but only when some cell actually falls back to it.Colour columns are detected by one shared predicate,
pl.plot._is_color_column.spatial_cellandpl.multigene_blendpreviously used different tests — a strict hex check in the renderer, a permissive colour check in the new function — so a column mixing#e41a1cwith a named colour passed one gate and failed the other. The result was drawn with the categorical palette: a wrong figure instead of an error.background='white', legal fortl.multigene_blend, hit exactly that._plot_raw_hex_colorsalso skipped any group whose colour was not a#literal, silently dropping those cells; colours are now normalised withto_hexinstead. Detection inspects the whole column (the old 100-row probe made the verdict depend on row order), accepts#rgb/#rrggbbaa, rejects non-string columns outright (is_color_likeaccepts floats as greys), and keeps a vectorised path for the all-hex case.read_sto._valid_border_offsetswidens toint32before takingabs.np.absonint16leavesabs(-32768) == -32768, so the plausibility guard added above passed precisely the corrupt value it existed to reject.tl.remove_long_linksno longer leaves neighbour-less rows at zero. Trimming could isolate a node that had neighbours at build time, and_row_normalizecannot normalise an empty row, soweights @ Xthen reported a context of zero for those cells — which downstream PCA reads as “expresses nothing” and clustering turns into an artificial cluster. Such rows now receive a self loop of weight 1.0, i.e. context = own expression.This is not a new convention:
build_spatial_weightsalready emits(i, i, 1.0)for a cell with no usable neighbour, so both paths agree.NaNwas the alternative and was rejected — it propagates silently through PCA and leaves the caller to decide when to drop rows. The number of repaired cells is logged atINFOon thetrackcelllogger.read_xenium_cellsegno longer writes progress to stdout. It usedlog = print if verbose else noop, which broke the rule the 0.4.0 changelog set for library code and could not be silenced by log level. Records now go through thetrackcelllogger;verbosestill gates them, so the switch keeps working. The logger carries aNullHandler, so a default import stays quiet — calllogging.basicConfig(level=logging.INFO)to see progress.atera_infoand the interactive ROI selector keep theirprintdeliberately: both are console-facing by design.
Added:
pl.multigene_blend— renders the composite produced bytl.multigene_blend(mode='blend')and draws the gene-to-colour legend.pl.spatial_cellalready rendered such a column correctly (it detects the raw-hex case and skips palette construction) but could not label it: a column of thousands of distinct hex strings carries no category names, while the gene-to-colour mapping sits unused inadata.uns['<key>_params']. The documented composite therefore shipped with no indication of which colour meant which gene. Nothing is recomputed — the function readsobsandunsonly, and zeroingXleaves the output unchanged.tl.atera_cell_qcandtl.filter_atera_genes— re-exported fromioas the same objects (tcl.tl.atera_cell_qc is tcl.io.atera_cell_qc). Both operate on an AnnData and never touch the filesystem, so they belong intlby the same rule that putsnhood_enrichmentthere and only its renderer inpl. Lookups for “QC” that started intlpreviously came up empty.atera_transcript_qcis deliberately not re-exported: its first argument is a run directory and it streams the point cloud from disk. It is IO that ends in a QC table, not computation, and it stays inio.
Version 0.5.0#
Breaking — the two module paths below are gone. Neither was ever part of the documented API, but both were reachable in 0.4.x, so this is called out.
trackcell/tl/sctransform.py→trackcell/tl/_sct_entry.pytrackcell/io/read_atera.py→trackcell/io/_atera.pyBoth files defined a function with the same name as the module. Binding that function in the package
__init__overwrote the submodule attribute, soimport trackcell.tl.sctransform as mreturned a function rather than the module, whilesys.modulesheld the module.inspect,mock.patchand anyimport a.b as ctherefore acted on a different object than requested, and the resultingAttributeErrorpointed nowhere near the cause.The public API is unchanged:
tcl.tl.sctransform(...)andtcl.io.read_atera(...)are still callable functions, andinspect.getsourceon them still returns real source. What changes is thatimport trackcell.tl.sctransformandfrom trackcell.tl.sctransform import sctransformnow raiseModuleNotFoundError— a loud failure instead of a silently wrong object.Migration: import from the package, not the module path.
from trackcell.tl import sctransform/from trackcell.io import read_atera. Private helpers move with the file (from trackcell.io._atera import _subset_cells).A sys.modules alias was considered and rejected:
import a.b as cprefers the parent-package attribute, which is the function, so an alias would leave the bug intact. No compatibility shim is provided for the same reason.
Version 0.4.9#
Fixed:
pl.spatial_celldecided categorical-vs-continuous per plotted panel, from the values that survived the subset. A gene’s raw counts are integers, so the integer-cardinality heuristic (at most 30 distinct values) fired inside small ROIs:color="CCND1"painted the first column of a 2 x 3 grid with 17 discrete colors and a legend of0 … 36while the other four panels stayed on the viridis ramp — the panel read as a cluster map. The decision is now made once per key from the full object, and gene expression is never treated as a label: integer codes for clusters live inadata.obs, a gene does not. Passcategorical=Trueto colour a gene categorically; an obs column that is deliberately integer-valued still works as before (<=30 levels => categorical).
Version 0.4.8#
Upgrade note — read_atera(load_groups=True) now writes
uns['cell_group_colors'] as a list aligned with
obs['cell_group'].cat.categories (scanpy / squidpy convention) instead of a
{group: hex} dict. Code that indexed it by group name must switch to
uns['atera_cell_group_palette'], which keeps the dict. The list form is what
sq.pl.spatial_scatter(color='cell_group') requires — the dict made squidpy
raise Expected palette to be of length 19, found 1, i.e. a plain
tcl.io.read_atera() -> sq.pl workflow could not plot Atera’s own
clustering at all without a manual palette=.
Fixed:
read_atera(load_groups=True)stored the vendor palette as a dict underuns['cell_group_colors'], which no plotting library reads positionally and whichAnnDatare-packs into a 0-d object array on the first subset or copy. It is now the conventional list, with the name-keyed map kept separately underuns['atera_cell_group_palette']. Groups missing a color incell_groups.csvnow get gray and a warning instead of vanishing.pl.spatial_celllost theadata.uns['<col>_colors']palette after any subset.AnnDatapacks a dict stored in.unsinto a 0-d object array as soon as the object is subset or copied, soread_atera(load_groups=True)’s{group: hex}palette scanned as one color and was thrown away. Every ROI panel plotted fromadata[mask].copy()silently got the default palette instead of the vendor colors.Alignment with
uns['<col>_colors']now followsobs[col].cat.categoriesfirst, notuns['<col>_categories'].AnnDataprunes the color list in lock-step with the categorical when a subset is taken (_remove_unused_categories) but leaves_categoriesuntouched, so trusting the latter mispaired colors and categories after the first subset._categoriesis still used as a fallback for plain object columns.
Version 0.4.7#
Upgrade note — the default palette for categorical columns in
pl.spatial_cell changed, so existing figures will shift color. palette=None
now honours adata.uns['<color>_colors'] (scanpy convention) and otherwise uses
one discrete color per category (tab20 / tab20b). Previously geopandas’
tab10 normalized to 0..n-1 was used, which gave every category past the
10th the same hue — a 15-cluster plot rendered 11 distinct colors. Pass an
explicit palette= (or store uns['<color>_colors']) for byte-identical
output to older versions.
Fixed:
pl.spatial_celllegend swatches did not match the polygons. The fills came from geopandas’ default (tab10sampled over0..n-1) while the legend was built fromtab20/tab20bsampled over0..n— different colormap and different sampling. On a 5-category column only the first two swatches were correct, so users “fixed” their figures with an explicit palette that was never needed. Fills and swatches now derive from a single color list.Categorical colors could shift by one category when the plotted subset’s category order differed from the order the color list was built from. The column is now pinned to that order (
pd.Categorical(..., categories=...)) before geopandas sees it.
Added:
pl.spatial_cell(..., frameon=)and the same parameter onpl.spatial_squarebin, matchingsquidpy.pl.spatial_scatter:Falsedrops the frame, the ticks and the axis labels (ax.axis('off')),Trueforces the frame on, and the defaultNoneleaves a caller-suppliedaxuntouched. There was previously no way to turn the frame off from the API, and passingframeon=through**kwargsreachedPatchCollection.set()and raisedAttributeError.palette=Nonenow readsadata.uns['<color>_colors'], aligned throughadata.uns['<color>_categories']when present — so the Atera vendor palette thatio.read_atera(load_groups=True)stores inuns['cell_group_colors']is used without being restated in every call. An explicitpalette=still wins, and a list whose length disagrees with the category count is ignored with a warning.
Version 0.4.6#
Upgrade note — scalebar lengths carrying a unit suffix other than µm/px now
raise ValueError instead of being silently converted to micrometres. A script
that passed "20mm" was drawing a 20 µm bar, not a 20 mm one; convert to a µm
length or pass microns_per_unit=.
Fixed:
pl.add_scale_barread an unknown unit suffix as micrometres:length="20mm"drew a bar labelled 20 µm — a 1000× error that renders perfectly, with no warning."50nm","3in"and"50%"behaved the same way. Unknown suffixes now raise, and so does a misspelledunit=("micronz"), which was the onlyadd_scale_barargument left unvalidated whilelocandlabel_positionalready raised.A bare numeric string was read as pixels while the same bare number was read as micrometres: the empty suffix matched
""in the pixel-alias set, solength=50drew 50 µm butlength="50"drew 50 px — a 3× difference on a Visium HD object (0.32512 µm/px) with only a pair of quotes to explain it. Both spellings now mean micrometres.pl.add_scale_barno longer draws outside the axes. The bar is clamped in points (caps, stroke, label, backing frame) and, becausetight_layout(),savefig(bbox_inches="tight"),set_aspect("equal")and window resizes move the axes box after the call, the geometry is recomputed by a placer artist on every draw. Reported symptom: caps and label sitting on the spine or cut off in saved figures.tl._gene_utils.align_gene_framededuplicated through a list membership scan, 2.42 s on a 20k-gene model frame (147× the equivalentalign_gene_list, which had already been fixed). It now uses a set and selects rows by position instead of rebuilding the frame fromSeriesobjects, which could also upcast column dtypes. Same frame: 0.023 s, dtypes preserved column by column.io.read_hd_binread a tab-separatedtissue_positions.csvwithsep=","— which does not raise, it returns a single column holding the whole header line. Thesep="\t"fallback was therefore unreachable, and the failure surfaced as “N expression barcodes are missing from tissue positions”, blaming the data for the file format. Parses are now validated against the barcode + coordinates schema, and an unparseable file reports the separators it tried.
Added:
io.read_atera(..., load_groups=True)attaches Atera’s own per-cell clustering fromcell_groups.csvintoobs['cell_group'](Categorical) with the vendor palette inuns['cell_group_colors'], so the cluster labels people actually see in Atera Explorer are available without a manual join. Bundles without the file are skipped silently.New notebook
notebooks/Atera_spatial_roi_demoand a “Circular ROI (point + physical radius)” section inusage/visualization. The notebook runs on a raw Atera breast-cancer bundle: Atera’s owncell_groups.csvclustering, whole-section point plots (total_counts+cell_groupside by side), a 2 x 3 lattice of 300 µm ROIs, the six ROIs beside the remaining tissue, six distance-to-center maps coloured by physical µm, and cell polygons (spatial_cell) at a 100 µm radius for both cluster and gene expression. Scale bars follow each panel’s field of view — 1000 µm, 100 µm, 50 µm.
Changed:
Coverage no longer counts
trackcell/benchmark(development scaffolding, excluded from the wheel since 0.4.3). It was padding the denominator with lines no user can execute: the same test run now reports 80% instead of 70%.coverage reportwithout--includeno longer aborts with “No source for code” on a transient module that a dependency ``exec``s into the working directory.
Version 0.4.5#
Added:
tl.cells_in_radius(adata, center, radius)selects cells inside a circle defined by a center point and a physical radius.centerusesobsm['spatial']coordinates (what you read off the plot) whileradiusis in µm by default, soscalefactors['microns_per_pixel']is applied on Visium / Visium HD pixel data — a hand-rolled Euclidean test there silently measures pixels, not micrometres (3× off on a 0.32512 µm/px object).radius_unit='data'opts out;return_distances=Truealso returns each cell’s distance to the center in µm.pl.mark_circle(ax, xy, radius, ...)draws the matching circle on an overview plot, the circular counterpart ofpl.mark_region. It shares the unit semantics withtl.cells_in_radius(radius_unit='um'+adata), so the annotation and the selection cannot drift apart.
Version 0.4.4#
Added:
pl.spatial_cell(scalebar=...)/pl.spatial_squarebin(scalebar=...)and the standalonepl.add_scale_bar(ax, adata, ...)draw a physical scale bar (e.g. 50 µm) on spatial plots. The length is derived from the visible extent —scalebar=Truepicks a nice 1/2/5 × 10ⁿ value at ~18% of the width, so the same object yields 500 µm when shown whole and 20 µm when zoomed into a 200 µm window. Fixed lengths (50,"50um","20px") and a dict of style/ placement options (loc,pad,offset,color,linewidth,fontsize,caps,label,frame, …) are supported.pl.resolve_microns_per_unit/pl.nice_scale_lengthare public helpers. The µm-per-data-unit factor is inferred fromcoord_unitmetadata (Atera and trackcell readers already store µm) orscalefactors['microns_per_pixel'](Visium / Visium HD pixels);scalebar=dict(microns_per_unit=...)overrides. Bars shorter than ~2% of the visible width warn instead of silently rendering an illegible smudge.
Version 0.4.3#
Upgrade note — four of these change results, not only error messages:
tl.diff_nhood_enrichment(pvalues=True)— p-values are now(count+1)/(n_perms+1)and missing cluster pairs no longer collapse to zero, so pairs that used to look significant may stop being so. Apvalue_adj(Benjamini-Hochberg) matrix is returned alongside; report that rather than the raw matrix.tl.sweep_resolutions/tl.spatial_cluster— the Leiden fallback path now usesn_iterations=2like the primary path. Only affects environments withoutpython-igraph; stability scores from such a sweep are not comparable with 0.4.2.io.read_sto_bin— bins with negative coordinates now decode to the correct centres instead of ~4.29e11. Anything derived from those coordinates must be rebuilt.io.read_xenium_cellseg— matrix/metadata overlap below 90% now raises rather than returning a silently truncated object. A load that used to “work” and now fails has genuinely inconsistent inputs.
Fixed:
tl._gene_utils.build_gene_alias_lookuplet the first gene to claim a.N/-Nalias keep it, so with bothA.1andA-1present the realA-1resolved toA.1— a different gene, silently. Exact names now win over aliases, andalign_gene_listdeduplicates with a set instead of an O(n^2) membership scan.tl._nhood.diff_nhood_enrichment(pvalues=True)produced anti-conservative p-values: a category absent from one condition became NaN after reindexing, andNaN >= xis always False, so the count never incremented for those cells. Values now use the(count+1)/(n_perms+1)estimator (p can no longer be 0) and a Benjamini-Hochberg matrix is returned aspvalue_adj.io.read_sto_*left duplicate GEF gene symbols invar_names, which makesget_locreturn a slice:X[mask, slice]silently becomes an (n, k) matrix and plotting fails somewhere unrelated. Duplicates are renamed with a numeric suffix, warned about, and the original symbols kept invar['gene_symbol'].io.read_sto_binpacked bin ids as(x << 32) | yafter casting touint64. GEF coordinates are relative to an origin that is not always the array corner, so a negative bin index wrapped to ~4.29e9 and produced nonsense bin centres. The packing now shifts to a non-negative origin and unshifts when decoding, so negative coordinates stay exact.pl.spatial_cellclassified every integerobscolumn as continuous, so integer-coded cluster labels (leidenas int8, cluster ids as int64) were drawn as a viridis gradient with no legend. Columns are now classified by cardinality (Categorical/object/bool always, integers with at most 30 levels), and a newcategorical=argument overrides the inference either way.pl.selectproduced arbitrary ROI membership for a self-intersecting lasso (tracing a region and retracing a diagonal is a normal mouse artefact): an invalid polygon’scontainsresults are undefined, and one test case selected only one of the two cells the user had drawn around. The ring is now repaired withmake_validbefore testing membership.pl.select.RegionSelector.savere-initialised the wholeobscolumn toNonebefore writing the current ROIs, so adding one ROI to an object restored from a previous h5ad discarded every earlier label. Only cells inside a ROI recorded in this session are overwritten now.io.read_xenium_cellsegonly printed a warning when the expression matrix andcells.parquetdisagreed, andverbose=Falsesilenced it — a partial-matrix run therefore “succeeded” with far fewer cells than expected. Zero overlap raises with both id lists; below 90% raises; the remainder logs atwarningthrough the logger.io.read_sto_cellbindivided byimg.max()when normalising the tissue image, emittinginvalid value encountered in divideon a blank capture. It also storedhiresandlowresas the same array object, so the h5ad carried the full image twice and mutating one changed the other. Blank captures render black, andlowresis now a genuinely downsampled copy.io.read_aterawithregion=/n_cells=(the preview path) subset the object after building polygons and leftuns['cell_boundaries']['cell_idx']at its pre-subset length, so every vertex offset addressed the wrong cell — silently, since the geometry table itself was trimmed correctly.io.read_sto_*resolved an ambiguous GEF directory by takingcandidates[0]ingloborder, which is filesystem-dependent: the same directory could yield a different chip on a different machine. Candidates are sorted by name and the warning names all of them.tl._autores/tl.spatial_clusterfell back from the igraph Leiden backend on(ImportError, TypeError, ValueError). A parameter error was therefore retried on a second backend instead of surfacing, and the fallback ran with leidenalg’s defaultn_iterations(-1 vs 2) — so a resolution sweep could compare clusters from two different algorithms and report the difference as stability. OnlyImportErrortriggers a fallback now, both branches usen_iterations=2, and the switch warns.
Changed:
Development tooling is now pinned to the exact versions used locally, in all three places that run it.
blackwas pinned>=26.0,<27.0inpyproject.tomlbut24.10.0in.pre-commit-config.yaml;flake8was^6.0.0in one place and7.1.1in the other, while the maintainer ran7.4.1;pytestwas^7.0.0against a local9.0.2. Two formatter versions in one repository make “pre-commit reformats what CI just accepted” an expected outcome rather than a risk.The wheel no longer bundles
trackcell/benchmark— 2592 lines of development scaffolding (including two.Rscripts) with zero imports from library code. It was 20 of 64 wheel entries and 12.5% of the package, and it skewed every coverage number.scripts/check_package.pynow fails if it reappears.Optional-dependency upper bounds were guesses that the maintainer’s own environment already violated:
python-igraph<1.0against an installed 1.0.0,harmonypy<1.0against 2.1.0. CI therefore installed versions nobody had run. Bounds widened to the majors actually in use.trackcell/py.typedcontainedpartial, which has meaning only for stub-only distributions; mypy only checks that the file exists. Emptied.Coverage ratchets added for
io/serialize.py(>= 70%) andio/convert_annohdcell.py(>= 12%, a floor that can only move up).
Version 0.4.2#
Upgrade note: vst(do_regularize=False) now returns real residuals
where 0.4.1 returned NaN, and integrate_pair_xgb applies a larger (and
correct) correction. Re-run affected analyses rather than mixing versions.
Fixed:
tl._sctransform.vst(do_regularize=False)ignored R’s rule thatn_genesis dropped when regularisation is off (sctransform::vst: “will use all genes”). Step 1 stayed subsampled, the extrapolation step never ran, andmodel_pars_fit.reindex(genes)left the un-subsampled genes NaN — 80% of the residual matrix in a 500-gene/n_genes=100run. Step 1 now uses every gene, and any gene still without a model raises instead of yielding NaN.tl.integration._xgboost_integration.integrate_pair_xgbcomputeddelta = y_pred @ pca.components_, which omitspca.mean_. The mean is the bulk of a batch shift, so the correction was systematically too small by exactly that term. Now usespca.inverse_transform.tl.slice_separation.dbscan_slice_labelsfailed silently in three ways: non-finite coordinates surfaced as sklearn’s opaque “Input contains NaN”; every cluster belowmin_cellsmarked 100% of cellsdebriswithout a word; and a pixel-coordinate slide given a µmepscollapsed to one slice. Each now raises or warns with the actual cause and the relevant numbers, including a units hint whenepsis more than 25x the median nearest-neighbour spacing of a single surviving cluster.
Version 0.4.1#
Upgrade note: every integrate_rpca / integrate_sct_rpca /
integrate_pair result changes. Anchor weighting was inverted (see Fixed),
so integrated embeddings, UMAPs and cluster labels produced by 0.4.0 are not
comparable to 0.4.1. Re-run integration rather than mixing outputs from the two
versions.
Fixed:
tl.integrationanchor weighting was inverted. Seurat’sIntegrateDataconverts kNN distances to similarities before callingFindWeightsC(Seurat 4.4.0,R/integration.R:3820:distances <- 1 - (distances / distances[, ncol(x = distances)]));integrate_data.integrate_pairpassed raw Annoy distances into the same formula (src/integration.cpp:49), so the nearest anchor received the smallest weight. Everyintegrate_rpca/integrate_sct_rpca/integrate_pairrun was affected, and no test could catch it because the only integration test compared two copies of the same formula. The conversion now lives in_distance_to_similarityand is covered bytests/test_integrate_data.py::test_weights_decrease_with_distance.integrate_pairnow emits awarningwhen fewer query cells carry anchors thank_weight, instead of silently narrowing the weight kernel.tl._sctransform.get_residualslabelled residual rows with the requested gene order but filled them invar_namesorder, so whenevergenes != umi_genes— i.e. anysctransform(residual_features=[...])call with a user-ordered marker panel — every residual was attached to the wrong gene, silently. Rows are now selected by position fromumi_genes; duplicate gene names raise instead of mismatching, and_xgboost_integrationindexes residuals by label rather than position.io.concat_atera_roisstored per-ROI offsets as a dict oftupleinuns['atera']['offsets']. anndata has no serializer fortuple, so the merged object could never be written withsave_h5ad/write_h5ad. Offsets are nowfloat64arrays of length 2.io.serializegeometry round trips: a missing polygon no longer aborts the write (Nonein an object column raisedTypeError; it is now stored as an empty string and read back asNone), every non-geometry column is preserved (attribute columns and the active column order used to be dropped), andGeoDataFrame.crssurvives via a<key>__crssidecar. The WKT codec now lives in one place —io.restore_geometriesdelegates toserialize.restore_geometriesinstead of keeping a second, lossier copy.
Changed:
tests/conftest.pyskips every@pytest.mark.slowtest when the benchmark data root is absent. A clean checkout previously produced tenFileNotFoundErrorfailures forpytest -m slowdespite README and CONTRIBUTING both promising skips.CI now runs the same
flake8 trackcell tests scriptscommand documented in CONTRIBUTING (previously it ran two narrow--selectsubsets, so the documented command was permanently red with 122 findings)..flake8ignoresE501(black owns wrapping) and grantsE402only to the three files where the matplotlib backend must be configured before importing pyplot.scripts/check_package.pygains--expect-version. The release workflow now passes the triggering git tag, which is the only value that can disagree withpyproject.toml— the previous checks compared artifacts built from the same source and therefore could never fail.
Version 0.4.0#
Behavior change:
Library code no longer prints progress to stdout. Readers and
multigene_blendemitINFOrecords under thetrackcelllogger (silent by default; opt in vialogging). Non-fatal data problems (missing tissue image orscalefactors_json.json) now raiseRuntimeWarningviawarnings.warn(). Intentionally displayed report output (atera_info, the interactive ROI selector) still prints. See the Logging usage page.
Added:
trackcell._logging.get_logger()— structured logging bootstrap with aNullHandlersoimport trackcellstays silent.IO test coverage for
read_hd_bin/read_hd_cellseg/read_stodriven by synthetic but structurally faithful vendor fixtures (tests/conftest.py). CI enforces coverage minimums (read_data≥ 75%,read_sto≥ 60%).scripts/check_package.pynow validates the built wheel’sVersionagainst the source version, closing the stale-wheel false positive.
Changed:
pl.plotandpl.selectno longer silently swallow exceptions; optional rendering steps log atdebugand a visible draw failure logs awarning.read_data’s H5-fallback notice is logged atINFO.
Fixed:
read_sto_cellbinnow reads scalaroffsetX/offsetYGEF attributes correctly (a parsing bug previously forced them to0) and records them inuns["spatial"][sample]["metadata"]asoffset_x/offset_y/offset_um. Coordinates remain in the GEF/image frame (offsets are not added).Removed dead code in
pl.plot.spatial_cell(edges_draw; dual-color edges are already drawn by_draw_categorical_edges) and in_sctransform_v2.build_poisson_gene_tables(unused Poisson-set locals); no behavior change.
Hygiene:
Stop tracking
.annovibe/im.json(contained bot credentials); ignore.annovibe/.Moved benchmark/debug helper scripts out of
tests/intodev/; renamedtests/sct_benchmark_data.py→tests/_sct_benchmark_data.py.Removed root-level
test_import.py; movedpromotion_article.mdtodocs/marketing/.
Version 0.3.47#
Bug fixes:
sctransform(copy=True)now returns the modified copy (previously it silently returnedNoneand discarded the result).store_residuals_in='layer'residuals are now aligned toadata.var_namesinstead of being written in residual-variance order. The batch path now honoursstore_residuals_inas well.read_xenium_cellsegno longer raisesUnboundLocalErrorwhenbuild_polygons=Falseor whencell_boundaries.parquetis missing butnucleus_boundaries.parquetexists.New
trackcell.io.save_h5ad()/trackcell.io.flatten_geometries()serialize polygon GeoDataFrames to WKT (adata.write_h5adfails otherwise);restore_geometriesnow also handlesnucleus_geometries.split_by_slicenow reindexesuns['cell_boundaries']using the original observation positions (previously every slice received the first N cells’ vertices).spatial_clustervalidatesmode/method/integrate/graph_mode(invalid values used to silently do nothing), and its preprocessing no longer requiresscikit-misc:seurat_v3is used on raw counts when available, otherwise it falls back toseuraton log-normalized data.layer/use_raware part of the neighborhood cache key.prep_sct_integrationnow defaults tokey_added='sct_prep', matchingintegrate_rpca/run_sct_integration.score_anchors_seuratno longer mixes batch1 and batch2 index spaces (shared-neighbour counts were inflated by spurious cross-dataset matches).multigene_blendsupports more than seven genes without an explicit palette, honourslayer/percentile clipping in facet mode, and no longer writesunswheninplace=False.RegionSelector.save(key_added=...)writes the requested column.read_hd_bin/read_hd_cellseginfer sample names correctly from SpaceRanger layouts;read_hd_cellseghandles list-valued classifications.hd_labeldistfalls back tometadata['pixel_size']/ Xeniumexperiment['pixel_size']when no scalefactor is available.STOmics: circular cell diameter from area,
gene_name_indexhonoured for GEM input, andimage_pathsupported for GEM input.diff_nhood_enrichmentrestricts the permutation null to the two compared conditions.
Tests: regression coverage for the fixes above (SCT copy/layer order, h5ad geometry round-trip, Xenium boundaries, slice boundary alignment, anchor scoring, multigene blends, ROI saving, preprocessing fallback).
Version 0.3.46#
Pin
pyarrowto<22: pyarrow 22+ no longer works with the NumPy 1.x ABI used by trackcell, which brokepd.read_parquetfor Xenium / SpaceRanger tables on Python 3.11–3.12.Skip the RPCA cache-release test when the optional
annoypackage is not installed (it is covered by the CI integration job).
Version 0.3.45#
Packaging fixes:
trackcell[clustering]now actually installsleidenalgandpython-igraph(the extra was previously empty andpoetry checkfailed).New
integrationextra (annoy,harmonypy,bbknn) andinteractiveextra (ipympl); both were previously either mandatory or documented as manual installs.Direct dependencies (
anndata,scipy,scikit-learn,statsmodels,patsy,joblib,matplotlib,pyarrow) are now declared explicitly instead of relying on scanpy transitives.pyarrowis required to read Xenium / SpaceRanger parquet tables.Added the MIT license (
LICENSE+ package metadata).Removed the machine-specific
/Volumes/process/tmp/tcl_testbenchmark path; useTRACKCELL_BENCHMARK_ROOT(default~/trackcell_benchmark).
Testing: added a CI workflow (Python 3.10–3.12) with lint, wheel metadata validation, and the fast test suite. Heavy R/Seurat parity tests are marked
slowand require external benchmark data.Fixes:
The numpy fallback RNG used when the optional
rrngis not installed now normalizes sampling probabilities like R’ssample(prob=), fixingValueError: probabilities do not sum to 1in SCT v2.Integration tests that require the optional
annoypackage are skipped when it is not installed.
Performance:
_row_gmean_sparseis now vectorized (~30x faster on realistic sparse matrices, bit-identical results). Removed ineffective object-mode numba caching/nogilfrom SCT residuals and GLM helpers, eliminating import-timeNumbaWarningnoise.
Version 0.3.44#
Atera support (
trackcell.io.read_atera):read_ateraauto-detects official (Atera 1.x Zarr) and preview (Xenium-v4 compatible) bundles;read_atera_cellseg/read_atera_previeware the explicit entry points.atera_inforeports cells/genes/polygons/transcripts without loading the matrix.Unified schema across formats:
var_namesare gene symbols,var['gene_ids']/var['feature_types']/var['is_gene_expression'],obs['barcode'],obsm['spatial']in µm, polygons inuns['spatial'][sample].filter_atera_genesremoves negative-control codewords before HVG/PCA.iter_atera_transcripts/read_atera_transcriptsstream the single-molecule point cloud withgenes/region/min_qvfilters; the gene-range fast path reads only the requested genes.atera_cell_qc/atera_transcript_qc(Q-score, assignment rate, nuclear fraction, per-gene nuclear fraction, density).list_atera_rois/iter_atera_rois/concat_atera_roisfor run directories; offsets are required unless ROIs are already aligned.pl.atera_qc_summary,pl.atera_transcript_density,pl.atera_nuclear_fractionread everything fromadata.read_xenium_cellseggainedbuild_polygons,include_nucleus,store_wktandverbose(backward compatible).Documented limits: no isoform, splice-junction, spliced/unspliced or RNA-velocity support; no customer barcodes.
New docs: Atera; new tests:
tests/test_atera.py.
YardCluster CellCharter-inspired extensions:
Multi-hop neighborhood aggregation (
neighborhood_features(n_layers=...),spatial_cluster(n_layers=...)).Automatic Leiden resolution selection by clustering stability (
resolution="auto",tcl.tl.sweep_resolutions,tcl.tl.select_resolution).Gaussian-mixture clustering backend (
yard_cluster(method="gmm"), BIC-basedn_clustersselection).Post-analysis tools:
tcl.tl.connected_components,tcl.tl.nhood_enrichment,tcl.tl.diff_nhood_enrichment, andtcl.tl.remove_long_links.Enrichment heatmaps:
tcl.pl.nhood_enrichment,tcl.pl.diff_nhood_enrichment(diverging colormap, p-value stars).
SCT runtime backend cleanup:
Remove the R subprocess bridge and the public
method='r'/r_vst_export_*paths.resolve_sct_integration_methodis gone withsct_method; the backend is selected explicitly viasct_v2_backend.Add explicit
v2_backend='python'|'pyglmGamPoi'selection. Pure Python is the deterministic default;pyglmGamPoiis optional and never selected automatically.Add a vectorized
MASS::theta.ml-compatible NB offset fallback and separate thesqrt(N)HVG-ranking clip from the tightersqrt(N/30)stored assay clip.Move readers and R export scripts into
trackcell.benchmarkso offline Seurat parity checks remain available without a runtime R dependency.
SCT + RPCA benchmark on project AA/A04 (3 × 10x samples, 27,129 cells):
Pure Python
v2_backend='python'vs Seurat R v4SCTransform(vst.flavor='v2').SCT HVG Jaccard median 0.939, IntegrationFeatures Jaccard 0.933, PrepSCTIntegration correlation 0.988, anchor count ratio 0.989.
Python SCT 1.83× faster (175s vs 320s); RPCA slower due to Numba weight construction.
See SCT + RPCA integration evaluation for the full tables and
<benchmark-root>/SCTRPCAbench/report.jsonfor the raw results.
Version 0.3.43#
SCT + RPCA integration (Seurat v4 parity first):
Split API:
run_sct_integration,integrate_rpca,sct_prep_matrix;integrate_sct_rpcaremains a thin wrapper.Hybrid R step-1 /
inject_r_scale_datapath for prep and anchor parity (benchmark integrate corr ~0.96 vs Seurat).Explicit opt-in memory release:
release_sct_integration_cacheand documented manualunsone-liners (no automatic cache trimming).
Performance (RPCA path):
Vectorised / chunked IntegrateData weight construction (Numba).
n_trees_weight(default 10; use 50 for Seurat parity).integration_dtype='float32'default;float64for parity.sct_batch_n_jobsfor parallel per-batch SCT.
Docs & benchmark:
docs/source/usage/batch_integration.rst— SCT+RPCA / Harmony / BBKNN.docs/source/benchmark/rpca_evaluation.rst+scripts/run_rpca_benchmark.py.trackcell/benchmark/rpca/stepwise and E2E RPCA evaluation suite.
Version 0.3.42#
Fix
pyproject.tomlPoetry extras: declarepyglmGamPoi/xgboostas optional dependencies and reference bare package names in[tool.poetry.extras](fixes PyPI release workflow for v0.3.41).
Version 0.3.41#
SCT v2 parity fixes (native pyglmGamPoi path):
Fix
vst()step-1 cell slicing: usecells.get_indexer(cells_step1)so count columns align withcell_attroffset (wascells.isin, wrong order).mark_suspicious_thetauses full-matrix row means/variances (matches Rget_model_pars).Seurat-parity benchmark loader assigns R rownames by position for duplicate genes (
.Nvs scanpy-N).
SCT benchmark (docs → Benchmark → SCT evaluation):
trackcell/benchmark/sct/— stepwise R→Python injection + end-to-end comparison on GSE288946 (3 samples, 6 seeds).scripts/run_sct_benchmark.py— R export viaata+ Python metrics.QC: ≥100 cells/gene, ≥50 genes/cell. Native HVG Jaccard ~0.98 vs R.
Optional dependency
trackcell[sct]→pyglmGamPoi>=0.2.1.
Version 0.3.40#
Fix background image cropping in ROI views:
_process_background_imagenow usesdata_coords_rangeto crop the background image to the visible data region before passing it toimshow(matching scanpy’s behaviour). Previously, the full image was always rendered and then zoomed, which could cause alignment drift between the background image and cell geometries on ROI-subset data due to matplotlib downsampling of large images.
Version 0.3.39#
Fix background image direction when ``invert_y=False``:
spatial_cellandspatial_squarebinnow respectinvert_y=Falsefor colored background image overlays by vertically flipping the image, matching the existingcolor=Nonebehavior. Previously, the background image was rendered unflipped while axis limits were inverted, causing ROI views to appear inconsistent when compared to manually-cropped images.
Version 0.3.38#
Fix ssDNA grayscale image → RGB in
io.read_sto: STOmics ssDNA images are single-channel grayscale.sc.pl.spatialapplies viridis colormap to 2D arrays, producing misleading purple backgrounds. The reader now converts to (H, W, 3) RGB at load time.``trackcell[clustering]`` extra:
leidenalgandpython-igraphare now an optional extra (pip install trackcell[clustering]) rather than hard dependencies.
Version 0.3.37#
Relax Python version constraint from
>=3.10,<3.12to>=3.10,<3.13to allow installation on Python 3.12 environments.Docs fixes (:pr:`#—`):
STOmics notebook now has embedded figures (PCA, UMAP, spatial cell polygons with ssDNA background, ROI zoom with cell boundaries).
Gallery thumbnails for STOmics and YardCluster notebooks.
usage.rstupdated to mention STOmics support.
Version 0.3.36#
STOmics (Stereo-seq) GEF/GEM data support (:pr:`#—`):
New IO module (
io/read_sto.py):read_sto_cellbin()— reads STOmics cellbin GEF (HDF5) and creates an AnnData with cell polygon geometries (cellBorder→ Shapely polygons). Supports both file and folder path input with auto-discovery.read_sto_bin()— reads STOmics squarebin/tissue GEF files for bin-level analysis. Supports automatic bin merging and GEM.gzip fallback with auto-redirect to matching GEF.Auto-discovers ssDNA tissue images from
03.register/directory (sibling or parent of GEF path).Reads
resolutionattribute (500nm/unit) from GEF metadata and stores proper physical scalefactors (pixel_size_um,resolution_nm,tissue_hires_scalef).Handles
cellBordersentinel stripping (32767 padding for cells with fewer than 32 vertices).
New example notebooks:
STOmics_mouse_brain_demo— full STOmics cellbin read→QC→Leiden clustering→spatial visualization→subset→cell boundary zoom-in workflow.YardCluster_STOmics_demo— YardCluster spatial clustering on STOmics mouse brain (auto mode: celltype + domain output).
Documentation updates:
usage/reading.rst— added “Reading STOmics (Stereo-seq) Data” section.examples.rst— linked both new notebooks.
Image auto-discovery for STOmics readers —
image_pathparameter accepts file, register directory, or None (auto-discover from03.register/sibling of GEF).
Version 0.3.35#
Defensive fixes from code review (:pr:`#—`):
Spatial weights NaN / zero-division protection (
tl._spatial_graph.build_spatial_weights):Handle duplicate spatial coordinates correctly (use neighbour index, not zero-distance, to exclude self).
Filter out non-finite distances before computing the Gaussian bandwidth.
Guard against zero or non-finite weight-sum with uniform fallback.
Validate input shapes (
coords.ndim == 2,batch_labelslength).
Annohdcell polygon generation robustness (
io.convert_annohdcell.bins_to_cell_polygon):Colinear bins now produce a valid buffered Polygon instead of a LineString.
Exception fallback uses
Point(…).buffer(…)instead of a degenerate 3-identical-point polygon.
Input alignment checks in SpaceRanger readers (
io.read_data.read_hd_bin/read_hd_cellseg):Reject duplicate barcodes or missing tissue positions early with clear error messages.
Warn when expression barcodes lack segmentation geometries, and vice versa.
Use
reindexinstead of.loc[]for safer alignment.Protect against
IndexErroron empty classification / geometry columns.
YardCluster sparse-matrix scaling (
tl.spatial_cluster):_scale_for_yardclusternow useszero_center=Falsewhenadata.Xis sparse, avoiding accidental densification / OOM.
DE-merge guard against expensive pair enumeration (
tl._cluster_merge.merge_clusters_de):New
max_de_testsparameter (default 2000). When the number of potential cluster-pair comparisons exceeds the cap, the merge is skipped with a warning instead of running a large number of Wilcoxon tests.Parameter exposed through
yard_clusterandspatial_clusterasmerge_max_de_tests.
Bug fix: ``integrate=’separate’`` batch label corruption (
tl.spatial_cluster):Fixed a bug where batch-prefixed labels were written as a single string containing the entire array instead of per-cell labels.
Classification color-parsing robustness (
io.read_data.convert_classification_to_color_dict):Rewritten to tolerate mixed dict / JSON-string / list formats without relying on
DataFrame.explode().unique().
``hd_labeldist`` explicit coordinate-system control (
tl.spatial.hd_labeldist):New
coordinate_systemparameter:'fullres','hires', or'auto'(default, preserves old heuristic but warns when ambiguous).New
library_id,microns_per_pixel,hires_scaleoverrides.Resolved parameters stored in
adata.uns/DataFrame.attrsfor reproducibility.
Plotting geometry auto-sync after subset (
pl.plot.spatial_cell/pl.select.select_regions):_sync_geometries_to_obsautomatically filters and re-ordersuns['spatial'][sample]['geometries']to match currentadata.obs_nameson first use after subsetting.Simplified
spatial_cellgeometry-bounds validation: replaced nested retry loop with a single pass +aspect='equal'fallback.spatial_cellandspatial_squarebinno longer callfig.tight_layout()on user-provided axes.Added
from __future__ import annotationsso geopandas type hints don’t break module import when geopandas is absent.The following files were changed as part of this work:
trackcell/tl/_spatial_graph.pytrackcell/tl/_cluster_merge.pytrackcell/tl/spatial_cluster.pytrackcell/tl/spatial.pytrackcell/io/convert_annohdcell.pytrackcell/io/read_data.pytrackcell/pl/plot.pytrackcell/pl/select.pytests/test_yardcluster.pytests/test_convert_annohdcell.py(new)tests/test_read_data_helpers.py(new)tests/test_spatial.py(new)tests/test_plot_helpers.py(new)
Version 0.3.34#
Documentation overhaul — synchronized all usage tutorials with actual function signatures and parameters:
Fixed
spatial_cell(..., sample=...)→library_id=...in all code examples (12 places across docstrings, RST, Markdown).New usage tutorial:
docs/source/usage/annohdcell_conversion.rst— annohdcell (bin2cell) conversion, now integrated into Sphinx.README.md: added YardCluster, DBSCAN slice separation, interactive ROI selection, and mark_region sections.spatial_clustering.rst: documented missing advanced parameters (preprocess,layer,use_raw,hvg_by_batch,scale_by_batch,harmony_integrate,copy).computing_distances.rst: addedhd_labeldistmethodparameter (kdtree vs cdist) and colony centroid distance section (mark_colony_centroids,distance_to_nearest_centroids).visualization.rst: fixed garbled key-parameters section forselect_regions, added missingalpha_facet/showfor facet mode,library_id/figsizefor ROI select.examples.rst: replaced duplicate toctree with:doc:links.annohdcell_conversion.rst: addedcreate_polygonsandn_jobsmethod-specific parameter docs.
Version 0.3.33#
DBSCAN spatial slice separation (
tcl.tl.spatial_slice_cluster):Split Xenium TMA regions into physical tissue sections (
S001–SNNN) via density clustering on cell centroids (CCHD defaults:eps=80µm,min_samples=10,min_cells=1000).read_xenium_cellseg(..., slice_separate=True)for one-step load + annotate.Helpers:
split_by_slice,slice_cluster_summary,write_slice_annotation.
Micro-region colony clustering (GC / tumor nests):
spatial_colony_cluster— DBSCAN on BANKSY-filtered subsets (defaults:eps=50,min_samples=5,min_cluster_size=40).mark_colony_centroidsanddistance_to_nearest_centroidsfor GCC/TNC distance analysis (CCHD54_1_GC_dist.ipynbworkflow).New tutorial:
docs/source/usage/xenium_slice_separation.rst.
Version 0.3.32#
YardCluster spatial clustering (
tcl.tl.spatial_cluster):Lightweight CPU pipeline combining BANKSY-style neighborhood features, dual-channel identity/context embeddings, and scanpy Leiden clustering.
Function group:
spatial_neighbors,neighborhood_features,yard_embed,yard_cluster.Multi-sample support:
integrate='separate'/'joint'(Harmony).Optional DE-guided cluster merging, sketch mode for large datasets, and
gradient_mode='cosphi'|'regression'.New usage tutorial:
docs/source/usage/spatial_clustering.rst; Colon Cancer demo notebook updated.
Version 0.3.31#
Fix selectors not responding in ipympl:
Changed all selectors from
useblit=Truetouseblit=False(blitting breaks RectangleSelector/EllipseSelector/LassoSelector in the ipympl backend).Added
fig.canvas.draw()after selector creation to ensure widgets initialize properly.
Version 0.3.30#
Hotfix: fix ``_mode_buttons`` AttributeError —
_build_toolbar()is now called before_connect_all_selectors()so that_update_toolbar_highlight()has access to the toolbar button dict.
Version 0.3.29#
Fix notebook ROI selector UX — no more blocking ``input()``:
tcl.pl.select_regionsno longer callsinput()after each ROI. ROIs are now auto-named (ROI_1,ROI_2, …) with a configurableroi_prefixparameter — the interactive workflow is never interrupted.Inline toolbar added at the bottom of the figure with clickable buttons:
■ Rect,● Ellipse,✎ Lasso,✕ Clear,↩ Undo. The active mode is highlighted in blue.Selected cells are now highlighted in real-time with coloured scatter points (cycling through 10 distinct colours).
New method
selector.rename_roi(old, new)for post-hoc renaming.New method
selector.undo()to remove the last ROI (boundary, highlight, and data).Keyboard shortcuts
r/e/lkept for power users.
Version 0.3.28#
Replace napari ROI selection with Jupyter-native matplotlib selector:
tcl.pl.select_regionskeeps the original function name but now uses matplotlib widgets / ipympl instead of napari/Qt.Keyboard-toggle between all shape modes:
r``=rectangle, ``e``=ellipse, ``l``=lasso — no ``shape_typeparameter needed.Interactive ROI naming via
input()after each selection (auto-generatesROI_1,ROI_2, … on empty input).inplaceparameter replacescopy(scanpy convention):inplace=True(default) writes toadata.obs;inplace=False→ useselector.to_adata().Supports both cellbin geometry intersection and squarebin centroid selection.
Returns a
RegionSelectorcontroller withrois,polygons,save(),clear(),to_adata(), anddisconnect().Removes napari from public plotting API and package dependencies.
Version 0.3.27#
Fix Jupyter kernel crash in select_regions: auto-detect Jupyter environment and enable Qt GUI integration (%gui qt) before calling napari.run() to prevent Qt/IPython event loop conflict.
Version 0.3.26#
napari ROI selection now supports squarebin data:
New
modeparameter ("auto"/"cellbin"/"squarebin").New
basisparameter for squarebin coordinate key inadata.obsm.Auto-detection: cellbin if geometries found, squarebin otherwise.
Squarebin extraction uses point-in-polygon (
Point.within) on bin centroids.
Version 0.3.25#
Fix PyPI auto-publish: update pyproject.toml version to match __init__.py so poetry build produces correct package version.
Fix workflow: username → user for pypa/gh-action-pypi-publish >= v1.12.
Version 0.3.24#
Added napari-based interactive ROI selection:
New module
trackcell.pl.napariwith three public functions.Supports rectangle, polygon, freehand, and any shape.
copyparameter for in-place vs. dict return.napari is an optional extra (
pip install 'trackcell[napari]').
Version 0.3.23#
Added ``show`` parameter to ``mark_region``:
show=True(default) now callsplt.show()automatically after adding the rectangle, somark_regionworks out of the box without requiringshow=Falsein the plotting function and a manualplt.show().Set
show=Falseto defer display when chaining multiplemark_regioncalls or when callingplt.show()manually.Motivation: The previous workflow required
show=False,ax=ax, andplt.show()— a pattern many users overlooked, causing the rectangle to appear invisible. Now the simplest usage works:ax = tcl.pl.spatial_cell(adata, color="CellType") tcl.pl.mark_region(ax, xlim=(54500, 56000), ylim=(15000, 16000))
Updated documentation:
Simplified
mark_regionexamples in the user guide to showcase the new default-behavior workflowDocumented the new
showparameter in both the docstring and the visualization guide
Version 0.3.22#
Rewrote ``mark_region`` for robustness: * Fixed invisible rectangle bug on inverted y-axis: normalized negative
width/height from
get_ylim()returning(bottom, top)withbottom > topAdded
zorder=100default to ensure the rectangle always renders on top of cells/binsAdded
fill_colorandfill_alphaparameters for optional semi-transparent fillAdded
refresh=Trueparameter — callscanvas.draw_idle()after adding the patch (setrefresh=Falsefor batch marking then manually refresh at end)Increased
edges_widthdefault from 1.0 to 2.0 for better visibility
Updated documentation: * Added
.. important::admonition aboutax=ax, show=Falsepattern formark_region* Added examples forspatial_cell,spatial_squarebin, filled regions, and multi-region batching * Documented all new parameters:fill_color,fill_alpha,zorder,refresh* Noted y-axis normalization behavior withinvert_y
Version 0.3.21#
Fixed ``invert_y`` not working when ``color=None``: * Root cause:
set_ylim(h, 0)already produces image convention withorigin='upper';the subsequent
invert_yaxis()call double-inverted the y-axis, making bothinvert_y=Trueandinvert_y=Falsevisually identical.Fix: removed the redundant
invert_yaxis()from bothspatial_cellandspatial_squarebincolor-None code paths.For
invert_y=False(Cartesian), the H&E image is now pre-flipped viaimg[::-1]beforeimshow()to keep it right-side-up.
Cleaned up ``mark_region``: * Removed unused
Circleimport inside the function body. * Added comprehensive documentation to the user guide with usage examplesfor both
spatial_cellandspatial_squarebin.Documented coordinate convention behavior with
invert_y.
Version 0.3.20#
Added ``shape`` parameter to ``spatial_squarebin``: *
shape='circle'(default): renders bins as centered circles (radius = bin_size / 2) *shape='square': renders bins as filled rectangles (original behavior) * Invalid shape values raiseValueError* Also aliased intcl.pl.spatial_bin()Added ``invert_y`` parameter to ``spatial_cell`` and ``spatial_squarebin``: *
invert_y=True(default): y-axis increases top-to-bottom (image coordinates, matches H&E) *invert_y=False: y-axis increases bottom-to-top (Cartesian convention)Documentation updates: * Documented
edge_colorboundary overlap behavior inspatial_cell:adjacent shared boundaries are drawn by category; the last-drawn category determines the visible color
Version 0.3.19#
Added dedicated HD squarebin plotting: * Added
tcl.pl.spatial_squarebin()for squarebin/bin-level HD visualization * Addedtcl.pl.spatial_bin()alias for a shorter, intuitive API * Supports plotting obs columns, genes, categorical values, and continuous values * Supportscrop_coordfor coordinate-based regional zoomingImproved no-color spatial rendering for HD plots: * When
color=None, squarebin plots now display the H&E image and spatial coordinate extent * Added axis/tick control for coordinate-aware inspection, matching the expected HD browsing workflow * Designed to complementtcl.pl.spatial_cell()for users working with non-cellseg squarebin dataDocumentation and examples updated: * Added dedicated squarebin usage examples to README and Sphinx docs * Added example script for squarebin visualization workflows * Reduced Sphinx autodoc build noise via mocked heavy imports for more stable online docs builds
Version 0.3.18#
Added ``read_xenium_cellseg`` function: * Reads 10x Xenium Analyzer output (cell_feature_matrix.h5, cells.parquet, cell_boundaries.parquet) * Automatically transposes CSC (genes × cells) to CSR (cells × genes) * Converts long-table boundary parquet to Shapely polygons + compact vertex arrays in a single pass * Reads optional
nucleus_boundaries.parquet,experiment.xenium, andgene_panel.json* Stores GeoDataFrame geometries (compatible withspatial_cell()) and WKT strings for serialization * Squidpy-compatibleuns['spatial']structureDual-color visualization in ``spatial_cell``: * Added
edge_colorparameter to color cell boundaries by a categorical column * Addededge_paletteparameter for custom edge color mapping * Fill (color) + Edge (edge_color) two-pass rendering for rich spatial views * Automatic dual legend: colorbar for fill, categorical legend for edgesMulti-gene visualization: *
tl.multigene_blend()with two modes:mode='blend': Weighted RGB blending, cell2location-style compositemode='facet': Faceted subplots with single-hue colormaps per gene
Raw hex color auto-detection in
spatial_cellfor blend mode outputSupports up to 7 genes with customizable colors, percentile clipping, and gamma
Version 0.2.8#
Major refactoring of ``spatial_cell`` function: * Refactored to use GeoDataFrame.plot() for efficient rendering and automatic legend generation * Integrated scanpy-style background image processing with scale_factor support * Fixed coordinate alignment issue when plotting subset data (image extent now matches data range) * Added support for gene expression visualization (color parameter can be a gene name from adata.var_names) * Legend and colorbar now positioned outside the plot area (right side) similar to sc.pl.spatial * Added
xlabel,ylabel, andshow_ticksparameters for axis customization *library_idparameter now auto-selects first available library_id when not specified (similar to sc.pl.spatial) * Addedalpha_imgparameter to control background image transparency * Improved categorical legend generation with custom palette supportEnhanced ``read_hd_cellseg`` function: * Added automatic detection of alternative segmentation file names (e.g.,
cell_segmentations.geojson) * Automatically addsspot_diameter_fullresto scalefactors if missing (required for sc.pl.spatial compatibility) * Improved error messages with suggestions for alternative filenamesDocumentation improvements: * Reorganized usage documentation into separate files (reading.rst, visualization.rst, computing_distances.rst) * Added directory structure requirements to reading documentation * Added comprehensive visualization optimization guide for large datasets * Updated examples with gene expression visualization
Version 0.2.5#
Fixed
read_hd_cellsegbug wherecellidcolumn was lost afterreset_index()Added robust handling for cases where
reset_index()creates'index'column instead of'cellid'Improved error messages for better debugging
Version 0.2.4#
Fixed
read_hd_cellsegbug wherecellidcolumn was missing when creating GeoDataFrameAdded field name detection for
cell_idcolumn (supports multiple naming variants)
Version 0.2.3#
Fixed
read_hd_cellsegto properly store cell geometries in GeoDataFrame format
Version 0.2.2#
Added
spatial_cellplotting function for visualizing cells as polygonsModified
read_hd_cellsegto store cell geometries in both GeoDataFrame and WKT formatRenamed
trackcell/io/spatial.pytotrackcell/io/read_data.pyRenamed
trackcell/pl/spatial.pytotrackcell/pl/plot.pyImproved documentation and examples
Version 0.2.1#
Added
read_hd_binfunction for reading bin-level data (2um/8um/16um)Enhanced
hd_labeldistwith automatic coordinate resolution detectionImproved memory efficiency with cKDTree method
Version 0.2.0#
Initial release with core functionality
read_hd_cellsegfor reading cell segmentation datahd_labeldistfor computing distances to labels