All files / src/pages/flowsheet-page/flowsheet/PropertiesSidebar/MachineLearning SuccesslyTrained.tsx

43.63% Statements 24/55
10% Branches 1/10
58.33% Functions 7/12
42.59% Lines 23/54

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                                                  33x 1x 1x 1x       1x 4x     1x 1x 1x 1x 1x 1x   1x                                   1x                 1x                                                                                                                               1x 2x             1x 1x                                             1x               3x   1x                                 3x                                                  
import { Button } from "@/ahuora-design-system/ui/button";
import { ScrollArea } from "@/ahuora-design-system/ui/scroll-area";
import {
    Select,
    SelectContent,
    SelectGroup,
    SelectItem,
    SelectLabel,
    SelectTrigger,
    SelectValue,
} from "@/ahuora-design-system/ui/select";
import { Separator } from "@/ahuora-design-system/ui/separator";
import { MlModelRead, useLazyCoreMlExportMlModelRetrieveQuery } from "@/api/apiStore.gen";
import { useState } from "react";
import {
    CartesianGrid,
    ReferenceArea,
    ResponsiveContainer,
    Scatter,
    ScatterChart,
    Tooltip,
    XAxis,
    YAxis,
} from "recharts";
 
const ShowChart = ({ chartData, name }) => {
    const minVal = chartData.min;
    const maxVal = chartData.max;
    const refLine = [
        { x: minVal, y: minVal },
        { x: maxVal, y: maxVal },
    ];
    const roundToNiceNumber = (num: number) => {
        return Number(num.toPrecision(2));
    };
 
    const [left, setLeft] = useState(roundToNiceNumber(minVal));
    const [right, setRight] = useState(roundToNiceNumber(maxVal));
    const [bottom, setBottom] = useState(roundToNiceNumber(minVal));
    const [top, setTop] = useState(roundToNiceNumber(maxVal));
    const [refAreaLeft, setRefAreaLeft] = useState(null);
    const [refAreaRight, setRefAreaRight] = useState(null);
 
    const zoom = () => {
        Iif (!refAreaLeft || !refAreaRight || refAreaLeft === refAreaRight) {
            setRefAreaLeft(null);
            setRefAreaRight(null);
            return;
        }
 
        const leftVal = Math.min(refAreaLeft, refAreaRight);
        const rightVal = Math.max(refAreaLeft, refAreaRight);
 
        setLeft(roundToNiceNumber(leftVal));
        setRight(roundToNiceNumber(rightVal));
        setBottom(roundToNiceNumber(leftVal));
        setTop(roundToNiceNumber(rightVal));
        setRefAreaLeft(null);
        setRefAreaRight(null);
    };
 
    const zoomOut = () => {
        setLeft(roundToNiceNumber(minVal));
        setRight(roundToNiceNumber(maxVal));
        setBottom(roundToNiceNumber(minVal));
        setTop(roundToNiceNumber(maxVal));
        setRefAreaLeft(null);
        setRefAreaRight(null);
    };
 
    return (
        <div className="select-none w-full" aria-label="QQ Plot">
            <h1 className="text-center">
                QQ Plot of the surrogate model's outlet {name}
            </h1>
            <div className="flex justify-end">
                <Button onClick={zoomOut} variant="outline" size="sm" className="mb-2">
                    Zoom to fit
                </Button>
            </div>
            <ResponsiveContainer width="100%" height={400}>
                <ScatterChart
                    width={730}
                    height={250}
                    margin={{ right: 0, left: 60, bottom: 20 }}
                    onMouseDown={(e) => setRefAreaLeft(e.xValue)}
                    onMouseMove={(e) => refAreaLeft && setRefAreaRight(e.xValue)}
                    onMouseUp={zoom}
                >
                    <CartesianGrid strokeDasharray="3 3" />
                    <XAxis
                        dataKey="x"
                        type="number"
                        name={`${chartData.output_label} (model)`}
                        label={{
                            value: `${chartData.output_label} (model)`,
                            offset: -15,
                            position: "insideBottom",
                        }}
                        domain={[left, right]}
                    />
                    <YAxis
                        dataKey="y"
                        type="number"
                        name={`${chartData.output_label} (data)`}
                        label={{
                            value: `${chartData.output_label} (data)`,
                            angle: -90,
                            position: "insideLeft",
                            offset: -50,
                        }}
                        domain={[bottom, top]}
                    />
                    <Tooltip cursor={{ strokeDasharray: "3 3" }} />
                    <Scatter
                        data={JSON.parse(chartData.qq_plot_data)}
                        fill="white"
                        shape="cross"
                    />
                    <Scatter data={refLine} fill="#249580" line={{ stroke: "#249580" }} />
                    {refAreaLeft && refAreaRight && (
                        <ReferenceArea
                            x1={refAreaLeft}
                            x2={refAreaRight}
                            strokeOpacity={0.3}
                        />
                    )}
                </ScatterChart>
            </ResponsiveContainer>
        </div>
    );
};
 
function ShowMetrics({ metric }) {
    return Object.entries(metric).map(([key, value], index) => (
        <p key={key} aria-label={`metric-${key}`}>
            {key}: {String(value)}
        </p>
    ));
}
 
export default function SuccesslyTrained({ model }: { model: MlModelRead }) {
    const [selected, setSelected] = useState(0);
    const [triggerDownload] = useLazyCoreMlExportMlModelRetrieveQuery();
 
    async function handleDownload() {
        const result = await triggerDownload({ model: model.id }).unwrap();
 
        // Convert JSON to Blob
        const blob = new Blob([JSON.stringify(result, null, 2)], {
            type: "application/json",
        });
 
        // Create a temporary download link
        const url = URL.createObjectURL(blob);
        const link = document.createElement("a");
        link.href = url;
        link.download = `model-${model.id}.json`;
        document.body.appendChild(link);
        link.click();
 
        // Cleanup
        link.remove();
        URL.revokeObjectURL(url);
    }
 
    Iif (model.charts.length === 0) {
        return (
            <div>
                <p>Success, you can use this in the flowsheet</p>
            </div>
        );
    }
 
    const columns = model.charts.map((chart) => chart.output_label);
 
    return (
        <ScrollArea className="h-full pr-3">
            <div className="flex flex-col gap-4">
                <div className="flex justify-between">
                    <div className="flex flex-row items-center gap-3">
                        <p>Show testing results for </p>
                        <Select onValueChange={setSelected} value={selected}>
                            <SelectTrigger
                                className="w-[180px]"
                                aria-label="view-ml-property"
                            >
                                <SelectValue placeholder="View property" />
                            </SelectTrigger>
                            <SelectContent>
                                <SelectGroup>
                                    <SelectLabel>Property</SelectLabel>
                                    {columns.map((column, index) => (
                                        <SelectItem
                                            key={index}
                                            value={index}
                                            ariaLabel={`graph-${column}`}
                                        >
                                            {column}
                                        </SelectItem>
                                    ))}
                                </SelectGroup>
                            </SelectContent>
                        </Select>
                    </div>
                    <Button onClick={handleDownload}>Download ml model</Button>
                </div>
                <Separator />
                <ShowChart
                    chartData={model.charts[selected]}
                    name={columns[selected]}
                />
                <Separator />
                <ShowMetrics metric={model.metrics[selected]} />
            </div>
        </ScrollArea>
    );
}