/
reference_breakdown_result.py
85 lines (62 loc) · 2.78 KB
/
reference_breakdown_result.py
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
from typing import List
import pandas as pd
from vortexasdk.api.search_result import Result
from vortexasdk.logger import get_logger
from vortexasdk.result_conversions import create_dataframe, create_list
from vortexasdk.api.breakdown_item import BreakdownItem
from vortexasdk.api.entity_flattening import convert_to_flat_dict
import pandas as pd
import functools
import os
from multiprocessing.pool import Pool
logger = get_logger(__name__)
def replace_keys(result):
# Creates a list of data entries with keys enriched by references
if len(result) == 0:
return list([])
else:
refs = result["reference"]
data = result["data"]
return list(map(lambda x: key_from_ref(x, refs), data))
def key_from_ref(datum, refs):
# Reads the label from references and adds the label to the output
key = datum["key"]
name = refs[key]["label"]
return {**datum, "label": name}
class ReferenceBreakdownResult(Result):
"""Container class that holds the result obtained from calling a breakdown endpoint enriched with reference data."""
def to_list(self) -> List[BreakdownItem]:
"""Represents time series as a list."""
# data enrichment step - labels from `reference` enrich entries from `data`
new_list = replace_keys(self)
return create_list(new_list, BreakdownItem)
def to_df(self, columns=None) -> pd.DataFrame:
"""Represents the breakdown as a dataframe.
Returns a `pd.DataFrame`, of breakdown items with columns:
key: id of the breakdown item
label: name of the breakdown item
value: The value of the breakdown for a given key
count: The number of records contributing to this breakdown record.
# Example:
If we're aggregating origin breakdown by vessel count, then the `key` column holds the id of the country,
the `label` holds the name of the country, the `value` column holds the number of unique vessels on that day,
and the `count` column holds the number of vessels movements contributing towards this day's movements.
"""
# data enrichment step - labels from `reference` replace keys from `data`
new_list = replace_keys(self)
if columns is None:
columns = DEFAULT_COLUMNS
logger.debug("Converting each breakdown to a flat dictionary")
flatten = functools.partial(
convert_to_flat_dict, cols=columns
)
with Pool(os.cpu_count()) as pool:
records = pool.map(flatten, new_list)
df = create_dataframe(
columns=columns,
default_columns=DEFAULT_COLUMNS,
data=records,
logger_description="ReferenceBreakdown",
)
return df
DEFAULT_COLUMNS = ["key", "label", "value", "count"]