panaxis 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
panaxis/consensus.py ADDED
@@ -0,0 +1,688 @@
1
+ """Infer chromosome-wise consensus HOG orders from oriented accession paths."""
2
+
3
+ from bisect import bisect_left, bisect_right
4
+ from collections import Counter, defaultdict
5
+ from dataclasses import dataclass, field, replace
6
+ from heapq import heapify, heappop, heappush
7
+ from math import floor
8
+ from statistics import median
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class Placement:
13
+ """One candidate location relative to the chromosome's backbone."""
14
+
15
+ hog: str
16
+ position: float | None
17
+ left_anchor: str | None = None
18
+ right_anchor: str | None = None
19
+ paired_accessions: tuple[str, ...] = ()
20
+ wide_interval_accessions: tuple[str, ...] = ()
21
+ one_sided_accessions: tuple[str, ...] = ()
22
+ core_anchor: bool = False
23
+ local_order_accessions: tuple[str, ...] = ()
24
+
25
+ @property
26
+ def evidence_weight(self):
27
+ return (
28
+ len(self.paired_accessions)
29
+ + 0.5 * len(self.wide_interval_accessions)
30
+ + 0.25 * len(self.one_sided_accessions)
31
+ )
32
+
33
+
34
+ @dataclass
35
+ class ChromosomeConsensus:
36
+ """Backbone, possible placements, and the edges removed to break cycles."""
37
+
38
+ chromosome: str
39
+ accessions: tuple[str, ...]
40
+ backbone: tuple[str, ...]
41
+ placements: list[Placement]
42
+ removed_edges: dict[tuple[str, str], tuple[str, ...]]
43
+ chromosome_support: dict[str, int] = field(default_factory=dict)
44
+ local_removed_edges: dict[int, dict[tuple[str, str], tuple[str, ...]]] = field(default_factory=dict)
45
+
46
+
47
+ def _adjacency_support(paths):
48
+ support = defaultdict(set)
49
+ for acc, path in paths.items():
50
+ counts = Counter(path)
51
+ # Adjacent tandem copies collapse to one run. Dispersed copies remain
52
+ # available for placement but cannot unambiguously anchor this path.
53
+ unambiguous = [hog for hog in path if counts[hog] == 1]
54
+ for edge in zip(unambiguous, unambiguous[1:]):
55
+ support[edge].add(acc)
56
+ return support
57
+
58
+
59
+ def _reaches(graph, start, target):
60
+ stack = [start]
61
+ seen = {start}
62
+ while stack:
63
+ node = stack.pop()
64
+ if node == target:
65
+ return True
66
+ for neighbor in graph[node]:
67
+ if neighbor not in seen:
68
+ seen.add(neighbor)
69
+ stack.append(neighbor)
70
+ return False
71
+
72
+
73
+ def _remove_cycles(nodes, support):
74
+ graph = {hog: {} for hog in sorted(nodes)}
75
+ removed = {}
76
+ # Keep the best-supported edges first. The reverse vote breaks ties in
77
+ # support among edges with stronger and weaker directional agreement.
78
+ edges = sorted(support, key=lambda edge: (
79
+ -len(support[edge]), len(support.get(edge[::-1], ())), edge,
80
+ ))
81
+ for source, target in edges:
82
+ if _reaches(graph, target, source):
83
+ removed[source, target] = tuple(sorted(support[source, target]))
84
+ else:
85
+ graph[source][target] = len(support[source, target])
86
+ return graph, removed
87
+
88
+
89
+ def _longest_backbone(graph, min_backbone_support):
90
+ if not graph:
91
+ return ()
92
+ indegrees = dict.fromkeys(graph, 0)
93
+ for neighbors in graph.values():
94
+ for target in neighbors:
95
+ indegrees[target] += 1
96
+
97
+ ready = [hog for hog in graph if indegrees[hog] == 0]
98
+ scores = dict.fromkeys(graph, (0, 0, 1))
99
+ previous = {}
100
+ while ready:
101
+ node = ready.pop()
102
+ shared, total, length = scores[node]
103
+ for target, support in graph[node].items():
104
+ score = (
105
+ shared + (support if support >= min_backbone_support else 0),
106
+ total + support,
107
+ length + 1,
108
+ )
109
+ if score > scores[target]:
110
+ scores[target] = score
111
+ previous[target] = node
112
+ indegrees[target] -= 1
113
+ if indegrees[target] == 0:
114
+ ready.append(target)
115
+
116
+ node = max(scores, key=scores.get)
117
+ path = [node]
118
+ while node in previous:
119
+ node = previous[node]
120
+ path.append(node)
121
+ return tuple(reversed(path))
122
+
123
+
124
+ def _path_locations(path, ranks):
125
+ """Yield a position and the quarter votes supported by each occurrence."""
126
+ counts = Counter(path)
127
+ anchor_indices = [
128
+ index for index, hog in enumerate(path) if hog in ranks and counts[hog] == 1
129
+ ]
130
+ next_anchor = iter(anchor_indices)
131
+ right = next(next_anchor, len(path))
132
+ left = -1
133
+ for index, hog in enumerate(path):
134
+ is_anchor = index == right
135
+ if is_anchor:
136
+ right = next(next_anchor, len(path))
137
+ low = ranks[path[left]] if left >= 0 else None
138
+ high = ranks[path[right]] if right < len(path) else None
139
+ rank = ranks.get(hog)
140
+ if low is not None and high is not None and low < high:
141
+ projected = low + (high - low) * (index - left) / (right - left)
142
+ if rank is not None and low < rank < high:
143
+ votes = 4 if high - low == 2 else 2
144
+ yield hog, float(rank), votes, True
145
+ else:
146
+ votes = 4 if high - low == 1 else 2
147
+ yield hog, projected, votes, False
148
+ elif low is not None and high is None:
149
+ if rank == low + 1:
150
+ yield hog, float(rank), 1, True
151
+ else:
152
+ yield hog, low + (index - left) / (len(path) - left), 1, False
153
+ elif low is None and high is not None:
154
+ if rank == high - 1:
155
+ yield hog, float(rank), 1, True
156
+ else:
157
+ yield hog, high - 1 + (index + 1) / (right + 1), 1, False
158
+ if is_anchor:
159
+ left = index
160
+
161
+
162
+ def _order_within_gap(placements, observations, min_local_support):
163
+ by_hog = {placement.hog: placement for placement in placements}
164
+ paths = {
165
+ acc: [hog for _, hog in sorted(entries)]
166
+ for acc, entries in observations.items()
167
+ }
168
+ support = {
169
+ edge: accessions for edge, accessions in _adjacency_support(paths).items()
170
+ if len(accessions) >= min_local_support
171
+ }
172
+ if not support:
173
+ return placements, {}
174
+ graph, removed = _remove_cycles(by_hog, support)
175
+ indegrees = dict.fromkeys(graph, 0)
176
+ local_support = defaultdict(set)
177
+ for node, neighbors in graph.items():
178
+ for neighbor in neighbors:
179
+ indegrees[neighbor] += 1
180
+ local_support[node].update(support[node, neighbor])
181
+ local_support[neighbor].update(support[node, neighbor])
182
+ ready = [(by_hog[hog].position, hog) for hog, degree in indegrees.items() if degree == 0]
183
+ heapify(ready)
184
+ ordered = []
185
+ gap = floor(placements[0].position)
186
+ while ready:
187
+ _, hog = heappop(ready)
188
+ position = gap + (len(ordered) + 1) / (len(by_hog) + 1)
189
+ ordered.append(replace(
190
+ by_hog[hog], position=position,
191
+ local_order_accessions=tuple(sorted(local_support[hog])),
192
+ ))
193
+ for neighbor in graph[hog]:
194
+ indegrees[neighbor] -= 1
195
+ if indegrees[neighbor] == 0:
196
+ heappush(ready, (by_hog[neighbor].position, neighbor))
197
+ return ordered, removed
198
+
199
+
200
+ def _candidate_placements(paths, backbone, *, min_local_support=None):
201
+ ranks = {hog: index for index, hog in enumerate(backbone, start=1)}
202
+ anchored = min_local_support is not None
203
+ observations = defaultdict(lambda: defaultdict(list))
204
+ for acc, path in paths.items():
205
+ for hog, position, votes, on_backbone in _path_locations(path, ranks):
206
+ if anchored and hog in ranks and not on_backbone:
207
+ continue
208
+ slot = int(position) if on_backbone else floor(position)
209
+ observations[hog, slot, on_backbone][acc].append((votes, position))
210
+
211
+ if anchored:
212
+ for hog, rank in ranks.items():
213
+ observations.setdefault((hog, rank, True), {})
214
+
215
+ placements = []
216
+ by_gap = defaultdict(list)
217
+ local_paths = defaultdict(lambda: defaultdict(list))
218
+ located_hogs = {hog for hog, _, _ in observations}
219
+ for (hog, slot, on_backbone), by_accession in sorted(observations.items()):
220
+ supporters = {4: [], 2: [], 1: []}
221
+ positions = {4: [], 2: [], 1: []}
222
+ for acc, entries in sorted(by_accession.items()):
223
+ best_votes = max(votes for votes, _ in entries)
224
+ supporters[best_votes].append(acc)
225
+ estimates = [value for votes, value in entries if votes == best_votes]
226
+ positions[best_votes].append(median(estimates))
227
+ if anchored and not on_backbone and best_votes == 4 and len(set(estimates)) == 1:
228
+ local_paths[slot][acc].append((estimates[0], hog))
229
+
230
+ if on_backbone:
231
+ position = float(slot)
232
+ left_index, right_index = slot - 2, slot
233
+ else:
234
+ # Integer coordinates belong to backbone HOGs. Place insertions
235
+ # strictly inside their projected gap, including exact projections.
236
+ position = max(slot + 1e-6, median(positions[4] or positions[2] or positions[1]))
237
+ left_index, right_index = slot - 1, slot
238
+ left_anchor = backbone[left_index] if left_index >= 0 else None
239
+ right_anchor = backbone[right_index] if right_index < len(backbone) else None
240
+ placement = Placement(
241
+ hog, position, left_anchor, right_anchor,
242
+ tuple(supporters[4]), tuple(supporters[2]), tuple(supporters[1]),
243
+ core_anchor=anchored and on_backbone,
244
+ local_order_accessions=tuple(supporters[4]) if anchored and on_backbone else (),
245
+ )
246
+ if anchored and not on_backbone:
247
+ by_gap[slot].append(placement)
248
+ else:
249
+ placements.append(placement)
250
+ local_removed = {}
251
+ for slot, entries in sorted(by_gap.items()):
252
+ ordered, removed = _order_within_gap(entries, local_paths[slot], min_local_support)
253
+ placements.extend(ordered)
254
+ if removed:
255
+ local_removed[slot] = removed
256
+ # A disconnected HOG still has a display chromosome but lacks a location.
257
+ observed_hogs = {hog for path in paths.values() for hog in path}
258
+ placements.extend(Placement(hog, None) for hog in sorted(observed_hogs - located_hogs))
259
+ return placements, local_removed
260
+
261
+
262
+ def infer_chromosome_order(
263
+ chromosome, paths, min_backbone_support=2, *,
264
+ core_anchors=None, min_local_support=2, method="anchored",
265
+ ):
266
+ """Infer one chromosome's order with a fixed core and local accession graphs.
267
+
268
+ Workflow
269
+ --------
270
+ Rank common single-copy anchors by their median within-core rank. Keep
271
+ their order fixed, project other occurrences into these intervals, and
272
+ resolve local precedence conflicts within each interval.
273
+
274
+ Parameters
275
+ ----------
276
+ chromosome : str
277
+ Name of the homologous chromosome.
278
+ paths : mapping of str to sequence of str
279
+ One oriented HOG path per accession, sorted in chromosomal order from
280
+ original annotations. Harmonize chromosome identities and directions
281
+ upstream. Keep repeat occurrences in the input. An empty path is allowed.
282
+ min_backbone_support : int
283
+ Primary path support threshold when using method="adjacency".
284
+ core_anchors : iterable of str or None
285
+ Supply HOGs already verified to occur exactly once on this chromosome
286
+ in each nonempty path. To exclude copies elsewhere in the genome,
287
+ pass a genome-wide single-copy set for this chromosome. The default
288
+ computes single-copy support from the supplied chromosome paths.
289
+ min_local_support : int
290
+ Distinct accessions required for an edge within an anchor interval.
291
+ Only accession paths with both adjacent anchors vote on local order.
292
+ method : {"anchored", "adjacency"}
293
+ Use the fixed-anchor method or reproduce the previous whole-chromosome
294
+ adjacency path as a comparison baseline.
295
+
296
+ Returns
297
+ -------
298
+ ChromosomeConsensus
299
+ Backbones, candidate placements, and rejected edges. In anchored mode
300
+ a chromosome lacking shared anchors keeps only zero-score placeholders.
301
+ No files are read or written.
302
+ """
303
+ if min(min_backbone_support, min_local_support) < 1:
304
+ raise ValueError("Support thresholds must be positive.")
305
+ if method not in {"anchored", "adjacency"}:
306
+ raise ValueError("method must be 'anchored' or 'adjacency'.")
307
+ chromosome_support = Counter(hog for path in paths.values() for hog in set(path))
308
+ if method == "anchored":
309
+ single_copy = [
310
+ {hog for hog, count in Counter(path).items() if count == 1}
311
+ for path in paths.values() if path
312
+ ]
313
+ shared = set.intersection(*single_copy) if single_copy else set()
314
+ anchors = shared if core_anchors is None else set(core_anchors)
315
+ if not anchors <= shared:
316
+ raise ValueError(f"{chromosome}: core anchors must be single-copy in every nonempty path.")
317
+ anchor_ranks = defaultdict(list)
318
+ for path in paths.values():
319
+ for rank, hog in enumerate(hog for hog in path if hog in anchors):
320
+ anchor_ranks[hog].append(rank)
321
+ backbone = tuple(sorted(anchors, key=lambda hog: (
322
+ median(anchor_ranks[hog]), sum(anchor_ranks[hog]), hog,
323
+ )))
324
+ placements, local_removed = _candidate_placements(
325
+ paths, backbone, min_local_support=min_local_support,
326
+ )
327
+ return ChromosomeConsensus(
328
+ chromosome, tuple(sorted(paths)), backbone, placements, {}, dict(chromosome_support), local_removed,
329
+ )
330
+
331
+ paths = {
332
+ acc: tuple(hog for index, hog in enumerate(path) if index == 0 or hog != path[index - 1])
333
+ for acc, path in paths.items()
334
+ }
335
+ nodes = {hog for path in paths.values() for hog in path}
336
+ graph, removed = _remove_cycles(nodes, _adjacency_support(paths))
337
+ backbone = _longest_backbone(graph, min_backbone_support)
338
+ placements, _ = _candidate_placements(paths, backbone)
339
+ return ChromosomeConsensus(
340
+ chromosome, tuple(sorted(paths)), backbone, placements, removed, dict(chromosome_support),
341
+ )
342
+
343
+
344
+ def assemble_consensus(chromosome_results, all_hogs, fallback_chromosome=None):
345
+ """Select one placement per HOG across independently inferred chromosomes.
346
+
347
+ Parameters
348
+ ----------
349
+ chromosome_results : iterable of ChromosomeConsensus
350
+ Results in the desired chromosome display order. Chromosome names must
351
+ be unique. Use all accessions across which scores should be comparable.
352
+ all_hogs : iterable of str
353
+ Full HOG inventory. HOGs absent from the input paths are included.
354
+ fallback_chromosome : str or None
355
+ Display chromosome for HOGs absent from all paths. The first supplied
356
+ chromosome is the default. These HOGs have no inferred position.
357
+
358
+ Returns
359
+ -------
360
+ order, candidates : tuple of lists of dict
361
+ The final unique HOG order and an audit table of candidate positions.
362
+ Scores are on a 0–100 scale using the union of input accessions as the
363
+ denominator. A tight pair of flanks contributes one vote. A pair
364
+ spanning additional backbone HOGs contributes half a vote, and a
365
+ single flank contributes a quarter vote. Each accession contributes
366
+ at most once per candidate. Core anchors take precedence over projected
367
+ candidates. Chromosome, interval, and local order support are recorded
368
+ separately. Zero-score placeholders are retained in the final order.
369
+ """
370
+ results = list(chromosome_results)
371
+ chromosomes = [result.chromosome for result in results]
372
+ if not chromosomes or len(chromosomes) != len(set(chromosomes)):
373
+ raise ValueError("Provide at least one result and unique chromosome names.")
374
+ if fallback_chromosome is None:
375
+ fallback_chromosome = chromosomes[0]
376
+ chromosome_index = {chromosome: index for index, chromosome in enumerate(chromosomes)}
377
+ if fallback_chromosome not in chromosome_index:
378
+ raise ValueError("fallback_chromosome must be among the supplied chromosomes.")
379
+
380
+ accessions = {acc for result in results for acc in result.accessions}
381
+ chromosome_support = {result.chromosome: result.chromosome_support for result in results}
382
+ by_hog = defaultdict(list)
383
+ for result in results:
384
+ for placement in result.placements:
385
+ by_hog[placement.hog].append((result.chromosome, placement))
386
+ for hog in set(all_hogs) - by_hog.keys():
387
+ by_hog[hog].append((fallback_chromosome, Placement(hog, None)))
388
+
389
+ order = []
390
+ candidates = []
391
+ for hog, locations in sorted(by_hog.items()):
392
+ locations.sort(key=lambda entry: (
393
+ not entry[1].core_anchor, -entry[1].evidence_weight, -len(entry[1].paired_accessions),
394
+ entry[1].position is None, chromosome_index[entry[0]],
395
+ float("inf") if entry[1].position is None else entry[1].position,
396
+ ))
397
+ for index, (chromosome, placement) in enumerate(locations):
398
+ supporters = (
399
+ *placement.paired_accessions, *placement.wide_interval_accessions,
400
+ *placement.one_sided_accessions,
401
+ )
402
+ if placement.paired_accessions:
403
+ evidence = "two_flanks"
404
+ elif placement.wide_interval_accessions:
405
+ evidence = "wide_interval"
406
+ elif supporters:
407
+ evidence = "one_flank"
408
+ elif placement.core_anchor:
409
+ evidence = "core_rank_only"
410
+ else:
411
+ evidence = "placeholder"
412
+ row = {
413
+ "hog": hog, "chromosome": chromosome, "position": placement.position,
414
+ "left_anchor": placement.left_anchor, "right_anchor": placement.right_anchor,
415
+ "score": 100 * placement.evidence_weight / max(1, len(accessions)),
416
+ "n_support": len(supporters), "n_tight_flanks": len(placement.paired_accessions),
417
+ "n_wide_interval": len(placement.wide_interval_accessions),
418
+ "n_chromosome_support": chromosome_support[chromosome].get(hog, 0),
419
+ "n_local_order_support": len(placement.local_order_accessions),
420
+ "core_anchor": placement.core_anchor,
421
+ "supporting_accessions": tuple(sorted(supporters)),
422
+ "evidence": evidence, "selected": index == 0,
423
+ }
424
+ candidates.append(row)
425
+ if index == 0:
426
+ order.append(row.copy())
427
+
428
+ order.sort(key=lambda row: (
429
+ chromosome_index[row["chromosome"]], row["position"] is None,
430
+ row["position"], row["hog"],
431
+ ))
432
+ ranks = Counter()
433
+ for row in order:
434
+ ranks[row["chromosome"]] += 1
435
+ row["rank"] = ranks[row["chromosome"]]
436
+ return order, candidates
437
+
438
+
439
+ @dataclass(frozen=True)
440
+ class CollinearityBlock:
441
+ """Ordered rank pairs and collinear path statistics for one chromosome pair."""
442
+
443
+ pairs: tuple[tuple[int, int], ...]
444
+ strand: str
445
+ pvalue: float
446
+ score: float
447
+
448
+
449
+ def _score_collinear_paths(points, order, direction, max_gap, gap_penalty):
450
+ """Propagate anchor-chain scores in one orientation and retain predecessor links."""
451
+ x_order = [direction * points[index][0] for index in order]
452
+ scores = [50.0] * len(points)
453
+ parent = [-1] * len(points)
454
+ used = set()
455
+ for index in order:
456
+ x, y = points[index]
457
+ x *= direction
458
+ start = bisect_right(x_order, x)
459
+ stop = bisect_left(x_order, x + max_gap, lo=start)
460
+ best_gap = max_gap
461
+ previous_x = x
462
+ for cursor in range(start, stop):
463
+ other = order[cursor]
464
+ next_x, next_y = points[other]
465
+ next_x *= direction
466
+ delta_y = next_y - y
467
+ if not 0 < delta_y < max_gap:
468
+ continue
469
+ if delta_y > best_gap and next_x > previous_x:
470
+ break
471
+ gain = 50 + (next_x - x + delta_y) * gap_penalty
472
+ score = scores[index] + gain
473
+ if gain > 0 and score > scores[other]:
474
+ scores[other] = score
475
+ parent[other] = index
476
+ used.update((index, other))
477
+ best_gap = min(best_gap, delta_y)
478
+ previous_x = next_x
479
+ return scores, parent, used
480
+
481
+
482
+ def find_collinear_blocks(
483
+ loc_pair_list, min_size=5, max_gap=25, max_pvalue=1.0, min_score=50,
484
+ gap_penalty=-1, coverage_ratio=0.8,
485
+ ):
486
+ """Find forward and reverse collinear chains for one chromosome pair.
487
+
488
+ Uses the rank-based chaining logic from yxcompgen's synteny_block.py: fixed
489
+ anchor grading, bounded transitions with gap penalties, and path selection
490
+ by score and remaining coverage. Equal scores use input anchor order.
491
+
492
+ Parameters
493
+ ----------
494
+ loc_pair_list : iterable of pairs of int
495
+ Query and subject gene ranks. Distinct copies may share a rank on one
496
+ axis. Supply one chromosome pair at a time.
497
+ min_size, max_gap, max_pvalue, min_score : number
498
+ Reporting filters and the exclusive maximum allowed rank gap on either
499
+ axis. Extraction requires at least five anchors, as in the source.
500
+ gap_penalty : float
501
+ Non-positive cost per rank step on either axis.
502
+ coverage_ratio : float
503
+ Fraction of a chain that must remain after previously reported chains
504
+ in the same orientation have claimed anchors. The cutoff is exclusive.
505
+
506
+ Returns
507
+ -------
508
+ list of CollinearityBlock
509
+ Rank pairs in increasing query order, strand, block compactness statistic
510
+ (pvalue), and chain score. No files are read or written.
511
+ """
512
+ points = sorted(((x, y) for x, y in loc_pair_list), key=lambda pair: pair[0])
513
+ x_values = [pair[0] for pair in points]
514
+ times = [1] * len(points)
515
+ blocks = []
516
+ ascending = range(len(points))
517
+ descending = sorted(ascending, key=lambda index: (-points[index][0], points[index][1]))
518
+ for direction, order in ((1, ascending), (-1, descending)):
519
+ scores, parent, active = _score_collinear_paths(points, order, direction, max_gap, gap_penalty)
520
+ endpoints = sorted(active, key=lambda index: (-scores[index], index))
521
+ for end in endpoints:
522
+ if end not in active:
523
+ continue
524
+ remaining = []
525
+ length = 0
526
+ node = end
527
+ while node != -1:
528
+ length += 1
529
+ if node in active:
530
+ remaining.append(node)
531
+ node = parent[node]
532
+ if length < 5 or len(remaining) / length <= coverage_ratio:
533
+ active.remove(end)
534
+ continue
535
+
536
+ active.difference_update(remaining)
537
+ pairs = tuple(sorted(points[index] for index in remaining))
538
+ x_min, x_max = pairs[0][0], pairs[-1][0]
539
+ y_min, y_max = min(y for _, y in pairs), max(y for _, y in pairs)
540
+ width, height = x_max - x_min + 1, y_max - y_min + 1
541
+ box = [
542
+ index for index in range(bisect_left(x_values, x_min), bisect_right(x_values, x_max))
543
+ if y_min <= points[index][1] <= y_max
544
+ ]
545
+ count = len(remaining)
546
+ score = scores[end]
547
+ # Count previous uses of all candidate anchors in this box.
548
+ multiplicity = sum(times[index] for index in box)
549
+ for index in box:
550
+ times[index] += 1
551
+ pvalue = round(
552
+ (1 - score / count / 50) * (multiplicity - count + 1) / len(box)
553
+ * (width - count + 1) * (height - count + 1) / width / height, 4,
554
+ )
555
+ if count >= min_size and pvalue <= min(max_pvalue, 1) and score >= min_score:
556
+ blocks.append(CollinearityBlock(pairs, "+" if direction == 1 else "-", pvalue, score))
557
+ return blocks
558
+
559
+
560
+ def compare_consensus_collinearity(consensus_order, accession_paths, **block_options):
561
+ """Compare the consensus with one accession using every original HOG copy.
562
+
563
+ Parameters
564
+ ----------
565
+ consensus_order : iterable of dict
566
+ Main table from assemble_consensus. Only HOGs with a positive score
567
+ are eligible anchors. Their full display ranks remain the query axis.
568
+ accession_paths : mapping of str to sequence of str
569
+ Chromosome-to-HOG paths in original accession order. Each occurrence,
570
+ including tandem copies, counts as one accession rank.
571
+ **block_options
572
+ Keyword arguments forwarded to find_collinear_blocks.
573
+
574
+ Returns
575
+ -------
576
+ dict
577
+ Nonempty block lists keyed by (consensus chromosome, accession
578
+ chromosome). The two axes use 1-based ranks.
579
+ """
580
+ consensus_by_hog = {
581
+ row["hog"]: (row["chromosome"], row["rank"])
582
+ for row in consensus_order if row["score"] > 0
583
+ }
584
+ pairs = defaultdict(list)
585
+ for chromosome, path in accession_paths.items():
586
+ for rank, hog in enumerate(path, start=1):
587
+ if hog in consensus_by_hog:
588
+ consensus_chr, consensus_rank = consensus_by_hog[hog]
589
+ pairs[consensus_chr, chromosome].append((consensus_rank, rank))
590
+
591
+ result = {}
592
+ for chromosomes, anchors in sorted(pairs.items()):
593
+ blocks = find_collinear_blocks(anchors, **block_options)
594
+ if blocks:
595
+ result[chromosomes] = blocks
596
+ return result
597
+
598
+
599
+ def plot_collinearity_dotplot(segments, consensus_sizes, accession_sizes, accession_name):
600
+ """Draw chromosome grids and top/left span depth for called collinear blocks.
601
+
602
+ Parameters
603
+ ----------
604
+ segments : iterable of dict
605
+ Rows contain consensus_chr, accession_chr, xstart, xend, ystart, yend,
606
+ and layer (foreground or background). Local rank spans are inclusive.
607
+ consensus_sizes, accession_sizes : mapping of str to int
608
+ Chromosome lengths in gene ranks, in the desired display order.
609
+ accession_name : str
610
+ Label for the vertical axis.
611
+
612
+ Returns
613
+ -------
614
+ matplotlib.figure.Figure
615
+ Blue shows retained blocks over the gray full block set. The margins
616
+ overlay retained depth in coral on full depth in gray.
617
+ """
618
+ import matplotlib.pyplot as plt
619
+ import numpy as np
620
+ from matplotlib.collections import LineCollection
621
+ from matplotlib.ticker import MaxNLocator
622
+
623
+ x_chromosomes, y_chromosomes = list(consensus_sizes), list(accession_sizes)
624
+ x_edges = np.r_[0, np.cumsum(list(consensus_sizes.values()))]
625
+ y_edges = np.r_[0, np.cumsum(list(accession_sizes.values()))]
626
+ x_offsets, y_offsets = dict(zip(x_chromosomes, x_edges)), dict(zip(y_chromosomes, y_edges))
627
+ all_lines, retained_lines = [], []
628
+ depths = np.zeros((2, x_edges[-1] + 1)), np.zeros((2, y_edges[-1] + 1))
629
+ for segment in segments:
630
+ x_offset = x_offsets[segment["consensus_chr"]]
631
+ y_offset = y_offsets[segment["accession_chr"]]
632
+ x1, x2 = x_offset + segment["xstart"], x_offset + segment["xend"]
633
+ y1, y2 = y_offset + segment["ystart"], y_offset + segment["yend"]
634
+ line = [(x1 - 0.5, y1 - 0.5), (x2 - 0.5, y2 - 0.5)]
635
+ all_lines.append(line)
636
+ retained = segment["layer"] == "foreground"
637
+ if retained:
638
+ retained_lines.append(line)
639
+ for values, first, last in ((depths[0], x1, x2), (depths[1], y1, y2)):
640
+ lo, hi = sorted((first, last))
641
+ values[0, lo - 1] += 1
642
+ values[0, hi] -= 1
643
+ if retained:
644
+ values[1, lo - 1] += 1
645
+ values[1, hi] -= 1
646
+
647
+ fig = plt.figure(figsize=(8, 8))
648
+ grid = fig.add_gridspec(
649
+ 2, 2, width_ratios=(0.065, 1), height_ratios=(0.065, 1),
650
+ left=0.072, right=0.884, bottom=0.092, top=0.955, wspace=0.025, hspace=0.025,
651
+ )
652
+ main = fig.add_subplot(grid[1, 1])
653
+ top = fig.add_subplot(grid[0, 1], sharex=main)
654
+ left = fig.add_subplot(grid[1, 0], sharey=main)
655
+ for x in x_edges[1:-1]:
656
+ main.axvline(x, color="#999999", linewidth=0.5, zorder=0)
657
+ for y in y_edges[1:-1]:
658
+ main.axhline(y, color="#999999", linewidth=0.5, zorder=0)
659
+ main.add_collection(LineCollection(all_lines, colors="#AEAEAE", linewidths=1.1))
660
+ main.add_collection(LineCollection(retained_lines, colors="#1F77B4", linewidths=1.35))
661
+ main.set_xlim(0, x_edges[-1])
662
+ main.set_ylim(y_edges[-1], 0)
663
+ main.set_xticks((x_edges[1:] + x_edges[:-1]) / 2, x_chromosomes)
664
+ main.set_yticks((y_edges[1:] + y_edges[:-1]) / 2, y_chromosomes)
665
+ main.yaxis.tick_right()
666
+ main.yaxis.set_label_position("right")
667
+ main.tick_params(length=0, pad=5)
668
+ main.set_xlabel("Sorghum consensus HOG order", labelpad=9, fontsize=15)
669
+ main.set_ylabel(accession_name, labelpad=10, fontsize=15)
670
+
671
+ for axis, changes, horizontal in ((top, depths[0], True), (left, depths[1], False)):
672
+ full, retained = np.cumsum(changes, axis=1)[:, :-1]
673
+ edges = np.arange(len(full) + 1)
674
+ for depth, color in ((full, "#AEAEAE"), (retained, "#F8766D")):
675
+ axis.stairs(depth, edges, fill=True, color=color, linewidth=0,
676
+ orientation="vertical" if horizontal else "horizontal")
677
+ depth_limit = max(1, int(full.max()))
678
+ if horizontal:
679
+ axis.set_ylim(0, depth_limit * 1.04)
680
+ axis.tick_params(axis="x", bottom=False, labelbottom=False)
681
+ axis.yaxis.set_major_locator(MaxNLocator(3, integer=True, prune="upper"))
682
+ else:
683
+ axis.set_xlim(depth_limit * 1.04, 0)
684
+ axis.tick_params(axis="y", left=False, labelleft=False)
685
+ axis.xaxis.set_major_locator(MaxNLocator(3, integer=True, prune="upper"))
686
+ axis.tick_params(length=2, pad=1, labelsize=8)
687
+ axis.spines[["top", "right"]].set_visible(False)
688
+ return fig