Skip to content
Merged
Show file tree
Hide file tree
Changes from 11 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
136 changes: 114 additions & 22 deletions apps/class-solid/src/components/Analysis.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,29 @@
import { For, Match, Show, Switch, createMemo, createUniqueId } from "solid-js";
import { BmiClass } from "@classmodel/class/bmi";
import {
type Accessor,
For,
Match,
type Setter,
Show,
Switch,
createMemo,
createSignal,
createUniqueId,
} from "solid-js";
import { getThermodynamicProfiles, getVerticalProfiles } from "~/lib/profiles";
import { type Analysis, deleteAnalysis, experiments } from "~/lib/store";
import { MdiCog, MdiContentCopy, MdiDelete, MdiDownload } from "./icons";
import LinePlot from "./plots/LinePlot";
import { SkewTPlot } from "./plots/skewTlogP";
import { Button } from "./ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "./ui/select";

/** https://github.com/d3/d3-scale-chromatic/blob/main/src/categorical/Tableau10.js */
const colors = [
Expand All @@ -28,6 +46,11 @@ const linestyles = ["none", "5,5", "10,10", "15,5,5,5", "20,10,5,5,5,10"];
* It only works if the time axes are equal
*/
export function TimeSeriesPlot() {
const [xVariable, setXVariable] = createSignal("t");
const [yVariable, setYVariable] = createSignal("theta");
Copy link
Collaborator

Choose a reason for hiding this comment

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

When saving/restoring a session or sharing a link would it make sense to also store the variable selection?

If so we would need to lift those signals to the analyses store.

Copy link
Member Author

Choose a reason for hiding this comment

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

I think that would make sense in the future, so I have done as you suggested. Variables are now set in the store. Regarding the URL, I think we should wait for the analysis interface to stabilize, so we can add it later.

const xVariableOptions = ["t"]; // TODO: separate plot types for timeseries and x-vs-y? Use time axis?
const yVariableOptions = BmiClass.get_output_var_names();

const chartData = createMemo(() => {
return experiments
.filter((e) => e.running === false) // Skip running experiments
Expand All @@ -41,9 +64,9 @@ export function TimeSeriesPlot() {
color: colors[(j + 1) % 10],
linestyle: linestyles[i % 5],
data:
perm.output?.t.map((tVal, i) => ({
x: tVal,
y: perm.output?.h[i] || Number.NaN,
perm.output?.t.map((tVal, ti) => ({
x: perm.output ? perm.output[xVariable()][ti] : Number.NaN,
y: perm.output ? perm.output[yVariable()][ti] : Number.NaN,
})) || [],
};
});
Expand All @@ -53,9 +76,13 @@ export function TimeSeriesPlot() {
color: colors[0],
linestyle: linestyles[i],
data:
experimentOutput?.t.map((tVal, i) => ({
x: tVal,
y: experimentOutput?.h[i] || Number.NaN,
experimentOutput?.t.map((tVal, ti) => ({
x: experimentOutput
? experimentOutput[xVariable()][ti]
: Number.NaN,
y: experimentOutput
? experimentOutput[yVariable()][ti]
: Number.NaN,
})) || [],
},
...permutationRuns,
Expand All @@ -64,17 +91,43 @@ export function TimeSeriesPlot() {
});

return (
<LinePlot
data={chartData}
xlabel="Time [s]"
ylabel="Mixed-layer height [m]"
/>
<>
{/* TODO: get label for yVariable from model config */}
<LinePlot data={chartData} xlabel={() => "Time [s]"} ylabel={yVariable} />
<div class="flex justify-around">
<Picker
value={xVariable}
setValue={setXVariable as Setter<string>}
options={xVariableOptions}
label="x-axis"
/>
<Picker
value={yVariable}
setValue={setYVariable as Setter<string>}
options={yVariableOptions}
label="y-axis"
/>
</div>
</>
);
}

export function VerticalProfilePlot() {
const variable = "theta";
const time = -1;
const [time, setTime] = createSignal<number>(-1);
const [variable, setVariable] = createSignal("theta");

// TODO also check time of permutations.
const timeOptions = experiments
.filter((e) => e.running === false)
.flatMap((e) => (e.reference.output ? e.reference.output.t : []));
const variableOptions = {
theta: "Potential temperature [K]",
q: "Specific humidity [kg/kg]",
};

// TODO: refactor this? We could have a function that creates shared ChartData
// props (linestyle, color, label) generic for each plot type, and custom data
// formatting as required by specific chart
const profileData = createMemo(() => {
return experiments
.filter((e) => e.running === false) // Skip running experiments
Expand All @@ -86,7 +139,7 @@ export function VerticalProfilePlot() {
color: colors[(j + 1) % 10],
linestyle: linestyles[i % 5],
label: `${e.name}/${p.name}`,
data: getVerticalProfiles(p.output, p.config, variable, time),
data: getVerticalProfiles(p.output, p.config, variable(), time()),
};
});

Expand All @@ -103,20 +156,59 @@ export function VerticalProfilePlot() {
dtheta: [],
},
e.reference.config,
variable,
time,
variable(),
time(),
),
},
...permutations,
];
});
});
return (
<LinePlot
data={profileData}
xlabel="Potential temperature [K]"
ylabel="Height [m]"
/>
<>
<LinePlot
data={profileData}
xlabel={() =>
variableOptions[variable() as keyof typeof variableOptions]
}
ylabel={() => "Height [m]"}
/>
<Picker
value={variable}
setValue={setVariable as Setter<string>}
options={Object.keys(variableOptions)}
label="variable: "
/>
</>
);
}

type PickerProps = {
value: Accessor<string>;
setValue: Setter<string>;
options: string[];
label?: string;
};

function Picker(props: PickerProps) {
return (
<div class="flex items-center gap-2">
<p>{props.label}</p>
<Select
value={props.value()}
onChange={props.setValue}
options={props.options}
placeholder="Select value..."
itemComponent={(props) => (
<SelectItem item={props.item}>{props.item.rawValue}</SelectItem>
)}
>
<SelectTrigger aria-label="Variable" class="w-[180px]">
<SelectValue<string>>{(state) => state.selectedOption()}</SelectValue>
</SelectTrigger>
<SelectContent />
</Select>
</div>
);
}

Expand Down
40 changes: 17 additions & 23 deletions apps/class-solid/src/components/plots/Axes.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Code generated by AI and checked/modified for correctness

import * as d3 from "d3";
import { For } from "solid-js";
import { For, createEffect } from "solid-js";
import { useChartContext } from "./ChartContainer";

type AxisProps = {
Expand All @@ -14,25 +14,22 @@ type AxisProps = {

export const AxisBottom = (props: AxisProps) => {
const [chart, updateChart] = useChartContext();
props.domain && chart.scaleX.domain(props.domain());
createEffect(() => {
props.domain && updateChart("scalePropsX", { domain: props.domain() });
props.type && updateChart("scalePropsX", { type: props.type });
});

if (props.type === "log") {
const range = chart.scaleX.range();
const domain = chart.scaleX.range();
updateChart("scaleX", d3.scaleLog().domain(domain).range(range));
}

const format = props.tickFormat ? props.tickFormat : d3.format(".3g");
const ticks = props.tickValues || generateTicks(chart.scaleX.domain());
const format = () => (props.tickFormat ? props.tickFormat : d3.format(".3g"));
const ticks = () => props.tickValues || generateTicks(chart.scaleX.domain());
return (
<g transform={`translate(0,${chart.innerHeight - 0.5})`}>
<line x1="0" x2={chart.innerWidth} y1="0" y2="0" stroke="currentColor" />
<For each={ticks}>
<For each={ticks()}>
{(tick) => (
<g transform={`translate(${chart.scaleX(tick)}, 0)`}>
<line y2="6" stroke="currentColor" />
<text y="9" dy="0.71em" text-anchor="middle">
{format(tick)}
{format()(tick)}
</text>
</g>
)}
Expand All @@ -46,16 +43,13 @@ export const AxisBottom = (props: AxisProps) => {

export const AxisLeft = (props: AxisProps) => {
const [chart, updateChart] = useChartContext();
props.domain && chart.scaleY.domain(props.domain());

if (props.type === "log") {
const range = chart.scaleY.range();
const domain = chart.scaleY.domain();
updateChart("scaleY", () => d3.scaleLog().range(range).domain(domain));
}
createEffect(() => {
props.domain && updateChart("scalePropsY", { domain: props.domain() });
props.type && updateChart("scalePropsY", { type: props.type });
});

const ticks = props.tickValues || generateTicks(chart.scaleY.domain());
const format = props.tickFormat ? props.tickFormat : d3.format(".0f");
const ticks = () => props.tickValues || generateTicks(chart.scaleY.domain());
const format = () => (props.tickFormat ? props.tickFormat : d3.format(".0f"));
return (
<g transform="translate(-0.5,0)">
<line
Expand All @@ -65,12 +59,12 @@ export const AxisLeft = (props: AxisProps) => {
y2={chart.scaleY.range()[1]}
stroke="currentColor"
/>
<For each={ticks}>
<For each={ticks()}>
{(tick) => (
<g transform={`translate(0, ${chart.scaleY(tick)})`}>
<line x2="-6" stroke="currentColor" />
<text x="-9" dy="0.32em" text-anchor="end">
{format(tick)}
{format()(tick)}
</text>
</g>
)}
Expand Down
46 changes: 41 additions & 5 deletions apps/class-solid/src/components/plots/ChartContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
import * as d3 from "d3";
import type { JSX } from "solid-js";
import { createContext, useContext } from "solid-js";
import { createContext, createEffect, useContext } from "solid-js";
import { type SetStoreFunction, createStore } from "solid-js/store";

type SupportedScaleTypes =
| d3.ScaleLinear<number, number, never>
| d3.ScaleLogarithmic<number, number, never>;
const supportedScales = {
linear: d3.scaleLinear<number, number, never>,
log: d3.scaleLog<number, number, never>,
};

type ScaleProps = {
domain: [number, number];
range: [number, number];
type: keyof typeof supportedScales;
};

interface Chart {
width: number;
height: number;
margin: [number, number, number, number];
innerWidth: number;
innerHeight: number;
scaleX: d3.ScaleLinear<number, number> | d3.ScaleLogarithmic<number, number>;
scaleY: d3.ScaleLinear<number, number> | d3.ScaleLogarithmic<number, number>;
scalePropsX: ScaleProps;
scalePropsY: ScaleProps;
scaleX: SupportedScaleTypes;
scaleY: SupportedScaleTypes;
}
type SetChart = SetStoreFunction<Chart>;
const ChartContext = createContext<[Chart, SetChart]>();
Expand All @@ -28,14 +44,34 @@ export function ChartContainer(props: {
const [marginTop, marginRight, marginBottom, marginLeft] = margin;
const innerHeight = height - marginTop - marginBottom;
const innerWidth = width - marginRight - marginLeft;
const initialScale = d3.scaleLinear<number, number, never>();
const [chart, updateChart] = createStore<Chart>({
width,
height,
margin,
innerHeight,
innerWidth,
scaleX: d3.scaleLinear().range([0, innerWidth]),
scaleY: d3.scaleLinear().range([innerHeight, 0]),
scalePropsX: { type: "linear", domain: [0, 1], range: [0, innerWidth] },
scalePropsY: { type: "linear", domain: [0, 1], range: [innerHeight, 0] },
scaleX: initialScale,
scaleY: initialScale,
});
createEffect(() => {
// Update scaleXInstance when scaleX props change
const scaleX = supportedScales[chart.scalePropsX.type]()
.range(chart.scalePropsX.range)
.domain(chart.scalePropsX.domain);
// .nice(); // TODO: could use this instead of getNiceAxisLimits
updateChart("scaleX", () => scaleX);
});

createEffect(() => {
// Update scaleYInstance when scaleY props change
const scaleY = supportedScales[chart.scalePropsY.type]()
.range(chart.scalePropsY.range)
.domain(chart.scalePropsY.domain);
// .nice();
updateChart("scaleY", () => scaleY);
});
return (
<ChartContext.Provider value={[chart, updateChart]}>
Expand Down
10 changes: 7 additions & 3 deletions apps/class-solid/src/components/plots/LinePlot.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ export default function LinePlot({
data,
xlabel,
ylabel,
}: { data: () => ChartData<Point>[]; xlabel?: string; ylabel?: string }) {
}: {
data: () => ChartData<Point>[];
xlabel?: () => string;
ylabel?: () => string;
}) {
const xLim = () =>
getNiceAxisLimits(data().flatMap((d) => d.data.flatMap((d) => d.x)));
const yLim = () =>
Expand All @@ -46,8 +50,8 @@ export default function LinePlot({
<ChartContainer>
<Legend entries={data} />
<Chart title="Vertical profile plot">
<AxisBottom domain={xLim} label={xlabel} />
<AxisLeft domain={yLim} label={ylabel} />
<AxisBottom domain={xLim} label={xlabel ? xlabel() : ""} />
<AxisLeft domain={yLim} label={ylabel ? ylabel() : ""} />
<For each={data()}>{(d) => Line(d)}</For>
</Chart>
</ChartContainer>
Expand Down
Loading
Loading