Skip to content

Commit

Permalink
Code cleanup. Renaming, remove unused code and minor refactoring
Browse files Browse the repository at this point in the history
- Rename files and functions
- Remove unused code
- Move files
- Minor refactoring
  • Loading branch information
jorgenherje committed Sep 5, 2023
1 parent 2a80233 commit ca03b4a
Show file tree
Hide file tree
Showing 14 changed files with 146 additions and 208 deletions.
23 changes: 18 additions & 5 deletions frontend/src/modules/SimulationTimeSeriesMatrix/preview.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
import { DrawPreviewFunc } from "@framework/Preview";

export const preview: DrawPreviewFunc = function (width: number, height: number) {
const paths: { x1: number; y1: number; x2: number; y2: number; x3: number; y3: number; xc: number; yc: number }[] =
[];
const numPaths = 10;
const paths: {
x1: number;
y1: number;
x2: number;
y2: number;
x3: number;
y3: number;
xc: number;
yc: number;
color: string;
}[] = [];
const numPaths = 9;
for (let i = 0; i < numPaths; i++) {
const x1 = 0;
const y1 = height - (i / numPaths) * height;
Expand All @@ -13,7 +22,11 @@ export const preview: DrawPreviewFunc = function (width: number, height: number)
const y3 = height - (((i - 1) / numPaths) * height) / 1.2;
const xc = width / 4;
const yc = height - (i / numPaths) * height - height / 12;
paths.push({ x1, y1, x2, y2, x3, y3, xc, yc });

// Assign colors based on position
const color = i < 3 ? "green" : i < 6 ? "red" : "blue";

paths.push({ x1, y1, x2, y2, x3, y3, xc, yc, color });
}
return (
<svg width={width} height={height} viewBox={`0 0 ${width} ${height}`}>
Expand All @@ -25,7 +38,7 @@ export const preview: DrawPreviewFunc = function (width: number, height: number)
key={index}
d={`M ${path.x1} ${path.y1} Q ${path.xc} ${path.yc} ${path.x2} ${path.y2} T ${path.x3} ${path.y3}`}
fill="none"
stroke="green"
stroke={path.color} // Set stroke color
strokeWidth={1}
/>
);
Expand Down
16 changes: 11 additions & 5 deletions frontend/src/modules/SimulationTimeSeriesMatrix/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { useVectorListQueries } from "./queryHooks";
import {
FanchartStatisticOption,
FanchartStatisticOptionEnumToStringMapping,
FrequencyEnumToStringMapping,
GroupBy,
GroupByEnumToStringMapping,
State,
Expand All @@ -30,7 +31,6 @@ import {
VisualizationMode,
VisualizationModeEnumToStringMapping,
} from "./state";
import { makeFrequencyDropdownOptions } from "./utils/elementOptionsUtils";
import { EnsembleVectorListsHelper } from "./utils/ensemblesVectorListHelper";

export function settings({ moduleContext, workbenchSession }: ModuleFCProps<State>) {
Expand Down Expand Up @@ -114,8 +114,9 @@ export function settings({ moduleContext, workbenchSession }: ModuleFCProps<Stat
setSelectedVectorNames(selection.selectedTags);
}

function handleFrequencySelectionChange(frequency: string) {
setResamplingFrequency(frequency as Frequency_api);
function handleFrequencySelectionChange(newFrequencyStr: string) {
const newFreq = newFrequencyStr !== "RAW" ? (newFrequencyStr as Frequency_api) : null;
setResamplingFrequency(newFreq);
}

function handleShowHistorical(event: React.ChangeEvent<HTMLInputElement>) {
Expand Down Expand Up @@ -189,8 +190,13 @@ export function settings({ moduleContext, workbenchSession }: ModuleFCProps<Stat
</CollapsibleGroup>
<CollapsibleGroup expanded={true} title="Resampling frequency">
<Dropdown
options={makeFrequencyDropdownOptions()}
value={resampleFrequency ?? makeFrequencyDropdownOptions()[0].value}
options={[
{ value: "RAW", label: "None (raw)" },
...Object.values(Frequency_api).map((val: Frequency_api) => {
return { value: val, label: FrequencyEnumToStringMapping[val] };
}),
]}
value={resampleFrequency ?? Frequency_api.MONTHLY}
onChange={handleFrequencySelectionChange}
/>
</CollapsibleGroup>
Expand Down
12 changes: 10 additions & 2 deletions frontend/src/modules/SimulationTimeSeriesMatrix/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ export const VisualizationModeEnumToStringMapping = {
[VisualizationMode.STATISTICS_AND_REALIZATIONS]: "Statistics + Realizations",
};

// NOTE: Add None as option?
export enum GroupBy {
ENSEMBLE = "ensemble",
TIME_SERIES = "timeSeries",
// None = "none",
}

// NOTE: Add None as option?
export const GroupByEnumToStringMapping = {
[GroupBy.ENSEMBLE]: "Ensemble",
[GroupBy.TIME_SERIES]: "Time Series",
// [GroupBy.None]: "None",
};

export const StatisticFunctionEnumToStringMapping = {
Expand All @@ -54,6 +54,14 @@ export const FanchartStatisticOptionEnumToStringMapping = {
[FanchartStatisticOption.P10_P90]: "P10/P90",
};

export const FrequencyEnumToStringMapping = {
[Frequency_api.DAILY]: "Daily",
[Frequency_api.WEEKLY]: "Weekly",
[Frequency_api.MONTHLY]: "Monthly",
[Frequency_api.QUARTERLY]: "Quarterly",
[Frequency_api.YEARLY]: "Yearly",
};

export interface State {
groupBy: GroupBy;
visualizationMode: VisualizationMode;
Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,27 @@ import {
VectorRealizationData_api,
VectorStatisticData_api,
} from "@api";
import { EnsembleIdent } from "@framework/EnsembleIdent";

import { FanchartData, FreeLineData, LowHighData, MinMaxData } from "./fanchartPlotting";
import { createFanchartTraces } from "./fanchartPlotting";
import { LineData, StatisticsData, createStatisticsTraces } from "./statisticsPlotting";
import { TimeSeriesPlotData } from "./timeSeriesPlotData";

import { TimeSeriesPlotData } from "../timeSeriesPlotData";

/**
Get line shape - "vh" for rate data, "linear" for non-rate data
*/
export function getLineShape(isRate: boolean): "linear" | "vh" {
return isRate ? "vh" : "linear";
}

/**
Utility function for creating vector realization traces for an array of vector realization data
for given vector.
*/
export function createVectorRealizationTraces(
vectorRealizationsData: VectorRealizationData_api[],
ensembleIdent: EnsembleIdent,
ensembleName: string,
color: string,
legendGroup: string,
// lineShape: "linear" | "spline" | "hv" | "vh" | "hvh" | "vhv",
Expand All @@ -27,19 +34,20 @@ export function createVectorRealizationTraces(
xaxis = "x"
): Partial<TimeSeriesPlotData>[] {
// TODO:
// - type: "scattergl" or "scatter"?
// - vector name?
// - realization number?
// - lineShape?
// - lineShape - Each VectorRealizationData_api element has its own `is_rate` property. Should we
// use that to determine the line shape or provide a lineShape argument?

return vectorRealizationsData.map((realization) => {
return {
x: realization.timestamps_utc_ms,
y: realization.values,
line: { width: 1, color: color, shape: getLineShape(realization.is_rate) },
mode: "lines",
hovertemplate: `${hoverTemplate}Realization: ${
realization.realization
}, Ensemble: ${ensembleIdent.getEnsembleName()}`,
type: "scattergl",
hovertemplate: `${hoverTemplate}Realization: ${realization.realization}, Ensemble: ${ensembleName}`,
// realizationNumber: realization.realization,
name: legendGroup,
legendgroup: legendGroup,
Expand All @@ -50,6 +58,9 @@ export function createVectorRealizationTraces(
});
}

/**
Utility function for creating trace for historical vector data
*/
export function createHistoricalVectorTrace(
vectorHistoricalData: VectorHistoricalData_api,
color = "black",
Expand All @@ -60,13 +71,11 @@ export function createHistoricalVectorTrace(
vectorName?: string,
legendRank?: number
): Partial<TimeSeriesPlotData> {
// TODO:
// - legendrank?
const hoverText = vectorName ? `History: ${vectorName}` : "History";

return {
line: { shape: getLineShape(vectorHistoricalData.is_rate), color: color },
mode: "lines",
type: "scatter",
x: vectorHistoricalData.timestamps_utc_ms,
y: vectorHistoricalData.values,
hovertext: hoverText,
Expand All @@ -80,6 +89,16 @@ export function createHistoricalVectorTrace(
};
}

/**
Utility function for creating traces representing statistical fanchart for given statistics data.
The function creates filled transparent area between P10 and P90, and between MIN and MAX, and a free line
for MEAN.
NOTE: P10 and P90, and MIN and MAX are considered to work in pairs, therefore the pairs are neglected if
only one of the statistics in each pair is present in the data. I.e. P10/P90 is neglected if only P10 or P90
is presented in the data. Similarly, MIN/MAX is neglected if only MIN or MAX is presented in the data.
*/
export function createVectorFanchartTraces(
vectorStatisticData: VectorStatisticData_api,
hexColor: string,
Expand All @@ -90,9 +109,6 @@ export function createVectorFanchartTraces(
showLegend = false,
legendRank?: number
): Partial<TimeSeriesPlotData>[] {
// NOTE:
// - provide selected statistics? and plot the selected pairs, or rely on the query result and use returned pairs?

const lowData = vectorStatisticData.value_objects.find((v) => v.statistic_function === StatisticFunction_api.P90);
const highData = vectorStatisticData.value_objects.find((v) => v.statistic_function === StatisticFunction_api.P10);
let lowHighData: LowHighData | undefined = undefined;
Expand Down Expand Up @@ -143,6 +159,12 @@ export function createVectorFanchartTraces(
});
}

/**
Utility function for creating traces for statistical lines for given statistics data.
The function creates lines for P10, P50, P90, MIN, MAX, and MEAN. Solid line for MEAN, various
dashed lines for the remaining statistics.
*/
export function createVectorStatisticsTraces(
vectorStatisticData: VectorStatisticData_api,
color: string,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { formatRgb, modeRgb, useMode } from "culori";
import { ScatterLine } from "plotly.js";

import { hexToRgbaStr } from "../ColorUtils/colors";
import { TimeSeriesPlotData } from "../plotUtils";
import { TimeSeriesPlotData } from "../timeSeriesPlotData";

/**
Definition of statistics data for free line trace in fanchart
Expand Down Expand Up @@ -79,7 +79,7 @@ function validateFanchartData(data: FanchartData): void {
}

if (data.freeLine !== undefined && samplesLength !== data.freeLine.data.length) {
throw new Error("Invalid fanchart mean value data length. data.samples.length !== free_line.data.length");
throw new Error("Invalid fanchart mean value data length. data.samples.length !== freeLine.data.length");
}

if (data.minimumMaximum !== undefined && samplesLength !== data.minimumMaximum.minimum.length) {
Expand Down Expand Up @@ -181,12 +181,15 @@ export function createFanchartTraces({

validateFanchartData(data);

// TODO: Get hex to rgba string using "culori"
const fillColorLight = hexToRgbaStr(hexColor, 0.3);
const fillColorDark = hexToRgbaStr(hexColor, 0.6);
const lineColor = hexToRgbaStr(hexColor, 1.0);
const convertRgb = useMode(modeRgb);
const rgb = convertRgb(hexColor);
if (rgb === undefined) {
throw new Error("Invalid conversion of hex color string: " + hexColor + " to rgb.");
}
const fillColorLight = formatRgb({ ...rgb, alpha: 0.3 });
const fillColorDark = formatRgb({ ...rgb, alpha: 0.6 });
const lineColor = formatRgb({ ...rgb, alpha: 1.0 });

// const getDefaultTrace=(statisticsName: string, values: number[]): Partial<TimeSeriesPlotData> =>{
function getDefaultTrace(statisticsName: string, values: number[]): Partial<TimeSeriesPlotData> {
const trace: Partial<TimeSeriesPlotData> = {
name: legendName ?? legendGroup,
Expand All @@ -195,6 +198,7 @@ export function createFanchartTraces({
xaxis: xaxis,
yaxis: yaxis,
mode: "lines",
type: "scatter",
line: { width: 0, color: lineColor, shape: lineShape },
legendgroup: legendGroup,
showlegend: false,
Expand Down
Loading

0 comments on commit ca03b4a

Please sign in to comment.