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

Variable picker #92

Merged
merged 16 commits into from
Jan 10, 2025
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
168 changes: 141 additions & 27 deletions apps/class-solid/src/components/Analysis.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,36 @@
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 {
type Analysis,
type ProfilesAnalysis,
type TimeseriesAnalysis,
deleteAnalysis,
experiments,
updateAnalysis,
} 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 @@ -27,7 +52,11 @@ const linestyles = ["none", "5,5", "10,10", "15,5,5,5", "20,10,5,5,5,10"];
/** Very rudimentary plot showing time series of each experiment globally available
* It only works if the time axes are equal
*/
export function TimeSeriesPlot() {
export function TimeSeriesPlot({ analysis }: { analysis: TimeseriesAnalysis }) {
const xVariableOptions = ["t"]; // TODO: separate plot types for timeseries and x-vs-y? Use time axis?
// TODO: add nice description from config as title and dropdown option for the variable picker.
const yVariableOptions = new BmiClass().get_output_var_names();

const chartData = createMemo(() => {
return experiments
.filter((e) => e.running === false) // Skip running experiments
Expand All @@ -41,9 +70,13 @@ 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
Peter9192 marked this conversation as resolved.
Show resolved Hide resolved
? perm.output[analysis.xVariable][ti]
: Number.NaN,
y: perm.output
? perm.output[analysis.yVariable][ti]
: Number.NaN,
})) || [],
};
});
Expand All @@ -53,9 +86,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[analysis.xVariable][ti]
Peter9192 marked this conversation as resolved.
Show resolved Hide resolved
: Number.NaN,
y: experimentOutput
? experimentOutput[analysis.yVariable][ti]
: Number.NaN,
})) || [],
},
...permutationRuns,
Expand All @@ -64,17 +101,50 @@ 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={() => analysis.yVariable}
/>
<div class="flex justify-around">
<Picker
value={() => analysis.xVariable}
setValue={(v) => updateAnalysis(analysis, { xVariable: v })}
options={xVariableOptions}
label="x-axis"
/>
<Picker
value={() => analysis.yVariable}
setValue={(v) => updateAnalysis(analysis, { yVariable: v })}
options={yVariableOptions}
label="y-axis"
/>
</div>
</>
);
}

export function VerticalProfilePlot() {
const variable = "theta";
const time = -1;
export function VerticalProfilePlot({
analysis,
}: { analysis: ProfilesAnalysis }) {
const [variable, setVariable] = createSignal("Potential temperature [K]");

// 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 = {
"Potential temperature [K]": "theta",
Peter9192 marked this conversation as resolved.
Show resolved Hide resolved
"Specific humidity [kg/kg]": "q",
};
const classVariable = () =>
variableOptions[analysis.variable as keyof typeof variableOptions];

// 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 +156,12 @@ 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,
classVariable(),
analysis.time,
),
};
});

Expand All @@ -103,20 +178,59 @@ export function VerticalProfilePlot() {
dtheta: [],
},
e.reference.config,
variable,
time,
classVariable(),
analysis.time,
),
},
...permutations,
];
});
});
return (
<LinePlot
data={profileData}
xlabel="Potential temperature [K]"
ylabel="Height [m]"
/>
<>
<LinePlot
data={profileData}
xlabel={variable}
ylabel={() => "Height [m]"}
/>
<Picker
value={() => analysis.variable}
setValue={(v) => updateAnalysis(analysis, { variable: v })}
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
class="whitespace-nowrap"
value={props.value()}
disallowEmptySelection={true}
onChange={props.setValue}
options={props.options}
placeholder="Select value..."
itemComponent={(props) => (
<SelectItem item={props.item}>{props.item.rawValue}</SelectItem>
)}
>
<SelectTrigger aria-label="Variable" class="min-w-[100px]">
<SelectValue<string>>{(state) => state.selectedOption()}</SelectValue>
</SelectTrigger>
<SelectContent />
</Select>
</div>
);
}

Expand Down Expand Up @@ -228,10 +342,10 @@ export function AnalysisCard(analysis: Analysis) {
<FinalHeights />
</Match>
<Match when={analysis.type === "timeseries"}>
<TimeSeriesPlot />
<TimeSeriesPlot analysis={analysis as TimeseriesAnalysis} />
</Match>
<Match when={analysis.type === "profiles"}>
<VerticalProfilePlot />
<VerticalProfilePlot analysis={analysis as ProfilesAnalysis} />
</Match>
<Match when={analysis.type === "skewT"}>
<ThermodynamicPlot />
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,
Peter9192 marked this conversation as resolved.
Show resolved Hide resolved
});
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
Loading
Loading