replicate_generator¶
tissue_simulator.replicate_generator ¶
Replicate tissue generator based on spatial statistics.
This module allows generation of random tissue replicates that match specified spatial interaction statistics. It uses an optimization-based approach to tune tissue parameters to achieve desired cell-cell interaction patterns.
TargetStatistics
dataclass
¶
TargetStatistics(interaction_stats: List[InteractionStatistics], cell_type_proportions: Optional[Dict[str, float]] = None, target_cell_count: Optional[int] = None, target_density: Optional[float] = None)
Target spatial statistics for replicate generation.
Attributes:
| Name | Type | Description |
|---|---|---|
interaction_stats |
List[InteractionStatistics]
|
List of InteractionStatistics defining target patterns |
cell_type_proportions |
Optional[Dict[str, float]]
|
Dict mapping cell types to target proportions (0-1) |
target_cell_count |
Optional[int]
|
Optional target for total cell count |
target_density |
Optional[float]
|
Optional target for packing fraction |
validate ¶
Validate that statistics are consistent.
Source code in tissue_simulator/replicate_generator.py
ReplicateStatistics
dataclass
¶
ReplicateStatistics(replicate_id: int, num_cells: int, cell_type_counts: Dict[str, int], packing_fraction: float, interaction_stats: List[InteractionStatistics], divergence_score: float, packing_report: Optional[Dict] = None, composition_error: Optional[float] = None, layout_flags: Optional[List[str]] = None)
Statistics for a generated replicate.
Attributes:
| Name | Type | Description |
|---|---|---|
replicate_id |
int
|
Unique identifier |
num_cells |
int
|
Total cell count |
cell_type_counts |
Dict[str, int]
|
Dict of counts per cell type |
packing_fraction |
float
|
Volume fraction occupied by cells |
interaction_stats |
List[InteractionStatistics]
|
Measured interaction statistics |
divergence_score |
float
|
Overall divergence from target statistics |
ReplicateGenerator ¶
ReplicateGenerator(target_stats: TargetStatistics, tissue_dimensions: Tuple[float, float, float], base_cell_radii: Dict[str, Tuple[float, float]], network_mode: str = 'contact', network_radius: Optional[float] = None, seed: Optional[int] = None, method: str = 'radius_tuning', coloring_params: Optional[Dict] = None, n_restarts: int = 1, radius_optimizer: str = 'heuristic', de_params: Optional[Dict] = None, density_model: Optional[DensityModel] = None, layout: str = 'resample', composition_weight: float = 4.0, composition_bin: float = 40.0, packing_params: Optional[Dict] = None)
Generate tissue replicates matching target spatial statistics.
This class uses an iterative approach to generate tissue samples that match specified spatial interaction patterns. It adjusts tissue parameters to achieve the desired statistics.
Initialize replicate generator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_stats
|
TargetStatistics
|
Target spatial statistics to match |
required |
tissue_dimensions
|
Tuple[float, float, float]
|
(height, width, thickness) in micrometers |
required |
base_cell_radii
|
Dict[str, Tuple[float, float]]
|
Dict mapping cell types to (min_radius, max_radius) |
required |
network_mode
|
str
|
"contact" or "radius" for spatial analysis |
'contact'
|
network_radius
|
Optional[float]
|
Distance threshold if using "radius" mode |
None
|
seed
|
Optional[int]
|
Random seed for reproducibility |
None
|
method
|
str
|
Replicate strategy. |
'radius_tuning'
|
coloring_params
|
Optional[Dict]
|
Optional overrides for the |
None
|
n_restarts
|
int
|
For |
1
|
radius_optimizer
|
str
|
For |
'heuristic'
|
de_params
|
Optional[Dict]
|
Optional overrides for |
None
|
density_model
|
Optional[DensityModel]
|
Optional :class: |
None
|
layout
|
str
|
|
'resample'
|
composition_weight
|
float
|
Weight of the spatial-composition term. It is multiplied by the squared mean degree of each replicate graph, which keeps its pull comparable to the edge-count term across graph sizes. The default 4.0 was chosen by ablation on synthetic nest processes (larger values trade pair-fraction accuracy for composition accuracy). |
4.0
|
composition_bin
|
float
|
Side in µm of the composition bins. |
40.0
|
packing_params
|
Optional[Dict]
|
Extra keyword arguments for
:class: |
None
|
Source code in tissue_simulator/replicate_generator.py
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 | |
from_coordinates
classmethod
¶
from_coordinates(filepath: str, network_mode: str = 'radius', network_radius: Optional[float] = 20.0, tissue_dimensions: Optional[Tuple[float, float, float]] = None, layout: str = 'resample', density_kwargs: Optional[Dict] = None, **kwargs) -> ReplicateGenerator
Replicate generator fitted to a coordinate CSV (the recommended path).
Reads the source region with
:func:~tissue_simulator.tissue.load_tissue_from_csv, extracts its
target statistics, fits a :class:~tissue_simulator.density.DensityModel
to it, and returns a method="graph_coloring" generator that packs
every replicate on a density-aware layout.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Coordinate CSV of the source region. |
required |
network_mode
|
str
|
Neighbor graph mode for targets and replicates. |
'radius'
|
network_radius
|
Optional[float]
|
Graph radius in µm for |
20.0
|
tissue_dimensions
|
Optional[Tuple[float, float, float]]
|
(height, width, thickness) of the replicates; defaults to the source region's. |
None
|
layout
|
str
|
|
'resample'
|
density_kwargs
|
Optional[Dict]
|
Keyword arguments for :meth: |
None
|
**kwargs
|
Other :class: |
{}
|
Source code in tissue_simulator/replicate_generator.py
generate_single_replicate ¶
generate_single_replicate(replicate_id: int, max_attempts: int = 1000, min_spacing: float = 0.5, allow_boundary: bool = True, max_iterations: int = 5, tolerance: float = 0.15, patience: Optional[int] = None, method: Optional[str] = None) -> Tuple[TissueSection, ReplicateStatistics]
Generate a single tissue replicate.
For method="radius_tuning" (default), iteratively generates tissues
and adjusts parameters to approach target statistics. For
method="graph_coloring", packs geometry once and assigns cell types
via simulated-annealing graph coloring (max_iterations / tolerance
apply only to the radius-tuning loop).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replicate_id
|
int
|
Unique identifier for this replicate |
required |
max_attempts
|
int
|
Max attempts for cell packing |
1000
|
min_spacing
|
float
|
Minimum spacing between cells |
0.5
|
allow_boundary
|
bool
|
Allow cells extending beyond bounds |
True
|
max_iterations
|
int
|
Max parameter adjustment iterations (radius-tuning only) |
5
|
tolerance
|
float
|
Acceptable divergence threshold (radius-tuning only) |
0.15
|
patience
|
Optional[int]
|
Optional adaptive-stopping budget for the radius-tuning
loop. When set, stop early once the best divergence has not
improved for |
None
|
method
|
Optional[str]
|
Override the instance |
None
|
Returns:
| Type | Description |
|---|---|
Tuple[TissueSection, ReplicateStatistics]
|
Tuple of (TissueSection, ReplicateStatistics) |
Source code in tissue_simulator/replicate_generator.py
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 | |
generate_replicates ¶
generate_replicates(num_replicates: int, max_attempts: int = 1000, min_spacing: float = 0.5, allow_boundary: bool = True, max_iterations: int = 5, tolerance: float = 0.15, patience: Optional[int] = None, parallel: bool = False, max_workers: Optional[int] = None) -> List[Tuple[TissueSection, ReplicateStatistics]]
Generate multiple tissue replicates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_replicates
|
int
|
Number of replicates to generate |
required |
max_attempts
|
int
|
Max attempts for cell packing per replicate |
1000
|
min_spacing
|
float
|
Minimum spacing between cells |
0.5
|
allow_boundary
|
bool
|
Allow cells extending beyond bounds |
True
|
max_iterations
|
int
|
Max parameter adjustment iterations (radius-tuning only) |
5
|
tolerance
|
float
|
Acceptable divergence threshold (radius-tuning only) |
0.15
|
patience
|
Optional[int]
|
Optional adaptive-stopping budget forwarded to each replicate. |
None
|
parallel
|
bool
|
When True, generate replicates concurrently with a
|
False
|
max_workers
|
Optional[int]
|
Worker count for the process pool (defaults to the executor's default when None). |
None
|
Returns:
| Type | Description |
|---|---|
List[Tuple[TissueSection, ReplicateStatistics]]
|
List of (TissueSection, ReplicateStatistics) tuples, in replicate order. |
Source code in tissue_simulator/replicate_generator.py
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 | |
consistency_report ¶
Quantify run-to-run consistency of generated replicates.
Reports, per method, the mean / standard deviation / coefficient of
variation of a chosen ReplicateStatistics metric, plus pairwise
Cohen's d and the per-group N needed to distinguish methods (via
:func:power_analysis.compare_initialization_variance). This is how
you measure whether one strategy is more consistent than another.
Note: a smaller coefficient of variation usually means more consistent,
but CV is std/|mean| and inflates when the mean sits near zero
(e.g. a method that matches the target almost perfectly). Read it
alongside the absolute std and mean in the returned per_method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replicates
|
Either a list of |
required | |
metric
|
str
|
ReplicateStatistics attribute to summarize
(default |
'divergence_score'
|
Returns:
| Type | Description |
|---|---|
Dict
|
The dict from :func: |
Dict
|
|
Dict
|
(Cohen's d, required N per group). NaN metric values (pairs with no |
Dict
|
signal) are dropped before summarizing. |
Source code in tissue_simulator/replicate_generator.py
export_replicate_statistics ¶
export_replicate_statistics(replicates: List[Tuple[TissueSection, ReplicateStatistics]], base_filename: str)
Export statistics for all replicates to CSV files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replicates
|
List[Tuple[TissueSection, ReplicateStatistics]]
|
List of (tissue, stats) tuples |
required |
base_filename
|
str
|
Base name for output files |
required |
Source code in tissue_simulator/replicate_generator.py
export_replicate_tissues ¶
export_replicate_tissues(replicates: List[Tuple[TissueSection, ReplicateStatistics]], output_dir: str)
Export each replicate tissue to a separate CSV file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
replicates
|
List[Tuple[TissueSection, ReplicateStatistics]]
|
List of (tissue, stats) tuples |
required |
output_dir
|
str
|
Directory for output files |
required |
Source code in tissue_simulator/replicate_generator.py
load_target_statistics_from_csv ¶
Load target statistics from a CSV file.
Expected CSV format: type_a, type_b, num_interactions, normalized_interactions, avg_distance, median_distance
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
str
|
Path to CSV file |
required |
Returns:
| Type | Description |
|---|---|
TargetStatistics
|
TargetStatistics object |
Source code in tissue_simulator/replicate_generator.py
load_target_statistics_from_tissue ¶
load_target_statistics_from_tissue(tissue: TissueSection, network_mode: str = 'contact', network_radius: Optional[float] = None) -> TargetStatistics
Extract target statistics from an existing tissue.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tissue
|
TissueSection
|
TissueSection to analyze |
required |
network_mode
|
str
|
"contact" or "radius" |
'contact'
|
network_radius
|
Optional[float]
|
Distance threshold for "radius" mode |
None
|
Returns:
| Type | Description |
|---|---|
TargetStatistics
|
TargetStatistics object |
Source code in tissue_simulator/replicate_generator.py
load_target_statistics_from_coordinates ¶
load_target_statistics_from_coordinates(filepath: str, network_mode: str = 'contact', network_radius: Optional[float] = None) -> TargetStatistics
Load FULL target statistics from a coordinate CSV file.
This is a convenience composition: it reads a tissue from a coordinate
CSV (one row per cell, with positions/radii/types) via
load_tissue_from_csv and then derives target statistics from that
reconstructed tissue via load_target_statistics_from_tissue. It is
exactly equivalent to::
load_target_statistics_from_tissue(
load_tissue_from_csv(filepath),
network_mode=network_mode,
network_radius=network_radius,
)
Because the statistics are computed from a real tissue, the returned
TargetStatistics is fully populated: it includes the measured
interaction statistics AND the cell_type_proportions and
target_density (packing fraction) inferred from the cell coordinates.
This is DISTINCT from load_target_statistics_from_csv, which reads a
precomputed interaction table (type_a, type_b,
normalized_interactions, ...) and therefore does NOT populate
cell_type_proportions or target_density. Use this function when
you have raw cell coordinates; use load_target_statistics_from_csv
when you already have an interaction-statistics table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
network_mode
|
str
|
"contact" (edges between touching cells) or "radius"
(edges between cells within |
'contact'
|
network_radius
|
Optional[float]
|
Distance threshold used when |
None
|
Returns:
| Type | Description |
|---|---|
TargetStatistics
|
TargetStatistics object with interactions, cell type proportions, |
TargetStatistics
|
target cell count, and target density populated. |
Source code in tissue_simulator/replicate_generator.py
fit_density_model_from_coordinates ¶
Fit a :class:~tissue_simulator.density.DensityModel to a coordinate CSV.
The companion of :func:load_target_statistics_from_coordinates;
equivalent to DensityModel.from_tissue(load_tissue_from_csv(filepath), **kwargs).