-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathselective-rerip-tiny-hyper-graph-solver.ts
More file actions
820 lines (763 loc) · 27.2 KB
/
Copy pathselective-rerip-tiny-hyper-graph-solver.ts
File metadata and controls
820 lines (763 loc) · 27.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
import {
createEmptyRegionIntersectionCache,
type Candidate,
type TinyHyperGraphProblem,
type TinyHyperGraphSolverOptions,
type TinyHyperGraphTopology,
} from "./core"
import { OutsideInPartialRipTinyHyperGraphSolver } from "./outside-in-partial-rip-tiny-hypergraph-solver"
import type { DistinctOwnerBlockerSearchResult } from "./find-distinct-owner-blocker-path"
import { findResourceBlockerPath } from "./findResourceBlockerPath"
import type { NetId, PortId, RegionId, RouteId } from "./types"
import { PortDistanceQueue } from "./PortDistanceQueue"
type RelaxedSearchState = {
portId: PortId
nextRegionId: RegionId
}
type CommittedCrossingGeometry = {
ownerRouteId: RouteId
lesserAngle: number
greaterAngle: number
layerMask: number
}
type PortDistanceSearch = {
costs: Float64Array
settled: Uint8Array
blockedPorts: Uint8Array
queue: PortDistanceQueue
}
type PortBlockerResource = {
kind: "port"
portId: PortId
owners: RouteId[]
}
type SameLayerIntersectionBlockerResource = {
kind: "same_layer_intersection"
regionId: RegionId
fromPortId: PortId
toPortId: PortId
owners: RouteId[]
}
export type SelectiveReripBlockerResource =
| PortBlockerResource
| SameLayerIntersectionBlockerResource
type RelaxedSearchHopData = {
resources: SelectiveReripBlockerResource[]
}
export type FailedOwnerPairCount = {
failedRouteId: RouteId
ownerRouteId: RouteId
count: number
}
export type SelectiveReripTinyHyperGraphStats = {
selectiveRipCount: number
selectivelyRippedRouteCount: number
globalReripCount: number
globalReripReason?:
| "no_path"
| "expansion_limit"
| "no_blocker_path"
| "failed_owner_cycle"
alternateBlockerSearchCount: number
alternateOwnerCount: number
failedOwnerPairCount: number
maxFailedOwnerPairCount: number
failedOwnerPairs: FailedOwnerPairCount[]
lastFailedRouteId?: RouteId
lastDirectOwnerRouteIds: RouteId[]
lastRepeatedOwnerRouteIds: RouteId[]
lastAlternateOwnerRouteIds: RouteId[]
lastRippedRouteIds: RouteId[]
lastRelaxedSearchExpandedLabelCount: number
lastAlternateSearchExpandedLabelCount: number
}
const createInitialSelectiveReripStats =
(): SelectiveReripTinyHyperGraphStats => ({
selectiveRipCount: 0,
selectivelyRippedRouteCount: 0,
globalReripCount: 0,
alternateBlockerSearchCount: 0,
alternateOwnerCount: 0,
failedOwnerPairCount: 0,
maxFailedOwnerPairCount: 0,
failedOwnerPairs: [],
lastDirectOwnerRouteIds: [],
lastRepeatedOwnerRouteIds: [],
lastAlternateOwnerRouteIds: [],
lastRippedRouteIds: [],
lastRelaxedSearchExpandedLabelCount: 0,
lastAlternateSearchExpandedLabelCount: 0,
})
export function orderConnectionsByNetCardinality<TConnection>(
connections: readonly TConnection[],
getNetId: (connection: TConnection) => string | number,
): TConnection[] {
const connectionCountByNetId = new Map<string | number, number>()
for (const connection of connections) {
const netId = getNetId(connection)
connectionCountByNetId.set(
netId,
(connectionCountByNetId.get(netId) ?? 0) + 1,
)
}
return connections
.map((connection, index) => ({ connection, index }))
.sort(
(left, right) =>
(connectionCountByNetId.get(getNetId(right.connection)) ?? 0) -
(connectionCountByNetId.get(getNetId(left.connection)) ?? 0) ||
left.index - right.index,
)
.map(({ connection }) => connection)
}
export function selectOwnerRouteIdsToRip(params: {
failedRouteId: RouteId
directOwnerRouteIds: readonly RouteId[]
alternateOwnerRouteIds?: readonly RouteId[]
}): Set<RouteId> {
const rippedRouteIds = new Set<RouteId>(
params.alternateOwnerRouteIds ?? params.directOwnerRouteIds,
)
rippedRouteIds.delete(params.failedRouteId)
if (rippedRouteIds.size === 0) {
throw new Error(
`SelectiveReripTinyHyperGraphSolver: route ${params.failedRouteId} has blocker resources but no distinct committed owner can be reripped`,
)
}
return rippedRouteIds
}
export function orderRoutesAfterSelectiveRerip(params: {
failedRouteId: RouteId
pendingRouteIds: readonly RouteId[]
rippedRouteIds: ReadonlySet<RouteId>
}): RouteId[] {
const pendingRouteIds = params.pendingRouteIds.filter(
(routeId) =>
routeId !== params.failedRouteId && !params.rippedRouteIds.has(routeId),
)
const rippedRouteIds = [...params.rippedRouteIds].filter(
(routeId) => routeId !== params.failedRouteId,
)
return [params.failedRouteId, ...pendingRouteIds, ...rippedRouteIds]
}
/**
* Keeps the normal tiny-hypergraph route acceptance policy while replacing a
* full rerip with a local repair of the occupied resources blocking a route.
* Committing the cleared witness preserves progress while congestion history
* encourages later repairs to use different local resources.
*/
export class SelectiveReripTinyHyperGraphSolver extends OutsideInPartialRipTinyHyperGraphSolver {
private readonly blockerResourceHistory = new Map<string, number>()
private readonly staticPortCostsByNetAndGoal = new Map<
NetId,
Map<PortId, PortDistanceSearch>
>()
private readonly failedOwnerPairCounts = new Map<
RouteId,
Map<RouteId, number>
>()
private readonly selectiveReripStats = createInitialSelectiveReripStats()
constructor(
topology: TinyHyperGraphTopology,
problem: TinyHyperGraphProblem,
options?: TinyHyperGraphSolverOptions,
) {
super(topology, problem, options)
this.USE_LAZY_ROUTE_HEURISTIC = true
}
override resetRoutingStateForRerip(): void {
this.staticPortCostsByNetAndGoal.clear()
super.resetRoutingStateForRerip()
}
override onAllRoutesRouted(): void {
this.staticPortCostsByNetAndGoal.clear()
super.onAllRoutesRouted()
}
/**
* Reverse shortest-path costs avoid occupied ports and account for cramped
* port penalties. Adding routes only removes available edges, so cached
* lower bounds remain valid until a rip releases occupied ports.
* Ignoring entry direction and region crossings keeps the search relaxed.
* Resume each reverse search only until the requested port is settled.
*/
override computeH(portId: PortId): number {
const routeId = this.state.currentRouteId!
const routeNetId = this.problem.routeNet[routeId]!
const goalPortId = this.getRouteEndPortId(routeId)
let costsByGoal = this.staticPortCostsByNetAndGoal.get(routeNetId)
if (!costsByGoal) {
costsByGoal = new Map<PortId, PortDistanceSearch>()
this.staticPortCostsByNetAndGoal.set(routeNetId, costsByGoal)
}
let search = costsByGoal.get(goalPortId)
if (!search) {
const costs = new Float64Array(this.topology.portCount).fill(
Number.POSITIVE_INFINITY,
)
costs[goalPortId] = 0
const queue = new PortDistanceQueue(this.topology.portCount)
queue.queue(goalPortId, 0)
// Snapshot occupancy so resumed searches use the same relaxed graph
// even after another route commits between queries for this net.
const blockedPorts = new Uint8Array(this.topology.portCount)
for (
let candidatePortId = 0;
candidatePortId < blockedPorts.length;
candidatePortId++
) {
const assignedNetId = this.state.portAssignment[candidatePortId]!
if (
this.isPortReservedForDifferentNet(candidatePortId) ||
(assignedNetId !== -1 && assignedNetId !== routeNetId)
) {
blockedPorts[candidatePortId] = 1
}
}
search = {
costs,
settled: new Uint8Array(this.topology.portCount),
blockedPorts,
queue,
}
costsByGoal.set(goalPortId, search)
}
const { costs, settled, blockedPorts, queue } = search
if (blockedPorts[portId] && portId !== goalPortId) {
return Number.POSITIVE_INFINITY
}
while (!settled[portId] && queue.length > 0) {
const currentPortId = queue.dequeue()!
const currentCost = costs[currentPortId]!
const currentX = this.topology.portX[currentPortId]!
const currentY = this.topology.portY[currentPortId]!
const currentPortPenalty = this.problem.portPenalty?.[currentPortId] ?? 0
for (const regionId of this.topology.incidentPortRegion[
currentPortId
]!) {
if (this.isRegionReservedForDifferentNet(regionId)) continue
for (const previousPortId of this.topology.regionIncidentPorts[
regionId
]!) {
if (settled[previousPortId] || blockedPorts[previousPortId]) continue
const dx =
this.topology.portX[previousPortId]! -
currentX
const dy =
this.topology.portY[previousPortId]! -
currentY
const cost =
currentCost +
Math.sqrt(dx * dx + dy * dy) * this.DISTANCE_TO_COST +
currentPortPenalty
if (cost >= costs[previousPortId]!) continue
costs[previousPortId] = cost
queue.queue(previousPortId, cost)
}
}
settled[currentPortId] = 1
}
return costs[portId]!
}
getSelectiveReripStats(): SelectiveReripTinyHyperGraphStats {
return {
...this.selectiveReripStats,
failedOwnerPairs: this.selectiveReripStats.failedOwnerPairs.map(
(pair) => ({
...pair,
}),
),
lastDirectOwnerRouteIds: [
...this.selectiveReripStats.lastDirectOwnerRouteIds,
],
lastRepeatedOwnerRouteIds: [
...this.selectiveReripStats.lastRepeatedOwnerRouteIds,
],
lastAlternateOwnerRouteIds: [
...this.selectiveReripStats.lastAlternateOwnerRouteIds,
],
lastRippedRouteIds: [...this.selectiveReripStats.lastRippedRouteIds],
}
}
override onOutOfCandidates(): void {
const failedRouteId = this.state.currentRouteId
if (failedRouteId === undefined) {
throw new Error(
"SelectiveReripTinyHyperGraphSolver: candidate search exhausted without a current route",
)
}
this.staticPortCostsByNetAndGoal.clear()
const directPath = this.findRelaxedBlockerPathPreferringPreservedRoutes()
if (!directPath.found || directPath.owners.size === 0) {
this.selectiveReripStats.globalReripCount += 1
this.selectiveReripStats.globalReripReason = !directPath.found
? directPath.reason
: "no_blocker_path"
this.selectiveReripStats.lastFailedRouteId = failedRouteId
this.selectiveReripStats.lastDirectOwnerRouteIds = []
this.selectiveReripStats.lastRepeatedOwnerRouteIds = []
this.selectiveReripStats.lastAlternateOwnerRouteIds = []
this.selectiveReripStats.lastRippedRouteIds = []
this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount =
directPath.expandedLabelCount
this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0
super.onOutOfCandidates()
this.publishSelectiveReripStats()
return
}
const directOwnerRouteIds = [...directPath.owners]
const repeatedOwnerRouteIds: RouteId[] = []
for (const ownerRouteId of directOwnerRouteIds) {
const count = this.incrementFailedOwnerPair(failedRouteId, ownerRouteId)
if (count >= 2) repeatedOwnerRouteIds.push(ownerRouteId)
}
const rippedRouteIds = selectOwnerRouteIdsToRip({
failedRouteId,
directOwnerRouteIds,
})
this.clearPartialRipPlans(rippedRouteIds)
for (const hop of directPath.hops) {
for (const resource of hop.data?.resources ?? []) {
const key = this.getBlockerResourceKey(resource)
this.blockerResourceHistory.set(
key,
(this.blockerResourceHistory.get(key) ?? 0) + 1,
)
const regionIds =
resource.kind === "port"
? this.topology.incidentPortRegion[resource.portId]!
: [resource.regionId]
for (const regionId of regionIds) {
this.state.regionCongestionCost[regionId] +=
resource.owners.length * this.RIP_CONGESTION_REGION_COST_FACTOR
}
}
}
this.rebuildCommittedState(rippedRouteIds)
this.state.ripCount += 1
this.state.currentRouteId = failedRouteId
this.state.currentRouteNetId = this.problem.routeNet[failedRouteId]!
this.state.unroutedRoutes = orderRoutesAfterSelectiveRerip({
failedRouteId,
pendingRouteIds: this.state.unroutedRoutes,
rippedRouteIds,
}).filter((routeId) => routeId !== failedRouteId)
this.state.candidateQueue.clear()
this.resetCandidateBestCosts()
this.state.goalPortId = this.getRouteEndPortId(failedRouteId)
let candidate: Candidate | undefined
for (const state of directPath.states) {
const g = candidate ? this.computeG(candidate, state.portId) : 0
if (!Number.isFinite(g)) {
throw new Error(
"Cleared blocker path still violates a hard routing constraint",
)
}
candidate = { ...state, g, h: 0, f: g, prevCandidate: candidate }
}
if (!candidate || candidate.portId !== this.state.goalPortId) {
throw new Error("Cleared blocker path does not reach the route goal")
}
this.onPathFound(candidate)
this.selectiveReripStats.selectiveRipCount += 1
this.selectiveReripStats.selectivelyRippedRouteCount += rippedRouteIds.size
this.selectiveReripStats.lastFailedRouteId = failedRouteId
this.selectiveReripStats.lastDirectOwnerRouteIds = directOwnerRouteIds
this.selectiveReripStats.lastRepeatedOwnerRouteIds = repeatedOwnerRouteIds
this.selectiveReripStats.lastAlternateOwnerRouteIds = []
this.selectiveReripStats.lastRippedRouteIds = [...rippedRouteIds]
this.selectiveReripStats.lastRelaxedSearchExpandedLabelCount =
directPath.expandedLabelCount
this.selectiveReripStats.lastAlternateSearchExpandedLabelCount = 0
this.publishSelectiveReripStats()
}
private getBlockerResourceKey(
resource: SelectiveReripBlockerResource,
): string {
if (resource.kind === "port") return `port:${resource.portId}`
const firstPortId = Math.min(resource.fromPortId, resource.toPortId)
const secondPortId = Math.max(resource.fromPortId, resource.toPortId)
return `crossing:${resource.regionId}:${firstPortId}:${secondPortId}`
}
protected findRelaxedBlockerPath(
forbiddenOwnerRouteIds: ReadonlySet<RouteId> = new Set<RouteId>(),
): DistinctOwnerBlockerSearchResult<
RelaxedSearchState,
RouteId,
RelaxedSearchHopData
> {
const routeId = this.state.currentRouteId
const routeNetId = this.state.currentRouteNetId
if (routeId === undefined || routeNetId === undefined) {
throw new Error(
"SelectiveReripTinyHyperGraphSolver: blocker search requires a current route and net",
)
}
const startPortId = this.getRouteStartPortId(routeId)
const goalPortId = this.getRouteEndPortId(routeId)
const startRegionId = this.getStartingNextRegionId(routeId, startPortId)
if (startRegionId === undefined) {
throw new Error(
`SelectiveReripTinyHyperGraphSolver: route ${this.describeRoute(routeId)} has no starting region for blocker search`,
)
}
const portOwners = this.getPortOwners()
// Committed segments stay unchanged throughout this synchronous search.
// Keep geometry local so the next search observes any intervening rerips.
const crossingGeometryByRegion = new Map<
RegionId,
CommittedCrossingGeometry[]
>()
return findResourceBlockerPath({
start: { portId: startPortId, nextRegionId: startRegionId },
getStateKey: ({ portId, nextRegionId }): number =>
this.getHopId(portId, nextRegionId),
isGoal: ({ portId }): boolean => portId === goalPortId,
getHops: (state) =>
this.getRelaxedSearchHops({
state,
goalPortId,
routeNetId,
portOwners,
forbiddenOwnerRouteIds,
crossingGeometryByRegion,
}),
getBlockerCost: (hop): number => {
let cost = 0
for (const resource of hop.data?.resources ?? []) {
const previousConflicts =
this.blockerResourceHistory.get(
this.getBlockerResourceKey(resource),
) ?? 0
cost += resource.owners.length * (1 + previousConflicts)
}
return cost
},
maxExpandedLabels: this.getRelaxedSearchExpansionLimit(),
})
}
protected findRelaxedBlockerPathPreferringPreservedRoutes(
forbiddenOwnerRouteIds: ReadonlySet<RouteId> = new Set<RouteId>(),
): DistinctOwnerBlockerSearchResult<
RelaxedSearchState,
RouteId,
RelaxedSearchHopData
> {
const preferredPreservedRouteIds =
this.getRouteIdsPreferredForPreservation()
if (preferredPreservedRouteIds.size === 0) {
return this.findRelaxedBlockerPath(forbiddenOwnerRouteIds)
}
const preferredForbiddenOwnerRouteIds = new Set(forbiddenOwnerRouteIds)
for (const routeId of preferredPreservedRouteIds) {
preferredForbiddenOwnerRouteIds.add(routeId)
}
const preferredPath = this.findRelaxedBlockerPath(
preferredForbiddenOwnerRouteIds,
)
if (preferredPath.found && preferredPath.owners.size > 0) {
return preferredPath
}
return this.findRelaxedBlockerPath(forbiddenOwnerRouteIds)
}
protected getRelaxedSearchExpansionLimit(): number {
let incidentHopCount = 0
for (const incidentRegions of this.topology.incidentPortRegion) {
incidentHopCount += incidentRegions.length
}
const ownerScale = Math.max(
4,
Math.ceil(Math.log2(this.problem.routeCount + 1)),
)
return Math.max(4096, incidentHopCount * ownerScale * 4)
}
private getRelaxedSearchHops(params: {
state: RelaxedSearchState
goalPortId: PortId
routeNetId: number
portOwners: ReadonlyMap<PortId, ReadonlySet<RouteId>>
forbiddenOwnerRouteIds: ReadonlySet<RouteId>
crossingGeometryByRegion: Map<RegionId, CommittedCrossingGeometry[]>
}): Array<{
state: RelaxedSearchState
distance: number
owners: RouteId[]
data: RelaxedSearchHopData
}> {
const { state, goalPortId, routeNetId } = params
if (this.isRegionReservedForDifferentNet(state.nextRegionId)) return []
const hops: Array<{
state: RelaxedSearchState
distance: number
owners: RouteId[]
data: RelaxedSearchHopData
}> = []
for (const neighborPortId of this.topology.regionIncidentPorts[
state.nextRegionId
] ?? []) {
if (neighborPortId === state.portId) continue
if (this.isPortReservedForDifferentNet(neighborPortId)) continue
if (
neighborPortId !== goalPortId &&
this.problem.portSectionMask[neighborPortId] === 0
) {
continue
}
const resources = this.getHopBlockerResources(
state.nextRegionId,
state.portId,
neighborPortId,
routeNetId,
params.portOwners,
params.crossingGeometryByRegion,
)
const owners: RouteId[] = []
for (const resource of resources) {
for (const owner of resource.owners) {
if (!owners.includes(owner)) owners.push(owner)
}
}
if (
owners.some((ownerRouteId) =>
params.forbiddenOwnerRouteIds.has(ownerRouteId),
)
) {
continue
}
let nextRegionId = state.nextRegionId
if (neighborPortId !== goalPortId) {
const [firstRegionId, secondRegionId] =
this.topology.incidentPortRegion[neighborPortId] ?? []
nextRegionId =
firstRegionId === state.nextRegionId ? secondRegionId : firstRegionId
if (
nextRegionId === undefined ||
this.isRegionReservedForDifferentNet(nextRegionId)
) {
continue
}
}
hops.push({
state: { portId: neighborPortId, nextRegionId },
distance:
Math.hypot(
this.topology.portX[state.portId]! -
this.topology.portX[neighborPortId]!,
this.topology.portY[state.portId]! -
this.topology.portY[neighborPortId]!,
) * this.DISTANCE_TO_COST +
(this.problem.portPenalty?.[neighborPortId] ?? 0) +
this.state.regionCongestionCost[state.nextRegionId]! +
this.computeRegionCostForRegion(
state.nextRegionId,
0,
0,
this.topology.portZ[state.portId] !==
this.topology.portZ[neighborPortId]
? 1
: 0,
1,
),
owners,
data: { resources },
})
}
return hops
}
private getHopBlockerResources(
regionId: RegionId,
fromPortId: PortId,
toPortId: PortId,
routeNetId: number,
portOwners: ReadonlyMap<PortId, ReadonlySet<RouteId>>,
crossingGeometryByRegion: Map<RegionId, CommittedCrossingGeometry[]>,
): SelectiveReripBlockerResource[] {
const resources: SelectiveReripBlockerResource[] = []
const assignedNetId = this.state.portAssignment[toPortId]!
if (assignedNetId !== -1 && assignedNetId !== routeNetId) {
const owners: RouteId[] = []
const toPortOwners = portOwners.get(toPortId)
if (toPortOwners) {
for (const routeId of toPortOwners) {
if (this.problem.routeNet[routeId] !== routeNetId) {
owners.push(routeId)
}
}
}
if (owners.length === 0) {
throw new Error(
`SelectiveReripTinyHyperGraphSolver: port ${toPortId} is assigned to foreign net ${assignedNetId} without a committed route owner`,
)
}
resources.push({ kind: "port", portId: toPortId, owners })
}
const sameLayerIntersectionOwners = this.getHardBlockedCrossingOwners(
regionId,
fromPortId,
toPortId,
crossingGeometryByRegion,
)
if (sameLayerIntersectionOwners.length > 0) {
resources.push({
kind: "same_layer_intersection",
regionId,
fromPortId,
toPortId,
owners: sameLayerIntersectionOwners,
})
}
return resources
}
private getPortOwners(): Map<PortId, Set<RouteId>> {
const ownersByPort = new Map<PortId, Set<RouteId>>()
for (const segments of this.state.regionSegments) {
for (const [routeId, fromPortId, toPortId] of segments) {
for (const portId of [fromPortId, toPortId]) {
const owners = ownersByPort.get(portId) ?? new Set<RouteId>()
owners.add(routeId)
ownersByPort.set(portId, owners)
}
}
}
return ownersByPort
}
private getHardBlockedCrossingOwners(
regionId: RegionId,
fromPortId: PortId,
toPortId: PortId,
crossingGeometryByRegion: Map<RegionId, CommittedCrossingGeometry[]>,
): RouteId[] {
if (!this.isKnownSingleLayerRegion(regionId)) return []
const routeNetId = this.state.currentRouteNetId
if (routeNetId === undefined) {
throw new Error(
"SelectiveReripTinyHyperGraphSolver: crossing ownership requires a current route net",
)
}
let committed = crossingGeometryByRegion.get(regionId)
if (!committed) {
committed = []
for (const [ownerRouteId, ownerFromPortId, ownerToPortId] of this.state
.regionSegments[regionId] ?? []) {
if (this.problem.routeNet[ownerRouteId] === routeNetId) continue
const geometry = this.populateSegmentGeometryScratch(
regionId,
ownerFromPortId,
ownerToPortId,
)
committed.push({
ownerRouteId,
lesserAngle: geometry.lesserAngle,
greaterAngle: geometry.greaterAngle,
layerMask: geometry.layerMask,
})
}
crossingGeometryByRegion.set(regionId, committed)
}
const owners: RouteId[] = []
if (committed.length === 0) return owners
const first = this.populateSegmentGeometryScratch(
regionId,
fromPortId,
toPortId,
)
const firstLesserAngle = first.lesserAngle
const firstGreaterAngle = first.greaterAngle
const firstLayerMask = first.layerMask
for (const second of committed) {
const ownerRouteId = second.ownerRouteId
if ((firstLayerMask & second.layerMask) === 0) continue
if (
firstLesserAngle === second.lesserAngle ||
firstLesserAngle === second.greaterAngle ||
firstGreaterAngle === second.lesserAngle ||
firstGreaterAngle === second.greaterAngle
) {
continue
}
const secondLesserInsideFirst =
firstLesserAngle < second.lesserAngle &&
second.lesserAngle < firstGreaterAngle
const secondGreaterInsideFirst =
firstLesserAngle < second.greaterAngle &&
second.greaterAngle < firstGreaterAngle
if (
secondLesserInsideFirst !== secondGreaterInsideFirst &&
!owners.includes(ownerRouteId)
) {
owners.push(ownerRouteId)
}
}
return owners
}
private rebuildCommittedState(rippedRouteIds: ReadonlySet<RouteId>): void {
this.state.regionSegments = this.state.regionSegments.map((segments) =>
segments.filter(([routeId]) => !rippedRouteIds.has(routeId)),
)
this.state.portAssignment.fill(-1)
this.state.regionIntersectionCaches = Array.from(
{ length: this.topology.regionCount },
() => createEmptyRegionIntersectionCache(),
)
for (
let regionId = 0;
regionId < this.state.regionSegments.length;
regionId++
) {
for (const [routeId, fromPortId, toPortId] of this.state.regionSegments[
regionId
]!) {
const routeNetId = this.problem.routeNet[routeId]!
this.state.currentRouteNetId = routeNetId
for (const portId of [fromPortId, toPortId]) {
const assignedNetId = this.state.portAssignment[portId]!
if (assignedNetId !== -1 && assignedNetId !== routeNetId) {
throw new Error(
`SelectiveReripTinyHyperGraphSolver: rebuilding committed routes found cross-net ownership at port ${portId} between net ${assignedNetId} and net ${routeNetId}`,
)
}
this.state.portAssignment[portId] = routeNetId
}
this.appendSegmentToRegionCache(regionId, fromPortId, toPortId)
}
}
this.state.currentRouteNetId = undefined
}
private incrementFailedOwnerPair(
failedRouteId: RouteId,
ownerRouteId: RouteId,
): number {
const ownerCounts =
this.failedOwnerPairCounts.get(failedRouteId) ??
new Map<RouteId, number>()
const count = (ownerCounts.get(ownerRouteId) ?? 0) + 1
ownerCounts.set(ownerRouteId, count)
this.failedOwnerPairCounts.set(failedRouteId, ownerCounts)
return count
}
private publishSelectiveReripStats(): void {
const failedOwnerPairs: FailedOwnerPairCount[] = []
for (const [failedRouteId, ownerCounts] of this.failedOwnerPairCounts) {
for (const [ownerRouteId, count] of ownerCounts) {
failedOwnerPairs.push({ failedRouteId, ownerRouteId, count })
}
}
failedOwnerPairs.sort(
(left, right) =>
left.failedRouteId - right.failedRouteId ||
left.ownerRouteId - right.ownerRouteId,
)
this.selectiveReripStats.failedOwnerPairs = failedOwnerPairs
this.selectiveReripStats.failedOwnerPairCount = failedOwnerPairs.length
this.selectiveReripStats.maxFailedOwnerPairCount = Math.max(
0,
...failedOwnerPairs.map(({ count }) => count),
)
this.stats = { ...this.stats, ...this.getSelectiveReripStats() }
}
private describeRoute(routeId: RouteId): string {
const connectionId = this.problem.routeMetadata?.[routeId]?.connectionId
return connectionId === undefined
? String(routeId)
: `${routeId} (${String(connectionId)})`
}
}