新增爆管侦测面板及相关功能模块
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
import { MapSkeleton } from "@components/loading/MapSkeleton";
|
||||
|
||||
export default function Loading() {
|
||||
return <MapSkeleton />;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
"use client";
|
||||
|
||||
import MapComponent from "@components/olmap/core/MapComponent";
|
||||
import MapToolbar from "@components/olmap/core/Controls/Toolbar";
|
||||
import BurstDetectionPanel from "@/components/olmap/BurstDetection/BurstDetectionPanel";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="relative h-full w-full overflow-hidden">
|
||||
<MapComponent>
|
||||
<MapToolbar queryType="scheme" schemeType="burst_detection" hiddenButtons={["style"]} />
|
||||
<BurstDetectionPanel />
|
||||
</MapComponent>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -18,13 +18,12 @@ import { ProjectProvider } from "@/contexts/ProjectContext";
|
||||
import { useAuthStore } from "@/store/authStore";
|
||||
|
||||
import { LiaNetworkWiredSolid } from "react-icons/lia";
|
||||
import { TbDatabaseEdit, TbLocationPin } from "react-icons/tb";
|
||||
import { TbDatabaseEdit, TbLocationPin, TbActivity } from "react-icons/tb";
|
||||
import { LuReplace } from "react-icons/lu";
|
||||
import { AiOutlineSecurityScan } from "react-icons/ai";
|
||||
import { AiOutlinePartition } from "react-icons/ai";
|
||||
import { MdWater, MdOutlineWaterDrop, MdCleaningServices } from "react-icons/md";
|
||||
import {
|
||||
Analytics as AnalyticsIcon,
|
||||
MyLocation as MyLocationIcon,
|
||||
Search as SearchIcon,
|
||||
} from "@mui/icons-material";
|
||||
@@ -193,6 +192,15 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
|
||||
label: "爆管定位",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "爆管侦测",
|
||||
list: "/hydraulic-simulation/burst-detection",
|
||||
meta: {
|
||||
parent: "Hydraulic Simulation",
|
||||
icon: <TbActivity className="w-6 h-6" />,
|
||||
label: "爆管侦测",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "DMA 漏损识别",
|
||||
list: "/hydraulic-simulation/dma-leak-detection",
|
||||
|
||||
@@ -0,0 +1,471 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo, useState, useCallback } from "react";
|
||||
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
|
||||
import RefreshIcon from "@mui/icons-material/Refresh";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
CircularProgress,
|
||||
Collapse,
|
||||
FormControl,
|
||||
MenuItem,
|
||||
Select,
|
||||
TextField,
|
||||
Typography,
|
||||
IconButton,
|
||||
} from "@mui/material";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
|
||||
import { useNotification } from "@refinedev/core";
|
||||
import dayjs, { Dayjs } from "dayjs";
|
||||
import "dayjs/locale/zh-cn";
|
||||
import { api } from "@/lib/api";
|
||||
import { NETWORK_NAME, config } from "@config/config";
|
||||
import { BurstDetectionResult } from "./types";
|
||||
|
||||
interface Props {
|
||||
onResult: (result: BurstDetectionResult) => void;
|
||||
}
|
||||
|
||||
interface SchemeItem {
|
||||
scheme_id: number;
|
||||
scheme_name: string;
|
||||
scheme_type: string;
|
||||
create_time: string;
|
||||
scheme_start_time: string;
|
||||
scheme_detail?: {
|
||||
modify_total_duration: number;
|
||||
};
|
||||
}
|
||||
|
||||
const AnalysisParameters: React.FC<Props> = ({ onResult }) => {
|
||||
const { open } = useNotification();
|
||||
const [schemeName, setSchemeName] = useState(`Burst_Detection_${Date.now()}`);
|
||||
const [dataSource, setDataSource] = useState<"monitoring" | "simulation">("monitoring");
|
||||
const [schemes, setSchemes] = useState<SchemeItem[]>([]);
|
||||
const [selectedSchemeId, setSelectedSchemeId] = useState<number | "">("");
|
||||
const [schemeLoading, setSchemeLoading] = useState(false);
|
||||
const [scadaStart, setScadaStart] = useState<Dayjs | null>(dayjs().subtract(3, "day"));
|
||||
const [scadaEnd, setScadaEnd] = useState<Dayjs | null>(dayjs());
|
||||
const [mu, setMu] = useState<number>(100);
|
||||
const [pointsPerDay, setPointsPerDay] = useState<number>(96);
|
||||
const [nEstimators, setNEstimators] = useState<number>(50);
|
||||
const [contaminationInput, setContaminationInput] = useState<string>("auto");
|
||||
const [advancedOpen, setAdvancedOpen] = useState(false);
|
||||
const [running, setRunning] = useState(false);
|
||||
const isSimulationMode = dataSource === "simulation";
|
||||
|
||||
const applySchemeTimeRange = useCallback((scheme: SchemeItem) => {
|
||||
const start = dayjs(scheme.scheme_start_time);
|
||||
const durationSeconds = scheme.scheme_detail?.modify_total_duration ?? 3600;
|
||||
const end = start.add(durationSeconds, "second");
|
||||
|
||||
setScadaStart(start);
|
||||
setScadaEnd(end);
|
||||
}, []);
|
||||
|
||||
const fetchSchemes = useCallback(
|
||||
async ({ force = false, notify = false }: { force?: boolean; notify?: boolean } = {}) => {
|
||||
if (schemeLoading || (!force && schemes.length > 0)) return;
|
||||
|
||||
setSchemeLoading(true);
|
||||
try {
|
||||
const response = await api.get(`${config.BACKEND_URL}/api/v1/getallschemes/`, {
|
||||
params: { network: NETWORK_NAME },
|
||||
});
|
||||
const burstSchemes = (response.data as SchemeItem[]).filter(
|
||||
(scheme) => scheme.scheme_type === "burst_analysis",
|
||||
);
|
||||
|
||||
setSchemes(burstSchemes);
|
||||
|
||||
if (selectedSchemeId) {
|
||||
const matchedScheme = burstSchemes.find(
|
||||
(scheme) => scheme.scheme_id === selectedSchemeId,
|
||||
);
|
||||
if (matchedScheme) {
|
||||
applySchemeTimeRange(matchedScheme);
|
||||
} else {
|
||||
setSelectedSchemeId("");
|
||||
}
|
||||
}
|
||||
|
||||
if (notify) {
|
||||
open?.({
|
||||
type: "success",
|
||||
message: "方案列表已刷新",
|
||||
description: `当前可选爆管分析方案 ${burstSchemes.length} 个`,
|
||||
});
|
||||
}
|
||||
} catch (error: any) {
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "刷新方案失败",
|
||||
description:
|
||||
error?.response?.data?.detail ?? error?.message ?? "无法获取爆管分析方案列表",
|
||||
});
|
||||
} finally {
|
||||
setSchemeLoading(false);
|
||||
}
|
||||
},
|
||||
[applySchemeTimeRange, open, schemeLoading, schemes.length, selectedSchemeId],
|
||||
);
|
||||
|
||||
const handleDataSourceChange = (value: "monitoring" | "simulation") => {
|
||||
setDataSource(value);
|
||||
if (value === "simulation") {
|
||||
void fetchSchemes();
|
||||
}
|
||||
};
|
||||
|
||||
const handleSchemeSelect = (schemeId: number) => {
|
||||
setSelectedSchemeId(schemeId);
|
||||
const scheme = schemes.find((item) => item.scheme_id === schemeId);
|
||||
if (scheme) {
|
||||
applySchemeTimeRange(scheme);
|
||||
}
|
||||
};
|
||||
|
||||
const timeWindowValid = useMemo(() => {
|
||||
if (!scadaStart || !scadaEnd) return false;
|
||||
return scadaEnd.diff(scadaStart, "day", true) >= 2;
|
||||
}, [scadaEnd, scadaStart]);
|
||||
|
||||
const contaminationValue = useMemo(() => {
|
||||
const normalized = contaminationInput.trim().toLowerCase();
|
||||
if (!normalized || normalized === "auto") {
|
||||
return "auto" as const;
|
||||
}
|
||||
const parsed = Number(normalized);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0 || parsed >= 0.5) {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
}, [contaminationInput]);
|
||||
|
||||
const isValid =
|
||||
Boolean(scadaStart && scadaEnd) &&
|
||||
timeWindowValid &&
|
||||
Number.isFinite(mu) &&
|
||||
mu > 0 &&
|
||||
Number.isFinite(pointsPerDay) &&
|
||||
pointsPerDay > 0 &&
|
||||
Number.isFinite(nEstimators) &&
|
||||
nEstimators > 0 &&
|
||||
contaminationValue !== null &&
|
||||
(dataSource !== "simulation" || Boolean(selectedSchemeId));
|
||||
|
||||
const handleRun = async () => {
|
||||
if (!isValid || !scadaStart || !scadaEnd || contaminationValue === null) {
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "参数不完整",
|
||||
description: "请检查时间范围(至少2天)和高级参数是否填写正确。",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setRunning(true);
|
||||
open?.({
|
||||
key: "burst-detection-analysis",
|
||||
type: "progress",
|
||||
message: "正在执行爆管侦测",
|
||||
description: "正在读取数据并计算异常分数。",
|
||||
undoableTimeout: 3,
|
||||
});
|
||||
|
||||
try {
|
||||
const selectedScheme =
|
||||
dataSource === "simulation"
|
||||
? schemes.find((item) => item.scheme_id === selectedSchemeId)
|
||||
: undefined;
|
||||
|
||||
const response = await api.post("/api/v1/burst-detection/detect/", {
|
||||
network: NETWORK_NAME,
|
||||
data_source: dataSource,
|
||||
scheme_name: schemeName.trim() || undefined,
|
||||
scada_start: scadaStart.toISOString(),
|
||||
scada_end: scadaEnd.toISOString(),
|
||||
mu,
|
||||
points_per_day: pointsPerDay,
|
||||
iforest_params: {
|
||||
n_estimators: nEstimators,
|
||||
contamination: contaminationValue,
|
||||
},
|
||||
simulation_scheme_name: selectedScheme?.scheme_name,
|
||||
simulation_scheme_type: selectedScheme?.scheme_type,
|
||||
});
|
||||
|
||||
onResult({
|
||||
...(response.data as BurstDetectionResult),
|
||||
scheme_name: schemeName.trim() || (response.data as BurstDetectionResult).scheme_name,
|
||||
algorithm_params: {
|
||||
mu,
|
||||
points_per_day: pointsPerDay,
|
||||
iforest_params: {
|
||||
n_estimators: nEstimators,
|
||||
contamination: contaminationValue,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
open?.({
|
||||
key: "burst-detection-analysis",
|
||||
type: "success",
|
||||
message: "爆管侦测完成",
|
||||
description: `共识别 ${response.data.summary?.anomaly_day_count ?? 0} 个异常日。`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
open?.({
|
||||
key: "burst-detection-analysis",
|
||||
type: "error",
|
||||
message: "侦测失败",
|
||||
description: error?.response?.data?.detail ?? error?.message ?? "请求失败",
|
||||
});
|
||||
} finally {
|
||||
setRunning(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box className="flex flex-col flex-1 min-h-0">
|
||||
<Box className="flex flex-col gap-3">
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="mb-1 font-medium">
|
||||
方案名称
|
||||
</Typography>
|
||||
<TextField
|
||||
value={schemeName}
|
||||
onChange={(event) => setSchemeName(event.target.value)}
|
||||
placeholder="请输入方案名称"
|
||||
fullWidth
|
||||
size="small"
|
||||
/>
|
||||
</Box>
|
||||
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="mb-1 font-medium">
|
||||
数据来源
|
||||
</Typography>
|
||||
<FormControl fullWidth size="small">
|
||||
<Select
|
||||
value={dataSource}
|
||||
onChange={(e) => handleDataSourceChange(e.target.value as "monitoring" | "simulation")}
|
||||
>
|
||||
<MenuItem value="monitoring">监测数据</MenuItem>
|
||||
<MenuItem value="simulation">模拟方案</MenuItem>
|
||||
</Select>
|
||||
</FormControl>
|
||||
</Box>
|
||||
|
||||
{isSimulationMode && (
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="mb-1 font-medium">
|
||||
选择爆管分析方案
|
||||
</Typography>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: 1 }}>
|
||||
<FormControl fullWidth size="small">
|
||||
<Select
|
||||
value={selectedSchemeId}
|
||||
onChange={(e) => handleSchemeSelect(Number(e.target.value))}
|
||||
disabled={schemeLoading}
|
||||
displayEmpty
|
||||
>
|
||||
<MenuItem value="" disabled>
|
||||
请选择方案
|
||||
</MenuItem>
|
||||
{schemes.map((scheme) => (
|
||||
<MenuItem key={scheme.scheme_id} value={scheme.scheme_id}>
|
||||
{scheme.scheme_name}
|
||||
</MenuItem>
|
||||
))}
|
||||
</Select>
|
||||
</FormControl>
|
||||
<IconButton
|
||||
size="small"
|
||||
color="primary"
|
||||
onClick={() => void fetchSchemes({ force: true, notify: true })}
|
||||
disabled={schemeLoading}
|
||||
aria-label="刷新爆管分析方案"
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: "divider",
|
||||
borderRadius: 1,
|
||||
}}
|
||||
>
|
||||
{schemeLoading ? (
|
||||
<CircularProgress size={18} color="inherit" />
|
||||
) : (
|
||||
<RefreshIcon fontSize="small" />
|
||||
)}
|
||||
</IconButton>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<LocalizationProvider
|
||||
dateAdapter={AdapterDayjs}
|
||||
adapterLocale="zh-cn"
|
||||
localeText={pickerZhCN.components.MuiLocalizationProvider.defaultProps.localeText}
|
||||
>
|
||||
<Box className="grid grid-cols-2 gap-2">
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="mb-1 font-medium">
|
||||
侦测开始时间
|
||||
</Typography>
|
||||
<DateTimePicker
|
||||
value={scadaStart}
|
||||
onChange={setScadaStart}
|
||||
maxDateTime={scadaEnd ? scadaEnd.subtract(2, "day") : undefined}
|
||||
disabled={isSimulationMode}
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
slotProps={{ textField: { size: "small", fullWidth: true } }}
|
||||
/>
|
||||
</Box>
|
||||
<Box>
|
||||
<Typography variant="subtitle2" className="mb-1 font-medium">
|
||||
侦测结束时间
|
||||
</Typography>
|
||||
<DateTimePicker
|
||||
value={scadaEnd}
|
||||
onChange={setScadaEnd}
|
||||
minDateTime={scadaStart ? scadaStart.add(2, "day") : undefined}
|
||||
disabled={isSimulationMode}
|
||||
format="YYYY-MM-DD HH:mm"
|
||||
slotProps={{ textField: { size: "small", fullWidth: true } }}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</LocalizationProvider>
|
||||
|
||||
<Box className="rounded-lg border border-blue-100 bg-blue-50 px-3 py-2 text-sm text-blue-900">
|
||||
当前页面为展示版:手动触发一次侦测,展示异常日、最新测点排名和结果表格,不做定时轮询。
|
||||
</Box>
|
||||
|
||||
<Box
|
||||
sx={{
|
||||
border: "1px solid",
|
||||
borderColor: "grey.200",
|
||||
borderRadius: 1,
|
||||
overflow: "hidden",
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
role="button"
|
||||
tabIndex={0}
|
||||
onClick={() => setAdvancedOpen((prev) => !prev)}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === "Enter" || event.key === " ") {
|
||||
setAdvancedOpen((prev) => !prev);
|
||||
}
|
||||
}}
|
||||
sx={{
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
px: 1.25,
|
||||
py: 0.75,
|
||||
cursor: "pointer",
|
||||
backgroundColor: "transparent",
|
||||
"&:hover": { backgroundColor: "action.hover" },
|
||||
}}
|
||||
>
|
||||
<Typography variant="body2" color="text.secondary">
|
||||
高级参数
|
||||
</Typography>
|
||||
<ExpandMoreIcon
|
||||
sx={{
|
||||
transform: advancedOpen ? "rotate(180deg)" : "rotate(0deg)",
|
||||
transition: "transform 0.2s ease",
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Collapse in={advancedOpen} timeout="auto" unmountOnExit>
|
||||
<Box
|
||||
sx={{
|
||||
px: 1.25,
|
||||
pt: 1.25,
|
||||
pb: 1.25,
|
||||
backgroundColor: "transparent",
|
||||
}}
|
||||
>
|
||||
<Box className="flex flex-col gap-3">
|
||||
<TextField
|
||||
type="number"
|
||||
label="频域截断系数"
|
||||
value={mu}
|
||||
onChange={(event) => setMu(Number(event.target.value))}
|
||||
size="small"
|
||||
fullWidth
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
type="number"
|
||||
label="每日采样点数"
|
||||
value={pointsPerDay}
|
||||
onChange={(event) => setPointsPerDay(Number(event.target.value))}
|
||||
size="small"
|
||||
fullWidth
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
type="number"
|
||||
label="孤立森林树数量"
|
||||
value={nEstimators}
|
||||
onChange={(event) => setNEstimators(Number(event.target.value))}
|
||||
size="small"
|
||||
fullWidth
|
||||
inputProps={{ min: 1 }}
|
||||
/>
|
||||
<TextField
|
||||
label="异常比例"
|
||||
value={contaminationInput}
|
||||
onChange={(event) => setContaminationInput(event.target.value)}
|
||||
size="small"
|
||||
fullWidth
|
||||
helperText="填写 auto 或 0~0.5 之间的小数。"
|
||||
error={contaminationValue === null}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</Collapse>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box className="mt-auto pt-3 flex gap-2">
|
||||
<Button
|
||||
variant="outlined"
|
||||
fullWidth
|
||||
disabled={running}
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
onClick={() => {
|
||||
setSchemeName(`Burst_Detection_${Date.now()}`);
|
||||
setScadaStart(dayjs().subtract(3, "day"));
|
||||
setScadaEnd(dayjs());
|
||||
setMu(100);
|
||||
setPointsPerDay(96);
|
||||
setNEstimators(50);
|
||||
setContaminationInput("auto");
|
||||
}}
|
||||
>
|
||||
重置
|
||||
</Button>
|
||||
<Button
|
||||
variant="contained"
|
||||
fullWidth
|
||||
disabled={!isValid || running}
|
||||
onClick={handleRun}
|
||||
className="bg-blue-600 hover:bg-blue-700"
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
>
|
||||
{running ? <CircularProgress size={20} color="inherit" /> : "开始侦测"}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default AnalysisParameters;
|
||||
@@ -0,0 +1,153 @@
|
||||
"use client";
|
||||
|
||||
import React, { useCallback, useState } from "react";
|
||||
import { Box, Drawer, IconButton, Tab, Tabs, Tooltip, Typography } from "@mui/material";
|
||||
import {
|
||||
Analytics as AnalyticsIcon,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
FormatListBulleted,
|
||||
Search as SearchIcon,
|
||||
} from "@mui/icons-material";
|
||||
import AnalysisParameters from "./AnalysisParameters";
|
||||
import DetectionResults from "./DetectionResults";
|
||||
import SchemeQuery from "./SchemeQuery";
|
||||
import { BurstDetectionResult } from "./types";
|
||||
|
||||
const TabPanel = ({
|
||||
value,
|
||||
index,
|
||||
children,
|
||||
}: {
|
||||
value: number;
|
||||
index: number;
|
||||
children: React.ReactNode;
|
||||
}) => (
|
||||
<div role="tabpanel" hidden={value !== index} className="flex-1 overflow-hidden flex flex-col">
|
||||
{value === index ? <Box className="flex-1 overflow-auto p-4 flex flex-col">{children}</Box> : null}
|
||||
</div>
|
||||
);
|
||||
|
||||
const BurstDetectionPanel: React.FC = () => {
|
||||
const [open, setOpen] = useState(true);
|
||||
const [tab, setTab] = useState(0);
|
||||
const [result, setResult] = useState<BurstDetectionResult | null>(null);
|
||||
|
||||
const drawerWidth = 450;
|
||||
const panelTitle = "爆管侦测";
|
||||
|
||||
const handleResult = useCallback((payload: BurstDetectionResult) => {
|
||||
setResult(payload);
|
||||
setTab(2);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<>
|
||||
{!open && (
|
||||
<Box
|
||||
className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
|
||||
onClick={() => setOpen(true)}
|
||||
sx={{ zIndex: 1300 }}
|
||||
>
|
||||
<Box className="flex flex-col items-center py-3 px-3 gap-1">
|
||||
<AnalyticsIcon className="text-[#257DD4] w-5 h-5" />
|
||||
<Typography
|
||||
variant="caption"
|
||||
className="text-gray-700 font-semibold my-1 text-xs"
|
||||
style={{ writingMode: "vertical-rl" }}
|
||||
>
|
||||
{panelTitle}
|
||||
</Typography>
|
||||
<ChevronLeft className="text-gray-600 w-4 h-4" />
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
<Drawer
|
||||
anchor="right"
|
||||
open={open}
|
||||
variant="persistent"
|
||||
hideBackdrop
|
||||
sx={{
|
||||
width: 0,
|
||||
flexShrink: 0,
|
||||
"& .MuiDrawer-paper": {
|
||||
width: drawerWidth,
|
||||
boxSizing: "border-box",
|
||||
position: "absolute",
|
||||
top: 16,
|
||||
right: 16,
|
||||
height: "calc(100vh - 32px)",
|
||||
maxHeight: "850px",
|
||||
borderRadius: "12px",
|
||||
boxShadow:
|
||||
"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
|
||||
backdropFilter: "blur(8px)",
|
||||
opacity: 0.95,
|
||||
transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
|
||||
border: "none",
|
||||
"&:hover": {
|
||||
opacity: 1,
|
||||
},
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
|
||||
<Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
|
||||
<Box className="flex items-center gap-2">
|
||||
<AnalyticsIcon className="w-5 h-5" />
|
||||
<Typography variant="h6" className="text-lg font-semibold">
|
||||
{panelTitle}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Tooltip title="收起">
|
||||
<IconButton size="small" onClick={() => setOpen(false)} sx={{ color: "primary.contrastText" }}>
|
||||
<ChevronRight fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
|
||||
<Box className="border-b border-gray-200 bg-white">
|
||||
<Tabs
|
||||
value={tab}
|
||||
onChange={(_, value) => setTab(value)}
|
||||
variant="fullWidth"
|
||||
sx={{
|
||||
minHeight: 48,
|
||||
"& .MuiTab-root": {
|
||||
minHeight: 48,
|
||||
textTransform: "none",
|
||||
fontSize: "0.875rem",
|
||||
fontWeight: 500,
|
||||
transition: "all 0.2s",
|
||||
},
|
||||
"& .Mui-selected": {
|
||||
color: "#257DD4",
|
||||
},
|
||||
"& .MuiTabs-indicator": {
|
||||
backgroundColor: "#257DD4",
|
||||
},
|
||||
}}
|
||||
>
|
||||
<Tab icon={<AnalyticsIcon fontSize="small" />} iconPosition="start" label="侦测参数" />
|
||||
<Tab icon={<SearchIcon fontSize="small" />} iconPosition="start" label="方案查询" />
|
||||
<Tab icon={<FormatListBulleted fontSize="small" />} iconPosition="start" label="侦测结果" />
|
||||
</Tabs>
|
||||
</Box>
|
||||
|
||||
<TabPanel value={tab} index={0}>
|
||||
<AnalysisParameters onResult={handleResult} />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} index={1}>
|
||||
<SchemeQuery onViewResult={handleResult} />
|
||||
</TabPanel>
|
||||
<TabPanel value={tab} index={2}>
|
||||
<DetectionResults result={result} />
|
||||
</TabPanel>
|
||||
</Box>
|
||||
</Drawer>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default BurstDetectionPanel;
|
||||
@@ -0,0 +1,610 @@
|
||||
"use client";
|
||||
|
||||
import React, { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Box, Button, Chip, Tooltip, Typography } from "@mui/material";
|
||||
import { DataGrid, GridColDef } from "@mui/x-data-grid";
|
||||
import { zhCN } from "@mui/x-data-grid/locales";
|
||||
import {
|
||||
FormatListBulleted,
|
||||
InfoOutlined as InfoOutlinedIcon,
|
||||
Room as RoomIcon,
|
||||
ShowChart as ShowChartIcon,
|
||||
CheckCircleOutline as CheckCircleIcon,
|
||||
ErrorOutline as ErrorOutlineIcon,
|
||||
} from "@mui/icons-material";
|
||||
import ReactECharts from "echarts-for-react";
|
||||
import dayjs from "dayjs";
|
||||
import { useMap } from "@components/olmap/core/MapComponent";
|
||||
import { queryFeaturesByIds } from "@/utils/mapQueryService";
|
||||
import { GeoJSON } from "ol/format";
|
||||
import Feature from "ol/Feature";
|
||||
import VectorLayer from "ol/layer/Vector";
|
||||
import VectorSource from "ol/source/Vector";
|
||||
import { Circle, Fill, Stroke, Style } from "ol/style";
|
||||
import { bbox, featureCollection } from "@turf/turf";
|
||||
import { BurstDetectionResult, BurstDetectionRow } from "./types";
|
||||
|
||||
interface Props {
|
||||
result: BurstDetectionResult | null;
|
||||
}
|
||||
|
||||
interface MetricCardProps {
|
||||
label: string;
|
||||
value: string;
|
||||
hint?: string;
|
||||
tone: "blue" | "orange" | "purple" | "green";
|
||||
}
|
||||
|
||||
const toneStyles: Record<
|
||||
MetricCardProps["tone"],
|
||||
{ bg: string; border: string; text: string; darkText: string }
|
||||
> = {
|
||||
blue: {
|
||||
bg: "from-blue-50 to-blue-100",
|
||||
border: "border-blue-200",
|
||||
text: "text-blue-700",
|
||||
darkText: "text-blue-900",
|
||||
},
|
||||
orange: {
|
||||
bg: "from-orange-50 to-orange-100",
|
||||
border: "border-orange-200",
|
||||
text: "text-orange-700",
|
||||
darkText: "text-orange-900",
|
||||
},
|
||||
purple: {
|
||||
bg: "from-purple-50 to-purple-100",
|
||||
border: "border-purple-200",
|
||||
text: "text-purple-700",
|
||||
darkText: "text-purple-900",
|
||||
},
|
||||
green: {
|
||||
bg: "from-green-50 to-green-100",
|
||||
border: "border-green-200",
|
||||
text: "text-green-700",
|
||||
darkText: "text-green-900",
|
||||
},
|
||||
};
|
||||
|
||||
const MetricCard = ({ label, value, hint, tone }: MetricCardProps) => {
|
||||
const style = toneStyles[tone];
|
||||
return (
|
||||
<Box className={`rounded-lg border bg-gradient-to-br p-3 shadow-sm ${style.bg} ${style.border}`}>
|
||||
<Typography variant="caption" className={`mb-1 block text-xs font-semibold uppercase tracking-wide ${style.text}`}>
|
||||
{label}
|
||||
</Typography>
|
||||
<Typography variant="body2" className={`font-bold ${style.darkText}`}>
|
||||
{value}
|
||||
</Typography>
|
||||
{hint ? (
|
||||
<Typography variant="caption" className={`mt-0.5 block text-xs opacity-80 ${style.text}`}>
|
||||
{hint}
|
||||
</Typography>
|
||||
) : null}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const EmptyState = () => (
|
||||
<Box className="flex h-full flex-col items-center justify-center bg-gray-50/50 p-6 text-center">
|
||||
<Box className="mb-4 rounded-full bg-white p-6 shadow-sm">
|
||||
<ShowChartIcon sx={{ fontSize: 48, color: "#cbd5e1" }} />
|
||||
</Box>
|
||||
<Typography variant="h6" className="mb-1 font-bold text-gray-700">
|
||||
等待侦测结果
|
||||
</Typography>
|
||||
<Typography variant="body2" className="max-w-xs text-gray-500">
|
||||
提交一次爆管侦测后,这里会展示异常天数、分数趋势、最新测点排名和结果表格。
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
|
||||
const getScoreLevel = (score: number) => {
|
||||
if (score <= -0.6) return { label: "高风险", color: "error" as const };
|
||||
if (score <= -0.2) return { label: "需关注", color: "warning" as const };
|
||||
return { label: "正常", color: "success" as const };
|
||||
};
|
||||
|
||||
const formatDateTime = (value?: string) => (value ? dayjs(value).format("YYYY-MM-DD HH:mm") : "-");
|
||||
|
||||
const DetectionResults: React.FC<Props> = ({ result }) => {
|
||||
const map = useMap();
|
||||
const highlightLayerRef = useRef<VectorLayer<VectorSource> | null>(null);
|
||||
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
|
||||
const [selectedDay, setSelectedDay] = useState<number | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!map) return;
|
||||
|
||||
const layer = new VectorLayer({
|
||||
source: new VectorSource(),
|
||||
style: new Style({
|
||||
stroke: new Stroke({ color: "#ef4444", width: 4 }),
|
||||
image: new Circle({
|
||||
radius: 7,
|
||||
fill: new Fill({ color: "#ef4444" }),
|
||||
stroke: new Stroke({ color: "#fff", width: 2 }),
|
||||
}),
|
||||
zIndex: 999,
|
||||
}),
|
||||
properties: {
|
||||
name: "爆管侦测高亮",
|
||||
value: "burst_detection_highlight",
|
||||
},
|
||||
});
|
||||
|
||||
map.addLayer(layer);
|
||||
highlightLayerRef.current = layer;
|
||||
|
||||
return () => {
|
||||
highlightLayerRef.current = null;
|
||||
map.removeLayer(layer);
|
||||
};
|
||||
}, [map]);
|
||||
|
||||
useEffect(() => {
|
||||
const source = highlightLayerRef.current?.getSource();
|
||||
if (!source) return;
|
||||
source.clear();
|
||||
highlightFeatures.forEach((feature) => source.addFeature(feature));
|
||||
}, [highlightFeatures]);
|
||||
|
||||
const defaultSelectedDay = useMemo(
|
||||
() =>
|
||||
result?.summary?.most_anomalous_day ??
|
||||
result?.summary?.latest_day?.Day ??
|
||||
result?.rows[0]?.Day ??
|
||||
null,
|
||||
[result],
|
||||
);
|
||||
|
||||
const activeSelectedDay = selectedDay ?? defaultSelectedDay;
|
||||
|
||||
const selectedRow = useMemo<BurstDetectionRow | null>(() => {
|
||||
if (!result || activeSelectedDay === null) return null;
|
||||
return result.rows.find((row) => row.Day === activeSelectedDay) ?? null;
|
||||
}, [activeSelectedDay, result]);
|
||||
|
||||
const scoreSeries = useMemo(
|
||||
() =>
|
||||
result?.rows.map((row) => ({
|
||||
value: [row.Day, Number(row.Score.toFixed(4))],
|
||||
itemStyle: {
|
||||
color: row.IsBurst ? "#ef4444" : row.Score <= -0.2 ? "#f59e0b" : "#10b981",
|
||||
},
|
||||
})) ?? [],
|
||||
[result],
|
||||
);
|
||||
|
||||
const rankingSeries = useMemo(
|
||||
() =>
|
||||
[...(result?.summary?.latest_sensor_rankings ?? [])]
|
||||
.sort((a, b) => a.latest_high_frequency_value - b.latest_high_frequency_value)
|
||||
.map((item) => ({
|
||||
name: item.sensor_node,
|
||||
value: Number(item.latest_high_frequency_value.toFixed(4)),
|
||||
})),
|
||||
[result],
|
||||
);
|
||||
|
||||
const locateSensors = async (sensorIds: string[]) => {
|
||||
if (!map || sensorIds.length === 0) return;
|
||||
|
||||
let features = await queryFeaturesByIds(sensorIds, "geo_junctions_mat");
|
||||
if (features.length === 0) {
|
||||
features = await queryFeaturesByIds(sensorIds, "geo_junctions");
|
||||
}
|
||||
if (features.length === 0) return;
|
||||
|
||||
setHighlightFeatures(features);
|
||||
|
||||
const geojsonFormat = new GeoJSON();
|
||||
const geojsonFeatures = features.map((feature) => geojsonFormat.writeFeatureObject(feature));
|
||||
// @ts-ignore turf typing with ol geojson objects
|
||||
const extent = bbox(featureCollection(geojsonFeatures));
|
||||
map.getView().fit(extent, {
|
||||
maxZoom: 18,
|
||||
duration: 1000,
|
||||
padding: [100, 100, 100, 100],
|
||||
});
|
||||
};
|
||||
|
||||
if (!result) {
|
||||
return <EmptyState />;
|
||||
}
|
||||
|
||||
const latestDay = result.summary?.latest_day;
|
||||
const latestLevel = latestDay ? getScoreLevel(latestDay.Score) : getScoreLevel(0);
|
||||
const mostAnomalousRow = result.rows.find((row) => row.Day === result.summary?.most_anomalous_day) ?? null;
|
||||
const mostAnomalousLevel = getScoreLevel(mostAnomalousRow?.Score ?? 0);
|
||||
const isBurstDetected = result.summary.burst_detected;
|
||||
|
||||
const chartOption = {
|
||||
tooltip: {
|
||||
trigger: "axis",
|
||||
formatter: (params: Array<{ data: { value: [number, number] } }>) => {
|
||||
const point = params[0]?.data?.value;
|
||||
if (!point) return "-";
|
||||
return `侦测日第 ${point[0]} 天<br/>异常分数:${point[1]}`;
|
||||
},
|
||||
},
|
||||
grid: { top: 30, left: 40, right: 20, bottom: 35 },
|
||||
xAxis: {
|
||||
type: "category",
|
||||
name: "侦测日",
|
||||
data: result.rows.map((row) => row.Day),
|
||||
axisLabel: { fontSize: 10 },
|
||||
},
|
||||
yAxis: {
|
||||
type: "value",
|
||||
name: "异常分数",
|
||||
axisLabel: { fontSize: 10 },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: "line",
|
||||
smooth: true,
|
||||
symbolSize: 8,
|
||||
data: scoreSeries,
|
||||
lineStyle: { color: "#2563eb", width: 2 },
|
||||
markLine: {
|
||||
symbol: "none",
|
||||
lineStyle: { type: "dashed", color: "#94a3b8" },
|
||||
data: [{ yAxis: 0 }],
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const rankingOption = {
|
||||
tooltip: {
|
||||
trigger: "axis",
|
||||
axisPointer: { type: "shadow" },
|
||||
},
|
||||
grid: { top: 20, left: 70, right: 20, bottom: 20 },
|
||||
xAxis: { type: "value", axisLabel: { fontSize: 10 } },
|
||||
yAxis: {
|
||||
type: "category",
|
||||
data: rankingSeries.map((item) => item.name),
|
||||
axisLabel: { fontSize: 10 },
|
||||
},
|
||||
series: [
|
||||
{
|
||||
type: "bar",
|
||||
data: rankingSeries.map((item) => ({
|
||||
value: item.value,
|
||||
itemStyle: {
|
||||
color: item.value <= -0.6 ? "#ef4444" : item.value <= -0.2 ? "#f59e0b" : "#10b981",
|
||||
},
|
||||
})),
|
||||
barWidth: 14,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const columns: GridColDef[] = [
|
||||
{
|
||||
field: "Day",
|
||||
headerName: "侦测日",
|
||||
width: 96,
|
||||
valueFormatter: (value?: number) => (typeof value === "number" ? `第 ${value} 天` : "-"),
|
||||
},
|
||||
{
|
||||
field: "Score",
|
||||
headerName: "异常分数",
|
||||
width: 120,
|
||||
valueFormatter: (value?: number) => (typeof value === "number" ? value.toFixed(4) : "-"),
|
||||
},
|
||||
{
|
||||
field: "IsBurst",
|
||||
headerName: "判定结果",
|
||||
width: 120,
|
||||
renderCell: ({ value }) => {
|
||||
const level = value ? { label: "爆管异常", color: "error" as const } : { label: "正常", color: "success" as const };
|
||||
return <Chip size="small" label={level.label} color={level.color} variant="outlined" />;
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const rows = result.rows.map((row) => ({ id: row.Day, ...row }));
|
||||
|
||||
return (
|
||||
<Box className="h-full overflow-auto p-1">
|
||||
<Box className="mb-4 space-y-3">
|
||||
{/* Status Banner */}
|
||||
<Box
|
||||
className={`rounded-lg px-4 py-3 flex items-center gap-3 border ${isBurstDetected
|
||||
? "bg-red-50 border-red-100 text-red-900"
|
||||
: "bg-green-50 border-green-100 text-green-900"
|
||||
}`}
|
||||
>
|
||||
{isBurstDetected ? (
|
||||
<ErrorOutlineIcon className="text-red-600" />
|
||||
) : (
|
||||
<CheckCircleIcon className="text-green-600" />
|
||||
)}
|
||||
<Box className="flex-1">
|
||||
<Typography variant="subtitle2" className="font-bold">
|
||||
{isBurstDetected
|
||||
? `侦测到异常信号 (共 ${result.summary.anomaly_day_count} 天)`
|
||||
: "未侦测到爆管异常"}
|
||||
</Typography>
|
||||
<Typography variant="caption" className="opacity-80">
|
||||
{isBurstDetected
|
||||
? "建议检查异常日期的压力波动情况"
|
||||
: "当前时间窗口内数据特征平稳,符合历史模式"}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Header */}
|
||||
<Box className="flex items-center justify-between px-1">
|
||||
<Box className="flex items-center gap-2">
|
||||
<Box className="h-4 w-1 rounded-full bg-blue-600" />
|
||||
<Typography variant="h6" className="truncate font-bold text-gray-900" sx={{ fontSize: "1.1rem" }}>
|
||||
{result.scheme_name || "爆管侦测结果"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="flex items-center gap-2">
|
||||
{result.username ? (
|
||||
<Chip
|
||||
label={result.username}
|
||||
size="small"
|
||||
sx={{
|
||||
height: 24,
|
||||
backgroundColor: "#f3f4f6",
|
||||
color: "#4b5563",
|
||||
border: "none",
|
||||
fontWeight: 500,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
<Button
|
||||
size="small"
|
||||
variant="outlined"
|
||||
startIcon={<RoomIcon />}
|
||||
onClick={() =>
|
||||
locateSensors(result.summary.latest_sensor_rankings.map((item) => item.sensor_node).slice(0, 5))
|
||||
}
|
||||
sx={{
|
||||
height: 24,
|
||||
minWidth: 0,
|
||||
padding: "0 8px",
|
||||
borderColor: "#bfdbfe",
|
||||
color: "#2563eb",
|
||||
fontSize: "0.75rem",
|
||||
"&:hover": { borderColor: "#60a5fa", backgroundColor: "#eff6ff" },
|
||||
}}
|
||||
>
|
||||
定位
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Configuration Summary */}
|
||||
<Box className="flex flex-wrap items-center gap-x-4 gap-y-2 rounded-lg border border-gray-100 bg-gray-50/50 px-3 py-2 text-xs text-gray-600">
|
||||
<Box className="flex items-center gap-1.5">
|
||||
<Box className="h-1.5 w-1.5 rounded-full bg-blue-400" />
|
||||
<span className="font-medium text-gray-700">时间窗口:</span>
|
||||
<span className="font-mono text-gray-600">
|
||||
{formatDateTime(result.scada_window?.start)} ~ {formatDateTime(result.scada_window?.end)}
|
||||
</span>
|
||||
</Box>
|
||||
<Box className="flex items-center gap-1.5">
|
||||
<Box className="h-1.5 w-1.5 rounded-full bg-purple-400" />
|
||||
<span className="font-medium text-gray-700">数据来源:</span>
|
||||
<span className="text-gray-600">
|
||||
{(() => {
|
||||
const ds = result.data_source;
|
||||
const os = result.observed_source;
|
||||
if (ds === "simulation") return "模拟数据";
|
||||
if (ds === "monitoring") return "监测数据";
|
||||
if (os === "simulation_scheme_timerange") return "模拟数据";
|
||||
if (os === "backend_timerange") return "监测数据";
|
||||
return os || "-";
|
||||
})()}
|
||||
</span>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Metrics Grid */}
|
||||
<Box className="grid grid-cols-2 gap-3">
|
||||
<MetricCard
|
||||
label="异常天数"
|
||||
value={`${result.summary.anomaly_day_count} / ${result.day_count}`}
|
||||
hint={`异常日:${result.summary.anomaly_days.join(", ") || "无"}`}
|
||||
tone={result.summary.anomaly_day_count > 0 ? "orange" : "green"}
|
||||
/>
|
||||
<MetricCard
|
||||
label="最异常日"
|
||||
value={
|
||||
result.summary.burst_detected && result.summary.most_anomalous_day
|
||||
? `第 ${result.summary.most_anomalous_day} 天`
|
||||
: "无"
|
||||
}
|
||||
hint={
|
||||
result.summary.burst_detected && mostAnomalousRow
|
||||
? `分数 ${mostAnomalousRow.Score.toFixed(4)} · ${mostAnomalousLevel.label}`
|
||||
: "-"
|
||||
}
|
||||
tone="purple"
|
||||
/>
|
||||
<MetricCard
|
||||
label="最新状态"
|
||||
value={latestLevel.label}
|
||||
hint={latestDay ? `第 ${latestDay.Day} 天 · 分数 ${latestDay.Score.toFixed(4)}` : "-"}
|
||||
tone={latestLevel.color === "success" ? "green" : "orange"}
|
||||
/>
|
||||
<MetricCard
|
||||
label="测点 / 样本"
|
||||
value={`${result.sensor_nodes.length} / ${result.sample_count}`}
|
||||
hint={`每日采样点数:${result.points_per_day}`}
|
||||
tone="blue"
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Score Trend Chart */}
|
||||
<Box className="mb-4 overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
|
||||
<Box className="flex items-center justify-between border-b border-gray-100 bg-white px-4 py-3">
|
||||
<Box className="flex items-center gap-2">
|
||||
<ShowChartIcon className="h-5 w-5 text-blue-600" />
|
||||
<Typography variant="subtitle1" className="font-bold text-gray-800">
|
||||
异常分数趋势
|
||||
</Typography>
|
||||
</Box>
|
||||
<Tooltip title="分数越小越异常,0 以下通常意味着更值得关注。">
|
||||
<InfoOutlinedIcon fontSize="small" className="text-gray-400" />
|
||||
</Tooltip>
|
||||
</Box>
|
||||
<Box sx={{ height: 250, px: 1.5, py: 1 }}>
|
||||
<ReactECharts
|
||||
option={chartOption}
|
||||
style={{ height: "100%", width: "100%" }}
|
||||
onEvents={{
|
||||
click: (params: { data?: { value?: [number, number] } }) => {
|
||||
const day = params?.data?.value?.[0];
|
||||
if (typeof day === "number") {
|
||||
setSelectedDay(day);
|
||||
}
|
||||
},
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Selected Day Interpretation */}
|
||||
<Box className="mb-4 overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
|
||||
<Box className="flex items-center justify-between border-b border-gray-100 bg-white px-4 py-3">
|
||||
<Typography variant="subtitle1" className="font-bold text-gray-800">
|
||||
选中日解读
|
||||
</Typography>
|
||||
{selectedRow ? (
|
||||
<Chip
|
||||
size="small"
|
||||
label={`第 ${selectedRow.Day} 天`}
|
||||
sx={{
|
||||
height: 22,
|
||||
backgroundColor: "rgba(37, 99, 235, 0.08)",
|
||||
color: "#2563eb",
|
||||
fontWeight: 600,
|
||||
fontSize: "0.75rem",
|
||||
border: "none",
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</Box>
|
||||
{selectedRow ? (
|
||||
<Box className="space-y-3 px-4 py-3">
|
||||
<Box className="flex items-center gap-2">
|
||||
<Chip
|
||||
label={getScoreLevel(selectedRow.Score).label}
|
||||
color={getScoreLevel(selectedRow.Score).color}
|
||||
variant="filled"
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="body2" className="text-gray-700">
|
||||
异常分数:<span className="font-semibold">{selectedRow.Score.toFixed(4)}</span>
|
||||
</Typography>
|
||||
<Typography variant="body2" className="text-gray-700">
|
||||
模型判定:{selectedRow.IsBurst ? "异常日(Prediction = -1)" : "正常日(Prediction = 1)"}
|
||||
</Typography>
|
||||
<Typography variant="body2" className="text-gray-700">
|
||||
解读建议:
|
||||
{selectedRow.Score <= -0.6
|
||||
? "高风险异常,建议优先复核对应测点的原始压力曲线与现场工况。"
|
||||
: selectedRow.Score <= -0.2
|
||||
? "存在可疑波动,建议结合相邻测点和调度记录进一步确认。"
|
||||
: "未见明显异常,可作为基线日参考。"}
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Typography variant="body2" className="px-4 py-3 text-gray-500">
|
||||
请在趋势图或表格中选择一天查看详细解释。
|
||||
</Typography>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
{/* Latest Sensor Rankings */}
|
||||
<Box className="mb-4 overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
|
||||
<Box className="flex items-center justify-between border-b border-gray-100 bg-white px-4 py-3">
|
||||
<Typography variant="subtitle1" className="font-bold text-gray-800">
|
||||
最新测点高频特征排名
|
||||
</Typography>
|
||||
<Typography variant="caption" className="text-gray-500">
|
||||
仅展示最新一天
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box sx={{ height: 260, px: 1.5, py: 1 }}>
|
||||
<ReactECharts option={rankingOption} style={{ height: "100%", width: "100%" }} />
|
||||
</Box>
|
||||
<Box className="flex flex-wrap gap-2 border-t border-gray-100 px-4 py-3">
|
||||
{result.summary.latest_sensor_rankings.slice(0, 5).map((item) => (
|
||||
<Button
|
||||
key={item.sensor_node}
|
||||
size="small"
|
||||
variant="outlined"
|
||||
onClick={() => locateSensors([item.sensor_node])}
|
||||
sx={{
|
||||
borderColor: "#bfdbfe",
|
||||
color: "#2563eb",
|
||||
"&:hover": { borderColor: "#60a5fa", backgroundColor: "#eff6ff" },
|
||||
}}
|
||||
>
|
||||
{item.sensor_node}
|
||||
</Button>
|
||||
))}
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
{/* Results Table */}
|
||||
<Box className="mb-4 overflow-hidden rounded-xl border border-gray-100 bg-white shadow-sm">
|
||||
<Box className="flex items-center justify-between border-b border-gray-100 bg-white px-4 py-3">
|
||||
<Box className="flex items-center gap-2">
|
||||
<FormatListBulleted className="h-5 w-5 text-blue-600" />
|
||||
<Typography variant="subtitle1" className="font-bold text-gray-800">
|
||||
结果表格
|
||||
</Typography>
|
||||
</Box>
|
||||
<Chip
|
||||
size="small"
|
||||
label={`${rows.length} 条`}
|
||||
sx={{
|
||||
height: 22,
|
||||
backgroundColor: "rgba(37, 99, 235, 0.08)",
|
||||
color: "#2563eb",
|
||||
fontWeight: 600,
|
||||
fontSize: "0.75rem",
|
||||
border: "none",
|
||||
}}
|
||||
/>
|
||||
</Box>
|
||||
<Box sx={{ height: 320, px: 1, py: 1 }}>
|
||||
<DataGrid
|
||||
rows={rows}
|
||||
columns={columns}
|
||||
columnBufferPx={100}
|
||||
localeText={zhCN.components.MuiDataGrid.defaultProps.localeText}
|
||||
initialState={{
|
||||
pagination: { paginationModel: { pageSize: 50, page: 0 } },
|
||||
}}
|
||||
pageSizeOptions={[50]}
|
||||
hideFooterSelectedRowCount
|
||||
sx={{
|
||||
border: "none",
|
||||
"& .MuiDataGrid-cell": { borderColor: "#f0f0f0" },
|
||||
"& .MuiDataGrid-columnHeaders": { backgroundColor: "#fafafa" },
|
||||
"& .MuiDataGrid-row:hover": { backgroundColor: "#f8fafc" },
|
||||
// Hide the rows per page selector since it's fixed to 50
|
||||
"& .MuiTablePagination-selectLabel": { display: "none" },
|
||||
"& .MuiTablePagination-input": { display: "none" },
|
||||
}}
|
||||
disableRowSelectionOnClick
|
||||
onRowClick={(params) => setSelectedDay(Number(params.row.Day))}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default DetectionResults;
|
||||
@@ -0,0 +1,350 @@
|
||||
"use client";
|
||||
|
||||
import React, { useState } from "react";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
Card,
|
||||
CardContent,
|
||||
Checkbox,
|
||||
Chip,
|
||||
Collapse,
|
||||
FormControlLabel,
|
||||
IconButton,
|
||||
Tooltip,
|
||||
Typography,
|
||||
} from "@mui/material";
|
||||
import { InfoOutlined as InfoIcon } from "@mui/icons-material";
|
||||
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
|
||||
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
|
||||
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
|
||||
import dayjs, { Dayjs } from "dayjs";
|
||||
import "dayjs/locale/zh-cn";
|
||||
import { useNotification } from "@refinedev/core";
|
||||
import { api } from "@/lib/api";
|
||||
import { NETWORK_NAME } from "@config/config";
|
||||
import {
|
||||
BurstDetectionResult,
|
||||
BurstDetectionSchemeDetail,
|
||||
BurstDetectionSchemeRecord,
|
||||
} from "./types";
|
||||
|
||||
interface Props {
|
||||
onViewResult: (result: BurstDetectionResult) => void;
|
||||
}
|
||||
|
||||
const SchemeQuery: React.FC<Props> = ({ onViewResult }) => {
|
||||
const { open } = useNotification();
|
||||
const [queryAll, setQueryAll] = useState(true);
|
||||
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs());
|
||||
const [schemes, setSchemes] = useState<BurstDetectionSchemeRecord[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [expandedId, setExpandedId] = useState<number | null>(null);
|
||||
|
||||
const buildDisplayResult = (
|
||||
scheme: Pick<BurstDetectionSchemeRecord, "scheme_name" | "username" | "create_time">,
|
||||
detail?: BurstDetectionSchemeDetail,
|
||||
): BurstDetectionResult | null => {
|
||||
const payload = detail?.result_payload;
|
||||
const summary = detail?.result_summary;
|
||||
const fallbackLatestDay = summary?.latest_day;
|
||||
|
||||
if (!payload && !summary) return null;
|
||||
|
||||
return {
|
||||
network: payload?.network ?? detail?.network ?? NETWORK_NAME,
|
||||
sensor_nodes: payload?.sensor_nodes ?? detail?.sensor_nodes ?? [],
|
||||
observed_source: payload?.observed_source ?? detail?.observed_source ?? "stored_scheme",
|
||||
sample_count: payload?.sample_count ?? 0,
|
||||
points_per_day: payload?.points_per_day ?? detail?.algorithm_params?.points_per_day ?? 1440,
|
||||
day_count: payload?.day_count ?? payload?.rows?.length ?? 0,
|
||||
rows: payload?.rows ?? (fallbackLatestDay ? [fallbackLatestDay] : []),
|
||||
summary:
|
||||
payload?.summary ??
|
||||
(summary
|
||||
? summary
|
||||
: {
|
||||
burst_detected: false,
|
||||
latest_day: fallbackLatestDay ?? { Day: 0, Score: 0, Prediction: 1, IsBurst: false },
|
||||
most_anomalous_day: 0,
|
||||
anomaly_days: [],
|
||||
anomaly_day_count: 0,
|
||||
latest_sensor_rankings: [],
|
||||
}),
|
||||
scada_window: payload?.scada_window ?? detail?.scada_window,
|
||||
scheme_name: payload?.scheme_name ?? scheme.scheme_name,
|
||||
username: payload?.username ?? scheme.username,
|
||||
create_time: payload?.create_time ?? scheme.create_time,
|
||||
algorithm_params: payload?.algorithm_params ?? detail?.algorithm_params,
|
||||
};
|
||||
};
|
||||
|
||||
const handleQuery = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const params: Record<string, string> = { network: NETWORK_NAME };
|
||||
if (!queryAll && queryDate) {
|
||||
params.query_date = queryDate.startOf("day").toISOString();
|
||||
}
|
||||
|
||||
const response = await api.get("/api/v1/burst-detection/schemes/", { params });
|
||||
setSchemes(response.data);
|
||||
open?.({
|
||||
type: "success",
|
||||
message: "查询成功",
|
||||
description: `共找到 ${response.data.length} 条侦测记录。`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "查询失败",
|
||||
description: error?.response?.data?.detail ?? "无法获取侦测方案列表",
|
||||
});
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleViewSchemeResult = async (schemeName: string) => {
|
||||
try {
|
||||
const response = await api.get(
|
||||
`/api/v1/burst-detection/schemes/${encodeURIComponent(schemeName)}`,
|
||||
{ params: { network: NETWORK_NAME } },
|
||||
);
|
||||
const schemeRecord = response.data as BurstDetectionSchemeRecord & {
|
||||
result_payload?: BurstDetectionResult;
|
||||
};
|
||||
const normalizedResult =
|
||||
schemeRecord.result_payload ??
|
||||
buildDisplayResult(
|
||||
{
|
||||
scheme_name: schemeRecord.scheme_name,
|
||||
username: schemeRecord.username,
|
||||
create_time: schemeRecord.create_time,
|
||||
},
|
||||
schemeRecord.scheme_detail,
|
||||
);
|
||||
|
||||
if (!normalizedResult) {
|
||||
throw new Error("方案详情缺少侦测结果数据");
|
||||
}
|
||||
|
||||
onViewResult(normalizedResult);
|
||||
open?.({
|
||||
type: "success",
|
||||
message: "方案加载成功",
|
||||
description: `已加载方案:${schemeName}`,
|
||||
});
|
||||
} catch (error: any) {
|
||||
open?.({
|
||||
type: "error",
|
||||
message: "查看详情失败",
|
||||
description: error?.response?.data?.detail ?? error?.message ?? "无法获取方案详情",
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Box className="flex h-full flex-col">
|
||||
<Box className="mb-2 rounded bg-gray-50 p-2">
|
||||
<Box className="flex items-center justify-between gap-2">
|
||||
<Box className="flex items-center gap-2">
|
||||
<FormControlLabel
|
||||
control={
|
||||
<Checkbox
|
||||
size="small"
|
||||
checked={queryAll}
|
||||
onChange={(event) => setQueryAll(event.target.checked)}
|
||||
/>
|
||||
}
|
||||
label={<Typography variant="body2">查询全部</Typography>}
|
||||
className="m-0"
|
||||
/>
|
||||
<LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
|
||||
<DatePicker
|
||||
value={queryDate}
|
||||
onChange={setQueryDate}
|
||||
disabled={queryAll}
|
||||
format="YYYY-MM-DD"
|
||||
slotProps={{ textField: { size: "small", sx: { width: 180 } } }}
|
||||
/>
|
||||
</LocalizationProvider>
|
||||
</Box>
|
||||
<Button
|
||||
variant="contained"
|
||||
onClick={handleQuery}
|
||||
disabled={loading}
|
||||
size="small"
|
||||
className="bg-blue-600 hover:bg-blue-700"
|
||||
sx={{ minWidth: 80 }}
|
||||
>
|
||||
{loading ? "查询中..." : "查询"}
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box className="flex-1 overflow-auto">
|
||||
{schemes.length === 0 ? (
|
||||
<Box className="flex h-full flex-col items-center justify-center text-center text-gray-400">
|
||||
<Typography variant="body2">暂无侦测方案</Typography>
|
||||
<Typography variant="caption" className="mt-1">
|
||||
运行一次展示版侦测后,可在这里回看历史结果。
|
||||
</Typography>
|
||||
</Box>
|
||||
) : (
|
||||
<Box className="space-y-2 p-2">
|
||||
<Typography variant="caption" className="px-2 text-gray-500">
|
||||
共 {schemes.length} 条记录
|
||||
</Typography>
|
||||
{schemes.map((scheme) => {
|
||||
const summary = scheme.scheme_detail?.result_summary;
|
||||
const payload = scheme.scheme_detail?.result_payload;
|
||||
const isBurst = payload?.summary?.burst_detected ?? summary?.burst_detected ?? false;
|
||||
const anomalyDayCount =
|
||||
payload?.summary?.anomaly_day_count ?? summary?.anomaly_day_count ?? 0;
|
||||
const mostAnomalousDay =
|
||||
payload?.summary?.most_anomalous_day ?? summary?.most_anomalous_day ?? "-";
|
||||
const sensorCount = payload?.sensor_nodes?.length ?? scheme.scheme_detail?.sensor_nodes?.length ?? 0;
|
||||
|
||||
return (
|
||||
<Card key={scheme.scheme_id} variant="outlined" className="transition-shadow hover:shadow-md">
|
||||
<CardContent className="p-3 pb-2 last:pb-3">
|
||||
<Box className="mb-2 flex items-start justify-between gap-2">
|
||||
<Box className="min-w-0 flex-1">
|
||||
<Box className="mb-1 flex items-center gap-2">
|
||||
<Typography
|
||||
variant="body2"
|
||||
className="truncate font-medium"
|
||||
title={scheme.scheme_name}
|
||||
>
|
||||
{scheme.scheme_name}
|
||||
</Typography>
|
||||
<Chip
|
||||
size="small"
|
||||
color={isBurst ? "error" : "success"}
|
||||
variant="outlined"
|
||||
label={isBurst ? "存在异常" : "正常"}
|
||||
className="h-5"
|
||||
/>
|
||||
</Box>
|
||||
<Typography variant="caption" className="block text-gray-500">
|
||||
创建时间:{dayjs(scheme.create_time).format("YYYY-MM-DD HH:mm")}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="ml-2 flex gap-1">
|
||||
<Tooltip title={expandedId === scheme.scheme_id ? "收起详情" : "查看详情"}>
|
||||
<IconButton
|
||||
size="small"
|
||||
onClick={() =>
|
||||
setExpandedId(expandedId === scheme.scheme_id ? null : scheme.scheme_id)
|
||||
}
|
||||
color="primary"
|
||||
className="p-1"
|
||||
>
|
||||
<InfoIcon fontSize="small" />
|
||||
</IconButton>
|
||||
</Tooltip>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Box className="grid grid-cols-3 gap-2">
|
||||
<Box className="rounded bg-gray-50 p-2">
|
||||
<Typography variant="caption" className="text-gray-500">
|
||||
异常天数
|
||||
</Typography>
|
||||
<Typography variant="body2" className="font-semibold text-gray-900">
|
||||
{anomalyDayCount}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="rounded bg-gray-50 p-2">
|
||||
<Typography variant="caption" className="text-gray-500">
|
||||
最异常日
|
||||
</Typography>
|
||||
<Typography variant="body2" className="font-semibold text-gray-900">
|
||||
{isBurst
|
||||
? typeof mostAnomalousDay === "number"
|
||||
? `第 ${mostAnomalousDay} 天`
|
||||
: mostAnomalousDay
|
||||
: "无"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="rounded bg-gray-50 p-2">
|
||||
<Typography variant="caption" className="text-gray-500">
|
||||
测点数
|
||||
</Typography>
|
||||
<Typography variant="body2" className="font-semibold text-gray-900">
|
||||
{sensorCount}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
|
||||
<Collapse in={expandedId === scheme.scheme_id}>
|
||||
<Box className="mt-2 border-t border-gray-200 pt-3">
|
||||
<Box className="space-y-2 rounded-md bg-gray-50 px-3 py-2">
|
||||
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
|
||||
<Typography variant="caption" className="text-gray-600">
|
||||
数据来源:
|
||||
</Typography>
|
||||
<Typography variant="caption" className="font-medium text-gray-900">
|
||||
{(() => {
|
||||
const ds = payload?.data_source;
|
||||
const os = payload?.observed_source ?? scheme.scheme_detail?.observed_source;
|
||||
if (ds === "simulation") return "模拟数据";
|
||||
if (ds === "monitoring") return "监测数据";
|
||||
if (os === "simulation_scheme_timerange") return "模拟数据";
|
||||
if (os === "backend_timerange") return "监测数据";
|
||||
return os || "-";
|
||||
})()}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
|
||||
<Typography variant="caption" className="text-gray-600">
|
||||
时间窗口:
|
||||
</Typography>
|
||||
<Typography variant="caption" className="font-medium text-gray-900">
|
||||
{payload?.scada_window?.start
|
||||
? `${dayjs(payload.scada_window.start).format("MM-DD HH:mm")} ~ ${dayjs(
|
||||
payload.scada_window.end,
|
||||
).format("MM-DD HH:mm")}`
|
||||
: "-"}
|
||||
</Typography>
|
||||
</Box>
|
||||
<Box className="grid grid-cols-[78px_1fr] items-center gap-x-2">
|
||||
<Typography variant="caption" className="text-gray-600">
|
||||
算法参数:
|
||||
</Typography>
|
||||
<Typography variant="caption" className="font-medium text-gray-900">
|
||||
频域截断系数:{scheme.scheme_detail?.algorithm_params?.mu ?? payload?.algorithm_params?.mu ?? "-"}
|
||||
,每日采样点数:
|
||||
{scheme.scheme_detail?.algorithm_params?.points_per_day ??
|
||||
payload?.algorithm_params?.points_per_day ??
|
||||
"-"}
|
||||
</Typography>
|
||||
</Box>
|
||||
</Box>
|
||||
<Box className="border-t border-gray-100 pt-2">
|
||||
<Button
|
||||
variant="contained"
|
||||
fullWidth
|
||||
size="small"
|
||||
className="bg-blue-600 hover:bg-blue-700"
|
||||
sx={{ textTransform: "none", fontWeight: 500 }}
|
||||
onClick={() => handleViewSchemeResult(scheme.scheme_name)}
|
||||
>
|
||||
查看侦测结果
|
||||
</Button>
|
||||
</Box>
|
||||
</Box>
|
||||
</Collapse>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export default SchemeQuery;
|
||||
@@ -0,0 +1,77 @@
|
||||
export interface BurstDetectionRow {
|
||||
Day: number;
|
||||
Score: number;
|
||||
Prediction: number;
|
||||
IsBurst: boolean;
|
||||
}
|
||||
|
||||
export interface BurstDetectionSensorRanking {
|
||||
sensor_node: string;
|
||||
latest_high_frequency_value: number;
|
||||
}
|
||||
|
||||
export interface BurstDetectionSummary {
|
||||
burst_detected: boolean;
|
||||
latest_day: BurstDetectionRow;
|
||||
most_anomalous_day: number;
|
||||
anomaly_days: number[];
|
||||
anomaly_day_count: number;
|
||||
latest_sensor_rankings: BurstDetectionSensorRanking[];
|
||||
}
|
||||
|
||||
export interface BurstDetectionAlgorithmParams {
|
||||
mu?: number;
|
||||
points_per_day?: number;
|
||||
iforest_params?: {
|
||||
n_estimators?: number;
|
||||
contamination?: number | "auto";
|
||||
random_state?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface BurstDetectionResult {
|
||||
network: string;
|
||||
sensor_nodes: string[];
|
||||
observed_source: string;
|
||||
sample_count: number;
|
||||
points_per_day: number;
|
||||
day_count: number;
|
||||
rows: BurstDetectionRow[];
|
||||
summary: BurstDetectionSummary;
|
||||
scada_window?: {
|
||||
start?: string;
|
||||
end?: string;
|
||||
};
|
||||
scheme_name?: string;
|
||||
username?: string;
|
||||
create_time?: string;
|
||||
data_source?: "monitoring" | "simulation";
|
||||
simulation_scheme?: {
|
||||
name?: string;
|
||||
type?: string;
|
||||
};
|
||||
algorithm_params?: BurstDetectionAlgorithmParams;
|
||||
}
|
||||
|
||||
export interface BurstDetectionSchemeDetail {
|
||||
network?: string;
|
||||
sensor_nodes?: string[];
|
||||
observed_source?: string;
|
||||
scada_window?: {
|
||||
start?: string;
|
||||
end?: string;
|
||||
};
|
||||
algorithm_params?: BurstDetectionAlgorithmParams;
|
||||
result_summary?: BurstDetectionSummary;
|
||||
result_payload?: BurstDetectionResult;
|
||||
}
|
||||
|
||||
export interface BurstDetectionSchemeRecord {
|
||||
scheme_id: number;
|
||||
scheme_name: string;
|
||||
scheme_type?: string;
|
||||
create_time: string;
|
||||
scheme_start_time?: string;
|
||||
username?: string;
|
||||
scheme_detail?: BurstDetectionSchemeDetail;
|
||||
}
|
||||
Reference in New Issue
Block a user