PavMatrix
PavMatrix
Constructor
The PavMatrix() class is the core data structure behind pavvis. By default, all that is required to generate it is
a pav.csv and accompanying metadata.csv file.
File formats
For more information on how these input files should be structured, see the concepts page.
__init__
Load and validate a PAV matrix with associated sample metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrix_path
|
str | Path
|
Path to the PAV matrix CSV. Genes must be rows (unique index), samples must be columns (unique headers), values must be 0 or 1. |
required |
metadata_path
|
str | Path
|
Path to the metadata CSV. Samples must be rows (index must match PAV matrix column headers exactly). |
required |
soft_core_min
|
float
|
Minimum presence frequency for soft core genes (inclusive). Defaults to 0.95. |
0.95
|
dispensable_min
|
float
|
Minimum presence frequency for dispensable genes (inclusive). Defaults to 0.15. |
0.15
|
private_min
|
float
|
Minimum presence frequency for private genes (exclusive lower bound — genes at exactly this frequency are excluded). Defaults to 0.0. |
0.0
|
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If either file path does not exist. |
ValueError
|
If sample IDs do not match between files, if any PAV value is not 0 or 1, if any cell is blank, or if thresholds are invalid. |
Identity & IDs
sample_ids
property
Sample identifiers, taken from the PAV matrix column headers.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of sample ID strings. |
gene_ids
property
Gene identifiers, taken from the PAV matrix row index.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
metadata_columns
property
Column names present in the loaded metadata DataFrame.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of metadata column name strings. |
Subsetting
subset() returns a new PavMatrix restricted to selected samples and/or genes, so any analysis or plot can be rerun
on part of the data — for example a single clade or region. Samples can be selected by ID, by a pandas query against
the metadata, or both. The original object is never modified.
subset
Return a new PavMatrix restricted to a subset of samples and/or genes.
Filters are combined: a sample is kept only if it is in samples (when
given) and matches query (when given). Samples and genes keep their order
from the original matrix. Gene categories are recomputed on the subset, so a
gene that is variable across the full matrix may be core or absent within
the subset. Thresholds are carried over; cached results (UMAP, Jaccard, PCoA)
are not, and the original object is left unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
list[str] | None
|
Sample IDs to keep. Defaults to None (all samples). |
None
|
genes
|
list[str] | None
|
Gene IDs to keep. Defaults to None (all genes). |
None
|
query
|
str | None
|
A pandas query string evaluated against the metadata, e.g.
|
None
|
drop_absent
|
bool
|
If True, remove genes absent from every retained sample. A UserWarning reports how many genes were dropped. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
PavMatrix
|
A new PavMatrix containing copies of the selected data. |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
ValueError
|
If any sample or gene ID is not found, or if the subset contains no samples or no genes. |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If drop_absent=True removes any genes, stating how many. |
modern = pm.subset(query="clade == 'Modern'")
europe_deep = pm.subset(query="continent == 'Europe' and depth > 10")
pair = pm.subset(samples=["Ability", "Agron"], drop_absent=True)
print(modern) # PavMatrix(34295 genes × 212 samples)
Gene categories are recomputed
Categories are always relative to the samples in the matrix. A gene that is variable across the full population
may be core, or absent, within a subset. Use drop_absent=True to remove genes that no retained sample carries.
Gene categories
gene_counts
property
Count of genes in each category and subcategory.
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict with keys 'core', 'soft_core', 'dispensable', 'private', and 'absent' |
dict[str, int]
|
mapping to integer counts. |
core_genes
property
Genes present in every sample (all values equal 1).
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
absent_genes
property
Genes absent from every sample (all values equal 0).
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
variable_genes
property
Genes present in at least one but not all samples.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
Variable gene subcategories
thresholds
property
Current variable gene subcategory thresholds.
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
Dict with keys 'soft_core_min', 'dispensable_min', 'private_min'. |
soft_core_genes
property
Variable genes present in >= soft_core_min and < 1.0 of samples.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
dispensable_genes
property
Variable genes present in >= dispensable_min and < soft_core_min of samples.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
private_genes
property
Variable genes present in > private_min and < dispensable_min of samples.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of gene ID strings. |
presence_frequency
property
Fraction of samples in which each gene is present.
Returns:
| Type | Description |
|---|---|
Series
|
pd.Series indexed by gene ID, with values in [0.0, 1.0]. |
Exclusive genes
exclusive_gene_counts
Count exclusive variable genes for each group in a discrete metadata column.
An exclusive gene is a variable gene present in at least one sample within a group and absent from every sample outside that group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str
|
A discrete metadata column name. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict mapping each group label to its exclusive gene count, sorted |
dict[str, int]
|
alphabetically by group label. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If column is not found in metadata. |
Summary tables
gene_table() and sample_table() collect per-gene and per-sample summaries into pandas DataFrames, ready to filter,
sort, merge with other data (such as functional annotations), or export with .to_csv() as supplementary tables.
gene_table
Summarise every gene's presence and category as a DataFrame.
The table always has these columns:
n_present: number of samples the gene is present in.frequency: fraction of samples the gene is present in.category: 'core', 'soft_core', 'dispensable', 'private', 'absent', or 'unclassified' for genes with a frequency in (0, private_min].
When column is given, it also has:
n_<group>: number of samples in each group the gene is present in.exclusive_to: the group a variable gene is present in exclusively (seeexclusive_gene_counts), or NaN if it is not exclusive to any group.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
column
|
str | None
|
An optional discrete metadata column used to add the per-group columns. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame indexed by gene ID. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If column is not a discrete metadata column. |
gt = pm.gene_table(column="clade")
gt.loc["gene_42"] # everything about one gene
gt[gt.exclusive_to == "AG3"].index # genes found only in AG3
gt[(gt.category == "dispensable") & (gt.n_Modern == 0)] # dispensable genes absent from Modern lines
gt.to_csv("gene_table.csv")
sample_table
Summarise every sample's gene content as a DataFrame.
The table has these columns:
n_genes: number of genes present in the sample.n_core,n_soft_core,n_dispensable,n_private: number of genes present in the sample from each category.n_singletons: number of genes present in this sample and no other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_metadata
|
bool
|
If True, append the sample's metadata columns. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
DataFrame indexed by sample ID. |
st = pm.sample_table(include_metadata=True)
st.sort_values("n_singletons", ascending=False).head(10) # accessions carrying the most unique genes
st.groupby("clade")["n_private"].mean() # private gene content per clade
st["n_genes"].corr(st["depth"]) # check gene counts against sequencing depth
Unclassified genes
By default private_min is 0, so every gene present in at least one sample gets a category. If you raise it
(e.g. private_min=0.01), genes rarer than that threshold are no longer private, but they aren't absent either.
gene_table() labels these genes "unclassified".
UMAP
Uniform Manifold Approximation Projection (UMAP) is a dimensionality reduction technique that is used to
visualise high-dimensional data. In the context of PAV, it can help gain insight into the relationships between samples
through similarity in PAV profiles. Generating UMAP embeddings can be done by calling the compute_umap() method. This
is not automatically called on initial construction of new PavMatrix() objects, as it can be computationally
intensive, particularly for large datasets.
compute_umap
Compute a 3D UMAP embedding of the samples and cache it on this object.
Always computes 3 components so the result can be used for both 2D and 3D plots without recomputing. The embedding is computed on the transposed PAV matrix (samples × genes). Re-calling with the same parameters returns the cached result immediately. Re-calling with different parameters recomputes and overwrites the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_neighbors
|
int
|
UMAP n_neighbors parameter. Controls local vs global structure. Defaults to 15. |
15
|
min_dist
|
float
|
UMAP min_dist parameter. Controls how tightly points are packed. Defaults to 0.1. |
0.1
|
metric
|
str
|
Distance metric passed to UMAP. Defaults to 'jaccard', which ignores shared absences and is appropriate for binary PAV data. |
'jaccard'
|
random_state
|
int | None
|
Random seed for reproducibility. Defaults to None. |
None
|
Returns:
| Type | Description |
|---|---|
PavMatrix
|
self, so calls can be chained: pm.compute_umap().plot... |
PCoA
Principal Coordinates Analysis (classical MDS) on Jaccard distance gives a linear ordination of the samples with a
known proportion of variation per axis. compute_pcoa() caches the result for the PCoA plots.
compute_pcoa
Compute a PCoA (classical MDS) of the samples on Jaccard distance and cache it.
Distances are D = 1 − J, where J is the Jaccard similarity from
compute_jaccard() (called automatically if needed). Jaccard distance is not
Euclidean, so the decomposition yields some negative eigenvalues; only axes with
positive eigenvalues are kept, and explained variance is each eigenvalue divided
by the sum of all positive eigenvalues. Re-calling with the same n_components
returns the cached result immediately.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_components
|
int | None
|
Number of leading axes to keep. If fewer positive axes exist, all of them are kept. None keeps every positive axis. Defaults to 10. |
10
|
Returns:
| Type | Description |
|---|---|
PavMatrix
|
self, so calls can be chained: pm.compute_pcoa().plot... |