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

74.59% Statements 91/122
60.2% Branches 59/98
31.25% Functions 5/16
86.41% Lines 70/81

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                                                    222x 222x 222x   257x 222x   257x 222x   222x   222x   222x       222x 4x           292x   222x                   296x 39x                   378x 372x       76x     76x                     182x             179x   202x 179x 179x 179x 179x 202x 200x   179x 179x 179x 200x 179x 179x   179x     179x 21x 179x 179x 221x 21x 179x 200x     179x 5x           221x   179x 2x     221x       37x 37x                 216x 179x 179x   179x   328x   79x           79x 420x 79x                     317x       51x                                         6x                                           536x 79x 179x   416x 337x 359x      
import { CircleX, Plus } from "lucide-react";
import { 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/objects.json";
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 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">
      {modelSet && mapMLModelsFn(modelSet)}
      {!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>;
 
// 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 = objects[currentObj!.objectType!];
  const propertySetGroups = objectSchema.propertySetGroups!;
  const schema = Object.values(propertySetGroups)[0];
  const progress = model.progress;
  const propertySet = currentObj?.properties;
 
  Iif (showTop == undefined) showTop = true;
 
  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,
      patchedUpdateMlModel: {
        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) => {
    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>
  );
}