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

V4/delays chart #755

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
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
2 changes: 1 addition & 1 deletion common/constants/baselines.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const PEAK_SCHEDULED_SERVICE = {
DEFAULT: 0,
};

export const PEAK_SPEED = {
export const PEAK_MPH = {
'line-red': 21.4,
'line-orange': 18,
'line-blue': 20.5,
Expand Down
3 changes: 2 additions & 1 deletion modules/commute/speed/utils/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { PEAK_MPH } from '../../../../common/constants/baselines';
import type { SpeedDataPoint } from '../../../../common/types/dataPoints';
import { CORE_TRACK_LENGTHS, PEAK_MPH } from '../../../speed/constants/speeds';
import { CORE_TRACK_LENGTHS } from '../../../speed/constants/speeds';

export const calculateCommuteSpeedWidgetValues = (
weeklyData: SpeedDataPoint[],
Expand Down
11 changes: 2 additions & 9 deletions modules/landing/utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
import type { ChartDataset } from 'chart.js';
import { round } from 'lodash';
import {
PEAK_RIDERSHIP,
PEAK_SCHEDULED_SERVICE,
PEAK_SPEED,
} from '../../common/constants/baselines';
import { PEAK_RIDERSHIP, PEAK_SCHEDULED_SERVICE, PEAK_MPH } from '../../common/constants/baselines';
import { LINE_COLORS } from '../../common/constants/colors';
import type { RidershipCount, DeliveredTripMetrics } from '../../common/types/dataPoints';
import type { Line } from '../../common/types/lines';
Expand All @@ -31,10 +27,7 @@ export const convertToSpeedDataset = (data: DeliveredTripMetrics[]) => {
label: `% of peak`,
data: data.map((datapoint) =>
datapoint.miles_covered
? round(
(100 * datapoint.miles_covered) / (datapoint.total_time / 3600) / PEAK_SPEED[line],
1
)
? round((100 * datapoint.miles_covered) / (datapoint.total_time / 3600) / PEAK_MPH[line], 1)
: Number.NaN
),
};
Expand Down
4 changes: 2 additions & 2 deletions modules/service/utils/graphUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ const shuttlingAnnotationBlockStyle = {
backgroundColor: CHART_COLORS.BLOCKS,
borderWidth: 0,
label: {
content: 'No data',
content: 'Service Disruption',
rotation: -90,
color: 'white',
color: '#505050',
display: true,
},
};
Expand Down
182 changes: 182 additions & 0 deletions modules/speed/DelaysChart.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import React, { useRef } from 'react';
import { round } from 'lodash';
import { Line } from 'react-chartjs-2';

import 'chartjs-adapter-date-fns';
import { enUS } from 'date-fns/locale';

import ChartjsPluginWatermark from 'chartjs-plugin-watermark';
import { useDelimitatedRoute } from '../../common/utils/router';
import { COLORS, LINE_COLORS } from '../../common/constants/colors';
import type { DeliveredTripMetrics } from '../../common/types/dataPoints';
import { drawSimpleTitle } from '../../common/components/charts/Title';
import { useBreakpoint } from '../../common/hooks/useBreakpoint';
import { watermarkLayout } from '../../common/constants/charts';
import { ChartBorder } from '../../common/components/charts/ChartBorder';
import { ChartDiv } from '../../common/components/charts/ChartDiv';
import { PEAK_MPH } from '../../common/constants/baselines';
import { getShuttlingBlockAnnotations } from '../service/utils/graphUtils';
import type { ParamsType } from './constants/speeds';

interface TripTimeIncreaseChartProps {
data: DeliveredTripMetrics[];
config: ParamsType;
startDate: string;
endDate: string;
showTitle?: boolean;
}

export const DelaysChart: React.FC<TripTimeIncreaseChartProps> = ({
data,
config,
startDate,
endDate,
showTitle = false,
}) => {
const { line, linePath } = useDelimitatedRoute();
const { tooltipFormat, unit, callbacks } = config;
const peak = PEAK_MPH[line ?? 'DEFAULT'];
const ref = useRef();
const isMobile = !useBreakpoint('md');
const labels = data.map((point) => point.date);
const shuttlingBlocks = getShuttlingBlockAnnotations(data);

return (
<ChartBorder>
<ChartDiv isMobile={isMobile}>
<Line
id={`speed-${linePath}`}
height={isMobile ? 240 : 200}
ref={ref}
redraw={true}
data={{
labels,
datasets: [
{
label: `Delay`,
borderColor: LINE_COLORS[line ?? 'default'],
pointRadius: 0,
pointBorderWidth: 0,
stepped: true,
pointHoverRadius: 6,
spanGaps: false,
pointHoverBackgroundColor: LINE_COLORS[line ?? 'default'],
pointBackgroundColor: LINE_COLORS[line ?? 'default'],
data: data.map((datapoint) => {
const mph = round(datapoint.miles_covered / (datapoint.total_time / 3600), 1);
return (100 * ((PEAK_MPH[line ?? 'DEFAULT'] - mph) / mph)).toFixed(1);
}),
},
],
}}
options={{
responsive: true,
maintainAspectRatio: false,
layout: {
padding: {
top: showTitle ? 25 : 0,
},
},
interaction: {
intersect: false,
},
// @ts-expect-error The watermark plugin doesn't have typescript support
watermark: watermarkLayout(isMobile),
plugins: {
tooltip: {
mode: 'index',
position: 'nearest',
callbacks: {
...callbacks,
label: (context) => {
return `Trips are ${context.parsed.y}% ${
context.parsed.y >= 0 ? 'longer' : 'shorter'
} than peak`;
},
},
},
legend: {
position: 'bottom',
labels: {
boxWidth: 15,
},
},
title: {
// empty title to set font and leave room for drawTitle fn
display: showTitle,
text: '',
},
annotation: {
// Add your annotations here
annotations: [...shuttlingBlocks],
},
},
scales: {
y: {
suggestedMin: 0,
suggestedMax: PEAK_MPH[line ?? 'DEFAULT'],
display: true,
ticks: {
color: COLORS.design.subtitleGrey,
},
title: {
display: true,
text: '% delay',
color: COLORS.design.subtitleGrey,
},
},
x: {
min: startDate,
max: endDate,
type: 'time',
time: {
unit: unit,
tooltipFormat: tooltipFormat,
displayFormats: {
month: 'MMM',
},
},
ticks: {
color: COLORS.design.subtitleGrey,
},
adapters: {
date: {
locale: enUS,
},
},
display: true,
title: {
display: false,
text: ``,
},
},
},
}}
plugins={[
{
id: 'customTitle',
afterDraw: (chart) => {
if (!data) {
// No data is present
const { ctx } = chart;
const { width } = chart;
const { height } = chart;
chart.clear();

ctx.save();
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = "16px normal 'Helvetica Nueue'";
ctx.fillText('No data to display', width / 2, height / 2);
ctx.restore();
}
if (showTitle) drawSimpleTitle(`Median Speed`, chart);
},
},
ChartjsPluginWatermark,
]}
/>
</ChartDiv>
</ChartBorder>
);
};
50 changes: 50 additions & 0 deletions modules/speed/DelaysChartWrapper.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import React from 'react';
import { CarouselGraphDiv } from '../../common/components/charts/CarouselGraphDiv';
import type { DeliveredTripMetrics } from '../../common/types/dataPoints';
import { NoDataNotice } from '../../common/components/notices/NoDataNotice';
import { getDetailsSpeedWidgetValues } from './utils/utils';
import type { ParamsType } from './constants/speeds';
import { DelaysChart } from './DelaysChart';

interface DelaysChartWrapperProps {
data: DeliveredTripMetrics[];
config: ParamsType;
startDate: string;
endDate: string;
}

export const DelaysChartWrapper: React.FC<DelaysChartWrapperProps> = ({
data,
config,
startDate,
endDate,
}) => {
const dataNoNulls = data.filter((datapoint) => datapoint.miles_covered);
if (dataNoNulls.length < 1) return <NoDataNotice isLineMetric />;
const { current, delta, average, peak } = getDetailsSpeedWidgetValues(dataNoNulls);
return (
<CarouselGraphDiv>
{/* <WidgetCarousel>
<WidgetForCarousel
widgetValue={new MPHWidgetValue(average, undefined)}
analysis={'Average'}
sentimentDirection={'positiveOnIncrease'}
layoutKind="no-delta"
/>
<WidgetForCarousel
widgetValue={new MPHWidgetValue(current, delta)}
analysis={`Current (${config.getWidgetTitle(dataNoNulls[dataNoNulls.length - 1].date)})`}
layoutKind="no-delta"
sentimentDirection={'positiveOnIncrease'}
/>
<WidgetForCarousel
widgetValue={new MPHWidgetValue(peak.mph, undefined)}
analysis={`Peak (${config.getWidgetTitle(peak.date)})`}
sentimentDirection={'positiveOnIncrease'}
layoutKind="no-delta"
/>
</WidgetCarousel> */}
<DelaysChart config={config} data={data} startDate={startDate} endDate={endDate} />
</CarouselGraphDiv>
);
};
7 changes: 6 additions & 1 deletion modules/speed/SpeedDetailsWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { WidgetDiv } from '../../common/components/widgets/WidgetDiv';
import { WidgetTitle } from '../dashboard/WidgetTitle';
import type { ParamsType } from './constants/speeds';
import { SpeedGraphWrapper } from './SpeedGraphWrapper';
import { DelaysChartWrapper } from './DelaysChartWrapper';

interface SpeedDetailsWrapperProps {
data: DeliveredTripMetrics[];
Expand All @@ -21,9 +22,13 @@ export const SpeedDetailsWrapper: React.FC<SpeedDetailsWrapperProps> = ({
return (
<>
<WidgetDiv>
<WidgetTitle title="Median speed" />
<WidgetTitle title="Speed" />
<SpeedGraphWrapper data={data} config={config} startDate={startDate} endDate={endDate} />
</WidgetDiv>
<WidgetDiv>
<WidgetTitle title="Trip delays" />
<DelaysChartWrapper data={data} config={config} startDate={startDate} endDate={endDate} />
</WidgetDiv>
</>
);
};
9 changes: 4 additions & 5 deletions modules/speed/SpeedGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@ import { useBreakpoint } from '../../common/hooks/useBreakpoint';
import { watermarkLayout } from '../../common/constants/charts';
import { ChartBorder } from '../../common/components/charts/ChartBorder';
import { ChartDiv } from '../../common/components/charts/ChartDiv';
import { PEAK_SPEED } from '../../common/constants/baselines';
import { PEAK_MPH } from '../../common/constants/baselines';
import { getShuttlingBlockAnnotations } from '../service/utils/graphUtils';
import { PEAK_MPH } from './constants/speeds';
import type { ParamsType } from './constants/speeds';

interface SpeedGraphProps {
Expand All @@ -35,7 +34,7 @@ export const SpeedGraph: React.FC<SpeedGraphProps> = ({
}) => {
const { line, linePath } = useDelimitatedRoute();
const { tooltipFormat, unit, callbacks } = config;
const peak = PEAK_SPEED[line ?? 'DEFAULT'];
const peak = PEAK_MPH[line ?? 'DEFAULT'];
const ref = useRef();
const isMobile = !useBreakpoint('md');
const labels = data.map((point) => point.date);
Expand Down Expand Up @@ -94,7 +93,7 @@ export const SpeedGraph: React.FC<SpeedGraphProps> = ({
callbacks: {
...callbacks,
label: (context) => {
return `${context.parsed.y} (${((100 * context.parsed.y) / peak).toFixed(
return `${context.parsed.y} mph (${((100 * context.parsed.y) / peak).toFixed(
1
)}% of peak)`;
},
Expand Down Expand Up @@ -186,7 +185,7 @@ export const SpeedGraph: React.FC<SpeedGraphProps> = ({
ctx.fillText('No data to display', width / 2, height / 2);
ctx.restore();
}
if (showTitle) drawSimpleTitle(`Median Speed`, chart);
if (showTitle) drawSimpleTitle(`Speed`, chart);
},
},
ChartjsPluginWatermark,
Expand Down
10 changes: 0 additions & 10 deletions modules/speed/constants/speeds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { TooltipCallbacks, TooltipItem, TooltipModel } from 'chart.js';
import type { _DeepPartialObject } from 'chart.js/dist/types/utils';
import dayjs from 'dayjs';
import { todayOrDate } from '../../../common/constants/dates';
import { PEAK_COMPLETE_TRIP_TIMES } from '../../../common/constants/baselines';

export type AggType = 'daily' | 'weekly' | 'monthly';
export type ParamsType = {
Expand Down Expand Up @@ -76,12 +75,3 @@ export const CORE_TRACK_LENGTHS = {
'line-blue': 5.38 + 5.37, //<Gov. Center -> Revere> + <reverse>
DEFAULT: 1,
};

export const PEAK_MPH = {
'line-red': CORE_TRACK_LENGTHS['line-red'] / (PEAK_COMPLETE_TRIP_TIMES['line-red'].value / 3600),
'line-orange':
CORE_TRACK_LENGTHS['line-orange'] / (PEAK_COMPLETE_TRIP_TIMES['line-orange'].value / 3600),
'line-blue':
CORE_TRACK_LENGTHS['line-blue'] / (PEAK_COMPLETE_TRIP_TIMES['line-blue'].value / 3600),
DEFAULT: 1,
};