All files / src/pages/flowsheet-page/pinch-analysis/hen-generation/utils hxNodes.ts

83.39% Statements 216/259
66.9% Branches 95/142
87.5% Functions 35/40
87.22% Lines 198/227

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                93x   93x 93x 99x 99x 99x 99x 99x   99x 99x 99x 99x         93x     93x 93x 93x 93x 99x 93x 93x 93x           93x                                                         93x 93x   6x 6x   12x 6x     6x 6x 6x 6x 6x 6x 6x   6x       6x                           6x       6x 6x 6x   6x                 6x 6x         93x                 186x 186x 186x 411x   186x 186x           39x 39x 39x 112x 216x 80x 80x       39x               176x 228x   176x   176x 176x   176x 388x   176x                           43x     43x 88x   88x 332x 332x     332x 514x   332x   176x 176x 176x     88x   43x                             43x 43x 43x 43x 88x 88x 88x 88x   43x                             46x 46x 93x 93x 93x 93x 99x   93x   46x                 46x   46x 132x 132x 132x 252x     132x 186x 186x 186x 186x             186x 186x 93x 186x       46x                 46x 46x 93x 93x 93x   93x 93x 93x               93x 93x 93x             93x 99x                   46x           99x 99x 99x 99x 99x 5x 5x   94x     99x 94x 94x   5x 5x 5x 5x       5x                 99x                                   46x 46x 46x   46x         396x 396x 396x 396x 396x     46x 99x 99x 99x   99x 99x 99x     99x   99x 99x   99x 99x   99x     46x                       46x   46x 93x 93x 186x 186x 186x 198x 198x 198x 198x 198x 198x   186x       46x           7x 7x 16x 9x 9x 9x     7x         7x 7x 16x 9x 9x 9x     7x  
import { widthOf } from "./henLayoutUtils";
import { MergedStream, Bounds, Pair, PairRec, SideInfo } from "../henTypes";
import { center, ovBounds } from "./bounds";
import { isHeatExchanger, makeHxKey } from "./nodeMarkers";
import { HenNodeRead, SegmentRead } from "@/api/apiStore.gen";
 
//HX row pairing
 
/**
 * Pair hot-side and cold-side row indices for a single HX
 * Build all hot/cold candidates with:
 * - width: horizontal overlap (via ovBounds/widthOf; 0 if none)
 * - gap: distance between row centers (smaller is better)
 *
 * returns an array of {hotRow, coldRow} of length:
 * - at least min(hotRows.length, coldRows.length), and
 * - up to max(hotRows.length, coldRows.length) when reuse is needed.
 */
export function matchRowsByOverlap(
  hotRows: number[],
  coldRows: number[],
  hotAlign: Bounds[],
  coldAlign: Bounds[]
): Array<{ hotRow: number; coldRow: number }> {
  Iif (!hotRows.length || !coldRows.length) return [];
 
  const candidates: Pair[] = [];
  for (const h of hotRows) {
    const hb = hotAlign[h]; // the hot row's horizontal bounds
    Iif (!hb) continue;
    for (const c of coldRows) {
      const cb = coldAlign[c]; // the cold row's horizontal bounds
      Iif (!cb) continue;
      // find overlap of hot and cold bounds
      const ov = ovBounds(hb, cb); // 1D intersection (or null)
      const w = widthOf(ov); // how much the hot and cold spans overlap (or 0 if null)
      const g = Math.abs(center(hb) - center(cb)); // centre distance (smlaller means the rows are closer horixontally)
      candidates.push({ h, c, width: w, gap: g });
    }
  }
 
  // prefer larger overlap (width descending), but tiebreak with smaller centre gap (ascending).
  candidates.sort((a, b) => b.width - a.width || a.gap - b.gap);
 
  // look through the sorted list once and accept a candidate only if NEITHER end (hot/cold side) has been used yet.
  const usedH = new Set<number>();
  const usedC = new Set<number>();
  const pairs: Array<{ hotRow: number; coldRow: number }> = [];
  for (const cand of candidates) {
    if (!usedH.has(cand.h) && !usedC.has(cand.c)) {
      pairs.push({ hotRow: cand.h, coldRow: cand.c }); //accept this pairing
      usedH.add(cand.h); // mark hot row as used
      usedC.add(cand.c); // mark cold row as used.
    }
  }
 
  // Fill to cover the smaller side's size.
  // if we still dont reach min(hot,cold) pairs yet, try pairing by remaining unpaired rows by nearest centre.
  Iif (pairs.length < Math.min(hotRows.length, coldRows.length)) {
    // find the rows that are STILL not paired yet on each side.
    const yetH = hotRows.filter((h) => !usedH.has(h));
    const yetC = coldRows.filter((c) => !usedC.has(c));
    // build all leftover hot/cold pairs, scored only by centre gap.
    const fill: Pair[] = [];
    for (const h of yetH) {
      const hb = hotAlign[h];
      for (const c of yetC) {
        const cb = coldAlign[c];
        const g = Math.abs(center(hb) - center(cb)); // closer centres are better
        fill.push({ h, c, width: 0, gap: g });
      }
    }
    fill.sort((a, b) => a.gap - b.gap); // pick closest centre pairs first
    // add as many as we still need without reusing any row.
    for (const f of fill) {
      Iif (!usedH.has(f.h) && !usedC.has(f.c)) {
        pairs.push({ hotRow: f.h, coldRow: f.c });
        usedH.add(f.h);
        usedC.add(f.c);
        Iif (pairs.length >= Math.min(hotRows.length, coldRows.length)) break;
      }
    }
  }
 
  // Extend to multiplicity (max side) by nearest reuse
  // If one side has more rows, we need more pairs than min(hot,cold).
  // We now allow reusing rows from the other side, picking nearest-center partners.
  const multiplicity = Math.max(hotRows.length, coldRows.length);
  if (pairs.length < multiplicity) {
    // which rows are already represented in the current pairs?
    const pairedH = new Set(pairs.map((p) => p.hotRow));
    const pairedC = new Set(pairs.map((p) => p.coldRow));
    // Rows that still havent appeared at all in pairs.
    const remainingH = hotRows.filter((h) => !pairedH.has(h));
    const remainingC = coldRows.filter((c) => !pairedC.has(c));
 
    // for a given hot row, find the cold row witht the smallest centre gap.
    const nearestCold = (h: number) => {
      const hb = hotAlign[h];
      let best: { c: number; gap: number } | null = null;
      for (const cc of coldRows) {
        const cb = coldAlign[cc];
        const g = Math.abs(center(hb) - center(cb));
        if (!best || g < best.gap) best = { c: cc, gap: g };
      }
      return best!.c;
    };
 
    // for a given cold row, find the hot row witht the smallest centre gap.
    const nearestHot = (c: number) => {
      const cb = coldAlign[c];
      let best: { h: number; gap: number } | null = null;
      for (const hh of hotRows) {
        const hb = hotAlign[hh];
        const g = Math.abs(center(hb) - center(cb));
        Iif (!best || g < best.gap) best = { h: hh, gap: g };
      }
      return best!.h;
    };
 
    // while we still need more pairs and have any remaining rows to introduce,
    // alternate: add a remaining hot (paired to its nearest cold), then a remaining cold
    // (paired to its nearest hot).
    while (
      pairs.length < multiplicity &&
      (remainingH.length || remainingC.length)
    ) {
      if (remainingH.length) {
        const h = remainingH.shift()!;
        pairs.push({ hotRow: h, coldRow: nearestCold(h) });
      }
      if (pairs.length >= multiplicity) break;
      Iif (remainingC.length) {
        const c = remainingC.shift()!;
        pairs.push({ hotRow: nearestHot(c), coldRow: c });
      }
    }
 
    // Absolute last resort: if we still didn’t reach multiplicity (e.g., missing bounds everywhere),
    // duplicate earlier pairs until we hit the target length.
    let j = 0;
    while (pairs.length < multiplicity && pairs.length > 0) {
      pairs.push(pairs[j++ % pairs.length]);
    }
  }
 
  return pairs;
}
 
/** For a given stream, return row indices where the HX node appears. */
export function getRowsWithHxNode(
  stream: MergedStream,
  hxNodeId?: number,
  expanded?: boolean
): number[] {
  Iif (!hxNodeId) return [];
  const indices: number[] = [];
  (stream.rawSegments ?? []).forEach((seg: SegmentRead, idx: number) => {
    if (Number(seg?.hen_node) === Number(hxNodeId)) indices.push(idx);
  });
  Iif (!indices.length) return [];
  return expanded ? indices : [0];
}
 
// HX presence/order/multiplicity -> global columns
// First-seen order of HX keys across streams.
export function detectHxOrder(streams: MergedStream[]): string[] {
  const order: string[] = [];
  const seen = new Set<string>();
  for (const s of streams ?? []) {
    for (const m of s.markers ?? []) {
      if (m.hxKey && m.label?.startsWith("E") && !seen.has(m.hxKey)) {
        seen.add(m.hxKey);
        order.push(m.hxKey);
      }
    }
  }
  return order;
}
 
/** How many rows the HX appears  on a stream (based on rawSegments). */
export function countRowsForHxOnStream(
  stream: MergedStream,
  hxKey: string
): number {
  const hxMarker = (stream.markers ?? []).find(
    (m) => m.hxKey === hxKey && m.henNode
  );
  Iif (!hxMarker?.henNode) return 0; // this hx doesnt appear in this stream
 
  const nodeId = hxMarker.henNode.id;
  let count = 0;
  // for each segment in rawSegments, if its hennode matches the marker's node id, increment.
  (stream.rawSegments ?? []).forEach((seg: SegmentRead) => {
    if (Number(seg?.hen_node) === Number(nodeId)) count++;
  });
  return count;
}
 
// compute the effective column multiplicity for each HX key across all streams.
// - Each HX can appear on multiple streams and on multiple rows per stream.
// - If a stream is "expanded", every row it occupies on that stream counts.
// - If a stream is not expanded, it contributes at most 1 to multiplicity.
// - The HX's overall multiplicity is the MAX contribution seen on any single stream.
// returns: Map<hxKey, multiplicity> (only keys with multiplicity > 0 are included)
export function computeHxMultiplicityByKey(
  streams: MergedStream[],
  hxKeys: string[],
  expandedBySde: Map<string, boolean>
): Map<string, number> {
  const out = new Map<string, number>();
 
  //for each hx key,
  for (const key of hxKeys) {
    let maxEff = 0; // track largest effetive contribution observed accross streams.
    // look through every stream to see how much this hx contributes there.
    for (const s of streams ?? []) {
      const sdeId = String(s.stream_data_entry);
      const expanded = expandedBySde.get(sdeId) ?? false; // is this stream expanded?
 
      // get the hx node marker for the actual hx hennode.
      const marker = (s.markers ?? []).find(
        (m) => m.hxKey === key && m.henNode
      );
      if (!marker?.henNode) continue; // else skip
 
      const rowsOnThisStream = countRowsForHxOnStream(s, key); // how many rows does this hx occupy in this stream?
      const eff = expanded ? rowsOnThisStream : Math.min(1, rowsOnThisStream); // if expanded, count all rows, else 1.
      if (eff > maxEff) maxEff = eff; // keep the largest contribution seen across streams
    }
    // record the largest contirbution.
    if (maxEff > 0) out.set(key, maxEff);
  }
  return out;
}
 
/**
 * Given order and multiplicity, allocate contiguous block indices per HX.
 * Returns start offset, width, and total columns.
 */
export function computeHxColumnBlocks(
  hxOrder: string[],
  multiplicityByKey: Map<string, number>
): {
  startByKey: Map<string, number>;
  widthByKey: Map<string, number>;
  totalWidth: number;
} {
  const startByKey = new Map<string, number>();
  const widthByKey = new Map<string, number>();
  let start = 0;
  for (const k of hxOrder) {
    const w = multiplicityByKey.get(k) ?? 1;
    startByKey.set(k, start);
    widthByKey.set(k, w);
    start += w;
  }
  return { startByKey, widthByKey, totalWidth: start };
}
 
/**
 * For each HX, map the columns (global Xs) it wants to occupy.
 * "columnXs" is the full global column coordinate list (already spaced).
 * "leftPad" lets you shift HX columns to account for non-HX pads on the left.
 */
export function computeHxColumnsByKey(
  hxOrder: string[],
  startByKey: Map<string, number>,
  widthByKey: Map<string, number>,
  columnXs: number[],
  leftPad: number
): Map<string, number[]> {
  const m = new Map<string, number[]>();
  for (const k of hxOrder) {
    const start = startByKey.get(k) ?? 0;
    const width = widthByKey.get(k) ?? 1;
    const xs: number[] = [];
    for (let i = 0; i < width; i++) {
      xs.push(columnXs[leftPad + start + i]);
    }
    m.set(k, xs);
  }
  return m;
}
 
// HX side discovery & row pairing across hot/cold
/** Build hot/cold SideInfo per HX key from streams. */
export function collectHxSides(
  streams: MergedStream[],
  expandedBySde: Map<string, boolean>
): Map<string, { hot?: SideInfo; cold?: SideInfo }> {
  const hxSides = new Map<string, { hot?: SideInfo; cold?: SideInfo }>();
 
  for (const s of streams ?? []) {
    const sdeId = String(s.stream_data_entry);
    const expanded = expandedBySde.get(sdeId) ?? false;
    const hxMarkers = (s.markers ?? []).filter(
      (m) => m.hxKey && m.label?.startsWith("E") && m.henNode
    );
 
    hxMarkers.forEach((m) => {
      const key = m.hxKey!;
      const nodeId = m.henNode?.id;
      const rows = getRowsWithHxNode(s, nodeId, expanded);
      const info: SideInfo = {
        sdeId,
        isHot: !!s.isHot,
        rows,
        stream: s,
        expanded,
      };
      const entry = hxSides.get(key) ?? {};
      if (s.isHot) entry.hot = info;
      else entry.cold = info;
      hxSides.set(key, entry);
    });
  }
 
  return hxSides;
}
 
/** Produce hot<->cold row pairings for every HX key. */
export function pairHxRowsForEachKey(
  hxSides: Map<string, { hot?: SideInfo; cold?: SideInfo }>,
  rowBoundsAlignBySdeId: Map<string, Bounds[]>,
  pairFn: typeof matchRowsByOverlap = matchRowsByOverlap
): PairRec[] {
  const out: PairRec[] = [];
  hxSides.forEach((entry, hxKey) => {
    const hot = entry.hot,
      cold = entry.cold;
    Iif (!hot || !cold) return;
 
    const hotAlign = rowBoundsAlignBySdeId.get(hot.sdeId) ?? [];
    const coldAlign = rowBoundsAlignBySdeId.get(cold.sdeId) ?? [];
    Iif (
      !hot.rows.length ||
      !cold.rows.length ||
      !hotAlign.length ||
      !coldAlign.length
    )
      return;
 
    const pairs = pairFn(hot.rows, cold.rows, hotAlign, coldAlign);
    const multiplicity = Math.max(hot.rows.length, cold.rows.length);
    const safePairs = pairs.length
      ? pairs.slice(0, multiplicity)
      : Array.from({ length: multiplicity }, (_, k) => ({
          hotRow: hot.rows[k % hot.rows.length],
          coldRow: cold.rows[k % cold.rows.length],
        }));
 
    safePairs.forEach(({ hotRow, coldRow }, k) => {
      out.push({
        hxKey,
        hotSdeId: hot.sdeId,
        coldSdeId: cold.sdeId,
        hotRow,
        coldRow,
        k,
      });
    });
  });
  return out;
}
 
// Computing shared X per hot/cold row pair (alignment)
/** Overlap if available; else use the narrower row. */
export function legalRegionForRowPair(bHot: Bounds, bCold: Bounds): Bounds {
  const overlap = ovBounds(bHot, bCold);
  const insetBounds = (b: Bounds, px: number): Bounds => {
    const l = b.left + px,
      r = b.right - px;
    if (r <= l) {
      const mid = (b.left + b.right) / 2;
      return { left: mid - 0.5, right: mid + 0.5 };
    }
    return { left: l, right: r };
  };
 
  if (overlap) {
    const w = Math.max(0, overlap.right - overlap.left);
    return insetBounds(overlap, Math.max(10, w * 0.12));
  } else {
    const wHot = bHot.right - bHot.left;
    const wCold = bCold.right - bCold.left;
    const anchor = wHot <= wCold ? bHot : bCold;
    const inset = Math.min(
      30,
      Math.max(10, Math.abs(anchor.right - anchor.left) * 0.15)
    );
    return insetBounds(anchor, inset);
  }
}
 
/** Clamp desired X into a legal region. */
export function projectDesiredIntoRegion(
  desiredX: number,
  region: Bounds
): number {
  return Math.max(region.left, Math.min(region.right, desiredX));
}
 
/**
 * Compute aligned HX Xs and row indices per side from row pairings and global columns.
 * - alignedHXByKey: hxKey → sdeid → X[]
 * - alignedHXRowsByKey: hxKey → sdeid → rowIndex[]
 * - candidateSharedXByKey: hxKey → first aligned X (good seed for persistence)
 */
export function computeAlignedHX(
  hxPairs: PairRec[],
  rowBoundsAlignBySdeId: Map<string, Bounds[]>,
  hxColumnsByKey: Map<string, number[]>
): {
  alignedHXByKey: Map<string, Map<string, number[]>>;
  alignedHXRowsByKey: Map<string, Map<string, number[]>>;
  candidateSharedXByKey: Map<string, number>;
} {
  const outXs = new Map<string, Map<string, number[]>>();
  const outRows = new Map<string, Map<string, number[]>>();
  const candidate = new Map<string, number>();
 
  const ensure = <T>(
    m: Map<string, Map<string, T[]>>,
    k: string,
    sub: string
  ) => {
    const mm = m.get(k) ?? new Map<string, T[]>();
    const arr = mm.get(sub) ?? [];
    mm.set(sub, arr);
    m.set(k, mm);
    return arr;
  };
 
  for (const { hxKey, hotSdeId, coldSdeId, hotRow, coldRow, k } of hxPairs) {
    const bHot = (rowBoundsAlignBySdeId.get(hotSdeId) ?? [])[hotRow];
    const bCold = (rowBoundsAlignBySdeId.get(coldSdeId) ?? [])[coldRow];
    Iif (!bHot || !bCold) continue;
 
    const region = legalRegionForRowPair(bHot, bCold);
    const cols = hxColumnsByKey.get(hxKey) ?? [];
    const desired = cols.length
      ? cols[k % cols.length]
      : (region.left + region.right) / 2;
    const xShared = projectDesiredIntoRegion(desired, region);
 
    ensure(outXs, hxKey, hotSdeId).push(xShared);
    ensure(outRows, hxKey, hotSdeId).push(hotRow);
 
    ensure(outXs, hxKey, coldSdeId).push(xShared);
    ensure(outRows, hxKey, coldSdeId).push(coldRow);
 
    if (!candidate.has(hxKey)) candidate.set(hxKey, xShared);
  }
 
  return {
    alignedHXByKey: outXs,
    alignedHXRowsByKey: outRows,
    candidateSharedXByKey: candidate,
  };
}
 
/** Build "must-pass" X positions per row per sde id (for expanded rows). */
export function buildHxXsByRowBySdeId(
  alignedHXByKey: Map<string, Map<string, number[]>>,
  alignedHXRowsByKey: Map<string, Map<string, number[]>>
): Map<string, Map<number, number[]>> {
  const out = new Map<string, Map<number, number[]>>();
 
  alignedHXByKey.forEach((bySdeId, hxKey) => {
    const rowsMap = alignedHXRowsByKey.get(hxKey);
    bySdeId.forEach((xs, sdeId) => {
      const perRow = out.get(sdeId) ?? new Map<number, number[]>();
      const rows = rowsMap?.get(sdeId) ?? [];
      for (let i = 0; i < xs.length; i++) {
        const r = rows[i];
        const x = xs[i];
        Iif (r == null || !Number.isFinite(x)) continue;
        const arr = perRow.get(r) ?? [];
        arr.push(x);
        perRow.set(r, arr);
      }
      out.set(sdeId, perRow);
    });
  });
 
  return out;
}
 
// if a HX node doesnt have an X position yet, assign the hx node with the smallest ID to be the "canonical" node for the HX
// so the other hx node (of the hx pair) will share the same x position as the canonical hx node.
export function buildHxCanonicalIdByKey(henNodes: HenNodeRead[]): Map<string, number> {
  const map = new Map<string, number>();
  (henNodes ?? []).forEach((n) => {
    if (isHeatExchanger(n)) {
      const key = makeHxKey(n)!;
      const prev = map.get(key);
      if (prev == null || n.id < prev) map.set(key, n.id);
    }
  });
  return map;
}
 
/** Persisted x_position per HX key (if present). */
export function buildHxStoredXByKey(henNodes: HenNodeRead[]): Map<string, number> {
  const map = new Map<string, number>();
  (henNodes ?? []).forEach((n) => {
    if (isHeatExchanger(n)) {
      const key = makeHxKey(n)!;
      const x = n.x_position as number | undefined;
      if (Number.isFinite(x) && !map.has(key)) map.set(key, x!);
    }
  });
  return map;
}