Skip to content

CrossIndex

CrossIndex manages sequences divided into named groups and computes cross-group pairwise comparisons. It is compatible with DotPlotter.

Workflow

Loading sequences and computing matches are separate explicit steps:

  1. Load sequences with add_sequence() or load_fasta().
  2. Call compute_matches() to compute k-mer matches between groups.
  3. Call reorder_contigs() or reorder_for_colinearity() (requires step 2).
  4. Plot with DotPlotter using query_group / target_group to specify groups.
  5. Optionally persist the layout with write_fasta() — contigs are written in the reordered order with reverse-oriented contigs reverse-complemented.

Progress is logged at INFO level for each loading and computation step. Warnings are emitted when a sequence name already exists in the same or another group.

Alignment scope by number of groups

  • 2 groupscompute_matches() compares the two groups.
  • 3+ groupscompute_matches() computes all non-self ordered pairs by default. Use the query_group / target_group arguments to restrict to a specific pair.

Quick start

from dot_explorer.paf_io import CrossIndex
from dot_explorer.dotplot import DotPlotter

cross = CrossIndex(k=15)
cross.load_fasta("assembly_a.fasta", group="a")
cross.load_fasta("assembly_b.fasta", group="b")

# Explicitly compute k-mer matches (required before reorder_contigs)
cross.compute_matches()
print("Computed pairs:", cross.computed_group_pairs)

# Sort contigs for maximum collinearity.  Each query contig is assigned to its
# best-matching target chromosome (argmax of the squared match weights) and
# ordered by its gravity centre there; reverse-oriented contigs are detected.
q_sorted, t_sorted = cross.reorder_contigs()
reversed_a = cross.reversed_contigs("a")  # query contigs to render flipped

# Plot directly from CrossIndex — sequence names resolved via group params.
# Reverse-oriented contigs are rendered flipped so they read along the main
# diagonal.  Omit reverse_contigs to auto-pull the detected set for query_group.
plotter = DotPlotter(cross)
plotter.plot(
    query_group="a",   # sequences from group 'a' as rows
    target_group="b",  # sequences from group 'b' as columns
    output_path="cross_plot.png",
    reverse_contigs=reversed_a,
)

Writing reordered / reoriented FASTA

write_fasta() persists a group's contigs in the current contig_order, reverse-complementing any contig flagged by reversed_contigs(). Orientation is always expressed relative to the target group, which stays the forward reference — so reorder the group you want to change as the query.

cross = CrossIndex(k=15)
cross.load_fasta("assembly_a.fasta", group="a")
cross.load_fasta("assembly_b.fasta", group="b")
cross.compute_matches(query_group="b", target_group="a")

# Reorder + reorient B against a FIXED A (A is not moved or flipped):
cross.reorder_for_colinearity("b", "a", reorder_target=False)

cross.write_fasta("assembly_a.sorted.fasta", "a")  # unchanged reference
cross.write_fasta("assembly_b.sorted.fasta", "b")  # reordered + reoriented

Pass reorder_target=True (the default) to let both assemblies be reordered; A remains the forward reference and B's contigs are the ones reverse-complemented. reorder_by_length(group) sets a length-sorted order for a group before writing. See the Writing Reordered FASTA tutorial for full worked examples.

Custom group names

cross = CrossIndex(k=15)
cross.load_fasta("genome_a.fasta", group="Group_A")
cross.load_fasta("genome_b.fasta", group="Group_B")

cross.compute_matches()  # auto-detects the two groups
q_sorted, t_sorted = cross.reorder_contigs()

# Plot with explicit group names
plotter = DotPlotter(cross)
plotter.plot(
    query_group="Group_A",
    target_group="Group_B",
    output_path="cross_plot.png",
)

# Or rename groups and use explicitly
cross.rename_group("Group_A", "query")
cross.rename_group("Group_B", "target")
cross.compute_matches(query_group="query", target_group="target")
q_sorted, t_sorted = cross.reorder_contigs(query_group="query", target_group="target")

Class

CrossIndex

Multi-group sequence index for cross-group pairwise comparisons.

Sequences are organised into named groups (e.g. 'assembly_a', 'assembly_b'). Each sequence is stored in a shared :class:~dot_explorer.SequenceIndex under a group:name internal key, which keeps names unique even when the same sequence identifier appears in multiple groups.

Workflow

Loading sequences and computing matches are separate, explicit steps:

  1. Load sequences via :meth:add_sequence or :meth:load_fasta. Each sequence addition is logged at DEBUG level. A WARNING is emitted if the name already exists in the same group (FM-index overwritten) or in a different group.
  2. Call :meth:compute_matches to find k-mer matches between groups. This must be done before calling :meth:reorder_contigs or :meth:reorder_for_colinearity.
  3. Inspect :attr:computed_group_pairs to verify which pairs have been computed.

Alignment scope by number of groups

  • 2 groups — :meth:compute_matches compares the two groups by default.
  • 3+ groups — all non-self ordered pairs by default. Use the query_group / target_group arguments to restrict to a specific pair.

DotPlotter compatibility

CrossIndex exposes :meth:get_sequence_length, :meth:compare_sequences_stranded, and :meth:sequence_names so that it can be passed directly to :class:~dot_explorer.dotplot.DotPlotter::

cross = CrossIndex(k=15)
cross.load_fasta("assembly_a.fasta", group="a")
cross.load_fasta("assembly_b.fasta", group="b")
cross.compute_matches()

from dot_explorer.dotplot import DotPlotter
plotter = DotPlotter(cross)
plotter.plot(
    query_names=cross.sequence_names(group="a"),
    target_names=cross.sequence_names(group="b"),
    output_path="cross_plot.png",
)

Parameters:

Name Type Description Default
k int

K-mer length to use for indexing and comparison.

required

Examples:

>>> from dot_explorer.paf_io import CrossIndex
>>> cross = CrossIndex(k=10)
>>> cross.load_fasta("genome_a.fasta", group="a")
>>> cross.load_fasta("genome_b.fasta", group="b")
>>> cross.compute_matches()
>>> paf_lines = cross.get_paf()
Source code in dot_explorer/paf_io.py
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
class CrossIndex:
    """Multi-group sequence index for cross-group pairwise comparisons.

    Sequences are organised into named groups (e.g. ``'assembly_a'``,
    ``'assembly_b'``).  Each sequence is stored in a shared
    :class:`~dot_explorer.SequenceIndex` under a ``group:name`` internal key,
    which keeps names unique even when the same sequence identifier appears
    in multiple groups.

    **Workflow**

    Loading sequences and computing matches are separate, explicit steps:

    1. Load sequences via :meth:`add_sequence` or :meth:`load_fasta`.
       Each sequence addition is logged at ``DEBUG`` level.  A ``WARNING``
       is emitted if the name already exists in the same group (FM-index
       overwritten) or in a different group.
    2. Call :meth:`compute_matches` to find k-mer matches between groups.
       This must be done before calling :meth:`reorder_contigs` or
       :meth:`reorder_for_colinearity`.
    3. Inspect :attr:`computed_group_pairs` to verify which pairs have been
       computed.

    **Alignment scope by number of groups**

    * **2 groups** — :meth:`compute_matches` compares the two groups by
      default.
    * **3+ groups** — all non-self ordered pairs by default.  Use the
      *query_group* / *target_group* arguments to restrict to a specific pair.

    **DotPlotter compatibility**

    ``CrossIndex`` exposes :meth:`get_sequence_length`,
    :meth:`compare_sequences_stranded`, and :meth:`sequence_names` so that it
    can be passed directly to :class:`~dot_explorer.dotplot.DotPlotter`::

        cross = CrossIndex(k=15)
        cross.load_fasta("assembly_a.fasta", group="a")
        cross.load_fasta("assembly_b.fasta", group="b")
        cross.compute_matches()

        from dot_explorer.dotplot import DotPlotter
        plotter = DotPlotter(cross)
        plotter.plot(
            query_names=cross.sequence_names(group="a"),
            target_names=cross.sequence_names(group="b"),
            output_path="cross_plot.png",
        )

    Parameters
    ----------
    k : int
        K-mer length to use for indexing and comparison.

    Examples
    --------
    >>> from dot_explorer.paf_io import CrossIndex
    >>> cross = CrossIndex(k=10)
    >>> cross.load_fasta("genome_a.fasta", group="a")
    >>> cross.load_fasta("genome_b.fasta", group="b")
    >>> cross.compute_matches()
    >>> paf_lines = cross.get_paf()
    """

    def __init__(self, k: int) -> None:
        """Initialise an empty CrossIndex.

        Parameters
        ----------
        k : int
            K-mer length to use when building the sequence index.
        """
        self._k: int = k
        self._index: SequenceIndex = SequenceIndex(k=k)
        # group_label -> ordered list of original (un-prefixed) sequence names
        self._groups: dict[str, list[str]] = {}
        # group_label -> internal prefix used in _index (supports rename_group)
        self._internal_group: dict[str, str] = {}
        # (query_group, target_group) -> list[PafRecord] from compute_matches
        self._records_by_pair: dict[tuple[str, str], list[PafRecord]] = {}
        # Merge flag used when each pair's records were computed, so cached
        # records are only served for calls requesting the same form.
        self._records_merge: dict[tuple[str, str], bool] = {}
        # group_label -> set of reverse-oriented contigs (from the last
        # collinearity reorder that used that group as the query axis)
        self._reversed: dict[str, set[str]] = {}

    @property
    def _paf_records(self) -> list[PafRecord]:
        """All cached PAF records across every computed group pair (flat list).

        Note: this property rebuilds the list on every access.  Avoid calling
        it repeatedly in a tight loop; assign to a local variable instead.
        """
        result: list[PafRecord] = []
        for recs in self._records_by_pair.values():
            result.extend(recs)
        return result

    @property
    def computed_group_pairs(self) -> list[tuple[str, str]]:
        """Group pairs for which k-mer matches have been computed.

        Returns
        -------
        list[tuple[str, str]]
            List of ``(query_group, target_group)`` pairs that have had
            :meth:`compute_matches` run on them.  Use this to confirm that
            the required pair is ready before calling
            :meth:`reorder_contigs`.
        """
        return list(self._records_by_pair.keys())

    def get_records_for_pair(
        self, query_group: str, target_group: str
    ) -> list['PafRecord']:
        """Return the cached :class:`PafRecord` list for a computed group pair.

        Parameters
        ----------
        query_group : str
            Query group label.
        target_group : str
            Target group label.

        Returns
        -------
        list[PafRecord]
            Cached PAF records for the pair.  Returns an empty list if
            :meth:`compute_matches` has not been called for this pair.
        """
        return list(self._records_by_pair.get((query_group, target_group), []))

    def make_internal_name(self, group: str, name: str) -> str:
        """Construct the internal (``'group:name'``) identifier for a sequence.

        This is the public counterpart of the internal :meth:`_make_internal`
        helper and is suitable for use by external code such as
        :class:`~dot_explorer.dotplot.DotPlotter`.

        Parameters
        ----------
        group : str
            Group label.
        name : str
            Un-prefixed sequence name.

        Returns
        -------
        str
            Internal identifier in ``'group:name'`` form, with any
            ``rename_group`` remapping applied.
        """
        return self._make_internal(group, name)

    # ------------------------------------------------------------------
    # Internal helpers
    # ------------------------------------------------------------------

    def _make_internal(self, group: str, name: str) -> str:
        """Format an internal (prefixed) name for use in SequenceIndex.

        Uses :attr:`_internal_group` to resolve the actual internal prefix,
        which may differ from *group* after a :meth:`rename_group` call.
        The ``get(group, group)`` fallback is safe because every call to
        :meth:`add_sequence` or :meth:`load_fasta` immediately registers the
        new group in ``_internal_group`` before any internal name is formed.
        """
        prefix = self._internal_group.get(group, group)
        return f'{prefix}:{name}'

    @staticmethod
    def _split_internal(internal: str) -> tuple[str, str]:
        """Split ``'group:name'`` into ``(group, name)``."""
        group, _, name = internal.partition(':')
        return group, name

    # ------------------------------------------------------------------
    # Adding sequences
    # ------------------------------------------------------------------

    def _check_name_collision(self, name: str, group: str) -> None:
        """Emit warnings if *name* already exists in the same or another group."""
        if name in self._groups.get(group, []):
            _log.warning(
                'CrossIndex: sequence %r already exists in group %r; '
                'its FM-index will be overwritten',
                name,
                group,
            )
        else:
            for other_g, other_names in self._groups.items():
                if other_g != group and name in other_names:
                    _log.warning(
                        'CrossIndex: sequence %r already exists in group %r; '
                        'adding the same name to group %r may cause confusion',
                        name,
                        other_g,
                        group,
                    )

    def add_sequence(self, name: str, seq: str, group: str = 'a') -> None:
        """Add a single sequence to the specified group.

        Logs a ``DEBUG``-level message for every sequence loaded, and a
        ``WARNING`` if *name* already exists in the same group (its FM-index
        will be overwritten) or in a different group (potential confusion).

        Parameters
        ----------
        name : str
            Sequence identifier (must be unique within the group).
        seq : str
            DNA sequence string.
        group : str, optional
            Group label.  Any non-empty string is accepted; ``':'`` is
            forbidden because it is used as an internal separator.
            Default is ``'a'``.

        Raises
        ------
        ValueError
            If *group* contains ``':'``.
        """
        if ':' in group:
            raise ValueError(f"Group name must not contain ':', got {group!r}")
        self._check_name_collision(name, group)
        _log.debug(
            'CrossIndex: adding sequence %r (len=%d) to group %r',
            name,
            len(seq),
            group,
        )
        if group not in self._groups:
            self._groups[group] = []
            self._internal_group[group] = group
        internal = self._make_internal(group, name)
        self._index.add_sequence(internal, seq)
        if name not in self._groups[group]:
            self._groups[group].append(name)

    def load_fasta(self, path: str, group: str = 'a') -> list[str]:
        """Load sequences from a FASTA file into the specified group.

        Logs an ``INFO``-level message when opening the file, a ``DEBUG``
        message for each sequence loaded (including sequence name and length),
        and a ``WARNING`` if any sequence name already exists in the same or
        another group.

        Parameters
        ----------
        path : str
            Path to a FASTA (``.fa`` / ``.fasta``) or gzipped FASTA file.
        group : str, optional
            Group label.  Default is ``'a'``.

        Returns
        -------
        list[str]
            The original (un-prefixed) sequence names that were loaded, in
            file order.

        Raises
        ------
        ValueError
            If *group* contains ``':'``, or if the file cannot be parsed, or
            if the FASTA file contains duplicate sequence names.
        """
        if ':' in group:
            raise ValueError(f"Group name must not contain ':', got {group!r}")
        from dot_explorer._dot_explorer import py_read_fasta

        _log.info('CrossIndex: loading sequences from %r into group %r', path, group)
        seqs = py_read_fasta(path)
        if group not in self._groups:
            self._groups[group] = []
            self._internal_group[group] = group
        names: list[str] = []
        for name, seq in seqs.items():
            self._check_name_collision(name, group)
            _log.debug(
                'CrossIndex: adding sequence %r (len=%d) to group %r',
                name,
                len(seq),
                group,
            )
            internal = self._make_internal(group, name)
            self._index.add_sequence(internal, seq)
            if name not in self._groups[group]:
                self._groups[group].append(name)
            names.append(name)
        _log.info(
            'CrossIndex: loaded %d sequence(s) from %r into group %r',
            len(names),
            path,
            group,
        )
        return names

    # ------------------------------------------------------------------
    # Properties and name helpers
    # ------------------------------------------------------------------

    @property
    def group_names(self) -> list[str]:
        """Return the list of group labels in insertion order.

        Returns
        -------
        list[str]
            Group labels.
        """
        return list(self._groups.keys())

    def sequence_names(self, group: str | None = None) -> list[str]:
        """Return internal (``group:name``) identifiers suitable for DotPlotter.

        Parameters
        ----------
        group : str or None, optional
            If given, return only names from that group.  If ``None``
            (default), return names from all groups.

        Returns
        -------
        list[str]
            Internal ``group:name`` strings in current :attr:`contig_order`.
        """
        if group is not None:
            return [self._make_internal(group, n) for n in self._groups.get(group, [])]
        result: list[str] = []
        for g, names in self._groups.items():
            result.extend(self._make_internal(g, n) for n in names)
        return result

    @property
    def contig_order(self) -> dict[str, list[str]]:
        """Current contig order per group as original (un-prefixed) names.

        Returns
        -------
        dict[str, list[str]]
            Mapping of group label → ordered list of sequence names.
            Updated in-place by :meth:`reorder_by_length` and
            :meth:`reorder_for_colinearity`.
        """
        return {g: list(names) for g, names in self._groups.items()}

    # ------------------------------------------------------------------
    # Backward-compatible properties (two-group a/b model)
    # ------------------------------------------------------------------

    @property
    def query_names(self) -> list[str]:
        """Un-prefixed names for group ``'a'`` (backward compatible).

        Returns
        -------
        list[str]
        """
        return list(self._groups.get('a', []))

    @property
    def target_names(self) -> list[str]:
        """Un-prefixed names for group ``'b'`` (backward compatible).

        Returns
        -------
        list[str]
        """
        return list(self._groups.get('b', []))

    # ------------------------------------------------------------------
    # DotPlotter-compatible interface
    # ------------------------------------------------------------------

    def get_sequence_length(self, name: str) -> int:
        """Return the length of the sequence identified by its internal name.

        Parameters
        ----------
        name : str
            Internal (``group:name``) identifier.

        Returns
        -------
        int
            Sequence length in bases.
        """
        return self._index.get_sequence_length(name)

    def compare_sequences_stranded(
        self, name1: str, name2: str, merge: bool = True
    ) -> list:
        """Compare two sequences by their internal names, returning stranded matches.

        Parameters
        ----------
        name1 : str
            Internal name of the query sequence.
        name2 : str
            Internal name of the target sequence.
        merge : bool, optional
            Whether to merge consecutive co-linear k-mer runs.
            Default is ``True``.

        Returns
        -------
        list of (int, int, int, int, str)
            List of ``(query_start, query_end, target_start, target_end, strand)``
            tuples.
        """
        return self._index.compare_sequences_stranded(name1, name2, merge)

    # ------------------------------------------------------------------
    # Contig reordering
    # ------------------------------------------------------------------

    def rename_group(self, old_name: str, new_name: str) -> None:
        """Rename a group label without re-indexing sequences.

        The internal prefix used in the underlying :class:`SequenceIndex` is
        preserved; only the public-facing group label is changed.

        Parameters
        ----------
        old_name : str
            Current group label to rename.
        new_name : str
            New group label.  Must not contain ``':'``.

        Raises
        ------
        KeyError
            If *old_name* is not a known group.
        ValueError
            If *new_name* contains ``':'`` or already exists as a group label.
        """
        if old_name not in self._groups:
            raise KeyError(f'Group {old_name!r} not found.')
        if ':' in new_name:
            raise ValueError(f"Group name must not contain ':', got {new_name!r}")
        if new_name in self._groups and new_name != old_name:
            raise ValueError(f'Group {new_name!r} already exists.')
        # Rebuild _groups preserving insertion order
        self._groups = {
            (new_name if k == old_name else k): v for k, v in self._groups.items()
        }
        # Update the internal-prefix mapping
        self._internal_group[new_name] = self._internal_group.pop(old_name)
        _log.info('CrossIndex: renamed group %r%r', old_name, new_name)

    def set_group_members(self, group: str, names: list[str]) -> None:
        """Assign a custom list of sequence names to an existing group.

        Only the logical membership list is updated; sequences already indexed
        are not moved or removed from the underlying
        :class:`~dot_explorer.SequenceIndex`.

        Parameters
        ----------
        group : str
            Group label to update.  The group must already exist.
        names : list[str]
            New ordered list of un-prefixed sequence names for the group.

        Raises
        ------
        KeyError
            If *group* is not a known group.

        Warns
        -----
        Logs a warning for every name that is also present in another group.
        """
        if group not in self._groups:
            raise KeyError(f'Group {group!r} not found.')
        for n in names:
            for other_g, other_ns in self._groups.items():
                if other_g != group and n in other_ns:
                    _log.warning(
                        'CrossIndex: sequence %r is assigned to both group %r and group %r',
                        n,
                        other_g,
                        group,
                    )
        self._groups[group] = list(names)

    def reorder_by_length(self, group: str | None = None) -> None:
        """Reorder contigs within one or all groups by descending sequence length.

        Updates :attr:`contig_order` in-place.

        Parameters
        ----------
        group : str or None, optional
            Group to reorder.  If ``None`` (default), all groups are reordered.
        """
        groups_to_sort = [group] if group is not None else list(self._groups.keys())
        for g in groups_to_sort:
            self._groups[g].sort(
                key=lambda n: self._index.get_sequence_length(
                    self._make_internal(g, n)
                ),
                reverse=True,
            )

    def reorder_for_colinearity(
        self,
        query_group: str,
        target_group: str,
        reorder_target: bool = True,
    ) -> None:
        """Reorder sequences in two groups to maximise dotplot collinearity.

        Uses the d-genies gravity algorithm.  Each query contig is assigned to
        its best-matching target chromosome, ordered by its gravity centre
        there, and flagged if reverse-oriented (see :meth:`reversed_contigs`).
        Updates :attr:`contig_order` in-place.

        Orientation is expressed relative to the target group, which is treated
        as the forward reference: only *query_group* contigs are flagged as
        reversed.  Order and orientation are derived from the k-mer engine's
        stranded matches (the same mechanism that populates the
        :meth:`compute_matches` cache).

        .. note::
            :meth:`compute_matches` must be called for ``(query_group,
            target_group)`` before calling this method.

        Parameters
        ----------
        query_group : str
            Group label for the query (y-axis / rows).
        target_group : str
            Group label for the target (x-axis / columns).
        reorder_target : bool, optional
            When ``True`` (default) both groups are reordered.  When ``False``
            the target group's order is left unchanged and only *query_group* is
            reordered against it — use this to align one assembly to another
            that must not move.  Default is ``True``.

        Raises
        ------
        KeyError
            If either group label is not present in the index.
        ValueError
            If :meth:`compute_matches` has not been called for this group
            pair.
        """
        pair = (query_group, target_group)
        if pair not in self._records_by_pair:
            raise ValueError(
                f'No matches computed for group pair {pair!r}. '
                'Call compute_matches() for this pair first.'
            )
        q_names = list(self._groups[query_group])
        t_names = list(self._groups[target_group])
        # Reuse the records cached by compute_matches instead of recomputing
        # the whole Q x T match grid: ordering and orientation are then
        # derived from exactly the matches that get plotted (including any
        # merge/min_block_len settings used at compute time).
        records = self._records_by_pair[pair]
        sorted_q, sorted_t, reversed_q = compute_gravity_contigs(
            records, q_names, t_names, sort_targets=reorder_target
        )
        self._groups[query_group] = sorted_q
        if reorder_target:
            self._groups[target_group] = sorted_t
        self._reversed[query_group] = reversed_q

    def _stranded_pair_records(
        self,
        q_int: str,
        t_int: str,
        q_name: str,
        t_name: str,
        merge: bool = True,
    ) -> list[PafRecord]:
        """Build both-strand PAF records for a single sequence pair.

        Matches come from
        :meth:`~dot_explorer.SequenceIndex.compare_sequences_stranded`, which
        reports forward (``'+'``) and reverse-complement (``'-'``) matches.
        Query coordinates are always on the forward strand, as required by
        the PAF specification.

        Parameters
        ----------
        q_int, t_int : str
            Internal (``'group:name'``) identifiers used for the comparison.
        q_name, t_name : str
            Un-prefixed names written into the records.
        merge : bool, optional
            Whether to merge co-linear k-mer runs.  Default is ``True``.

        Returns
        -------
        list[PafRecord]
            One record per stranded match block.
        """
        q_len = self._index.get_sequence_length(q_int)
        t_len = self._index.get_sequence_length(t_int)
        matches = self._index.compare_sequences_stranded(q_int, t_int, merge)
        return self._records_from_matches(q_name, t_name, q_len, t_len, matches)

    def _stranded_records(
        self,
        query_group: str,
        target_group: str,
        q_names: list[str],
        t_names: list[str],
        merge: bool = True,
        min_block_len: int = 0,
    ) -> list[PafRecord]:
        """Build both-strand PAF records for a group pair from the k-mer engine.

        Both the gravity ordering and the reverse-orientation check are driven
        from :meth:`~dot_explorer.SequenceIndex.compare_sequences_stranded`, which
        reports forward and reverse matches.  :meth:`compute_matches` caches
        records built through this same mechanism.

        Parameters
        ----------
        query_group, target_group : str
            Group labels for the query and target axes.
        q_names, t_names : list[str]
            Un-prefixed sequence names within each group.
        merge : bool, optional
            Whether to merge co-linear k-mer runs.  Default is ``True``.
        min_block_len : int, optional
            Drop matches whose longest span is shorter than this many bases
            (filtered natively before record construction).  Default is ``0``.

        Returns
        -------
        list[PafRecord]
            One record per stranded match block across every (query, target)
            pair, using un-prefixed names.
        """
        pairs = [
            (self._make_internal(query_group, q), self._make_internal(target_group, t))
            for q in q_names
            for t in t_names
        ]
        name_pairs = [(q, t) for q in q_names for t in t_names]

        batch = getattr(self._index, 'compare_pairs_stranded', None)
        records: list[PafRecord] = []
        if batch is not None:
            # One native call for the whole Q x T grid: the Rust side computes
            # every pair with the GIL released (and in parallel off-wasm),
            # instead of Q x T separate Python->Rust round-trips.
            lengths = {
                internal: self._index.get_sequence_length(internal)
                for pair in pairs
                for internal in pair
            }
            for (qi, ti), (q, t), matches in zip(
                pairs, name_pairs, batch(pairs, merge, min_block_len)
            ):
                records.extend(
                    self._records_from_matches(q, t, lengths[qi], lengths[ti], matches)
                )
        else:  # pragma: no cover - older compiled extension without the batch API
            for (qi, ti), (q, t) in zip(pairs, name_pairs):
                pair_records = self._stranded_pair_records(qi, ti, q, t, merge)
                if min_block_len:
                    pair_records = [
                        r
                        for r in pair_records
                        if r.alignment_block_len >= min_block_len
                    ]
                records.extend(pair_records)
        return records

    @staticmethod
    def _records_from_matches(
        q_name: str,
        t_name: str,
        q_len: int,
        t_len: int,
        matches: list[tuple[int, int, int, int, str]],
    ) -> list[PafRecord]:
        """Convert stranded match tuples for one pair into PAF records.

        Parameters
        ----------
        q_name, t_name : str
            Un-prefixed names written into the records.
        q_len, t_len : int
            Full sequence lengths for the pair.
        matches : list[tuple[int, int, int, int, str]]
            ``(query_start, query_end, target_start, target_end, strand)``
            tuples as returned by the k-mer engine.

        Returns
        -------
        list[PafRecord]
            One record per stranded match block.
        """
        records: list[PafRecord] = []
        for qs, qe, ts, te, strand in matches:
            block = max(qe - qs, te - ts)
            records.append(
                PafRecord(
                    query_name=q_name,
                    query_len=q_len,
                    query_start=qs,
                    query_end=qe,
                    strand=strand,
                    target_name=t_name,
                    target_len=t_len,
                    target_start=ts,
                    target_end=te,
                    residue_matches=block,
                    alignment_block_len=block,
                    mapping_quality=255,
                )
            )
        return records

    def reversed_contigs(self, group: str) -> set[str]:
        """Return reverse-oriented contigs for *group* from the last reorder.

        Populated by :meth:`reorder_for_colinearity` and
        :meth:`reorder_contigs` when *group* is used as the query axis.  Empty
        for groups that have not been reordered as a query.

        Parameters
        ----------
        group : str
            Group label.

        Returns
        -------
        set[str]
            Names of reverse-oriented contigs in *group*.
        """
        return set(self._reversed.get(group, set()))

    # ------------------------------------------------------------------
    # FASTA output
    # ------------------------------------------------------------------

    def get_sequence(self, name: str, group: str | None = None) -> str:
        """Return the stored sequence bases for a contig.

        Parameters
        ----------
        name : str
            Sequence name.  Un-prefixed when *group* is given, otherwise the
            internal ``'group:name'`` identifier.
        group : str or None, optional
            Group label the sequence belongs to.  When provided, *name* is the
            un-prefixed name.  Default is ``None``.

        Returns
        -------
        str
            The sequence bases.

        Raises
        ------
        KeyError
            If the sequence is not present in the index.
        """
        internal = self._make_internal(group, name) if group is not None else name
        return self._index.get_sequence(internal)

    def approx_bytes(self) -> dict[str, int]:
        """Return the underlying index's approximate heap footprint in bytes.

        Delegates to :meth:`SequenceIndex.approx_bytes`; Python-side record
        objects (:class:`PafRecord`) are not included.

        Returns
        -------
        dict[str, int]
            Keys ``'seq_bytes'``, ``'kmer_index'``, ``'pair_cache'`` and
            ``'total'``.
        """
        return self._index.approx_bytes()

    def write_fasta(
        self,
        path: str | Path,
        group: str,
        order: list[str] | None = None,
        reverse: set[str] | None = None,
        line_width: int = 60,
    ) -> None:
        """Write a group's contigs to a FASTA file, optionally reordered/reoriented.

        Contigs are written in *order* (default :attr:`contig_order` for the
        group, as set by the most recent reorder), and any contig named in
        *reverse* is written reverse-complemented (default
        :meth:`reversed_contigs` for the group).  This makes the FASTA match the
        collinearity-optimised dotplot layout: reordered along the axis and
        reverse-oriented contigs flipped to read forward.  Reverse-complemented
        records carry a ``reverse_complement`` note in their header description.

        Parameters
        ----------
        path : str or pathlib.Path
            Output FASTA path.
        group : str
            Group label whose contigs to write.
        order : list[str] or None, optional
            Ordered un-prefixed contig names to write.  Defaults to the group's
            current :attr:`contig_order`.
        reverse : set[str] or None, optional
            Contig names to reverse-complement.  Defaults to the group's
            :meth:`reversed_contigs` set.  Pass ``set()`` to disable flipping.
        line_width : int, optional
            Wrap sequence lines at this many bases.  ``0`` or negative writes
            each sequence on a single line.  Default is ``60``.

        Raises
        ------
        KeyError
            If *group* is unknown or a requested contig is not present.
        """
        if group not in self._groups:
            raise KeyError(f'Group {group!r} not found.')
        names = list(order) if order is not None else list(self._groups[group])
        rc_names = reverse if reverse is not None else self.reversed_contigs(group)

        with open(path, 'w') as fh:
            for name in names:
                seq = self.get_sequence(name, group=group)
                if name in rc_names:
                    seq = reverse_complement(seq)
                    fh.write(f'>{name} reverse_complement\n')
                else:
                    fh.write(f'>{name}\n')
                if line_width and line_width > 0:
                    for i in range(0, len(seq), line_width):
                        fh.write(seq[i : i + line_width] + '\n')
                else:
                    fh.write(seq + '\n')
        _log.info(
            'CrossIndex: wrote %d contigs from group %r to %s (%d reverse-complemented)',
            len(names),
            group,
            path,
            sum(1 for n in names if n in rc_names),
        )

    # ------------------------------------------------------------------
    # PAF output and match computation
    # ------------------------------------------------------------------

    def _get_default_group_pairs(self) -> list[tuple[str, str]]:
        """Return default group pairs for alignment.

        * 2 groups → one pair between the two groups.
        * 3+ groups → all non-self ordered pairs.
        """
        groups = list(self._groups.keys())
        if len(groups) == 2:
            return [(groups[0], groups[1])]
        return [
            (a, b) for i, a in enumerate(groups) for j, b in enumerate(groups) if i != j
        ]

    def compute_matches(
        self,
        query_group: str | None = None,
        target_group: str | None = None,
        merge: bool = True,
        min_block_len: int = 0,
    ) -> None:
        """Compute k-mer matches between groups and cache the results.

        This is the primary computation step and must be called **before**
        :meth:`reorder_contigs` or :meth:`reorder_for_colinearity`.  Matches
        are computed only between groups — not within a single group.

        When *query_group* and *target_group* are both ``None``:

        * **2 groups** — the single cross-group pair is used.
        * **3+ groups** — all non-self ordered pairs are computed.

        The computed records are stored internally, keyed by
        ``(query_group, target_group)``, and the pair is added to
        :attr:`computed_group_pairs`.

        Records cover **both strands**: reverse-complement matches are cached
        as ``'-'`` strand :class:`PafRecord` entries with query coordinates on
        the forward strand, as required by the PAF specification.  Plotting
        from the cache therefore renders reverse-oriented contigs correctly.

        Parameters
        ----------
        query_group : str or None, optional
            Group label for query sequences.  When ``None`` (default) the
            groups are auto-detected (see above).
        target_group : str or None, optional
            Group label for target sequences.  When ``None`` (default) the
            groups are auto-detected.
        merge : bool, optional
            Whether to merge consecutive co-linear k-mer runs into single
            alignment blocks.  Default is ``True``.
        min_block_len : int, optional
            Drop matches whose longest span (query or target) is shorter
            than this many bases, before they are materialised as records.
            Repeat-rich genome pairs can otherwise produce millions of
            short blocks that dominate memory and downstream processing.
            Default is ``0`` (keep all).

        Raises
        ------
        ValueError
            If group auto-detection fails (≠2 groups, no explicit params), or
            if only one of *query_group* / *target_group* is supplied.
        KeyError
            If an explicit group label is not present in the index.
        """
        if query_group is None and target_group is None:
            pairs = self._get_default_group_pairs()
        elif (query_group is None) ^ (target_group is None):
            raise ValueError('Provide both query_group and target_group, or neither.')
        else:
            if query_group not in self._groups:
                raise KeyError(f'Group {query_group!r} not found.')
            if target_group not in self._groups:
                raise KeyError(f'Group {target_group!r} not found.')
            pairs = [(query_group, target_group)]

        for qg, tg in pairs:
            q_seqs = self._groups.get(qg, [])
            t_seqs = self._groups.get(tg, [])
            _log.info(
                'CrossIndex.compute_matches: computing matches between '
                'group %r (%d sequence(s)) and group %r (%d sequence(s))',
                qg,
                len(q_seqs),
                tg,
                len(t_seqs),
            )
            pair_records = self._stranded_records(
                qg, tg, q_seqs, t_seqs, merge, min_block_len
            )
            self._records_by_pair[(qg, tg)] = pair_records
            self._records_merge[(qg, tg)] = merge
            _log.info(
                'CrossIndex.compute_matches: stored %d record(s) for pair (%r, %r)',
                len(pair_records),
                qg,
                tg,
            )

    def get_paf(
        self,
        group_pairs: list[tuple[str, str]] | None = None,
        merge: bool = True,
    ) -> list[str]:
        """Return PAF lines for cross-group sequence comparisons.

        Parameters
        ----------
        group_pairs : list of (str, str) or None, optional
            Explicit list of ``(query_group, target_group)`` pairs to compare.
            If ``None`` (default):

            * 2 groups → the single cross-group pair.
            * 3+ groups → all non-self ordered pairs.
        merge : bool, optional
            Whether to merge consecutive co-linear k-mer runs before
            generating PAF lines.  Default is ``True``.

        Returns
        -------
        list[str]
            PAF-formatted lines (12 tab-separated columns each).  Both
            strands are reported: reverse-complement matches appear as
            ``'-'`` strand lines with query coordinates on the forward
            strand, per the PAF specification.
        """
        if group_pairs is None:
            group_pairs = self._get_default_group_pairs()

        paf_lines: list[str] = []
        for query_group, target_group in group_pairs:
            # Serve from the compute_matches cache when it was computed in
            # the same form (also keeps any min_block_len filtering
            # consistent with what was plotted); fall back to on-demand
            # computation otherwise.
            pair = (query_group, target_group)
            cached = self._records_by_pair.get(pair)
            if cached is not None and self._records_merge.get(pair) == merge:
                paf_lines.extend(rec.to_line() for rec in cached)
                continue
            q_seqs = self._groups.get(query_group, [])
            t_seqs = self._groups.get(target_group, [])
            _log.info(
                'CrossIndex.get_paf: on-demand computation of %d x %d alignments '
                'between group %r and group %r '
                '(tip: call compute_matches() first to pre-cache results)',
                len(q_seqs),
                len(t_seqs),
                query_group,
                target_group,
            )
            records = self._stranded_records(
                query_group, target_group, q_seqs, t_seqs, merge
            )
            paf_lines.extend(rec.to_line() for rec in records)
        return paf_lines

    def run_merge(
        self,
        group_pairs: list[tuple[str, str]] | None = None,
    ) -> None:
        """Compute merged alignments and store the result as :attr:`_paf_records`.

        .. deprecated::
            Use :meth:`compute_matches` instead.  ``run_merge`` now delegates
            to ``compute_matches`` and is retained only for backward
            compatibility.

        Parameters
        ----------
        group_pairs : list of (str, str) or None, optional
            Group pairs to compare (same semantics as :meth:`compute_matches`).
            Defaults to all cross-group pairs.
        """
        if group_pairs is None:
            self.compute_matches(merge=True)
        else:
            for qg, tg in group_pairs:
                self.compute_matches(query_group=qg, target_group=tg, merge=True)

    # ------------------------------------------------------------------
    # Backward-compatible API (two-group a/b model)
    # ------------------------------------------------------------------

    def get_paf_all(self, merge: bool = True) -> list[str]:
        """Return PAF lines for all cross-group comparisons.

        Backward-compatible wrapper around :meth:`get_paf`.  When a group
        ``'b'`` is present, computes ``a`` vs ``b`` alignments; otherwise
        performs all-vs-all within group ``'a'``.

        Parameters
        ----------
        merge : bool, optional
            Whether to merge consecutive co-linear k-mer runs.
            Default is ``True``.

        Returns
        -------
        list[str]
            PAF-formatted lines.
        """
        if 'b' in self._groups and self._groups['b']:
            return self.get_paf(group_pairs=[('a', 'b')], merge=merge)
        # Single group or no group 'b': all-vs-all within group 'a'
        names_a = self._groups.get('a', [])
        _log.info(
            'CrossIndex: computing all-vs-all pairwise alignments '
            'within group a (%d sequences)',
            len(names_a),
        )
        paf_lines: list[str] = []
        for i, q_orig in enumerate(names_a):
            for j, t_orig in enumerate(names_a):
                if i == j:
                    continue
                q_int = self._make_internal('a', q_orig)
                t_int = self._make_internal('a', t_orig)
                records = self._stranded_pair_records(
                    q_int, t_int, q_orig, t_orig, merge
                )
                paf_lines.extend(rec.to_line() for rec in records)
        return paf_lines

    def reorder_contigs(
        self,
        query_names: list[str] | None = None,
        target_names: list[str] | None = None,
        query_group: str | None = None,
        target_group: str | None = None,
    ) -> tuple[list[str], list[str]]:
        """Sort contigs for maximum collinearity.

        .. note::
            :meth:`compute_matches` must be called for the relevant group pair
            before calling this method.

        When *query_group* and *target_group* are not provided the method
        auto-detects the two groups to compare:

        * If there are **exactly two groups**, those two groups are used
          (regardless of their labels) and an info-level log message records
          which groups were selected and the order of the returned tuple.
        * Otherwise a :exc:`ValueError` is raised and the caller must supply
          explicit group labels via *query_group* / *target_group*.

        Parameters
        ----------
        query_names : list[str] or None, optional
            Explicit un-prefixed names within *query_group* to reorder.
            Defaults to all sequences in *query_group*.
        target_names : list[str] or None, optional
            Explicit un-prefixed names within *target_group* to reorder.
            Defaults to all sequences in *target_group*.
        query_group : str or None, optional
            Group label for the query (first element of the returned tuple).
            When ``None`` the group is auto-detected (requires exactly two
            groups).
        target_group : str or None, optional
            Group label for the target (second element of the returned tuple).
            When ``None`` the group is auto-detected (requires exactly two
            groups).

        Returns
        -------
        tuple[list[str], list[str]]
            ``(sorted_query_names, sorted_target_names)`` — both using
            original un-prefixed names.  The log output names the groups
            in the same order as the tuple elements.

        Raises
        ------
        ValueError
            If groups cannot be auto-detected (i.e. there are not exactly two
            groups and no explicit group labels were supplied), if only one of
            *query_group* / *target_group* is given, or if
            :meth:`compute_matches` has not been called for the resolved group
            pair.
        KeyError
            If an explicitly supplied group label is not present.
        """
        groups = list(self._groups.keys())

        if query_group is None and target_group is None:
            if len(groups) == 2:
                query_group, target_group = groups[0], groups[1]
                _log.info(
                    'CrossIndex.reorder_contigs: auto-selected groups '
                    '%r (query / first) and %r (target / second)',
                    query_group,
                    target_group,
                )
            else:
                raise ValueError(
                    'reorder_contigs requires exactly two groups when query_group '
                    'and target_group are not specified; '
                    f'found {len(groups)} group(s): {groups!r}. '
                    'Provide query_group and target_group explicitly, or use '
                    'reorder_for_colinearity for full control.'
                )
        elif (query_group is None) ^ (target_group is None):
            raise ValueError('Provide both query_group and target_group, or neither.')
        else:
            _log.info(
                'CrossIndex.reorder_contigs: using groups '
                '%r (query / first) and %r (target / second)',
                query_group,
                target_group,
            )

        # Both labels are resolved (non-None) by the block above.
        assert query_group is not None and target_group is not None
        pair = (query_group, target_group)
        if pair not in self._records_by_pair:
            raise ValueError(
                f'No matches computed for group pair {pair!r}. '
                'Call compute_matches() for this pair first.'
            )

        q_names = (
            query_names if query_names is not None else list(self._groups[query_group])
        )
        t_names = (
            target_names
            if target_names is not None
            else list(self._groups[target_group])
        )
        # Order and reverse-orientation both come from the stranded matches;
        # the resulting order matches SequenceIndex.optimal_contig_order by
        # construction.
        records = self._stranded_records(query_group, target_group, q_names, t_names)
        sorted_q, sorted_t, reversed_q = compute_gravity_contigs(
            records, q_names, t_names
        )
        self._reversed[query_group] = reversed_q
        return sorted_q, sorted_t

    # ------------------------------------------------------------------
    # Dunder methods
    # ------------------------------------------------------------------

    def __repr__(self) -> str:
        """Return a concise machine-readable representation.

        Returns
        -------
        str
            ``CrossIndex(k=<k>, groups={<label>=<n>, ...})``.
        """
        group_info = ', '.join(f'{g}={len(names)}' for g, names in self._groups.items())
        return f'CrossIndex(k={self._k}, groups={{{group_info}}})'

    def __str__(self) -> str:
        """Return a human-readable stats summary.

        Returns
        -------
        str
            Multi-line summary of groups, sequence counts, computed pairs,
            and cached PAF record count.
        """
        n_total = sum(len(v) for v in self._groups.values())
        lines = [f'CrossIndex (k={self._k})']
        lines.append(f'  Total sequences : {n_total}')
        for g, names in self._groups.items():
            lines.append(f'  Group {g!r:12s}: {len(names):>6d} sequences')
        if self._records_by_pair:
            for (qg, tg), recs in self._records_by_pair.items():
                lines.append(
                    f'  Computed pair   : ({qg!r}, {tg!r}) → {len(recs)} record(s)'
                )
        else:
            lines.append('  Computed pairs  : none (call compute_matches() first)')
        lines.append(f'  PAF records     : {len(self._paf_records)}')
        return '\n'.join(lines)

Attributes

computed_group_pairs property

Group pairs for which k-mer matches have been computed.

Returns:

Type Description
list[tuple[str, str]]

List of (query_group, target_group) pairs that have had :meth:compute_matches run on them. Use this to confirm that the required pair is ready before calling :meth:reorder_contigs.

group_names property

Return the list of group labels in insertion order.

Returns:

Type Description
list[str]

Group labels.

contig_order property

Current contig order per group as original (un-prefixed) names.

Returns:

Type Description
dict[str, list[str]]

Mapping of group label → ordered list of sequence names. Updated in-place by :meth:reorder_by_length and :meth:reorder_for_colinearity.

query_names property

Un-prefixed names for group 'a' (backward compatible).

Returns:

Type Description
list[str]

target_names property

Un-prefixed names for group 'b' (backward compatible).

Returns:

Type Description
list[str]

Methods:

__init__(k)

Initialise an empty CrossIndex.

Parameters:

Name Type Description Default
k int

K-mer length to use when building the sequence index.

required
Source code in dot_explorer/paf_io.py
def __init__(self, k: int) -> None:
    """Initialise an empty CrossIndex.

    Parameters
    ----------
    k : int
        K-mer length to use when building the sequence index.
    """
    self._k: int = k
    self._index: SequenceIndex = SequenceIndex(k=k)
    # group_label -> ordered list of original (un-prefixed) sequence names
    self._groups: dict[str, list[str]] = {}
    # group_label -> internal prefix used in _index (supports rename_group)
    self._internal_group: dict[str, str] = {}
    # (query_group, target_group) -> list[PafRecord] from compute_matches
    self._records_by_pair: dict[tuple[str, str], list[PafRecord]] = {}
    # Merge flag used when each pair's records were computed, so cached
    # records are only served for calls requesting the same form.
    self._records_merge: dict[tuple[str, str], bool] = {}
    # group_label -> set of reverse-oriented contigs (from the last
    # collinearity reorder that used that group as the query axis)
    self._reversed: dict[str, set[str]] = {}

get_records_for_pair(query_group, target_group)

Return the cached :class:PafRecord list for a computed group pair.

Parameters:

Name Type Description Default
query_group str

Query group label.

required
target_group str

Target group label.

required

Returns:

Type Description
list[PafRecord]

Cached PAF records for the pair. Returns an empty list if :meth:compute_matches has not been called for this pair.

Source code in dot_explorer/paf_io.py
def get_records_for_pair(
    self, query_group: str, target_group: str
) -> list['PafRecord']:
    """Return the cached :class:`PafRecord` list for a computed group pair.

    Parameters
    ----------
    query_group : str
        Query group label.
    target_group : str
        Target group label.

    Returns
    -------
    list[PafRecord]
        Cached PAF records for the pair.  Returns an empty list if
        :meth:`compute_matches` has not been called for this pair.
    """
    return list(self._records_by_pair.get((query_group, target_group), []))

make_internal_name(group, name)

Construct the internal ('group:name') identifier for a sequence.

This is the public counterpart of the internal :meth:_make_internal helper and is suitable for use by external code such as :class:~dot_explorer.dotplot.DotPlotter.

Parameters:

Name Type Description Default
group str

Group label.

required
name str

Un-prefixed sequence name.

required

Returns:

Type Description
str

Internal identifier in 'group:name' form, with any rename_group remapping applied.

Source code in dot_explorer/paf_io.py
def make_internal_name(self, group: str, name: str) -> str:
    """Construct the internal (``'group:name'``) identifier for a sequence.

    This is the public counterpart of the internal :meth:`_make_internal`
    helper and is suitable for use by external code such as
    :class:`~dot_explorer.dotplot.DotPlotter`.

    Parameters
    ----------
    group : str
        Group label.
    name : str
        Un-prefixed sequence name.

    Returns
    -------
    str
        Internal identifier in ``'group:name'`` form, with any
        ``rename_group`` remapping applied.
    """
    return self._make_internal(group, name)

add_sequence(name, seq, group='a')

Add a single sequence to the specified group.

Logs a DEBUG-level message for every sequence loaded, and a WARNING if name already exists in the same group (its FM-index will be overwritten) or in a different group (potential confusion).

Parameters:

Name Type Description Default
name str

Sequence identifier (must be unique within the group).

required
seq str

DNA sequence string.

required
group str

Group label. Any non-empty string is accepted; ':' is forbidden because it is used as an internal separator. Default is 'a'.

'a'

Raises:

Type Description
ValueError

If group contains ':'.

Source code in dot_explorer/paf_io.py
def add_sequence(self, name: str, seq: str, group: str = 'a') -> None:
    """Add a single sequence to the specified group.

    Logs a ``DEBUG``-level message for every sequence loaded, and a
    ``WARNING`` if *name* already exists in the same group (its FM-index
    will be overwritten) or in a different group (potential confusion).

    Parameters
    ----------
    name : str
        Sequence identifier (must be unique within the group).
    seq : str
        DNA sequence string.
    group : str, optional
        Group label.  Any non-empty string is accepted; ``':'`` is
        forbidden because it is used as an internal separator.
        Default is ``'a'``.

    Raises
    ------
    ValueError
        If *group* contains ``':'``.
    """
    if ':' in group:
        raise ValueError(f"Group name must not contain ':', got {group!r}")
    self._check_name_collision(name, group)
    _log.debug(
        'CrossIndex: adding sequence %r (len=%d) to group %r',
        name,
        len(seq),
        group,
    )
    if group not in self._groups:
        self._groups[group] = []
        self._internal_group[group] = group
    internal = self._make_internal(group, name)
    self._index.add_sequence(internal, seq)
    if name not in self._groups[group]:
        self._groups[group].append(name)

load_fasta(path, group='a')

Load sequences from a FASTA file into the specified group.

Logs an INFO-level message when opening the file, a DEBUG message for each sequence loaded (including sequence name and length), and a WARNING if any sequence name already exists in the same or another group.

Parameters:

Name Type Description Default
path str

Path to a FASTA (.fa / .fasta) or gzipped FASTA file.

required
group str

Group label. Default is 'a'.

'a'

Returns:

Type Description
list[str]

The original (un-prefixed) sequence names that were loaded, in file order.

Raises:

Type Description
ValueError

If group contains ':', or if the file cannot be parsed, or if the FASTA file contains duplicate sequence names.

Source code in dot_explorer/paf_io.py
def load_fasta(self, path: str, group: str = 'a') -> list[str]:
    """Load sequences from a FASTA file into the specified group.

    Logs an ``INFO``-level message when opening the file, a ``DEBUG``
    message for each sequence loaded (including sequence name and length),
    and a ``WARNING`` if any sequence name already exists in the same or
    another group.

    Parameters
    ----------
    path : str
        Path to a FASTA (``.fa`` / ``.fasta``) or gzipped FASTA file.
    group : str, optional
        Group label.  Default is ``'a'``.

    Returns
    -------
    list[str]
        The original (un-prefixed) sequence names that were loaded, in
        file order.

    Raises
    ------
    ValueError
        If *group* contains ``':'``, or if the file cannot be parsed, or
        if the FASTA file contains duplicate sequence names.
    """
    if ':' in group:
        raise ValueError(f"Group name must not contain ':', got {group!r}")
    from dot_explorer._dot_explorer import py_read_fasta

    _log.info('CrossIndex: loading sequences from %r into group %r', path, group)
    seqs = py_read_fasta(path)
    if group not in self._groups:
        self._groups[group] = []
        self._internal_group[group] = group
    names: list[str] = []
    for name, seq in seqs.items():
        self._check_name_collision(name, group)
        _log.debug(
            'CrossIndex: adding sequence %r (len=%d) to group %r',
            name,
            len(seq),
            group,
        )
        internal = self._make_internal(group, name)
        self._index.add_sequence(internal, seq)
        if name not in self._groups[group]:
            self._groups[group].append(name)
        names.append(name)
    _log.info(
        'CrossIndex: loaded %d sequence(s) from %r into group %r',
        len(names),
        path,
        group,
    )
    return names

sequence_names(group=None)

Return internal (group:name) identifiers suitable for DotPlotter.

Parameters:

Name Type Description Default
group str or None

If given, return only names from that group. If None (default), return names from all groups.

None

Returns:

Type Description
list[str]

Internal group:name strings in current :attr:contig_order.

Source code in dot_explorer/paf_io.py
def sequence_names(self, group: str | None = None) -> list[str]:
    """Return internal (``group:name``) identifiers suitable for DotPlotter.

    Parameters
    ----------
    group : str or None, optional
        If given, return only names from that group.  If ``None``
        (default), return names from all groups.

    Returns
    -------
    list[str]
        Internal ``group:name`` strings in current :attr:`contig_order`.
    """
    if group is not None:
        return [self._make_internal(group, n) for n in self._groups.get(group, [])]
    result: list[str] = []
    for g, names in self._groups.items():
        result.extend(self._make_internal(g, n) for n in names)
    return result

get_sequence_length(name)

Return the length of the sequence identified by its internal name.

Parameters:

Name Type Description Default
name str

Internal (group:name) identifier.

required

Returns:

Type Description
int

Sequence length in bases.

Source code in dot_explorer/paf_io.py
def get_sequence_length(self, name: str) -> int:
    """Return the length of the sequence identified by its internal name.

    Parameters
    ----------
    name : str
        Internal (``group:name``) identifier.

    Returns
    -------
    int
        Sequence length in bases.
    """
    return self._index.get_sequence_length(name)

compare_sequences_stranded(name1, name2, merge=True)

Compare two sequences by their internal names, returning stranded matches.

Parameters:

Name Type Description Default
name1 str

Internal name of the query sequence.

required
name2 str

Internal name of the target sequence.

required
merge bool

Whether to merge consecutive co-linear k-mer runs. Default is True.

True

Returns:

Type Description
list of (int, int, int, int, str)

List of (query_start, query_end, target_start, target_end, strand) tuples.

Source code in dot_explorer/paf_io.py
def compare_sequences_stranded(
    self, name1: str, name2: str, merge: bool = True
) -> list:
    """Compare two sequences by their internal names, returning stranded matches.

    Parameters
    ----------
    name1 : str
        Internal name of the query sequence.
    name2 : str
        Internal name of the target sequence.
    merge : bool, optional
        Whether to merge consecutive co-linear k-mer runs.
        Default is ``True``.

    Returns
    -------
    list of (int, int, int, int, str)
        List of ``(query_start, query_end, target_start, target_end, strand)``
        tuples.
    """
    return self._index.compare_sequences_stranded(name1, name2, merge)

rename_group(old_name, new_name)

Rename a group label without re-indexing sequences.

The internal prefix used in the underlying :class:SequenceIndex is preserved; only the public-facing group label is changed.

Parameters:

Name Type Description Default
old_name str

Current group label to rename.

required
new_name str

New group label. Must not contain ':'.

required

Raises:

Type Description
KeyError

If old_name is not a known group.

ValueError

If new_name contains ':' or already exists as a group label.

Source code in dot_explorer/paf_io.py
def rename_group(self, old_name: str, new_name: str) -> None:
    """Rename a group label without re-indexing sequences.

    The internal prefix used in the underlying :class:`SequenceIndex` is
    preserved; only the public-facing group label is changed.

    Parameters
    ----------
    old_name : str
        Current group label to rename.
    new_name : str
        New group label.  Must not contain ``':'``.

    Raises
    ------
    KeyError
        If *old_name* is not a known group.
    ValueError
        If *new_name* contains ``':'`` or already exists as a group label.
    """
    if old_name not in self._groups:
        raise KeyError(f'Group {old_name!r} not found.')
    if ':' in new_name:
        raise ValueError(f"Group name must not contain ':', got {new_name!r}")
    if new_name in self._groups and new_name != old_name:
        raise ValueError(f'Group {new_name!r} already exists.')
    # Rebuild _groups preserving insertion order
    self._groups = {
        (new_name if k == old_name else k): v for k, v in self._groups.items()
    }
    # Update the internal-prefix mapping
    self._internal_group[new_name] = self._internal_group.pop(old_name)
    _log.info('CrossIndex: renamed group %r%r', old_name, new_name)

set_group_members(group, names)

Assign a custom list of sequence names to an existing group.

Only the logical membership list is updated; sequences already indexed are not moved or removed from the underlying :class:~dot_explorer.SequenceIndex.

Parameters:

Name Type Description Default
group str

Group label to update. The group must already exist.

required
names list[str]

New ordered list of un-prefixed sequence names for the group.

required

Raises:

Type Description
KeyError

If group is not a known group.

Warns:

Type Description
Logs a warning for every name that is also present in another group.
Source code in dot_explorer/paf_io.py
def set_group_members(self, group: str, names: list[str]) -> None:
    """Assign a custom list of sequence names to an existing group.

    Only the logical membership list is updated; sequences already indexed
    are not moved or removed from the underlying
    :class:`~dot_explorer.SequenceIndex`.

    Parameters
    ----------
    group : str
        Group label to update.  The group must already exist.
    names : list[str]
        New ordered list of un-prefixed sequence names for the group.

    Raises
    ------
    KeyError
        If *group* is not a known group.

    Warns
    -----
    Logs a warning for every name that is also present in another group.
    """
    if group not in self._groups:
        raise KeyError(f'Group {group!r} not found.')
    for n in names:
        for other_g, other_ns in self._groups.items():
            if other_g != group and n in other_ns:
                _log.warning(
                    'CrossIndex: sequence %r is assigned to both group %r and group %r',
                    n,
                    other_g,
                    group,
                )
    self._groups[group] = list(names)

reorder_by_length(group=None)

Reorder contigs within one or all groups by descending sequence length.

Updates :attr:contig_order in-place.

Parameters:

Name Type Description Default
group str or None

Group to reorder. If None (default), all groups are reordered.

None
Source code in dot_explorer/paf_io.py
def reorder_by_length(self, group: str | None = None) -> None:
    """Reorder contigs within one or all groups by descending sequence length.

    Updates :attr:`contig_order` in-place.

    Parameters
    ----------
    group : str or None, optional
        Group to reorder.  If ``None`` (default), all groups are reordered.
    """
    groups_to_sort = [group] if group is not None else list(self._groups.keys())
    for g in groups_to_sort:
        self._groups[g].sort(
            key=lambda n: self._index.get_sequence_length(
                self._make_internal(g, n)
            ),
            reverse=True,
        )

reorder_for_colinearity(query_group, target_group, reorder_target=True)

Reorder sequences in two groups to maximise dotplot collinearity.

Uses the d-genies gravity algorithm. Each query contig is assigned to its best-matching target chromosome, ordered by its gravity centre there, and flagged if reverse-oriented (see :meth:reversed_contigs). Updates :attr:contig_order in-place.

Orientation is expressed relative to the target group, which is treated as the forward reference: only query_group contigs are flagged as reversed. Order and orientation are derived from the k-mer engine's stranded matches (the same mechanism that populates the :meth:compute_matches cache).

.. note:: :meth:compute_matches must be called for (query_group, target_group) before calling this method.

Parameters:

Name Type Description Default
query_group str

Group label for the query (y-axis / rows).

required
target_group str

Group label for the target (x-axis / columns).

required
reorder_target bool

When True (default) both groups are reordered. When False the target group's order is left unchanged and only query_group is reordered against it — use this to align one assembly to another that must not move. Default is True.

True

Raises:

Type Description
KeyError

If either group label is not present in the index.

ValueError

If :meth:compute_matches has not been called for this group pair.

Source code in dot_explorer/paf_io.py
def reorder_for_colinearity(
    self,
    query_group: str,
    target_group: str,
    reorder_target: bool = True,
) -> None:
    """Reorder sequences in two groups to maximise dotplot collinearity.

    Uses the d-genies gravity algorithm.  Each query contig is assigned to
    its best-matching target chromosome, ordered by its gravity centre
    there, and flagged if reverse-oriented (see :meth:`reversed_contigs`).
    Updates :attr:`contig_order` in-place.

    Orientation is expressed relative to the target group, which is treated
    as the forward reference: only *query_group* contigs are flagged as
    reversed.  Order and orientation are derived from the k-mer engine's
    stranded matches (the same mechanism that populates the
    :meth:`compute_matches` cache).

    .. note::
        :meth:`compute_matches` must be called for ``(query_group,
        target_group)`` before calling this method.

    Parameters
    ----------
    query_group : str
        Group label for the query (y-axis / rows).
    target_group : str
        Group label for the target (x-axis / columns).
    reorder_target : bool, optional
        When ``True`` (default) both groups are reordered.  When ``False``
        the target group's order is left unchanged and only *query_group* is
        reordered against it — use this to align one assembly to another
        that must not move.  Default is ``True``.

    Raises
    ------
    KeyError
        If either group label is not present in the index.
    ValueError
        If :meth:`compute_matches` has not been called for this group
        pair.
    """
    pair = (query_group, target_group)
    if pair not in self._records_by_pair:
        raise ValueError(
            f'No matches computed for group pair {pair!r}. '
            'Call compute_matches() for this pair first.'
        )
    q_names = list(self._groups[query_group])
    t_names = list(self._groups[target_group])
    # Reuse the records cached by compute_matches instead of recomputing
    # the whole Q x T match grid: ordering and orientation are then
    # derived from exactly the matches that get plotted (including any
    # merge/min_block_len settings used at compute time).
    records = self._records_by_pair[pair]
    sorted_q, sorted_t, reversed_q = compute_gravity_contigs(
        records, q_names, t_names, sort_targets=reorder_target
    )
    self._groups[query_group] = sorted_q
    if reorder_target:
        self._groups[target_group] = sorted_t
    self._reversed[query_group] = reversed_q

reversed_contigs(group)

Return reverse-oriented contigs for group from the last reorder.

Populated by :meth:reorder_for_colinearity and :meth:reorder_contigs when group is used as the query axis. Empty for groups that have not been reordered as a query.

Parameters:

Name Type Description Default
group str

Group label.

required

Returns:

Type Description
set[str]

Names of reverse-oriented contigs in group.

Source code in dot_explorer/paf_io.py
def reversed_contigs(self, group: str) -> set[str]:
    """Return reverse-oriented contigs for *group* from the last reorder.

    Populated by :meth:`reorder_for_colinearity` and
    :meth:`reorder_contigs` when *group* is used as the query axis.  Empty
    for groups that have not been reordered as a query.

    Parameters
    ----------
    group : str
        Group label.

    Returns
    -------
    set[str]
        Names of reverse-oriented contigs in *group*.
    """
    return set(self._reversed.get(group, set()))

get_sequence(name, group=None)

Return the stored sequence bases for a contig.

Parameters:

Name Type Description Default
name str

Sequence name. Un-prefixed when group is given, otherwise the internal 'group:name' identifier.

required
group str or None

Group label the sequence belongs to. When provided, name is the un-prefixed name. Default is None.

None

Returns:

Type Description
str

The sequence bases.

Raises:

Type Description
KeyError

If the sequence is not present in the index.

Source code in dot_explorer/paf_io.py
def get_sequence(self, name: str, group: str | None = None) -> str:
    """Return the stored sequence bases for a contig.

    Parameters
    ----------
    name : str
        Sequence name.  Un-prefixed when *group* is given, otherwise the
        internal ``'group:name'`` identifier.
    group : str or None, optional
        Group label the sequence belongs to.  When provided, *name* is the
        un-prefixed name.  Default is ``None``.

    Returns
    -------
    str
        The sequence bases.

    Raises
    ------
    KeyError
        If the sequence is not present in the index.
    """
    internal = self._make_internal(group, name) if group is not None else name
    return self._index.get_sequence(internal)

approx_bytes()

Return the underlying index's approximate heap footprint in bytes.

Delegates to :meth:SequenceIndex.approx_bytes; Python-side record objects (:class:PafRecord) are not included.

Returns:

Type Description
dict[str, int]

Keys 'seq_bytes', 'kmer_index', 'pair_cache' and 'total'.

Source code in dot_explorer/paf_io.py
def approx_bytes(self) -> dict[str, int]:
    """Return the underlying index's approximate heap footprint in bytes.

    Delegates to :meth:`SequenceIndex.approx_bytes`; Python-side record
    objects (:class:`PafRecord`) are not included.

    Returns
    -------
    dict[str, int]
        Keys ``'seq_bytes'``, ``'kmer_index'``, ``'pair_cache'`` and
        ``'total'``.
    """
    return self._index.approx_bytes()

write_fasta(path, group, order=None, reverse=None, line_width=60)

Write a group's contigs to a FASTA file, optionally reordered/reoriented.

Contigs are written in order (default :attr:contig_order for the group, as set by the most recent reorder), and any contig named in reverse is written reverse-complemented (default :meth:reversed_contigs for the group). This makes the FASTA match the collinearity-optimised dotplot layout: reordered along the axis and reverse-oriented contigs flipped to read forward. Reverse-complemented records carry a reverse_complement note in their header description.

Parameters:

Name Type Description Default
path str or Path

Output FASTA path.

required
group str

Group label whose contigs to write.

required
order list[str] or None

Ordered un-prefixed contig names to write. Defaults to the group's current :attr:contig_order.

None
reverse set[str] or None

Contig names to reverse-complement. Defaults to the group's :meth:reversed_contigs set. Pass set() to disable flipping.

None
line_width int

Wrap sequence lines at this many bases. 0 or negative writes each sequence on a single line. Default is 60.

60

Raises:

Type Description
KeyError

If group is unknown or a requested contig is not present.

Source code in dot_explorer/paf_io.py
def write_fasta(
    self,
    path: str | Path,
    group: str,
    order: list[str] | None = None,
    reverse: set[str] | None = None,
    line_width: int = 60,
) -> None:
    """Write a group's contigs to a FASTA file, optionally reordered/reoriented.

    Contigs are written in *order* (default :attr:`contig_order` for the
    group, as set by the most recent reorder), and any contig named in
    *reverse* is written reverse-complemented (default
    :meth:`reversed_contigs` for the group).  This makes the FASTA match the
    collinearity-optimised dotplot layout: reordered along the axis and
    reverse-oriented contigs flipped to read forward.  Reverse-complemented
    records carry a ``reverse_complement`` note in their header description.

    Parameters
    ----------
    path : str or pathlib.Path
        Output FASTA path.
    group : str
        Group label whose contigs to write.
    order : list[str] or None, optional
        Ordered un-prefixed contig names to write.  Defaults to the group's
        current :attr:`contig_order`.
    reverse : set[str] or None, optional
        Contig names to reverse-complement.  Defaults to the group's
        :meth:`reversed_contigs` set.  Pass ``set()`` to disable flipping.
    line_width : int, optional
        Wrap sequence lines at this many bases.  ``0`` or negative writes
        each sequence on a single line.  Default is ``60``.

    Raises
    ------
    KeyError
        If *group* is unknown or a requested contig is not present.
    """
    if group not in self._groups:
        raise KeyError(f'Group {group!r} not found.')
    names = list(order) if order is not None else list(self._groups[group])
    rc_names = reverse if reverse is not None else self.reversed_contigs(group)

    with open(path, 'w') as fh:
        for name in names:
            seq = self.get_sequence(name, group=group)
            if name in rc_names:
                seq = reverse_complement(seq)
                fh.write(f'>{name} reverse_complement\n')
            else:
                fh.write(f'>{name}\n')
            if line_width and line_width > 0:
                for i in range(0, len(seq), line_width):
                    fh.write(seq[i : i + line_width] + '\n')
            else:
                fh.write(seq + '\n')
    _log.info(
        'CrossIndex: wrote %d contigs from group %r to %s (%d reverse-complemented)',
        len(names),
        group,
        path,
        sum(1 for n in names if n in rc_names),
    )

compute_matches(query_group=None, target_group=None, merge=True, min_block_len=0)

Compute k-mer matches between groups and cache the results.

This is the primary computation step and must be called before :meth:reorder_contigs or :meth:reorder_for_colinearity. Matches are computed only between groups — not within a single group.

When query_group and target_group are both None:

  • 2 groups — the single cross-group pair is used.
  • 3+ groups — all non-self ordered pairs are computed.

The computed records are stored internally, keyed by (query_group, target_group), and the pair is added to :attr:computed_group_pairs.

Records cover both strands: reverse-complement matches are cached as '-' strand :class:PafRecord entries with query coordinates on the forward strand, as required by the PAF specification. Plotting from the cache therefore renders reverse-oriented contigs correctly.

Parameters:

Name Type Description Default
query_group str or None

Group label for query sequences. When None (default) the groups are auto-detected (see above).

None
target_group str or None

Group label for target sequences. When None (default) the groups are auto-detected.

None
merge bool

Whether to merge consecutive co-linear k-mer runs into single alignment blocks. Default is True.

True
min_block_len int

Drop matches whose longest span (query or target) is shorter than this many bases, before they are materialised as records. Repeat-rich genome pairs can otherwise produce millions of short blocks that dominate memory and downstream processing. Default is 0 (keep all).

0

Raises:

Type Description
ValueError

If group auto-detection fails (≠2 groups, no explicit params), or if only one of query_group / target_group is supplied.

KeyError

If an explicit group label is not present in the index.

Source code in dot_explorer/paf_io.py
def compute_matches(
    self,
    query_group: str | None = None,
    target_group: str | None = None,
    merge: bool = True,
    min_block_len: int = 0,
) -> None:
    """Compute k-mer matches between groups and cache the results.

    This is the primary computation step and must be called **before**
    :meth:`reorder_contigs` or :meth:`reorder_for_colinearity`.  Matches
    are computed only between groups — not within a single group.

    When *query_group* and *target_group* are both ``None``:

    * **2 groups** — the single cross-group pair is used.
    * **3+ groups** — all non-self ordered pairs are computed.

    The computed records are stored internally, keyed by
    ``(query_group, target_group)``, and the pair is added to
    :attr:`computed_group_pairs`.

    Records cover **both strands**: reverse-complement matches are cached
    as ``'-'`` strand :class:`PafRecord` entries with query coordinates on
    the forward strand, as required by the PAF specification.  Plotting
    from the cache therefore renders reverse-oriented contigs correctly.

    Parameters
    ----------
    query_group : str or None, optional
        Group label for query sequences.  When ``None`` (default) the
        groups are auto-detected (see above).
    target_group : str or None, optional
        Group label for target sequences.  When ``None`` (default) the
        groups are auto-detected.
    merge : bool, optional
        Whether to merge consecutive co-linear k-mer runs into single
        alignment blocks.  Default is ``True``.
    min_block_len : int, optional
        Drop matches whose longest span (query or target) is shorter
        than this many bases, before they are materialised as records.
        Repeat-rich genome pairs can otherwise produce millions of
        short blocks that dominate memory and downstream processing.
        Default is ``0`` (keep all).

    Raises
    ------
    ValueError
        If group auto-detection fails (≠2 groups, no explicit params), or
        if only one of *query_group* / *target_group* is supplied.
    KeyError
        If an explicit group label is not present in the index.
    """
    if query_group is None and target_group is None:
        pairs = self._get_default_group_pairs()
    elif (query_group is None) ^ (target_group is None):
        raise ValueError('Provide both query_group and target_group, or neither.')
    else:
        if query_group not in self._groups:
            raise KeyError(f'Group {query_group!r} not found.')
        if target_group not in self._groups:
            raise KeyError(f'Group {target_group!r} not found.')
        pairs = [(query_group, target_group)]

    for qg, tg in pairs:
        q_seqs = self._groups.get(qg, [])
        t_seqs = self._groups.get(tg, [])
        _log.info(
            'CrossIndex.compute_matches: computing matches between '
            'group %r (%d sequence(s)) and group %r (%d sequence(s))',
            qg,
            len(q_seqs),
            tg,
            len(t_seqs),
        )
        pair_records = self._stranded_records(
            qg, tg, q_seqs, t_seqs, merge, min_block_len
        )
        self._records_by_pair[(qg, tg)] = pair_records
        self._records_merge[(qg, tg)] = merge
        _log.info(
            'CrossIndex.compute_matches: stored %d record(s) for pair (%r, %r)',
            len(pair_records),
            qg,
            tg,
        )

get_paf(group_pairs=None, merge=True)

Return PAF lines for cross-group sequence comparisons.

Parameters:

Name Type Description Default
group_pairs list of (str, str) or None

Explicit list of (query_group, target_group) pairs to compare. If None (default):

  • 2 groups → the single cross-group pair.
  • 3+ groups → all non-self ordered pairs.
None
merge bool

Whether to merge consecutive co-linear k-mer runs before generating PAF lines. Default is True.

True

Returns:

Type Description
list[str]

PAF-formatted lines (12 tab-separated columns each). Both strands are reported: reverse-complement matches appear as '-' strand lines with query coordinates on the forward strand, per the PAF specification.

Source code in dot_explorer/paf_io.py
def get_paf(
    self,
    group_pairs: list[tuple[str, str]] | None = None,
    merge: bool = True,
) -> list[str]:
    """Return PAF lines for cross-group sequence comparisons.

    Parameters
    ----------
    group_pairs : list of (str, str) or None, optional
        Explicit list of ``(query_group, target_group)`` pairs to compare.
        If ``None`` (default):

        * 2 groups → the single cross-group pair.
        * 3+ groups → all non-self ordered pairs.
    merge : bool, optional
        Whether to merge consecutive co-linear k-mer runs before
        generating PAF lines.  Default is ``True``.

    Returns
    -------
    list[str]
        PAF-formatted lines (12 tab-separated columns each).  Both
        strands are reported: reverse-complement matches appear as
        ``'-'`` strand lines with query coordinates on the forward
        strand, per the PAF specification.
    """
    if group_pairs is None:
        group_pairs = self._get_default_group_pairs()

    paf_lines: list[str] = []
    for query_group, target_group in group_pairs:
        # Serve from the compute_matches cache when it was computed in
        # the same form (also keeps any min_block_len filtering
        # consistent with what was plotted); fall back to on-demand
        # computation otherwise.
        pair = (query_group, target_group)
        cached = self._records_by_pair.get(pair)
        if cached is not None and self._records_merge.get(pair) == merge:
            paf_lines.extend(rec.to_line() for rec in cached)
            continue
        q_seqs = self._groups.get(query_group, [])
        t_seqs = self._groups.get(target_group, [])
        _log.info(
            'CrossIndex.get_paf: on-demand computation of %d x %d alignments '
            'between group %r and group %r '
            '(tip: call compute_matches() first to pre-cache results)',
            len(q_seqs),
            len(t_seqs),
            query_group,
            target_group,
        )
        records = self._stranded_records(
            query_group, target_group, q_seqs, t_seqs, merge
        )
        paf_lines.extend(rec.to_line() for rec in records)
    return paf_lines

run_merge(group_pairs=None)

Compute merged alignments and store the result as :attr:_paf_records.

.. deprecated:: Use :meth:compute_matches instead. run_merge now delegates to compute_matches and is retained only for backward compatibility.

Parameters:

Name Type Description Default
group_pairs list of (str, str) or None

Group pairs to compare (same semantics as :meth:compute_matches). Defaults to all cross-group pairs.

None
Source code in dot_explorer/paf_io.py
def run_merge(
    self,
    group_pairs: list[tuple[str, str]] | None = None,
) -> None:
    """Compute merged alignments and store the result as :attr:`_paf_records`.

    .. deprecated::
        Use :meth:`compute_matches` instead.  ``run_merge`` now delegates
        to ``compute_matches`` and is retained only for backward
        compatibility.

    Parameters
    ----------
    group_pairs : list of (str, str) or None, optional
        Group pairs to compare (same semantics as :meth:`compute_matches`).
        Defaults to all cross-group pairs.
    """
    if group_pairs is None:
        self.compute_matches(merge=True)
    else:
        for qg, tg in group_pairs:
            self.compute_matches(query_group=qg, target_group=tg, merge=True)

get_paf_all(merge=True)

Return PAF lines for all cross-group comparisons.

Backward-compatible wrapper around :meth:get_paf. When a group 'b' is present, computes a vs b alignments; otherwise performs all-vs-all within group 'a'.

Parameters:

Name Type Description Default
merge bool

Whether to merge consecutive co-linear k-mer runs. Default is True.

True

Returns:

Type Description
list[str]

PAF-formatted lines.

Source code in dot_explorer/paf_io.py
def get_paf_all(self, merge: bool = True) -> list[str]:
    """Return PAF lines for all cross-group comparisons.

    Backward-compatible wrapper around :meth:`get_paf`.  When a group
    ``'b'`` is present, computes ``a`` vs ``b`` alignments; otherwise
    performs all-vs-all within group ``'a'``.

    Parameters
    ----------
    merge : bool, optional
        Whether to merge consecutive co-linear k-mer runs.
        Default is ``True``.

    Returns
    -------
    list[str]
        PAF-formatted lines.
    """
    if 'b' in self._groups and self._groups['b']:
        return self.get_paf(group_pairs=[('a', 'b')], merge=merge)
    # Single group or no group 'b': all-vs-all within group 'a'
    names_a = self._groups.get('a', [])
    _log.info(
        'CrossIndex: computing all-vs-all pairwise alignments '
        'within group a (%d sequences)',
        len(names_a),
    )
    paf_lines: list[str] = []
    for i, q_orig in enumerate(names_a):
        for j, t_orig in enumerate(names_a):
            if i == j:
                continue
            q_int = self._make_internal('a', q_orig)
            t_int = self._make_internal('a', t_orig)
            records = self._stranded_pair_records(
                q_int, t_int, q_orig, t_orig, merge
            )
            paf_lines.extend(rec.to_line() for rec in records)
    return paf_lines

reorder_contigs(query_names=None, target_names=None, query_group=None, target_group=None)

Sort contigs for maximum collinearity.

.. note:: :meth:compute_matches must be called for the relevant group pair before calling this method.

When query_group and target_group are not provided the method auto-detects the two groups to compare:

  • If there are exactly two groups, those two groups are used (regardless of their labels) and an info-level log message records which groups were selected and the order of the returned tuple.
  • Otherwise a :exc:ValueError is raised and the caller must supply explicit group labels via query_group / target_group.

Parameters:

Name Type Description Default
query_names list[str] or None

Explicit un-prefixed names within query_group to reorder. Defaults to all sequences in query_group.

None
target_names list[str] or None

Explicit un-prefixed names within target_group to reorder. Defaults to all sequences in target_group.

None
query_group str or None

Group label for the query (first element of the returned tuple). When None the group is auto-detected (requires exactly two groups).

None
target_group str or None

Group label for the target (second element of the returned tuple). When None the group is auto-detected (requires exactly two groups).

None

Returns:

Type Description
tuple[list[str], list[str]]

(sorted_query_names, sorted_target_names) — both using original un-prefixed names. The log output names the groups in the same order as the tuple elements.

Raises:

Type Description
ValueError

If groups cannot be auto-detected (i.e. there are not exactly two groups and no explicit group labels were supplied), if only one of query_group / target_group is given, or if :meth:compute_matches has not been called for the resolved group pair.

KeyError

If an explicitly supplied group label is not present.

Source code in dot_explorer/paf_io.py
def reorder_contigs(
    self,
    query_names: list[str] | None = None,
    target_names: list[str] | None = None,
    query_group: str | None = None,
    target_group: str | None = None,
) -> tuple[list[str], list[str]]:
    """Sort contigs for maximum collinearity.

    .. note::
        :meth:`compute_matches` must be called for the relevant group pair
        before calling this method.

    When *query_group* and *target_group* are not provided the method
    auto-detects the two groups to compare:

    * If there are **exactly two groups**, those two groups are used
      (regardless of their labels) and an info-level log message records
      which groups were selected and the order of the returned tuple.
    * Otherwise a :exc:`ValueError` is raised and the caller must supply
      explicit group labels via *query_group* / *target_group*.

    Parameters
    ----------
    query_names : list[str] or None, optional
        Explicit un-prefixed names within *query_group* to reorder.
        Defaults to all sequences in *query_group*.
    target_names : list[str] or None, optional
        Explicit un-prefixed names within *target_group* to reorder.
        Defaults to all sequences in *target_group*.
    query_group : str or None, optional
        Group label for the query (first element of the returned tuple).
        When ``None`` the group is auto-detected (requires exactly two
        groups).
    target_group : str or None, optional
        Group label for the target (second element of the returned tuple).
        When ``None`` the group is auto-detected (requires exactly two
        groups).

    Returns
    -------
    tuple[list[str], list[str]]
        ``(sorted_query_names, sorted_target_names)`` — both using
        original un-prefixed names.  The log output names the groups
        in the same order as the tuple elements.

    Raises
    ------
    ValueError
        If groups cannot be auto-detected (i.e. there are not exactly two
        groups and no explicit group labels were supplied), if only one of
        *query_group* / *target_group* is given, or if
        :meth:`compute_matches` has not been called for the resolved group
        pair.
    KeyError
        If an explicitly supplied group label is not present.
    """
    groups = list(self._groups.keys())

    if query_group is None and target_group is None:
        if len(groups) == 2:
            query_group, target_group = groups[0], groups[1]
            _log.info(
                'CrossIndex.reorder_contigs: auto-selected groups '
                '%r (query / first) and %r (target / second)',
                query_group,
                target_group,
            )
        else:
            raise ValueError(
                'reorder_contigs requires exactly two groups when query_group '
                'and target_group are not specified; '
                f'found {len(groups)} group(s): {groups!r}. '
                'Provide query_group and target_group explicitly, or use '
                'reorder_for_colinearity for full control.'
            )
    elif (query_group is None) ^ (target_group is None):
        raise ValueError('Provide both query_group and target_group, or neither.')
    else:
        _log.info(
            'CrossIndex.reorder_contigs: using groups '
            '%r (query / first) and %r (target / second)',
            query_group,
            target_group,
        )

    # Both labels are resolved (non-None) by the block above.
    assert query_group is not None and target_group is not None
    pair = (query_group, target_group)
    if pair not in self._records_by_pair:
        raise ValueError(
            f'No matches computed for group pair {pair!r}. '
            'Call compute_matches() for this pair first.'
        )

    q_names = (
        query_names if query_names is not None else list(self._groups[query_group])
    )
    t_names = (
        target_names
        if target_names is not None
        else list(self._groups[target_group])
    )
    # Order and reverse-orientation both come from the stranded matches;
    # the resulting order matches SequenceIndex.optimal_contig_order by
    # construction.
    records = self._stranded_records(query_group, target_group, q_names, t_names)
    sorted_q, sorted_t, reversed_q = compute_gravity_contigs(
        records, q_names, t_names
    )
    self._reversed[query_group] = reversed_q
    return sorted_q, sorted_t

__repr__()

Return a concise machine-readable representation.

Returns:

Type Description
str

CrossIndex(k=<k>, groups={<label>=<n>, ...}).

Source code in dot_explorer/paf_io.py
def __repr__(self) -> str:
    """Return a concise machine-readable representation.

    Returns
    -------
    str
        ``CrossIndex(k=<k>, groups={<label>=<n>, ...})``.
    """
    group_info = ', '.join(f'{g}={len(names)}' for g, names in self._groups.items())
    return f'CrossIndex(k={self._k}, groups={{{group_info}}})'

__str__()

Return a human-readable stats summary.

Returns:

Type Description
str

Multi-line summary of groups, sequence counts, computed pairs, and cached PAF record count.

Source code in dot_explorer/paf_io.py
def __str__(self) -> str:
    """Return a human-readable stats summary.

    Returns
    -------
    str
        Multi-line summary of groups, sequence counts, computed pairs,
        and cached PAF record count.
    """
    n_total = sum(len(v) for v in self._groups.values())
    lines = [f'CrossIndex (k={self._k})']
    lines.append(f'  Total sequences : {n_total}')
    for g, names in self._groups.items():
        lines.append(f'  Group {g!r:12s}: {len(names):>6d} sequences')
    if self._records_by_pair:
        for (qg, tg), recs in self._records_by_pair.items():
            lines.append(
                f'  Computed pair   : ({qg!r}, {tg!r}) → {len(recs)} record(s)'
            )
    else:
        lines.append('  Computed pairs  : none (call compute_matches() first)')
    lines.append(f'  PAF records     : {len(self._paf_records)}')
    return '\n'.join(lines)