Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions python/CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ In development
list of individuals (``individuals=[]``), writing a sites-only VCF with no
``FORMAT`` or sample columns. (:user:`RClaudiuM`, :issue:`3463`)

**Bugfixes**

- Apply ``node_labels`` to sequence alignments when exporting NEXUS.
(:user:`rpinho`, :pr:`3514`)

--------------------
[1.0.4] - 2026-10-30
--------------------
Expand Down
22 changes: 22 additions & 0 deletions python/tests/test_phylo_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,28 @@ def test_nexus_default(self):
)
assert expected == self.ts().as_nexus(reference_sequence=ref)

@pytest.mark.parametrize("include_trees", [False, True])
def test_nexus_labels_with_alignments(self, include_trees):
nexus = self.ts().as_nexus(
reference_sequence="ACTGACTGAC",
node_labels={0: "human", 2: "bonobo"},
include_trees=include_trees,
)
dataset = dendropy.DataSet.get(data=nexus, schema="nexus")
matrix = dataset.char_matrices[0]
assert {taxon.label: str(matrix[taxon]) for taxon in matrix} == {
"human": "ACGGACTGAT",
"n1": "ACAGACTGAC",
"bonobo": "ACAGACTGAC",
}
if include_trees:
tree = dataset.tree_lists[0][0]
assert {node.taxon.label for node in tree.leaf_node_iter()} == {
"human",
"n1",
"bonobo",
}

def test_nexus_no_trees(self):
ref = "ACTGACTGAC"
expected = textwrap.dedent(
Expand Down
14 changes: 5 additions & 9 deletions python/tskit/text_formats.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,9 @@ def write_nexus(
print("BEGIN TAXA;", file=out)
print("", f"DIMENSIONS NTAX={ts.num_samples};", sep=indent, file=out)

if node_labels is not None:
taxlabels = " ".join(
node_labels[u] if u in node_labels else f"n{u}" for u in ts.samples()
)
else:
taxlabels = " ".join(f"n{u}" for u in ts.samples())
print("", f"TAXLABELS {taxlabels};", sep=indent, file=out)
labels = {} if node_labels is None else node_labels
sample_labels = [labels.get(u, f"n{u}") for u in ts.samples()]
print("", f"TAXLABELS {' '.join(sample_labels)};", sep=indent, file=out)
print("END;", file=out)

if include_alignments is None:
Expand All @@ -165,8 +161,8 @@ def write_nexus(
missing_data_character=missing_data_character,
isolated_as_missing=isolated_as_missing,
)
for u, alignment in zip(ts.samples(), alignments):
print(2 * indent, f"n{u}", " ", alignment, sep="", file=out)
for label, alignment in zip(sample_labels, alignments):
print(f"{2 * indent}{label} {alignment}", file=out)
print("", ";", sep=indent, file=out)
print("END;", file=out)

Expand Down
Loading