Skip to content

Unstable individual table topological sort #1653

@nikbaya

Description

@nikbaya

When tsk_individual_table_topological_sort is called, it may rearrange an individual table that is already in a topologically sorted order. For example, if we have two parents and their child in a table, the parents may switch IDs (see below for issue replication). The order of the parents does not matter in terms of the validity of the table, but it would be desirable to not sort individuals if there is no need.

Replication:

def add_individual(tables, time, parents=(-1, -1)):
    # Use flags to preserve original individual ID
    ind_id = tables.individuals.add_row(parents=parents, flags=len(tables.individuals))
    for _ in parents:
        tables.nodes.add_row(
            flags=tskit.NODE_IS_SAMPLE if time == 0 else 0,
            time=time,
            population=0,
            individual=ind_id,
    )
    return ind_id

tables = tskit.TableCollection(sequence_length=100)
tables.populations.add_row()

parents = [add_individual(tables, time=1) for _ in range(2)]
add_individual(tables, time=0, parents=parents)

print(tables.individuals)
# ╔══╤═════╤════════╤═══════╤════════╗
# ║id│flags│location│parents│metadata║
# ╠══╪═════╪════════╪═══════╪════════╣
# ║0 │    0│        │ -1, -1│     b''║
# ║1 │    1│        │ -1, -1│     b''║
# ║2 │    2│        │   0, 1│     b''║
# ╚══╧═════╧════════╧═══════╧════════╝
# Note: We've added flags that correspond to the original individual IDs

tables.sort()

print(tables.individuals)
# ╔══╤═════╤════════╤═══════╤════════╗
# ║id│flags│location│parents│metadata║
# ╠══╪═════╪════════╪═══════╪════════╣
# ║0 │    1│        │ -1, -1│     b''║
# ║1 │    0│        │ -1, -1│     b''║
# ║2 │    2│        │   1, 0│     b''║
# ╚══╧═════╧════════╧═══════╧════════╝
# Note: The flags correspond to the original individual IDs

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions