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

91.89% Statements 68/74
72.22% Branches 26/36
100% Functions 17/17
95.23% Lines 60/63

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              16x 14x   14x 24x   14x 24x   14x 14x   14x   16x   5x                     16x             16x 16x   16x 69x 69x   31x 31x   38x       69x 69x   16x 16x     38x 38x   69x 69x 69x   38x     16x 16x 69x     16x                     16x 52x   16x 16x   16x     38x 69x   38x   28x 28x   28x 28x   28x       52x     52x         16x         28x 18x 14x         28x 18x 18x             16x     60x 60x     16x    
import { HenNodeRead } from "@/api/apiStore.gen";
import { AggregatedStream, HenNodeMarker, MergedStream } from "../henTypes";
import { collectNodeMarkersForSid } from "./nodeMarkers";
 
// This function takes a list of hot MERGED streams (i.e. aggregated segments by sde id, and then concatenating "nextStreams" into one hot stream line.),
// then figures out what the stream render order should be
export function sortHotPriority(hotStreams: any[]) {
  const streams = hotStreams.map((item, idx) => {
    const markers: HenNodeMarker[] = item?.markers ?? [];
 
    const hxCount = markers.filter(
      (m) => m.label?.startsWith("E") && m.henNode,
    ).length;
    const nonHxCount = markers.filter(
      (m) => !m.label?.startsWith("E") && m.henNode,
    ).length;
    const totalCount = hxCount / 2 + nonHxCount;
    const mixed = hxCount > 0 && nonHxCount > 0 ? 1 : 0;
 
    return { item, idx, hxCount, nonHxCount, totalCount, mixed };
  });
  streams.sort((A, B) => {
    // Has both HX and non-HX first
    if (A.mixed !== B.mixed) return B.mixed - A.mixed;
 
    // Among same mixed-ness, prioritize by TOTAL nodes (HX + non-HX), desc
    Iif (A.totalCount !== B.totalCount) return B.totalCount - A.totalCount;
 
    // Tiebreaker: more non-HX nodes first (desc)
    Iif (A.nonHxCount !== B.nonHxCount) return B.nonHxCount - A.nonHxCount;
 
    // Final tiebreaker: preserve original order (stable)
    return A.idx - B.idx;
  });
  return streams.map((d) => d.item);
}
 
// build chain of sdes to get one whole aggregated stream (using nextStream)
export function buildSdeChain(
  sdes: Array<{ id: number; nextStream?: number | null }>,
) {
  const nextStream = new Map<string, string | undefined>();
  const hasNextStream = new Set<string>();
 
  (sdes ?? []).forEach((s) => {
    const id = String(s.id);
    const next = s.nextStream == null ? undefined : String(s.nextStream);
    if (next) {
      nextStream.set(id, next);
      hasNextStream.add(next);
    } else {
      nextStream.set(id, undefined);
    }
  });
 
  const allIds = (sdes ?? []).map((s) => String(s.id));
  const starters = allIds.filter((id) => !hasNextStream.has(id));
 
  const sdeChains: string[][] = [];
  const visited = new Set<string>();
 
  const walk = (startId: string) => {
    const chain: string[] = [];
    let current: string | undefined = startId;
    while (current && !visited.has(current)) {
      visited.add(current);
      chain.push(current);
      current = nextStream.get(current);
    }
    if (chain.length) sdeChains.push(chain);
  };
 
  starters.forEach(walk);
  allIds.forEach((id) => {
    Iif (!visited.has(id)) walk(id);
  });
 
  return sdeChains;
}
 
// merge relevant sdes together into one stream
// i.e. since all segments have an sde
// also include node markers to be rendered for that stream.
export function mergeRelevantSdes(
  aggregatedStreams: AggregatedStream[],
  sdeChains: string[][],
  henNodes: HenNodeRead[] | undefined,
): MergedStream[] {
  const aggregatedStream = new Map(
    aggregatedStreams.map((s) => [String(s.stream_data_entry), s]),
  );
  const counters = { Heater: 1, Cooler: 1, HeatExchanger: 1 };
  const hxLabelByKey = new Map<string, string>();
 
  const merged: MergedStream[] = [];
 
  for (const chain of sdeChains) {
    const parts = chain
      .map((id) => aggregatedStream.get(id))
      .filter(Boolean) as AggregatedStream[];
    if (!parts.length) continue;
 
    const head = parts[0];
    const tail = parts[parts.length - 1];
 
    const t_supply = supplyFromSde(head);
    const t_target = targetFromSde(tail);
 
    merged.push({
      ...head,
      t_supply,
      t_target,
      rawSegments: parts.flatMap((p) => p.rawSegments ?? []),
      sdeIds: chain,
      markers: chain.flatMap((id) =>
        collectNodeMarkersForSid(id, henNodes, counters, hxLabelByKey),
      ),
    });
  }
 
  return merged;
}
 
// get tsupply for each aggregated stream
function supplyFromSde(sde: AggregatedStream) {
  return sde.isHot
    ? Math.max(...sde.rawSegments.map((s: any) => s.t_supply))
    : Math.min(...sde.rawSegments.map((s: any) => s.t_supply));
}
 
// get ttarget for each aggregated stream
function targetFromSde(sde: AggregatedStream) {
  return sde.isHot
    ? Math.min(...sde.rawSegments.map((s: any) => s.t_target))
    : Math.max(...sde.rawSegments.map((s: any) => s.t_target));
}
 
// collect all supply/target temperatures for all segments in a stream.
export function collectAllTemps(
  streams: Array<{ rawSegments: any[] }>,
): number[] {
  const temps: number[] = [];
  for (const s of streams ?? []) {
    for (const seg of s.rawSegments ?? []) {
      if (seg?.t_supply != null) temps.push(Number(seg.t_supply));
      if (seg?.t_target != null) temps.push(Number(seg.t_target));
    }
  }
  return temps;
}