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

Error bar #975

Merged
merged 23 commits into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
3 changes: 3 additions & 0 deletions src/client/app/actions/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export function changeChartToRender(chartType: t.ChartTypes): t.ChangeChartToRen
export function toggleAreaNormalization(): t.ToggleAreaNormalizationAction {
return { type: ActionType.ToggleAreaNormalization };
}
export function toggleShowMinMax(): t.ToggleShowMinMaxAction {
return { type: ActionType.ToggleShowMinMax }
}

export function changeBarStacking(): t.ChangeBarStackingAction {
return { type: ActionType.ChangeBarStacking };
Expand Down
3 changes: 1 addition & 2 deletions src/client/app/actions/lineReadings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ function fetchGroupLineReadings(groupIDs: number[], timeInterval: TimeInterval,
dispatch(receiveGroupLineReadings(groupIDs, timeInterval, unitID, groupLineReadings));
};
}
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved

/**
* Fetches readings for the line chart of all selected meters and groups, if needed.
* @param timeInterval the interval over which to check
Expand Down Expand Up @@ -159,4 +158,4 @@ export function fetchNeededLineReadings(timeInterval: TimeInterval, unitID: numb

return Promise.all(promises);
};
}
}
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
45 changes: 45 additions & 0 deletions src/client/app/components/ErrorBarComponent.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */

import * as React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { State } from '../types/redux/state';
import { toggleShowMinMax } from '../actions/graph';
import translate from '../utils/translate';
import TooltipMarkerComponent from './TooltipMarkerComponent';

/**
* React Component rendering an Error Bar checkbox for toggle operation.
* @returns Error Bar checkbox with tooltip and label
*/
const ErrorBarComponent = () => {
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
const dispatch = useDispatch();
const graphState = useSelector((state: State) => state.graph);

/**
* Dispatches an action to toggle visibility of min/max lines on checkbox interaction
*/
const handleToggleShowMinMax = () => {
dispatch(toggleShowMinMax());
}

return (
<div className='checkbox'>
<input
type='checkbox'
style={{ marginRight: '10px' }}
onChange={() => handleToggleShowMinMax()}
checked={graphState.showMinMax}
id='errorBar'
/>
<label htmlFor='errorBar'>
{translate('error.bar')}
</label>
<TooltipMarkerComponent page='home' helpTextId='help.home.error.bar' />
</div>
);
};

export default ErrorBarComponent;

6 changes: 4 additions & 2 deletions src/client/app/components/ExportComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ export default function ExportComponent() {
const adminState = useSelector((state: State) => state.admin);
// readings state
const readingsState = useSelector((state: State) => state.readings);
// error bar state
const errorBarState = useSelector((state: State) => state.graph.showMinMax);
// Time range of graphic
const timeInterval = graphState.timeInterval;

Expand Down Expand Up @@ -84,7 +86,7 @@ export default function ExportComponent() {
const sortedReadings = _.sortBy(readings, item => item.startTimestamp, 'asc');
// Identifier for current meter.
const meterIdentifier = metersState[meterId].identifier;
graphExport(sortedReadings, meterIdentifier, unitLabel, unitIdentifier, chartName, scaling);
graphExport(sortedReadings, meterIdentifier, unitLabel, unitIdentifier, chartName, scaling, errorBarState);
}
}
}
Expand Down Expand Up @@ -324,4 +326,4 @@ export default function ExportComponent() {
</div> : ''}
</>
);
}
}
1 change: 1 addition & 0 deletions src/client/app/components/TooltipHelpComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ export default class TooltipHelpComponent extends React.Component<TooltipHelpPro
'help.home.chart.select': { link: `${HELP_URL}/graphType.html` },
'help.home.compare.interval.tip': { link: `${HELP_URL}/compareGraphic.html#usage` },
'help.home.compare.sort.tip': { link: `${HELP_URL}/compareGraphic.html#usage` },
'help.home.error.bar': { link: `${HELP_URL}/errorBar.html#usage` },
'help.home.export.graph.data': { link: `${HELP_URL}/export.html` },
'help.home.hide.or.show.options': { link: `${HELP_URL}/hideOptions.html` },
'help.home.map.interval.tip': { link: `${HELP_URL}/mapGraphic.html#usage` },
Expand Down
10 changes: 7 additions & 3 deletions src/client/app/components/UIOptionsComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import MapChartSelectComponent from './MapChartSelectComponent';
import ReactTooltip from 'react-tooltip';
import GraphicRateMenuComponent from './GraphicRateMenuComponent';
import AreaUnitSelectComponent from './AreaUnitSelectComponent';
import ErrorBarComponent from './ErrorBarComponent';

const Slider = createSliderWithTooltip(sliderWithoutTooltips);

Expand Down Expand Up @@ -88,8 +89,11 @@ class UIOptionsComponent extends React.Component<UIOptionsPropsWithIntl, UIOptio
<ChartSelectComponent />
<ChartDataSelectComponent />
<GraphicRateMenuComponent />
<AreaUnitSelectComponent/>

<AreaUnitSelectComponent />
{/* Controls error bar, specifically for the line chart. */}
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
{this.props.chartToRender === ChartTypes.line &&
<ErrorBarComponent />
}
{/* Controls specific to the bar chart. */}
{this.props.chartToRender === ChartTypes.bar &&
<div>
Expand Down Expand Up @@ -327,4 +331,4 @@ class UIOptionsComponent extends React.Component<UIOptionsPropsWithIntl, UIOptio
}
}

export default injectIntl(UIOptionsComponent);
export default injectIntl(UIOptionsComponent);
21 changes: 19 additions & 2 deletions src/client/app/containers/LineChartContainer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ function mapStateToProps(state: State) {
const timeInterval = state.graph.timeInterval;
const unitID = state.graph.selectedUnit;
const datasets: any[] = [];
const yMinData: number[] = [];
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
const yMaxData: number[] = [];
// The unit label depends on the unit which is in selectUnit state.
const graphingUnit = state.graph.selectedUnit;
// The current selected rate
Expand Down Expand Up @@ -71,7 +73,6 @@ function mapStateToProps(state: State) {
const hoverText: string[] = [];
const readings = _.values(readingsData.readings);
// The scaling is the factor to change the reading by. It divides by the area while will be 1 if no scaling by area.
// const scaling = currentSelectedRate.rate / meterArea;
readings.forEach(reading => {
// As usual, we want to interpret the readings in UTC. We lose the timezone as this as the start/endTimestamp
// are equivalent to Unix timestamp in milliseconds.
Expand All @@ -81,7 +82,16 @@ function mapStateToProps(state: State) {
xData.push(timeReading.format('YYYY-MM-DD HH:mm:ss'));
const readingValue = reading.reading * scaling;
yData.push(readingValue);
hoverText.push(`<b> ${timeReading.format('ddd, ll LTS')} </b> <br> ${label}: ${readingValue.toPrecision(6)} ${unitLabel}`);
const minValue = reading.min * scaling;
yMinData.push(minValue);
const maxValue = reading.max * scaling;
yMaxData.push(maxValue);
if (state.graph.showMinMax) {
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
hoverText.push(`<b> ${timeReading.format('ddd, ll LTS')} </b> <br> ${label}: ${readingValue.toPrecision(6)}` +
` ${unitLabel} <br> min: ${minValue.toPrecision(6)} <br> max: ${maxValue.toPrecision(6)}`);
} else {
hoverText.push(`<b> ${timeReading.format('ddd, ll LTS')} </b> <br> ${label}: ${readingValue.toPrecision(6)} ${unitLabel}`);
}
});

/*
Expand All @@ -103,6 +113,12 @@ function mapStateToProps(state: State) {
name: label,
x: xData,
y: yData,
error_y: state.graph.showMinMax ? {
type: 'data',
symmetric: false,
array: yMaxData.map((maxValue, index) => (maxValue - yData[index])),
arrayminus: yData.map((value, index) => (value - yMinData[index]))
} : undefined,
text: hoverText,
hoverinfo: 'text',
type: 'scatter',
Expand All @@ -113,6 +129,7 @@ function mapStateToProps(state: State) {
color: getGraphColor(colorID, DataType.Meter)
}
});

Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
}
}
}
Expand Down
11 changes: 9 additions & 2 deletions src/client/app/reducers/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@ const defaultState: GraphState = {
areaNormalization: false,
hotlinked: false,
optionsVisibility: true,
lineGraphRate: {label: 'hour', rate: 1},
renderOnce: false
lineGraphRate: { label: 'hour', rate: 1 },
renderOnce: false,
showMinMax: false
};

export default function graph(state = defaultState, action: GraphAction) {
Expand Down Expand Up @@ -93,6 +94,12 @@ export default function graph(state = defaultState, action: GraphAction) {
...state,
areaNormalization: !state.areaNormalization
};
case ActionType.ToggleShowMinMax:
return {
...state,
showMinMax: !state.showMinMax
};

Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
case ActionType.ChangeBarStacking:
return {
...state,
Expand Down
6 changes: 6 additions & 0 deletions src/client/app/translations/data.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ const localeData = {
"edit.unit": "Edit Unit",
"email": "Email",
"enable": "Enable",
"error.bar": "Error Bar",
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
"export.graph.data": "Export graph data",
"export.raw.graph.data": "Export graph meter data",
"failed.logging.in": "Failed logging in",
Expand Down Expand Up @@ -233,6 +234,7 @@ const localeData = {
"help.home.chart.select": "Any graph type can be used with any combination of groups and meters (except maps which only do meters within map). Line graphs show the usage (e.g., kW) vs. time. You can zoom and scroll with the controls right below the graph. Bar shows the total usage (e.g., kWh) for the time frame of each bar where you can control the time frame. Compare allows you to see the current usage vs. the usage in the last previous period for a day, week and four weeks. Map graphs show a spacial image of each meter where the circle size is related to four weeks of usage. Clicking on one of the choices (Line, Bar, Compare, Map) renders that graphic. Please visit {link} for further details and information.",
"help.home.compare.interval.tip": "Selects the time interval (Day, Week or 4 Weeks) to compare for current to previous. Please see {link} for further details and information.",
"help.home.compare.sort.tip": "Allows user to select the order of multiple comparison graphs to be Alphabetical (by name), Ascending (greatest to least reduction in usage) and Descending (least to greatest reduction in usage). Please see {link} for further details and information.",
"help.home.error.bar": "Toggles error bar with min and max value.Please visit {link} for further details and information.",
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
"help.home.export.graph.data": "With the \"Export graph data\" button, one can export the data for the graph when viewing either a line or compare graphic. The zoom and scroll feature on the line graph allows you to control the time frame of the data exported. The \"Export graph data\" button gives the data points for the graph and not the original meter data. The \"Export graph meter data\" gives the underlying meter data (line graphs only). Please visit {link} for further details and information on when meter data export is allowed.",
"help.home.hide.or.show.options": "With the \"Hide options\" button the options buttons and dropdown menus on the left and top of the OED window are all hidden. A new \"Menu\" button at the top, right of the web page is available to see these options including a button to \"Show options\" to reverse this choice. When the web page window becomes too small the options will automatically hide. Please visit {link} for further details and information.",
"help.home.select.groups": "Groups aggregate (sum the usage) of any combination of groups and meters. You can choose which groups to view in your graphic from the \"Groups:\" dropdown menu. Note you can type in text to limit which groups are shown. The Groups button in the top, right side of the window allows you to see more details about each group and, if you are an admin, to edit the groups. Please visit {link} for further details and information.",
Expand Down Expand Up @@ -602,6 +604,7 @@ const localeData = {
"edit.unit": "(need French) Edit Unit",
"email": "E-mail",
"enable": "Activer",
"error.bar": "(Need French) Error Bar",
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
"export.graph.data": "Exporter les données du diagramme",
"export.raw.graph.data": "(need French) Export graph meter data",
"failed.logging.in": "Echec de la connexion",
Expand Down Expand Up @@ -686,6 +689,7 @@ const localeData = {
"help.home.chart.select": "(Need French) Any graph type can be used with any combination of groups and meters (except maps which only do meters within map). Line graphs show the usage (e.g., kW) vs. time. You can zoom and scroll with the controls right below the graph. Bar shows the total usage (e.g., kWh) for the time frame of each bar where you can control the time frame. Compare allows you to see the current usage vs. the usage in the last previous period for a day, week and four weeks. Map graphs show a spacial image of each meter where the circle size is related to four weeks of usage. Clicking on one of the choices (Line, Bar, Compare, Map) renders that graphic. Please visit {link} for further details and information.",
"help.home.compare.interval.tip": "(Need French) Selects the time interval (Day, Week or 4 Weeks) to compare for current to previous. Please see {link} for further details and information.",
"help.home.compare.sort.tip": "(Need French) Allows user to select the order of multiple comparison graphs to be Alphabetical (by name), Ascending (greatest to least reduction in usage) and Descending (least to greatest reduction in usage). Please see {link} for further details and information.",
"help.home.error.bar": "(Need French) Toggles error bar with min and max value.Please visit {link} for further details and information.",
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
"help.home.export.graph.data": "(Need French) With the \"Export graph data\" button, one can export the data for the graph when viewing either a line or compare graphic. The zoom and scroll feature on the line graph allows you to control the time frame of the data exported. The \"Export graph data\" button gives the data points for the graph and not the original meter data. The \"Export graph meter data\" gives the underlying meter data (line graphs only). Please visit {link} for further details and information on when meter data export is allowed.",
"help.home.hide.or.show.options": "(Need French) With the \"Hide options\" button the options buttons and dropdown menus on the left and top of the OED window are all hidden. A new \"Menu\" button at the top, right of the web page is available to see these options including a button to \"Show options\" to reverse this choice. When the web page window becomes too small the options will automatically hide. Please visit {link} for further details and information.",
"help.home.select.groups": "(Need French) Groups aggregate (sum the usage) of any combination of groups and meters. You can choose which groups to view in your graphic from the \"Groups:\" dropdown menu. Note you can type in text to limit which groups are shown. The Groups button in the top, right side of the window allows you to see more details about each group and, if you are an admin, to edit the groups. Please visit {link} for further details and information.",
Expand Down Expand Up @@ -1055,6 +1059,7 @@ const localeData = {
"edit.unit": "(need Spanish) Edit Unit",
"email": "Correo Electronico",
"enable": "Activar",
"error.bar": "(Need Spanish) Error Bar",
"export.graph.data": "Exportar datos del gráfico",
"export.raw.graph.data": "Exportar datos gráficos de medidor",
"failed.logging.in": "Error al iniciar sesión",
Expand Down Expand Up @@ -1139,6 +1144,7 @@ const localeData = {
"help.home.chart.select": "Se puede usar cualquier tipo de gráfico con cualquier combinación de grupos y medidores (excepto los mapas que sólo hacen medidor dentro del mapa). Los gráficos de líneas muestran el uso (por ejemplo, kW) contra el tiempo. Puede hacer zoom y desplazarse con los controles justo debajo del gráfico. La barra muestra el uso total (por ejemplo, kWh) para el período de tiempo de cada barra donde puede controlar el período de tiempo. Comparar le permite ver el uso actual contra el uso de el último período anterior durante un día, una semana y cuatro semanas. Gráficos del mapa muestra un imagen especial de cada meter donde el talla del círculo está relacionado de cuatro semanas de uso. Al hacer clic en uno de las opciones (Línea, Barra, Comparar, Mapa) va a representa ese gráfico. Visite {link} para obtener más detalles e información.",
"help.home.compare.interval.tip": "Selecciona el intervalo de tiempo (Día, Semana o Cuatro semanas) para comparar el actual con el anterior. Por favor, vea {link} para más detalles e información.",
"help.home.compare.sort.tip": "Permite al usuario seleccionar el orden de los gráficos de comparación múltiple para que sean alfabéticos (por nombre), ascendentes (de mayor a menor reducción de uso) y descendentes (de menor a mayor reducción de uso). Por favor, vea {link} para más detalles e información.",
"help.home.error.bar": "(Need Spanish) Toggles error bar with min and max value.Please visit {link} for further details and information.",
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
"help.home.export.graph.data": "Con el botón \"Exportar data de gráfico\", uno puede exportar los datos del gráfico al ver una línea o comparar el gráfico. La función de zoom y desplazamiento en el gráfico de líneas le permite controlar el período de tiempo de los datos exportados. El \"Exportar data de gráfico\" botón da el puntos de dato para el gráfico y no los datos sin procesar de medidor. La \"Exportar el dato gráfhico de medidor\" proporciona los datos del medidor subyacente (solo gráficos de líneas). Visite {link} para obtener más detalles e información.",
"help.home.hide.or.show.options": "Con el botón \"Opciones de muelle\", los botones de opciones y los menús desplegables en la parte superior e izquierda de la ventana de OED están ocultos. Un nuevo botón \"Menú\" en la parte superior derecha de la página web está disponible para ver estas opciones, incluso un botón para \"mostrar opciones\" para revertir esta elección. Cuando la ventana de la página web se vuelve demasiado pequeña, las opciones se ocultarán automáticamente. Visite {link} para obtener más detalles e información.",
"help.home.select.groups": "Los grupos se agregan (suman el uso) de cualquier combinación de grupos y medidores. Puede elegir qué grupos ver en su gráfico desde el menú desplegable \"Groups:\" . Tenga en cuenta que puede escribir texto para limitar que grupos se muestran. El botón Grupos en la parte superior derecha de la ventana le permite ver más detalles sobre cada grupo y, si es un administrador, editar los grupos. Visite {link} para obtener más detalles e información.",
Expand Down
2 changes: 2 additions & 0 deletions src/client/app/types/readings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface LineReading {
reading: number;
startTimestamp: number;
endTimestamp: number;
min: number;
max: number;
}

export interface LineReadings {
Expand Down
1 change: 1 addition & 0 deletions src/client/app/types/redux/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export enum ActionType {
ChangeChartToRender = 'CHANGE_CHART_TO_RENDER',
ChangeBarStacking = 'CHANGE_BAR_STACKING',
ToggleAreaNormalization = 'TOGGLE_AREA_NORMALIZATION',
ToggleShowMinMax = 'TOGGLE_SHOW_MIN_MAX',
ChangeGraphZoom = 'CHANGE_GRAPH_ZOOM',
ChangeSliderRange = 'CHANGE_SLIDER_RANGE',
ResetRangeSliderStack = 'RESET_RANGE_SLIDER_STACK',
Expand Down
12 changes: 10 additions & 2 deletions src/client/app/types/redux/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export enum ChartTypes {

// Rates that can be graphed, only relevant to line graphs.
export const LineGraphRates = {
'second': (1/3600),
'minute': (1/60),
'second': (1 / 3600),
'minute': (1 / 60),
'hour': 1,
'day': 24
}
Expand Down Expand Up @@ -56,6 +56,12 @@ export interface ChangeChartToRenderAction {
export interface ToggleAreaNormalizationAction {
type: ActionType.ToggleAreaNormalization;
}
export interface ToggleShowMinMaxAction {
type: ActionType.ToggleShowMinMax;
}
export interface ToggleShowMinMaxAction {
Elias0127 marked this conversation as resolved.
Show resolved Hide resolved
type: ActionType.ToggleShowMinMax;
}

export interface ChangeBarStackingAction {
type: ActionType.ChangeBarStacking;
Expand Down Expand Up @@ -110,6 +116,7 @@ export type GraphAction =
| ResetRangeSliderStackAction
| ChangeBarStackingAction
| ToggleAreaNormalizationAction
| ToggleShowMinMaxAction
| ChangeChartToRenderAction
| UpdateBarDurationAction
| UpdateSelectedGroupsAction
Expand Down Expand Up @@ -146,4 +153,5 @@ export interface GraphState {
optionsVisibility: boolean;
lineGraphRate: LineGraphRate;
renderOnce: boolean;
showMinMax: boolean;
}
Loading