Python API
CRAIC is a library as well as a workbench. Everything the GUI does is available from Python, which is the supported way to script it or to build on it.
from craic import io, progressive, evaluate
from craic.ambiguity import reliability
from craic.domain import Alphabet
records = io.read_records("seqs.fasta")
aln = progressive.align(records, Alphabet.PROTEIN)
report = reliability.analyse(aln, do_perturbation=True)
print(report.col_combined) # per-column reliability, 0..1
truth = io.load_alignment("truth.fasta", alphabet=Alphabet.PROTEIN)
acc = evaluate.compare_to_reference(aln, truth)
print(acc.sp, acc.tc, acc.reliability_auc(report.col_combined))
Nothing below imports Qt, so all of it works headless.
The canonical model
craic.domain
Core domain model.
A single canonical representation is stored at the sequences' native level (nucleotide rows for DNA/RNA, amino-acid rows for protein). Codon and amino-acid views are derived projections of a coding nucleotide alignment, so the GUI can switch levels live without ever holding three copies of the data.
Alphabet
Level
Alignment
dataclass
Source code in craic/domain.py
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 | |
is_codon_aware
True if no codon contains a partial gap (frame is intact).
Source code in craic/domain.py
frame_break_columns
Codon columns where at least one row has a partial-gap codon.
Source code in craic/domain.py
internal_stops
(row, codon) for every stop codon that is not the last codon of
its sequence.
A stop in the middle of a coding sequence usually means one of three things, and the user needs to be told which is being assumed: the wrong genetic code (mitochondrial and Mollicute genes read TGA as tryptophan, the standard code reads it as a stop), the wrong reading frame, or a pseudogene. One check catches all three, which is why it is worth making even though CRAIC cannot tell them apart.
Trailing gaps are ignored, so a short sequence padded out to the alignment width is not reported as stopping early.
Source code in craic/domain.py
display
Project to a renderable matrix of string cells.
Returns cells[row][col] plus, for each display column, the starting
nucleotide index so the GUI can map selections back to nt coordinates.
Source code in craic/domain.py
amino_acid_alignment
A protein Alignment of the translated rows, for amino-acid-level tools.
For protein data this is the alignment itself; for a coding nucleotide alignment each amino-acid column corresponds to one codon column.
Source code in craic/domain.py
codon_col
CodingSpec
dataclass
How a nucleotide alignment maps to codons.
Source code in craic/domain.py
genetic_codes
Every NCBI translation table Biopython knows, as (id, name).
The list is not hard-coded here because it is not ours to curate: NCBI adds tables, and anything shipped as a fixed list goes stale silently. Table 1 is forced to the front so the standard code is the first thing offered.
Source code in craic/domain.py
code_name
The NCBI name for a table id, or a bare label if it is unknown.
translate_codon
Translate one (possibly gapped) codon to a single residue.
'---' -> '-' (clean gap), any partial gap -> 'X' (frameshift / indel ambiguity, surfaced rather than hidden), unknown -> 'X', stop -> '*'.
Source code in craic/domain.py
residue_index
Per column, the index of its residue in the ungapped sequence, or -1.
column_index
membership
(sequence, residue) -> column for every non-gap cell.
by="index" keys on the sequence's position, by="id" on its
identifier. Both are needed: scores computed per row want the position,
while anything comparing two alignments has to match on the name.
Source code in craic/domain.py
normalise_gaps
ungap
match_ids
Map each reference id onto the corresponding id in other.
Several aligners (MAFFT among them) truncate FASTA identifiers at the first whitespace. Matching on the raw string then misses every sequence, and because a miss increments the pair denominator without incrementing the numerator, every column silently scores zero agreement — a wrong result that looks exactly like a real one. So: try the ids as given, then try them truncated, and if neither matches, say so.
Source code in craic/domain.py
Reading and writing
craic.io
Reading and writing alignments / unaligned record sets.
read_records
load_alignment
load_alignment(path: str, fmt: Optional[str] = None, alphabet: Optional[Alphabet] = None, coding: Optional[CodingSpec] = None) -> Alignment
Source code in craic/io.py
write_fasta
Source code in craic/io.py
The acceleration layer
The single primitive everything else is built on. The Rust core and the NumPy mirror satisfy the same contract and are cross-validated to ~1e-9; callers cannot tell which answered.
craic.accel
Acceleration layer: one pair-HMM posterior primitive, Rust or NumPy.
Design notes
- The compiled
craic_accelextension (src/lib.rs) is used when present. - A NumPy fallback mirrors it line-for-line so the workbench runs anywhere and so the two implementations can be cross-validated in the test-suite (Liskov: callers cannot tell which one answered).
- Emission models are built here, not in Rust, so the core stays biology-agnostic. DNA/RNA use an identity-driven model; protein uses BLOSUM45 converted to a proper joint probability via Robinson background frequencies.
backend
pair_posteriors
pair_posteriors(a_idx: Sequence[int], b_idx: Sequence[int], k: int, joint_flat: Sequence[float], bg: Sequence[float], delta: float = 0.02, epsilon: float = 0.5) -> np.ndarray
Dispatch to Rust if available, else the NumPy mirror. Returns (m, n).
delta and epsilon are validated here, in the one place both backends
go through. Out-of-range values are not a curiosity: delta >= 0.5 makes
log(1 - 2*delta) undefined, which the Rust core turns into NaN that
propagates silently through every posterior and out into every reliability
score, while the NumPy path raises. A silently wrong number is worse than a
loud failure, so both now fail loudly.
Source code in craic/accel.py
The built-in aligner
craic.progressive
A small, self-contained progressive aligner (the always-available engine).
ProbCons-style, built entirely on CRAIC's pair-HMM posteriors:
- estimate the emission divergence and gap parameters from the data (no hard-coded assumption that sequences are ~90% identical),
- compute all pairwise posterior "match" matrices,
- apply the ProbCons consistency transformation (re-estimate each pairwise posterior using every third sequence), and
- align progressively by pure maximum-expected-accuracy decoding of the transformed posteriors -- gap placement falls out of the model, so there are no ad-hoc gap constants.
It is still deliberately modest (no sequence weighting, no iterative refinement) and is meant to always be available, not to beat MAFFT; but it is genuine posterior decoding rather than a heuristic. The pair-HMM inner loop runs in the Rust core when built, with the NumPy fallback otherwise.
align
align(records: Sequence[Record], alphabet: Alphabet, model: Optional[EmissionModel] = None, delta: Optional[float] = None, epsilon: Optional[float] = None, effort: str = 'med', consistency_iters: Optional[int] = None, refine_iters: Optional[int] = None, guide: Optional[str] = None, estimate: bool = True, consistency_mem_gb: float = 1.0, progress=None, cancelled=None, guide_seed: Optional[int] = None, sparse: Optional[bool] = None, matrix: Optional[str] = None) -> Alignment
Progressive multiple alignment by posterior decoding, tiered by memory.
Small/medium families get the full ProbCons consistency transformation
(accurate). Families whose dense pairwise posteriors would exceed
consistency_mem_gb fall back automatically to streaming plain-MEA: each
pairwise posterior is computed on demand and discarded, so peak memory is a
single L x L matrix and the aligner scales to large inputs (less accurate; for
large jobs an external engine is still preferable). progress(done, total)
is called before each merge and cancelled() is polled throughout.
matrix names the protein substitution matrix (default
accel.PROTEIN_MATRIX); it is ignored for nucleotides and when model
is given.
Source code in craic/progressive.py
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 | |
estimate_params
Emission model and gap parameters read off a committed alignment.
Returns (model, delta, epsilon). This is the single place that turns an
alignment into pair-HMM parameters, so that a column is always scored
under the model the data implies rather than under a fixed default. The
reliability scores and the aligner's own pilot pass both go through it.
Note that for protein data emission_model is currently independent of
the estimated identity — one matrix, BLOSUM45, is used at every divergence —
so theta affects nucleotide models only. The gap parameters are
estimated for both alphabets. The clamp on theta below means it carries
no information under 55% identity in any case, which is where most protein
reference data sits; keying the protein matrix to divergence would have to
read the raw identity, not this.
Source code in craic/progressive.py
consistency_transform
consistency_transform(P, n, iters=2, cancelled=None, sparse: Optional[bool] = None, threshold: float = SPARSE_THRESHOLD)
ProbCons consistency transformation: re-estimate each pairwise posterior P(x,y) using every third sequence z, P'(x,y) = (1/n) sum_z P(x,z) P(z,y).
This is the most expensive thing CRAIC does — O(n^3) matrix products of
L x L matrices per iteration — and it is what sets the largest family the
workbench can handle with consistency turned on. Posteriors are overwhelmingly
near-zero, so when SciPy is available the matrices are thresholded at
threshold and the products run sparse, which is how ProbCons itself does
it. sparse=False forces the dense implementation; the two are compared
directly in the test-suite rather than assumed equivalent.
Dropping entries below threshold does change the numbers slightly. It is
a deliberate approximation, not a refactor, which is why the dense path is
kept and why the tests check that the resulting alignments agree.
Source code in craic/progressive.py
sparse_available
Whether SciPy is present, which is what the sparse transform needs.
Reliability
craic.ambiguity.reliability
Per-column / per-residue reliability + live masking.
Two complementary, well-grounded signals:
- consistency (TCS / heads-style): for each alignment column, average the pair-HMM posterior P(res_i ~ res_j) over the residue pairs that column asserts are homologous. High = the unaligned-sequence evidence supports the column. Uses the CRAIC core directly.
- perturbation (guide-tree / gap-regime sensitivity, in the spirit of
GUIDANCE but not equivalent to it): re-align the same sequences under an
ensemble of perturbed guide trees across a few gap regimes, and measure what
fraction of each residue's asserted homologies survive. See
:func:
perturbationfor what the ensemble does and does not sample.
Both live in [0, 1]; combined averages them. A threshold turns either into a
column mask that the viewer previews live before you commit.
Two properties this module is careful about, because getting either wrong produces a plausible-looking number that is wrong:
- Both scores are computed under parameters estimated from the alignment
being scored (:func:
craic.progressive.estimate_params), not under a fixed default. Scoring a 40%-identity family under a 90%-identity model makes every column look unreliable and biases masking toward destroying exactly the divergent data that masking decisions are about. - A failed ensemble is an error, not a score of zero. If no replicate
completes, :func:
perturbationraises :class:EnsembleFailurerather than returning all-nan, which downstream would be indistinguishable from "every column is maximally unreliable" and would mask the whole alignment away.
EnsembleFailure
Bases: RuntimeError
Every replicate in the perturbation ensemble failed.
Raised rather than returning an all-nan score, which a threshold would read as "mask everything".
analyse
analyse(aln: Alignment, do_perturbation: bool = True, model: Optional[EmissionModel] = None, n_replicates: int = 16) -> Reliability
Source code in craic/ambiguity/reliability.py
consistency
consistency(aln: Alignment, model: Optional[EmissionModel] = None, max_pairs: int = 300, seed: int = 0, delta: Optional[float] = None, epsilon: Optional[float] = None) -> Tuple[np.ndarray, np.ndarray]
Return (col_score[length], cell_score[n, length] with nan at gaps).
model, delta and epsilon default to the values estimated from
aln itself rather than to library defaults; pass them explicitly only
to score under a model of your own choosing.
Source code in craic/ambiguity/reliability.py
perturbation
perturbation(aln: Alignment, alphabet: Optional[Alphabet] = None, n_replicates: int = 16, seed: int = 0, deltas: Tuple[float, ...] = _PERTURB_DELTAS, stats: Optional[Dict[str, int]] = None) -> Tuple[np.ndarray, np.ndarray]
Return (col_score[length], cell_score[n, length] with nan at gaps).
Re-align the same sequences under n_replicates perturbed guide trees
(cycling through the gap regimes in deltas) and, for each residue, score
the fraction of its reference-asserted homologies that survive across the
ensemble. A residue with no asserted partners (a singleton column) has no
residue-pair evidence and is left nan rather than scored a free 1.0.
What this is. A sensitivity analysis of one engine: how stable are the homologies this alignment asserts, when the guide tree is perturbed and the gap model is varied? Low scores mark residues whose placement is an artefact of a particular tree or gap cost.
What this is not. It is not GUIDANCE. GUIDANCE bootstraps alignment columns to build perturbed guide trees and re-aligns with the same aligner that produced the reference, over ~100 replicates. Here the replicates come from CRAIC's built-in engine under plain posterior decoding (no consistency pass), which is a weaker aligner than the one that may have produced the reference and a different aligner if the reference came from MAFFT or PRANK. In that case the score conflates genuine alignment uncertainty with systematic between-method difference. Read it as a stability probe, and read the disagreement map for between-method evidence.
Raises :class:EnsembleFailure if no replicate completes. If some fail, a
warning is issued and the surviving replicates are used; analyse records
the count on the report.
Source code in craic/ambiguity/reliability.py
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 252 253 254 | |
keep_mask
Columns to keep: scores >= threshold.
This is the one definition of a reliability mask in CRAIC. It previously existed twice with opposite handling of unscoreable (nan) columns — the GUI kept them, the benchmark dropped them — so the mask a user exported was not the mask the benchmark evaluated.
A nan column is one with no residue-pair evidence at all (a singleton
column, or one whose ensemble evidence is missing). unscored="drop" is
the default and the conservative choice for downstream phylogenetics: a
column that could not be assessed is not evidence. unscored="keep"
retains them.
Raises ValueError if every column is unscoreable, which means the
reliability analysis failed rather than that the alignment is worthless.
Source code in craic/ambiguity/reliability.py
Accuracy against a known answer
craic.evaluate
Accuracy of an alignment against a known-true reference.
Sum-of-pairs and total-column scores, per-column correctness, and the ROC AUC of
a score predicting that correctness. These used to live in benchmarks/ where
only the benchmark harness could reach them; they are here so that the GUI's
truth mode, the command line and the benchmark all compute accuracy the same
way. A number shown to a student and a number printed in a paper being produced
by two different implementations is exactly the drift worth designing out.
A "reference" here is a trusted alignment of the same sequences — a structural reference such as BAliBASE, or the known-true alignment of a simulated dataset.
Accuracy
dataclass
How an inferred alignment compares with a trusted reference.
Source code in craic/evaluate.py
correct_mask
property
Columns that are entirely correct (nan columns count as not-correct, since they assert nothing to be correct about).
reliability_auc
How well a per-column score predicts which columns are actually right.
Source code in craic/evaluate.py
ColumnTruth
dataclass
What the reference says about one inferred column.
agree are the residues the reference groups together and the alignment
got right; intruders are residues placed here that belong elsewhere; and
missing are residues that belong here but were placed elsewhere. A
correct column has neither of the latter two.
Source code in craic/evaluate.py
describe
The same thing in words, for the command line and for tooltips.
Source code in craic/evaluate.py
Placement
dataclass
One residue, where it sits, and where the reference says it belongs.
Source code in craic/evaluate.py
target_col
class-attribute
instance-attribute
The inferred column holding most of its true partners — where it would
have to move to join them. None if it has no true partners to join.
compare_to_reference
compare_to_reference(aln: Alignment, reference: Alignment, core: Optional[ndarray] = None) -> Accuracy
Score aln against a trusted reference alignment of the same sequences.
See :func:matched_rows on how the two are paired up.
Source code in craic/evaluate.py
matched_rows
The reference's rows, reordered onto aln's own sequence order.
The two are matched on sequence id (tolerating the whitespace truncation some aligners apply), so that a reference whose sequences are listed differently — which is usual — is still usable. If the two do not describe the same sequences, or describe them with different residues, that is an error rather than a very low score: a reference for the wrong data would otherwise read as an alignment that is entirely wrong.
Source code in craic/evaluate.py
sp_score
sp_score(true_rows: Sequence[str], inf_rows: Sequence[str], core: Optional[ndarray] = None) -> Tuple[float, float]
(recall, precision) of homologous residue pairs. Recall is the SP score.
core is a boolean mask over the reference columns. Published BAliBASE
SP figures are restricted to the reference's core blocks, so a score
computed over all columns is not comparable with them — pass the core mask
when one is available, and label the result accordingly when it is not.
Source code in craic/evaluate.py
tc_score
tc_score(true_rows: Sequence[str], inf_rows: Sequence[str], core: Optional[ndarray] = None) -> float
Total-column score: fraction of reference columns reproduced exactly.
See :func:sp_score on core.
Source code in craic/evaluate.py
col_correct_fraction
Per inferred column, the fraction of its asserted pairs that are true.
nan for a column that asserts no pair at all (a singleton column): it
makes no claim, so it can be neither right nor wrong. Those columns are not
counted as errors anywhere downstream.
Source code in craic/evaluate.py
cell_correct_fraction
cell_correct_fraction(inf_rows: Sequence[str], true_rows: Sequence[str], grid: Optional[ndarray] = None) -> np.ndarray
Per residue, the fraction of its partners in that column that are homologous.
The per-cell counterpart of :func:col_correct_fraction, and exactly
consistent with it: a column's score is the mean of its cells' scores. One
misplaced residue in an otherwise sound
column scores 0 while its neighbours stay near 1, which is what makes the
culprit visible rather than merely the damage.
nan for a gap, and for a residue with no partners at all — a residue
alone in its column asserts nothing, so it can be neither right nor wrong.
Source code in craic/evaluate.py
true_column_grid
(n_seqs, n_cols) of true-alignment columns, -1 where a cell is a gap.
Entry [s, c] is the column the reference puts the residue that the
inferred alignment placed at row s, column c. Two residues are
homologous exactly when their entries are equal, which is the whole of the
comparison — every function below is a different way of reading this grid.
Source code in craic/evaluate.py
explain_column
explain_column(inf_rows: Sequence[str], true_rows: Sequence[str], col: int, ids: Optional[Sequence[str]] = None, grid: Optional[ndarray] = None) -> ColumnTruth
Account for one inferred column against the reference.
Pass grid from :func:true_column_grid to explain many columns without
rebuilding the lookup each time.
Source code in craic/evaluate.py
auc
ROC AUC: probability a random positive outranks a random negative.
Ties count as half, via midranks, so a score that cannot discriminate at all returns 0.5 rather than an order-dependent number.
Source code in craic/evaluate.py
Simulation
craic.simulate
Ground-truth sequence simulator.
Used by the benchmark harness and by the workbench itself: a dataset whose true alignment is known exactly is the only way to show, rather than assert, what a reliability score is doing — which makes it as much a teaching device as a benchmarking one.
Evolves DNA down a random binary tree with JC69 substitutions and insertions /
deletions, tracking the TRUE alignment (which residues are homologous) and the
TRUE topology. Divergence is controlled by the branch-length range and indel
load by indel_rate. Because the homology of every residue is known exactly,
this is the clean way to evaluate a per-column reliability score.
A caveat that belongs in any write-up using these numbers. The default
generative model here — JC69, uniform base frequencies, one rate for every site,
geometric indel lengths — is close to the model CRAIC's pair-HMM assumes, so
CRAIC's inference model is nearly well-specified on this data while MAFFT and
MUSCLE carry empirical matrices tuned for real sequences. That is a structural
advantage to CRAIC, not a bug, but it must be disclosed. rate_alpha turns on
gamma-distributed among-site rate variation and indel_zipf gives indel
lengths a heavy tail, both of which break the correspondence; run the sweep with
and without them and report both.
simulate
simulate(taxa: int = 8, root_len: int = 200, seed: int = 0, indel_rate: float = 2.0, bmin: float = 0.04, bmax: float = 0.28, rate_alpha: float = 0.0, indel_zipf: float = 0.0) -> dict
Return dict(names, seqs=[(name, ungapped)], true_rows=[gapped], tree).
rate_alpha > 0 draws each site's relative substitution rate from a
gamma(alpha, 1/alpha), i.e. among-site rate variation with mean 1; smaller
alpha means more heterogeneity. indel_zipf > 1 replaces the geometric
indel-length distribution with a Zipf one. Both default to off, which
reproduces earlier results exactly; both should be exercised before claiming
a result generalises — see the module docstring.
Source code in craic/simulate.py
Model-free trimming
Faithful reimplementations of the published column-selection rules, offered as complementary signals to the model-based reliability score.
craic.ambiguity.trimming
Model-free column trimming and sequence-outlier detection.
Faithful reimplementations of the algorithms behind widely-used tools, offered as complements to CRAIC's model-based posterior reliability (which is derived from the pair-HMM). These use only gaps and residue conservation -- no probabilistic model -- so they are cheap and always available:
gap_score/gap_threshold_mask-- MSA_trimmer-style gappiness.similarity_score-- per-column conservation.gappyout_mask/trimal_strict_mask-- trimAl-style automatic trimming.gblocks_mask-- Gblocks-style conserved blocks.sequence_scores/outlier_sequences-- EvalMSA / OD-seq-style outliers.
These are reimplementations of the published algorithms, not the original code, and are not guaranteed identical to the reference tools; for authoritative filtering, run the originals (trimAl, Gblocks, EvalMSA).
gap_score
Fraction of non-gap residues per column (trimAl gap score). 1 = no gaps.
similarity_score
Mean pairwise residue similarity per column in [0, 1] (trimAl-style). Gaps excluded; a column with 0/1 residues scores 0/1.
Source code in craic/ambiguity/trimming.py
Sessions
craic.session
The working session as a document.
A curation session is more than its alignment. It is also the reference alignment truth mode is scoring against, the column annotations, the named sequence groups, the provenance log of how the alignment was arrived at, and the view state that makes any of it legible. Exporting FASTA or NEXUS keeps the residues and silently discards all of that — fine as an export, useless as a way to put work down and pick it up again.
So a session is its own small document: readable JSON, no dependencies, and versioned so that an old file can be recognised rather than misread. The alignment can still be saved to any standard format at any time; the two are separate acts, because they answer different questions ("give this to another program" versus "let me carry on tomorrow").
The module is deliberately free of Qt, so that the command line, the tests and the crash-recovery autosave can all use it without a display.
Session
dataclass
Everything needed to resume a curation session.
Source code in craic/session.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 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 | |
save
Write the session, atomically.
Via a temporary file and a rename, because the autosave writes this repeatedly and a crash during the write is exactly the moment the file matters most — a half-written recovery file is worse than none.
Source code in craic/session.py
describe
One-line summary, for a recovery prompt or the command line.
Source code in craic/session.py
SessionError
is_session_file
Whether path looks like a session document, cheaply.