Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add event lines to plots #18

Merged
merged 3 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 50 additions & 8 deletions app/components/LineChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,26 @@ import {
Tooltip,
Legend,
ResponsiveContainer,
ReferenceLine,
} from "recharts";
import { vialColors } from "~/utils/chart/colors";
import groupBy from "lodash/groupBy";
import { HistoricDatum } from "client";

const processData = (data, vials, property) => {
const processData = (
data: HistoricDatum[],
vials: string[],
property: string,
) => {
const filtered = data.filter((entry) => vials.includes(`${entry.vial}`));
const timed = filtered.map((entry) => ({
timestamp: new Date(
Math.round(entry.timestamp) * 1000,
).toLocaleTimeString(),
timestamp: Math.round(entry.timestamp),
vial: `vial_${entry.vial}`,
data: entry.data[property],
}));
// group for plotting by shared x-axis on timestamp. Without this the plotting
// utility will consider each entry as a separate line (inefficient)
const grouped = groupBy(timed, "timestamp");
const grouped: (typeof timed)[] = groupBy(timed, "timestamp");
// grouped creates an object keyed by group with arrays of objects, but
// plotting wants array of objects keyed by line discriminator (vial)
return Object.values(grouped).map((group) => ({
Expand All @@ -31,8 +35,30 @@ const processData = (data, vials, property) => {
}));
};

export const HardwareLineChart = ({ vials, rawData, property = "raw" }) => {
const processEvents = (data: HistoricDatum[], vials: string[]) => {
const filtered = data.filter((entry) =>
entry.vial ? vials.includes(`${entry.vial}`) : true,
);
return filtered.map((entry) => ({
timestamp: Math.round(entry.timestamp),
vial: `vial_${entry.vial}`,
data: entry.data,
}));
};

export const HardwareLineChart = ({
vials,
rawData,
events,
property = "raw",
}: {
vials: string[];
rawData: HistoricDatum[];
events: HistoricDatum[];
property: string;
}) => {
const formattedData = processData(rawData, vials, property);
const eventData = processEvents(events, vials);

return (
<div>
Expand All @@ -41,11 +67,19 @@ export const HardwareLineChart = ({ vials, rawData, property = "raw" }) => {
<ResponsiveContainer width="100%" height={400}>
<LineChart data={formattedData}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="timestamp" />
<XAxis
dataKey="timestamp"
type="number"
domain={["dataMin", "dataMax"]}
scale="time"
tickFormatter={(unixTime) =>
new Date(unixTime * 1000).toLocaleTimeString()
}
/>
<YAxis />
<Tooltip />
<Legend />
{vials.map((vial: number, index: number) => (
{vials.map((vial: string, index: number) => (
<Line
key={vial}
type="monotone"
Expand All @@ -55,6 +89,14 @@ export const HardwareLineChart = ({ vials, rawData, property = "raw" }) => {
connectNulls={true}
/>
))}
{eventData.map((event) => (
<ReferenceLine
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice!

key={`${event.timestamp}${event.data.message}`}
x={event.timestamp}
label={event.data.message}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Label will take a component as prop, and daisyUI provides a tooltip: https://daisyui.com/components/tooltip/,

label = {() => {
  return (
    <div className="tooltip" data-tip={event.data.message}>
      {event.data.message.length > 20 ? `${event.data.message.slice(0, 20)}...` : event.data.message}
    </div>
  )
}}

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks cool, but when I do this I don't see any text at all. I tried with plain div and span elements like this, doesn't seem to show. There may be some requirements it has on the underlying element...

stroke="red"
/>
))}
</LineChart>
</ResponsiveContainer>
<div className="divider"></div>
Expand Down
40 changes: 31 additions & 9 deletions app/routes/devices.$id.hardware.$hardware_name.history.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { db } from "~/utils/db.server";
import { HardwareLineChart } from "~/components/LineChart";
import { loader as rootLoader } from "~/root";
import { WrenchScrewdriverIcon, XCircleIcon } from "@heroicons/react/24/solid";
import flatMap from "lodash/flatMap";

export const handle = {
breadcrumb: (
Expand Down Expand Up @@ -67,20 +68,35 @@ export async function loader({ params, request }: LoaderFunctionArgs) {

const properties = searchParams.get("properties")?.split(",");

const { data } = await Evolver.history({
query: {
name: hardware_name,
vials,
properties,
},
client: evolverClient,
const results = Promise.allSettled([
Evolver.history({
query: {
name: hardware_name,
},
body: {
vials,
properties,
kinds: ["sensor"],
},
client: evolverClient,
}),
Evolver.history({
body: {
kinds: ["event"],
},
client: evolverClient,
}),
]).then((results) => {
return results.map((result) => result.value.data);
});

return json({ data: data?.data });
const [hist, events] = await results;

return json({ data: hist?.data, events: events?.data });
}

export default function Hardware() {
const { data } = useLoaderData<typeof loader>();
const { data, events } = useLoaderData<typeof loader>();
const {
ENV: { EXCLUDED_PROPERTIES },
} = useRouteLoaderData<typeof rootLoader>("root");
Expand All @@ -101,6 +117,11 @@ export default function Hardware() {
hardwareHistory[0].data,
).filter((property) => excludedProperties.includes(property) === false);

// shape of data is not ideal here, we have a struct mapping event name to
// array of events. Here we drop name, probably change to backend could keep
// the name in the struct
const allEvents = flatMap(events);

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, did you test this change with a chart that shows multiple vials' histories?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, the thing worked around here is that event will be tagged from a particular logger (main device, or controller), e.g.

{ "main_device": [...], "controller": [...]}

each may be tagged with vial (shown only for that plot) or not (global), but we need to bring all those named things into a single array. I think I might change backend shape since either you wan't it all where each element says where it came from, or you are selecting only one, where this structure is redundant 😄

let selectedProperties: string[] = allHardwareVialsProperties;
let selectedVials: string[] = [];
if (searchParams.has("vials")) {
Expand All @@ -127,6 +148,7 @@ export default function Hardware() {
rawData={hardwareHistory}
vials={selectedVials}
property={property}
events={allEvents}
/>
);
charts.push(chart);
Expand Down
Loading