All files / src/pages/flowsheet-page/flowsheet/LeftSideBar/Formulas MLProperties.tsx

72.78% Statements 107/147
52.54% Branches 62/118
25% Functions 5/20
84.21% Lines 80/95

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                                                    265x 265x 265x   301x 265x   301x 265x   265x   265x   265x     265x   20x     66x   54x     12x   437x     265x 4x           337x   265x                   351x 39x                   421x 439x       103x                           103x                     220x             220x   257x 220x 220x 220x 220x 243x 241x   220x 220x     220x 241x   241x 220x 220x   220x   220x 23x 243x     220x 21x 220x 220x 262x 21x 220x 241x     220x 5x           262x   220x 2x     262x       36x 36x                 256x 220x 220x   220x           353x   88x           88x 454x 88x                     352x       61x                                         6x                                           647x 88x 220x   484x 396x 418x      
import { CircleX, Plus } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { useSearchParams } from "react-router-dom";
import { AutoSelectInput } from "@/ahuora-design-system/ui/auto-select-input";
import { Badge } from "@/ahuora-design-system/ui/badge";
import { Button } from "@/ahuora-design-system/ui/button";
import {
  Finding,
  MlModelRead,
  ObjectTypeEnum,
  useCoreMlCreateMutation,
  useCoreMlcolumnmappingListQuery,
  useCoreMlDestroyMutation,
  useCoreMlListQuery,
  useCoreMlPartialUpdateMutation,
  useDiagnosticsEvaluateSimulationObjectPropertyRulesQuery,
  useUnitopsSimulationobjectsRetrieveQuery,
} from "@/api/apiStore.gen";
import { ObjectType } from "@/data/ObjectTypes.gen";
import objs from "@/data/unitOpConfigs";
import { useCurrentObjectId } from "@/hooks/flowsheetObjects";
import { ToolTipCover } from "../../../../../ahuora-design-system/ui/tooltip";
import { RuleFinding } from "../../Diagnostics/useRuleValidation";
import MachineLearningData from "../../PropertiesSidebar/MachineLearning/MachineLearningData";
import { OrderedPropertyList } from "../../PropertiesSidebar/PropertyPanel/Properties";
 
export const MLProperties = () => {
  const currentObjectId = useCurrentObjectId();
  const currentObject = useUnitopsSimulationobjectsRetrieveQuery({
    id: currentObjectId,
  }).data;
  const { data: modelSet } = useCoreMlListQuery({
    simulationObject: currentObjectId,
  });
  const [createMLModel] = useCoreMlCreateMutation();
  const isMachineLearningBlock =
    currentObject?.objectType === ObjectTypeEnum.MachineLearningBlock;
  const disableAddMLModel =
    isMachineLearningBlock && (modelSet?.length ?? 0) > 0;
 
  const addButtonTooltip = disableAddMLModel
    ? "Only one machine learning model can be attached."
    : "Add a machine learning model.";
  const displayedModels = useMemo(() => {
    if (!modelSet) {
      return [];
    }
 
    const sortedModels = [...modelSet].sort((a, b) => a.id - b.id);
    if (!isMachineLearningBlock) {
      return sortedModels;
    }
 
    return sortedModels
      .sort((a, b) => Number(modelHasState(b)) - Number(modelHasState(a)))
      .slice(0, 1);
  }, [isMachineLearningBlock, modelSet]);
 
  const onAddMLModel = () => {
    createMLModel({
      createMlModel: {
        simulationObject: currentObjectId,
        surrogate_model: {},
      },
    });
  };
 
  const mapMLModelsFn = (modelSet) => {
    return [...modelSet] // clone to avoid mutating original
      .sort((a, b) => a.id - b.id)
      .map((model) => {
        return <MLCard key={model.id} model={model} />;
      });
  };
 
  return (
    <div className="flex flex-col gap-2">
      {mapMLModelsFn(displayedModels)}
      {!isMachineLearningBlock && (
        <ToolTipCover asChild content={addButtonTooltip}>
          <Button
            variant="secondary"
            onClick={onAddMLModel}
            disabled={disableAddMLModel}
          >
            <Plus aria-label="Add ML Model" /> Add ML Model
          </Button>
        </ToolTipCover>
      )}
    </div>
  );
};
 
const objects = objs as Record<string, ObjectType>;
 
function modelHasState(model: MlModelRead): boolean {
  return Boolean(
    model.csv_file_name ||
      model.csv_upload_session ||
      model.csv_headers?.length ||
      model.charts?.length ||
      model.metrics?.length ||
      Object.keys(model.surrogate_model ?? {}).length,
  );
}
 
// Convert backend Finding to UI RuleFinding format for frontend display give it an id etc
const toRuleFinding = (finding: Finding): RuleFinding => ({
  id:
    finding.id ??
    `${finding.ruleReference ?? "finding"}-${finding.propertyId ?? "property"}-${finding.title}`,
  severity: finding.severity,
  title: finding.title,
  description: finding.description,
  ruleReference: finding.ruleReference ?? undefined,
  propertyKey: finding.propertyKey ?? undefined,
});
 
export function MLCard({
  model,
  showTop,
}: {
  model: MlModelRead;
  showTop?: boolean;
}) {
  const [searchParams] = useSearchParams();
 
  const currentObjectId = +(searchParams.get("object") || 0);
  const [updateModel] = useCoreMlPartialUpdateMutation();
  const [deleteModel] = useCoreMlDestroyMutation();
  const [openMLDialog, setOpenMLDialog] = useState(false);
  const { data: currentObj } = useUnitopsSimulationobjectsRetrieveQuery(
    { id: currentObjectId },
    { skip: !currentObjectId }, // Skip the query if no valid ID
  );
  const { data: columnMappings } = useCoreMlcolumnmappingListQuery();
  const objectSchema = currentObj?.objectType
    ? objects[currentObj.objectType]
    : undefined;
  const propertySetGroups = objectSchema?.propertySetGroups;
  const schema = propertySetGroups
    ? Object.values(propertySetGroups)[0]
    : undefined;
  const progress = model.active_step ?? 0;
  const propertySet = currentObj?.properties;
 
  Iif (showTop == undefined) showTop = true;
 
  useEffect(() => {
    setOpenMLDialog(false);
  }, [currentObjectId]);
 
  const { data: objectRuleFindings } =
    useDiagnosticsEvaluateSimulationObjectPropertyRulesQuery(
      {
        flowsheet: currentObj?.flowsheet ?? 0,
        simulationObjectId: currentObj?.id ?? 0,
      },
      {
        skip: !currentObj?.id || !currentObj?.flowsheet,
      },
    );
 
  const onUpdateName = (value: string) => {
    updateModel({
      id: model.id,
      patchedPatchMlModel: {
        displayName: value,
      },
    });
  };
 
  const onDeleteModel = () => {
    deleteModel({
      id: model.id,
    });
  };
 
  const ruleFindingsByPropertyKey = useMemo(() => {
    // We group once here, then each property row reads only its own findings.
    const groupedFindings: Record<string, RuleFinding[]> = {};
    objectRuleFindings?.findings?.forEach((finding) => {
      if (!finding.propertyKey) {
        // Object-level findings (no propertyKey) are not shown inline on a field.
        return;
      }
      if (!groupedFindings[finding.propertyKey]) {
        groupedFindings[finding.propertyKey] = [];
      }
      groupedFindings[finding.propertyKey].push(toRuleFinding(finding));
    });
    return groupedFindings;
  }, [objectRuleFindings?.findings]);
 
  const mapMLPropsFn = (model, propertySet) => {
    if (!schema) {
      return null;
    }
 
    const mappingsForModel =
      columnMappings?.filter((mapping) => mapping.model === model.id) || [];
 
    const mappedPropertyInfoIds = new Set(
      mappingsForModel
        .map((mapping) => mapping.propertyInfo)
        .filter((id): id is number => id != null),
    );
 
    const mlProps = propertySet.ContainedProperties.filter((property) =>
      mappedPropertyInfoIds.has(property.id),
    );
 
    return (
      <>
        <OrderedPropertyList
          properties={mlProps}
          schema={schema}
          ruleFindingsByPropertyKey={ruleFindingsByPropertyKey}
        />
      </>
    );
  };
 
  return (
    <div className="bg-muted rounded-lg pb-1 min-h-full">
      {showTop && (
        <>
          <div
            className="flex flex-row p-2 justify-between bg-accent items-center gap-2 rounded-t-lg"
            aria-label="ml-model-div"
          >
            <Badge className="max-w-100" aria-label="ml-model-name">
              <AutoSelectInput
                aria-label="ml-model-name"
                textSize="text-xs"
                textColor="text-primary"
                width="max-w-500"
                value={model.displayName}
                onUpdateValue={onUpdateName}
              />
            </Badge>
 
            <div className="flex items-center gap-2 ml-auto">
              <Button
                className="h-6 text-xs"
                aria-label="view-ml-model"
                onClick={() => setOpenMLDialog(true)}
              >
                {progress !== 0 ? "View" : "Set-up"}
              </Button>
              {currentObj?.objectType !==
                ObjectTypeEnum.MachineLearningBlock && (
                <CircleX
                  size={16}
                  className="cursor-pointer"
                  aria-label="delete-ml-model"
                  onClick={onDeleteModel}
                />
              )}
            </div>
          </div>
          <MachineLearningData
            open={openMLDialog}
            onOpenChange={setOpenMLDialog}
            hideTrigger={true}
            model={model}
          />
        </>
      )}
      <div
        className={`rounded-md flex flex-col -mx-2 -mt-6 ${currentObj?.objectType !== ObjectTypeEnum.Stream && "-mb-4"}`}
      >
        {mapMLPropsFn(model, propertySet || { ContainedProperties: [] })}
      </div>
    </div>
  );
}