|
60 | 60 |
|
61 | 61 | local sqrt = math.sqrt |
62 | 62 | local max = math.max |
| 63 | +local min = math.min |
63 | 64 | local floor = math.floor |
64 | 65 |
|
65 | 66 | ------------------------------------------------------------------------------------- |
@@ -1535,24 +1536,31 @@ local function ComputeMaxPotentials(flowMode) |
1535 | 1536 | local totalP, totalD = subPmax[r], subDmax[r] |
1536 | 1537 | local sP, sD = subPmax[cid], subDmax[cid] |
1537 | 1538 | local oP, oD = totalP - sP, totalD - sD |
1538 | | - local capAB = (sP < oD) and sP or oD |
1539 | | - local capBA = (oP < sD) and oP or sD |
1540 | | - local cap = (capAB > capBA) and capAB or capBA |
| 1539 | + local capAB = min(sP, oD) |
| 1540 | + local capBA = min(oP, sD) |
| 1541 | + local cap = max(capAB, capBA) |
1541 | 1542 | capacities[key] = cap |
1542 | 1543 | local potentialSrcSubtree = capAB > capBA |
1543 | 1544 |
|
1544 | 1545 | local flow, flowSrcSubtree |
1545 | 1546 | if flowMode then |
1546 | | - -- Realized flow across a tree edge is defined by conservation. |
1547 | | - -- The grids are MSTs, so each edge is the only path between its subtree S (cid side) and the rest |
1548 | | - -- Power that physically crosses it equals S's net export flow = | subPcur[S] - subDcur[S] | |
1549 | | - local net = subPcur[cid] - subDcur[cid] |
1550 | | - if net >= 0 then |
1551 | | - flow, flowSrcSubtree = net, true -- subtree exports → cid is source |
1552 | | - else |
1553 | | - flow, flowSrcSubtree = -net, false -- subtree imports → parent is source |
| 1547 | + -- Realized flow across a tree edge = one side's surplus capped by the |
| 1548 | + -- other side's deficit (the power that actually has to cross to serve |
| 1549 | + -- consumption). Net export alone overcounts: two producers with no sink |
| 1550 | + -- each look like a surplus, but nothing crosses — neither side needs the |
| 1551 | + -- other's power, so it exits to global storage at its own node. |
| 1552 | + -- netS = subtree (cid) net, netR = rest-of-grid net. |
| 1553 | + local netS = subPcur[cid] - subDcur[cid] |
| 1554 | + local netR = (subPcur[r] - subDcur[r]) - netS |
| 1555 | + if netS > 0 and netR < 0 then -- S surplus feeds R deficit |
| 1556 | + flow = min(netS, -netR) -- surplus S capped by deficit R |
| 1557 | + flowSrcSubtree = true -- cid is source |
| 1558 | + elseif netR > 0 and netS < 0 then -- R surplus feeds S deficit |
| 1559 | + flow = min(netR, -netS) -- surplus R capped by deficit S |
| 1560 | + flowSrcSubtree = false -- parent is source |
| 1561 | + else -- both surplus or both deficit → nothing crosses |
| 1562 | + flow, flowSrcSubtree = 0, potentialSrcSubtree |
1554 | 1563 | end |
1555 | | - if flow <= 0 then flowSrcSubtree = potentialSrcSubtree end |
1556 | 1564 | else |
1557 | 1565 | flow, flowSrcSubtree = 0, potentialSrcSubtree |
1558 | 1566 | end |
|
0 commit comments