Tree builder

damicore_tree_builder builds a deterministic Neighbor Joining tree from a distance matrix and writes it in Newick form.

Functions

damicore_tree_builder.build_tree(matrix_path: str | Path, labels_path: str | Path, output_dir: str | Path, *, config: TreeBuildConfig | None = None) → TreeBuildResult

Build and persist a deterministic Neighbor Joining tree.

Takes distance.npy and labels.json as the distance stage writes them, and writes tree.json and tree.nwk into output_dir; both must be absent, since a tree is never overwritten. output_dir is created before that check, so even a rejected call leaves the directory behind. Joining runs against a private tree-work.npy memory map inside output_dir, so the input matrix is left untouched and peak RAM does not grow with the matrix; once that workspace exists it is removed on every exit path, but a failure while creating it, a full disk being the realistic one, can leave it behind. The two artifacts are re-read and validated after writing, and deleted again if that fails, so a rejected tree never survives to block the next run. Ties in the Q criterion are broken by label order, which makes the output a function of the matrix and its labels alone. Negative branch lengths are reported in the result, never clamped. tree.json is the input damicore_clusterizer.cluster_tree() expects.

Raises:

TreeBuilderError – tree.json or tree.nwk already exists (output_directory_conflict_error); the labels artifact or the persisted tree is invalid, or the edges form a cycle (artifact_validation_error); the matrix is unreadable, mis-shaped, non-finite, or not symmetric with a zero diagonal (distance_matrix_validation_error).

damicore_tree_builder.neighbor_joining(matrix: NDArray[floating[Any]], labels: Sequence[str]) → Tree

Build a deterministic Neighbor Joining tree, copying the input matrix.

Models

class damicore_tree_builder.Tree(*, schema_version: Literal[1] = 1, root_id: str, nodes: tuple[TreeNode, ...], edges: tuple[TreeEdge, ...])
schema_version: Literal[1]
root_id: str
nodes: tuple[TreeNode, ...]
edges: tuple[TreeEdge, ...]
class damicore_tree_builder.TreeBuildConfig(*, q_block_size: Annotated[int, Gt(gt=0)] = 512)
q_block_size: int
class damicore_tree_builder.TreeBuildResult(*, tree_path: Path, newick_path: Path, leaf_count: Annotated[int, Ge(ge=0)], negative_branch_count: Annotated[int, Ge(ge=0)], timing: Annotated[float, Ge(ge=0)])
tree_path: Path
newick_path: Path
leaf_count: int
negative_branch_count: int
timing: float
class damicore_tree_builder.TreeEdge(*, source: str, target: str, length: Annotated[float, AllowInfNan(allow_inf_nan=False)])
source: str
target: str
length: float
class damicore_tree_builder.TreeNode(*, id: str, kind: Literal['leaf', 'internal'], label: str | None = None)
id: str
kind: Literal['leaf', 'internal']
label: str | None

Errors

class damicore_tree_builder.TreeBuilderError(message: str, *, code: str = 'tree_builder_error', **context: object)