forked from datacommonsorg/website
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchart_loader.tsx
More file actions
756 lines (700 loc) · 20.1 KB
/
chart_loader.tsx
File metadata and controls
756 lines (700 loc) · 20.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
/**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Component for retrieving and transforming data into a form ready for plotting
* and passing the data to a `Chart` component that plots the scatter plot.
*/
import { dataRowsToCsv } from "@datacommonsorg/client";
import _ from "lodash";
import React, {
ReactElement,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import { Point } from "../../chart/draw_scatter";
import { CSV_FIELD_DELIMITER } from "../../constants/tile_constants";
import { ChartEmbed } from "../../place/chart_embed";
import {
DEFAULT_POPULATION_DCID,
WEBSITE_SURFACE,
} from "../../shared/constants";
import { FacetSelectorFacetInfo } from "../../shared/facet_selector/facet_selector";
import {
buildObservationSpecs,
ObservationSpec,
} from "../../shared/observation_specs";
import {
EntityObservation,
EntityObservationList,
PointAllApiResponse,
PointApiResponse,
SeriesApiResponse,
StatMetadata,
} from "../../shared/stat_types";
import { StatVarFacetMap, StatVarSpec } from "../../shared/types";
import { getCappedStatVarDate, saveToFile } from "../../shared/util";
import { scatterDataToCsv } from "../../utils/chart_csv_utils";
import { getDataCommonsClient } from "../../utils/data_commons_client";
import { FacetResponse, getSeriesWithin } from "../../utils/data_fetch_utils";
import { getPlaceScatterData } from "../../utils/scatter_data_utils";
import { getMergedSvg, transformCsvHeader } from "../../utils/tile_utils";
import { Chart } from "./chart";
import { useFacetMetadata } from "./compute/facet_metadata";
import {
Axis,
AxisWrapper,
Context,
IsLoadingWrapper,
PlaceInfo,
} from "./context";
import { getStatAllWithinPlace, getStatWithinPlace } from "./util";
type Cache = {
// key here is stat var.
statVarsData: Record<string, EntityObservation>;
allStatVarsData: Record<string, EntityObservationList>;
metadataMap: Record<string, StatMetadata>;
baseFacets: FacetResponse;
populationData: SeriesApiResponse;
noDataError: boolean;
error: boolean;
xAxis: Axis;
yAxis: Axis;
place: PlaceInfo;
};
type ChartData = {
points: { [placeDcid: string]: Point };
sources: Set<string>;
xUnit: string;
yUnit: string;
xDenomFacets: Set<string>;
yDenomFacets: Set<string>;
xNumerFacets: Set<string>;
yNumerFacets: Set<string>;
};
export function ChartLoader(): ReactElement {
const { x, y, place, display } = useContext(Context);
const cache = useCache();
const chartData = useChartData(cache);
const { facetSelectorMetadata, facetListLoading, facetListError } =
useFacetMetadata(cache?.baseFacets || null);
const containerRef = useRef<HTMLDivElement>(null);
const embedModalElement = useRef<ChartEmbed>(null);
const xVal = x.value;
const yVal = y.value;
const shouldRenderChart =
areStatVarInfoLoaded(xVal, yVal) && !_.isEmpty(chartData);
/**
* The stat var specs for the current chart configuration.
*/
const currentStatVarSpecs: StatVarSpec[] = useMemo(() => {
if (!xVal.statVarDcid || !yVal.statVarDcid) return [];
return [
{
statVar: xVal.statVarDcid,
denom: xVal.perCapita ? xVal.denom : undefined,
unit: chartData?.xUnit || undefined,
scaling: undefined,
log: xVal.log,
name: xVal.statVarInfo?.title || xVal.statVarDcid,
facetId: xVal.metahash || undefined,
date: xVal.date || undefined,
},
{
statVar: yVal.statVarDcid,
denom: yVal.perCapita ? yVal.denom : undefined,
unit: chartData?.yUnit || undefined,
scaling: undefined,
log: yVal.log,
name: yVal.statVarInfo?.title || yVal.statVarDcid,
facetId: yVal.metahash || undefined,
date: yVal.date || undefined,
},
];
}, [xVal, yVal, chartData]);
/**
* Convert facet metadata and mappings (derived from the chart store) into a format
* to be used for citation display in the embed modal, as well as the metadata modal.
*/
const { facets, statVarToFacets } = useMemo(() => {
const facets: Record<string, StatMetadata> = {};
const statVarToFacets: StatVarFacetMap = {};
if (!cache || !cache.metadataMap || !chartData) {
return { facets, statVarToFacets };
}
// Helper to map plotted facets to their variable and populate metadata
const processFacets = (
statVarDcid: string,
plottedFacets: Set<string>
): void => {
if (!statVarDcid || !plottedFacets || plottedFacets.size === 0) return;
if (!statVarToFacets[statVarDcid]) {
statVarToFacets[statVarDcid] = new Set();
}
for (const facetId of Array.from(plottedFacets)) {
statVarToFacets[statVarDcid].add(facetId);
if (cache.metadataMap[facetId]) {
facets[facetId] = cache.metadataMap[facetId];
}
}
};
//Add in numerators that appear in the chart
processFacets(xVal.statVarDcid, chartData.xNumerFacets);
processFacets(yVal.statVarDcid, chartData.yNumerFacets);
//Add in denominators that appear in the chart
if (xVal.perCapita && xVal.denom) {
processFacets(xVal.denom, chartData.xDenomFacets);
}
if (yVal.perCapita && yVal.denom) {
processFacets(yVal.denom, chartData.yDenomFacets);
}
return { facets, statVarToFacets };
}, [
cache,
chartData,
xVal.statVarDcid,
xVal.perCapita,
xVal.denom,
yVal.statVarDcid,
yVal.perCapita,
yVal.denom,
]);
/**
* Callback function for building observation specifications.
* This is used by the API dialog to generate API calls (e.g., cURL
* commands) for the user.
*
* @returns An array of `ObservationSpec` objects.
*/
const getObservationSpecs = useCallback((): ObservationSpec[] => {
if (
currentStatVarSpecs.length === 0 ||
!place.value.enclosingPlace.dcid ||
!place.value.enclosedPlaceType
) {
return [];
}
const entityExpression = `${place.value.enclosingPlace.dcid}<-containedInPlace+{typeOf:${place.value.enclosedPlaceType}}`;
const specsWithDate = currentStatVarSpecs.map((spec) => ({
...spec,
date: getCappedStatVarDate(spec.statVar, spec.date) || "LATEST",
}));
return buildObservationSpecs({
statVarSpecs: specsWithDate,
statVarToFacets,
entityExpression,
});
}, [
currentStatVarSpecs,
place.value.enclosingPlace.dcid,
place.value.enclosedPlaceType,
statVarToFacets,
]);
/**
* Returns callback for fetching chart CSV data.
* @returns A promise that resolves to chart CSV data.
*/
const getDataCsv = useCallback(async (): Promise<string> => {
// Assume both variables will have the same date
/*
TODO (nick-next): Update getDataCsv to handle different dates for different variables
see also scatter_tile.tsx.
*/
if (
currentStatVarSpecs.length === 0 ||
!place.value.enclosingPlace.dcid ||
!place.value.enclosedPlaceType
) {
return "";
}
const dataCommonsClient = getDataCommonsClient();
const date = getCappedStatVarDate(
currentStatVarSpecs[0].statVar,
currentStatVarSpecs[0].date
);
const rows = await dataCommonsClient.getDataRows({
childType: place.value.enclosedPlaceType,
date,
parentEntity: place.value.enclosingPlace.dcid,
variables: [],
statVarSpecs: currentStatVarSpecs,
});
return dataRowsToCsv(rows, CSV_FIELD_DELIMITER, transformCsvHeader);
}, [
currentStatVarSpecs,
place.value.enclosingPlace.dcid,
place.value.enclosedPlaceType,
]);
/**
* Shows the chart embed (download) modal.
*/
const handleEmbed = useCallback((): void => {
if (!embedModalElement.current || !containerRef.current) return;
const { svgXml, height, width } = getMergedSvg(containerRef.current);
embedModalElement.current.show(
svgXml,
getDataCsv,
width,
height,
"",
"",
"",
chartData?.sources ? Array.from(chartData.sources) : [],
WEBSITE_SURFACE
);
}, [getDataCsv, chartData?.sources]);
if (!shouldRenderChart) {
return <></>;
}
const xFacetInfo = getFacetInfo(
xVal,
facetSelectorMetadata[xVal.statVarDcid]
);
const yFacetInfo = getFacetInfo(
yVal,
facetSelectorMetadata[yVal.statVarDcid]
);
const onSvFacetIdUpdated = (update): void => {
for (const sv of Object.keys(update)) {
if (x.value.statVarDcid === sv) {
x.setMetahash(update[sv]);
} else if (y.value.statVarDcid === sv) {
y.setMetahash(update[sv]);
}
}
};
return (
<div ref={containerRef}>
{shouldRenderChart && (
<>
{cache.noDataError || cache.error || _.isEmpty(chartData.points) ? (
<div className="error-message">
Sorry, no data available. Try different stat vars or place
options.
</div>
) : (
<>
<Chart
points={chartData.points}
xLabel={getLabel(xVal)}
yLabel={getLabel(yVal)}
xLog={xVal.log}
yLog={yVal.log}
xPerCapita={xVal.perCapita}
yPerCapita={yVal.perCapita}
xUnit={chartData.xUnit}
yUnit={chartData.yUnit}
placeInfo={place.value}
display={display}
sources={chartData.sources}
facets={facets}
statVarToFacets={statVarToFacets}
statVarSpecs={currentStatVarSpecs}
svFacetId={{
[x.value.statVarDcid]: x.value.metahash,
[y.value.statVarDcid]: y.value.metahash,
}}
onSvFacetIdUpdated={onSvFacetIdUpdated}
facetList={[xFacetInfo, yFacetInfo]}
facetListLoading={facetListLoading}
facetListError={facetListError}
handleEmbed={handleEmbed}
getObservationSpecs={getObservationSpecs}
containerRef={containerRef}
/>
<ChartEmbed
ref={embedModalElement}
entities={Object.keys(chartData.points)}
facets={facets}
statVarSpecs={currentStatVarSpecs}
statVarToFacets={statVarToFacets}
/>
</>
)}
</>
)}
</div>
);
}
/**
* Hook that returns a cache containing population and statvar data.
*/
function useCache(): Cache {
const { x, y, place, isLoading } = useContext(Context);
const [cache, setCache] = useState(null);
const xVal = x.value;
const yVal = y.value;
const placeVal = place.value;
/**
* When statvars, enclosing place, child place type, or any plot options change,
* re-retreive data.
*/
useEffect(() => {
if (
!isLoading.areDataLoading &&
!areDataLoaded(cache, xVal, yVal, placeVal)
) {
void loadData(x, y, placeVal, isLoading, setCache);
}
}, [xVal, yVal, placeVal]);
return cache;
}
/**
* Fills cache with population and statvar data.
* @param x
* @param y
* @param place
* @param isLoading
* @param setCache
*/
async function loadData(
x: AxisWrapper,
y: AxisWrapper,
place: PlaceInfo,
isLoading: IsLoadingWrapper,
setCache: (cache: Cache) => void
): Promise<void> {
isLoading.setAreDataLoading(true);
const statResponsePromise: Promise<PointApiResponse> = getStatWithinPlace(
place.enclosingPlace.dcid,
place.enclosedPlaceType,
[x.value, y.value],
"", // apiRoot
WEBSITE_SURFACE
);
const statAllResponsePromise: Promise<PointAllApiResponse> =
getStatAllWithinPlace(
place.enclosingPlace.dcid,
place.enclosedPlaceType,
[x.value, y.value],
WEBSITE_SURFACE
);
const populationSvList = new Set([DEFAULT_POPULATION_DCID]);
for (const axis of [x.value, y.value]) {
if (axis.denom) {
populationSvList.add(axis.denom);
}
}
const populationPromise: Promise<SeriesApiResponse> = getSeriesWithin(
"",
place.enclosingPlace.dcid,
place.enclosedPlaceType,
Array.from(populationSvList),
null, // facetIds
WEBSITE_SURFACE
);
try {
const [statResponse, statAllResponse, populationData] = await Promise.all([
statResponsePromise,
statAllResponsePromise,
populationPromise,
]);
const metadataMap = {
...(statResponse.facets || {}),
...(statAllResponse.facets || {}),
...(populationData.facets || {}),
};
const baseFacets: FacetResponse = {};
const statVars = [x.value.statVarDcid, y.value.statVarDcid];
for (const sv of statVars) {
baseFacets[sv] = {};
if (statAllResponse.data[sv]) {
for (const placeDcid in statAllResponse.data[sv]) {
for (const obs of statAllResponse.data[sv][placeDcid]) {
if (metadataMap[obs.facet]) {
baseFacets[sv][obs.facet] = metadataMap[obs.facet];
}
}
}
}
}
const allStatVarsData = statAllResponse.data;
const noDataError =
_.isEmpty(statResponse.data) ||
Object.values(statResponse.data).every(_.isEmpty);
const cache: Cache = {
allStatVarsData,
metadataMap,
baseFacets,
noDataError,
error: false,
populationData,
statVarsData: statResponse.data,
xAxis: x.value,
yAxis: y.value,
place,
};
setCache(cache);
} catch {
setCache({
statVarsData: {},
allStatVarsData: {},
metadataMap: {},
baseFacets: {},
populationData: null,
noDataError: true,
error: true,
xAxis: x.value,
yAxis: y.value,
place,
});
alert("Error fetching data.");
} finally {
isLoading.setAreDataLoading(false);
}
}
/**
* Hook that returns the processed chart data for rendering a scatter chart.
* @param cache
*/
function useChartData(cache: Cache): ChartData {
const { x, y, place, display } = useContext(Context);
const [chartData, setChartData] = useState(null);
const xVal = x.value;
const yVal = y.value;
const placeVal = place.value;
/**
* Regenerates chartData after population and statvar data are retrieved
* and after plot options change.
*/
useEffect(() => {
if (
_.isEmpty(cache) ||
!areDataLoaded(cache, xVal, yVal, placeVal) ||
_.isNull(placeVal.enclosedPlaces)
) {
return;
}
const chartData = getChartData(xVal, yVal, placeVal, cache);
setChartData(chartData);
const downloadButton = document.getElementById("download-link");
if (downloadButton) {
downloadButton.style.display = "inline-block";
downloadButton.onclick = (): void =>
downloadData(xVal, yVal, placeVal, chartData.points);
}
}, [cache, xVal, yVal, placeVal, display.chartType]);
return chartData;
}
/**
* Extract data for a given facet from all the facets data.
*
* TODO: this can be moved to a shared util module.
*/
function extractFacetData(
data: EntityObservationList,
facetId: string
): EntityObservation {
if (_.isEmpty(facetId)) {
return null;
}
const result = {};
for (const place in data) {
for (const obs of data[place]) {
if (obs.facet === facetId) {
result[place] = obs;
break;
}
}
}
return result;
}
/**
* Takes fetched data and processes it to be in a form that can be used for
* rendering the chart component
* @param x
* @param y
* @param place
* @param chartType
* @param cache
*/
function getChartData(
x: Axis,
y: Axis,
place: PlaceInfo,
cache: Cache
): ChartData {
let xStatData = extractFacetData(
cache.allStatVarsData[x.statVarDcid],
x.metahash
);
if (_.isEmpty(xStatData)) {
xStatData = cache.statVarsData[x.statVarDcid];
}
let yStatData = extractFacetData(
cache.allStatVarsData[y.statVarDcid],
y.metahash
);
if (_.isEmpty(yStatData)) {
yStatData = cache.statVarsData[y.statVarDcid];
}
const points = {};
const sources: Set<string> = new Set();
let xUnit = "";
let yUnit = "";
const xDenomFacets: Set<string> = new Set();
const yDenomFacets: Set<string> = new Set();
const xNumerFacets: Set<string> = new Set();
const yNumerFacets: Set<string> = new Set();
for (const namedPlace of place.enclosedPlaces) {
const xDenom = x.perCapita ? x.denom : null;
const yDenom = y.perCapita ? y.denom : null;
const placeChartData = getPlaceScatterData(
namedPlace,
xStatData,
yStatData,
{}, // empty denomByFacet since we only care about the singular populationData here
cache.populationData,
cache.metadataMap,
xDenom,
yDenom
);
if (_.isEmpty(placeChartData)) {
continue;
}
placeChartData.sources.forEach((source) => {
if (!_.isEmpty(source)) {
sources.add(source);
}
});
// Compile the used numerator and denominator facets
if (placeChartData.xDenomFacet) {
xDenomFacets.add(placeChartData.xDenomFacet);
}
if (placeChartData.yDenomFacet) {
yDenomFacets.add(placeChartData.yDenomFacet);
}
const xNumerFacet = xStatData?.[namedPlace.dcid]?.facet;
if (xNumerFacet) {
xNumerFacets.add(xNumerFacet);
}
const yNumerFacet = yStatData?.[namedPlace.dcid]?.facet;
if (yNumerFacet) {
yNumerFacets.add(yNumerFacet);
}
points[namedPlace.dcid] = placeChartData.point;
xUnit = xUnit || placeChartData.xUnit;
yUnit = yUnit || placeChartData.yUnit;
}
return {
points,
sources,
xUnit,
yUnit,
xDenomFacets,
yDenomFacets,
xNumerFacets,
yNumerFacets,
};
}
function getFacetInfo(
axis: Axis,
metadataMapForSv: Record<string, StatMetadata>
): FacetSelectorFacetInfo {
const metadataMap = metadataMapForSv || {};
return {
dcid: axis.statVarDcid,
metadataMap,
name: axis.statVarInfo.title || axis.statVarDcid,
};
}
/**
* Checks if the stat var info for an axis has been loaded.
* @param axis
*/
function isStatVarInfoLoaded(axis: Axis): boolean {
return !_.isNull(axis.statVarInfo);
}
/**
* Checks if the stat var info for both axes has been loaded.
*/
function areStatVarInfoLoaded(x: Axis, y: Axis): boolean {
return isStatVarInfoLoaded(x) && isStatVarInfoLoaded(y);
}
/**
* Checks if the population (for per capita) and statvar data
* have been loaded for both axes.
* @param cache
* @param x
* @param y
* @param place
*/
function areDataLoaded(
cache: Cache,
x: Axis,
y: Axis,
place: PlaceInfo
): boolean {
if (
_.isEmpty(cache) ||
_.isEmpty(cache.xAxis) ||
_.isEmpty(cache.yAxis) ||
_.isEmpty(cache.place)
) {
return false;
}
const xStatVar = x.statVarDcid;
const yStatVar = y.statVarDcid;
return (
xStatVar in cache.statVarsData &&
yStatVar in cache.statVarsData &&
cache.xAxis.date === x.date &&
cache.yAxis.date === y.date &&
cache.xAxis.denom === x.denom &&
cache.yAxis.denom === y.denom &&
cache.place.enclosingPlace.dcid === place.enclosingPlace.dcid &&
cache.place.enclosedPlaceType === place.enclosedPlaceType
);
}
/**
* Saves data to a CSV file.
* @param x
* @param y
* @param place
* @param points
*/
function downloadData(
x: Axis,
y: Axis,
place: PlaceInfo,
points: { [placeDcid: string]: Point }
): void {
const csv = scatterDataToCsv(
x.statVarDcid,
DEFAULT_POPULATION_DCID,
y.statVarDcid,
DEFAULT_POPULATION_DCID,
points
);
saveToFile(
`${x.statVarDcid}+` +
`${y.statVarDcid}+` +
`${place.enclosingPlace.name}+` +
`${place.enclosedPlaceType}.csv`,
csv
);
}
/**
* Gets the label given an axis.
* @param axis
*/
function getLabel(axis: Axis): string {
const name = axis.statVarInfo.title || axis.statVarDcid;
return `${name}${axis.perCapita ? " Per Capita" : ""}`;
}