-
Notifications
You must be signed in to change notification settings - Fork 115
/
core.py
executable file
·2998 lines (2529 loc) · 110 KB
/
core.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
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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import copy
import importlib
import itertools
import logging
import os
import sys
import numpy as np
import pandas as pd
from pandas.api.types import is_integer
from pathlib import Path
from tempfile import TemporaryDirectory
from pyam.slice import IamSlice
from pyam.filter import filter_by_time_domain, filter_by_year, filter_by_dt_arg
try:
from datapackage import Package
HAS_DATAPACKAGE = True
except ImportError:
Package = None
HAS_DATAPACKAGE = False
from pyam.run_control import run_control
from pyam.utils import (
write_sheet,
read_file,
read_pandas,
format_data,
merge_meta,
find_depth,
pattern_match,
to_list,
isstr,
islistable,
print_list,
s,
DEFAULT_META_INDEX,
META_IDX,
IAMC_IDX,
SORT_IDX,
ILLEGAL_COLS,
)
from pyam.filter import (
datetime_match,
)
from pyam.plotting import PlotAccessor
from pyam.compute import IamComputeAccessor
from pyam._compare import _compare
from pyam.aggregation import (
_aggregate,
_aggregate_region,
_aggregate_time,
_aggregate_recursive,
_group_and_agg,
)
from pyam._ops import _op_data
from pyam.units import convert_unit
from pyam.index import (
get_index_levels,
get_index_levels_codes,
get_keep_col,
verify_index_integrity,
replace_index_values,
)
from pyam.time import swap_time_for_year, swap_year_for_time
from pyam.logging import raise_data_error, deprecation_warning
logger = logging.getLogger(__name__)
class IamDataFrame(object):
"""Scenario timeseries data and meta indicators
The class provides a number of diagnostic features (including validation of
data, completeness of variables provided), processing tools (e.g.,
unit conversion), as well as visualization and plotting tools.
Parameters
----------
data : :class:`pandas.DataFrame` or file-like object as str or :class:`pathlib.Path`
Scenario timeseries data following the IAMC data format or
a supported variation as pandas object or a path to a file.
meta : :class:`pandas.DataFrame`, optional
A dataframe with suitable 'meta' indicators for the new instance.
The index will be downselected to scenarios present in `data`.
index : list, optional
Columns to use for resulting IamDataFrame index.
kwargs
If `value=<col>`, melt column `<col>` to 'value' and use `<col>` name
as 'variable'; or mapping of required columns (:code:`IAMC_IDX`) to
any of the following:
- one column in `data`
- multiple columns, to be concatenated by :code:`|`
- a string to be used as value for this column
Notes
-----
A :class:`pandas.DataFrame` can have the required dimensions
as columns or index.
R-style integer column headers (i.e., `X2015`) are acceptable.
When initializing an :class:`IamDataFrame` from an xlsx file,
|pyam| will per default parse all sheets starting with 'data' or 'Data'
for timeseries and a sheet 'meta' to populate the respective table.
Sheet names can be specified with kwargs :code:`sheet_name` ('data')
and :code:`meta_sheet_name` ('meta'), where
values can be a string or a list and '*' is interpreted as a wildcard.
Calling the class with :code:`meta_sheet_name=False` will
skip the import of the 'meta' table.
When initializing an :class:`IamDataFrame` from an object that is already
an :class:`IamDataFrame` instance, the new object will be hard-linked to
all attributes of the original object - so any changes on one object
(e.g., with :code:`inplace=True`) may also modify the other object!
This is intended behaviour and consistent with pandas but may be confusing
for those who are not used to the pandas/Python universe.
"""
def __init__(self, data, meta=None, index=DEFAULT_META_INDEX, **kwargs):
"""Initialize an instance of an IamDataFrame"""
if isinstance(data, IamDataFrame):
if kwargs:
raise ValueError(
f"Invalid arguments for initializing from IamDataFrame: {kwargs}"
)
if index != data.index.names:
msg = f"Incompatible `index={index}` with {type(data)} "
raise ValueError(msg + f"(index={data.index.names})")
for attr, value in data.__dict__.items():
setattr(self, attr, value)
else:
self._init(data, meta, index=index, **kwargs)
def _init(self, data, meta=None, index=DEFAULT_META_INDEX, **kwargs):
"""Process data and set attributes for new instance"""
# pop kwarg for meta_sheet_name (prior to reading data from file)
meta_sheet = kwargs.pop("meta_sheet_name", "meta")
# if meta is given explicitly, verify that index matches
if meta is not None and not meta.index.names == index:
raise ValueError(
f"Incompatible `index={index}` with `meta` (index={meta.index.names})!"
)
# try casting to Path if file-like is string or LocalPath or pytest.LocalPath
try:
data = Path(data)
except TypeError:
pass
# read from file
if isinstance(data, Path):
data = Path(data) # casting str or LocalPath to Path
if not data.is_file():
raise FileNotFoundError(f"No such file: '{data}'")
logger.info(f"Reading file {data}")
_data = read_file(data, index=index, **kwargs)
# cast data from pandas
elif isinstance(data, pd.DataFrame) or isinstance(data, pd.Series):
_data = format_data(data.copy(), index=index, **kwargs)
# unsupported `data` args
elif islistable(data):
raise ValueError(
"Initializing from list is not supported, "
"use `IamDataFrame.append()` or `pyam.concat()`"
)
else:
raise ValueError("IamDataFrame constructor not properly called!")
self._data, index, self.time_col, self.extra_cols = _data
# define `meta` dataframe for categorization & quantitative indicators
self.meta = pd.DataFrame(index=_make_index(self._data, cols=index))
self.reset_exclude()
# if given explicitly, merge meta dataframe after downselecting
if meta is not None:
self.set_meta(meta)
# if initializing from xlsx, try to load `meta` table from file
if meta_sheet and isinstance(data, Path) and data.suffix in [".xlsx", ".xls"]:
excel_file = pd.ExcelFile(data)
if meta_sheet in excel_file.sheet_names:
self.load_meta(excel_file, sheet_name=meta_sheet, ignore_conflict=True)
self._set_attributes()
# execute user-defined code
if "exec" in run_control():
self._execute_run_control()
# add the `plot` and `compute` handlers
self.plot = PlotAccessor(self)
self._compute = None
def _set_attributes(self):
"""Utility function to set attributes, called on __init__/filter/append/..."""
# add/reset internal time-index attribute (set when first using `time`)
setattr(self, "_time", None)
# add/reset year attribute (only if time domain is year, i.e., all integer)
if self.time_col == "year":
setattr(self, "year", get_index_levels(self._data, "year"))
# add/reset internal time domain attribute (set when first using `time_domain`)
setattr(self, "_time_domain", None)
# set non-standard index columns as attributes
for c in self.meta.index.names:
if c not in META_IDX:
setattr(self, c, get_index_levels(self.meta, c))
# set extra data columns as attributes
for c in self.extra_cols:
setattr(self, c, get_index_levels(self._data, c))
def _finalize(self, data, append, **args):
"""Append `data` to `self` or return as new IamDataFrame with copy of `meta`"""
if append:
self.append(data, **args, inplace=True)
else:
if data is None or data.empty:
return _empty_iamframe(self.dimensions + ["value"])
return IamDataFrame(data, meta=self.meta, **args)
def __getitem__(self, key):
_key_check = [key] if isstr(key) else key
if isinstance(key, IamSlice):
return IamDataFrame(self._data.loc[key])
elif key == "value":
return pd.Series(self._data.values, name="value")
elif set(_key_check).issubset(self.meta.columns):
return self.meta.__getitem__(key)
else:
return self.get_data_column(key)
def __len__(self):
return len(self._data)
def __repr__(self):
return self.info()
@property
def compute(self):
"""Access to advanced computation methods, see :class:`IamComputeAccessor`"""
if self._compute is None:
self._compute = IamComputeAccessor(self)
return self._compute
def info(self, n=80, meta_rows=5, memory_usage=False):
"""Print a summary of the object index dimensions and meta indicators
Parameters
----------
n : int
The maximum line length
meta_rows : int
The maximum number of meta indicators printed
"""
# concatenate list of index dimensions and levels
info = f"{type(self)}\nIndex:\n"
c1 = max([len(i) for i in self.dimensions]) + 1
c2 = n - c1 - 5
info += "\n".join(
[
f" * {i:{c1}}: {print_list(getattr(self, i), c2)}"
for i in self.index.names
]
)
# concatenate list of index of _data (not in index.names)
info += "\nTimeseries data coordinates:\n"
info += "\n".join(
[
f" {i:{c1}}: {print_list(getattr(self, i), c2)}"
for i in self.dimensions
if i not in self.index.names
]
)
# concatenate list of (head of) meta indicators and levels/values
def print_meta_row(m, t, lst):
_lst = print_list(lst, n - len(m) - len(t) - 7)
return f" {m} ({t}) {_lst}"
info += "\nMeta indicators:\n"
info += "\n".join(
[
print_meta_row(m, t, self.meta[m].unique())
for m, t in zip(
self.meta.columns[0:meta_rows], self.meta.dtypes[0:meta_rows]
)
]
)
# print `...` if more than `meta_rows` columns
if len(self.meta.columns) > meta_rows:
info += "\n ..."
# add info on size (optional)
if memory_usage:
size = self._data.memory_usage() + sum(self.meta.memory_usage())
info += f"\nMemory usage: {size} bytes"
return info
def _execute_run_control(self):
for module_block in run_control()["exec"]:
fname = module_block["file"]
functions = module_block["functions"]
dirname = os.path.dirname(fname)
if dirname:
sys.path.append(dirname)
module = os.path.basename(fname).split(".")[0]
mod = importlib.import_module(module)
for func in functions:
f = getattr(mod, func)
f(self)
@property
def index(self):
"""Return all model-scenario combinations as :class:`pandas.MultiIndex`
The index allows to loop over the available model-scenario combinations
using:
.. code-block:: python
for model, scenario in df.index:
...
"""
return self.meta.index
@property
def model(self):
"""Return the list of (unique) model names"""
return self._get_meta_index_levels("model")
@property
def scenario(self):
"""Return the list of (unique) scenario names"""
return self._get_meta_index_levels("scenario")
def _get_meta_index_levels(self, name):
"""Return the list of a level from meta"""
if name in self.meta.index.names:
return get_index_levels(self.meta, name)
# in case of non-standard meta.index.names
raise KeyError(f"Index `{name}` does not exist!")
@property
def region(self):
"""Return the list of (unique) regions"""
return get_index_levels(self._data, "region")
@property
def variable(self):
"""Return the list of (unique) variables"""
return get_index_levels(self._data, "variable")
@property
def unit(self):
"""Return the list of (unique) units"""
return get_index_levels(self._data, "unit")
@property
def unit_mapping(self):
"""Return a dictionary of variables to (list of) corresponding units"""
def list_or_str(x):
x = list(x.drop_duplicates())
return x if len(x) > 1 else x[0]
return (
pd.DataFrame(
zip(self.get_data_column("variable"), self.get_data_column("unit")),
columns=["variable", "unit"],
)
.groupby("variable")
.apply(lambda u: list_or_str(u.unit))
.to_dict()
)
@property
def time(self):
"""The time index, i.e., axis labels related to the time domain.
Returns
-------
- A :class:`pandas.Int64Index` if the :attr:`time_domain` is 'year'
- A :class:`pandas.DatetimeIndex` if the :attr:`time_domain` is 'datetime'
- A :class:`pandas.Index` if the :attr:`time_domain` is 'mixed'
"""
if self._time is None:
self._time = pd.Index(
self._data.index.unique(level=self.time_col).values, name="time"
)
return self._time
@property
def data(self):
"""Return the timeseries data as a long :class:`pandas.DataFrame`"""
if self.empty: # reset_index fails on empty with `datetime` column
return pd.DataFrame([], columns=self.dimensions + ["value"])
return self._data.reset_index()
def get_data_column(self, column):
"""Return a `column` from the timeseries data in long format
Equivalent to :meth:`IamDataFrame.data[column] <IamDataFrame.data>`.
Parameters
----------
column : str
The column name.
Returns
-------
pd.Series
"""
return pd.Series(self._data.index.get_level_values(column), name=column)
@property
def dimensions(self):
"""Return the list of `data` columns (index names & data coordinates)"""
return list(self._data.index.names)
@property
def coordinates(self):
"""Return the list of `data` coordinates (columns not including index names)"""
return [i for i in self._data.index.names if i not in self.index.names]
@property
def time_domain(self):
"""Indicator of the time domain: 'year', 'datetime', or 'mixed'"""
if self._time_domain is None:
if self.time_col == "year":
self._time_domain = "year"
elif isinstance(self.time, pd.DatetimeIndex):
self._time_domain = "datetime"
else:
self._time_domain = "mixed"
return self._time_domain
def copy(self):
"""Make a deepcopy of this object
See :func:`copy.deepcopy` for details.
"""
return copy.deepcopy(self)
def head(self, *args, **kwargs):
"""Identical to :meth:`pandas.DataFrame.head()` operating on data"""
return self.data.head(*args, **kwargs)
def tail(self, *args, **kwargs):
"""Identical to :meth:`pandas.DataFrame.tail()` operating on data"""
return self.data.tail(*args, **kwargs)
@property
def empty(self):
"""Indicator whether this object is empty"""
return self._data.empty
def equals(self, other):
"""Test if two objects contain the same data and meta indicators
This function allows two IamDataFrame instances to be compared against
each other to see if they have the same timeseries data and meta
indicators. nan's in the same location of the meta table are considered
equal.
Parameters
----------
other : IamDataFrame
the other :class:`IamDataFrame` to be compared with `self`
"""
if not isinstance(other, IamDataFrame):
raise ValueError("`other` is not an `IamDataFrame` instance")
if compare(self, other).empty and self.meta.equals(other.meta):
return True
else:
return False
def append(
self,
other,
ignore_meta_conflict=False,
inplace=False,
verify_integrity=True,
**kwargs,
):
"""Append any IamDataFrame-like object to this object
Indicators in `other.meta` that are not in `self.meta` are merged.
Missing values are set to `NaN`.
Conflicting `data` rows always raise a `ValueError`.
Parameters
----------
other : IamDataFrame, pandas.DataFrame or data file
Any object castable as IamDataFrame to be appended
ignore_meta_conflict : bool, optional
If False and `other` is an IamDataFrame, raise an error if
any meta columns present in `self` and `other` are not identical.
inplace : bool, optional
If True, do operation inplace and return None
verify_integrity : bool, optional
If True, verify integrity of index
kwargs
Passed to :class:`IamDataFrame(other, **kwargs) <IamDataFrame>`
if `other` is not already an IamDataFrame
Returns
-------
IamDataFrame
If *inplace* is :obj:`False`.
None
If *inplace* is :obj:`True`.
Raises
------
ValueError
If time domain or other timeseries data index dimension don't match.
"""
if other is None:
return None if inplace else self.copy()
if not isinstance(other, IamDataFrame):
other = IamDataFrame(other, **kwargs)
ignore_meta_conflict = True
if self.extra_cols != other.extra_cols:
raise ValueError("Incompatible timeseries data index dimensions")
if other.empty:
return None if inplace else self.copy()
ret = self.copy() if not inplace else self
if ret.time_col != other.time_col:
if ret.time_col == "year":
ret.swap_year_for_time(inplace=True)
else:
other = other.swap_year_for_time(inplace=False)
# merge `meta` tables
ret.meta = merge_meta(ret.meta, other.meta, ignore_meta_conflict)
# append other.data (verify integrity for no duplicates)
_data = pd.concat([ret._data, other._data])
if verify_integrity:
verify_index_integrity(_data)
# merge extra columns in `data`
ret.extra_cols += [i for i in other.extra_cols if i not in ret.extra_cols]
ret._data = _data.sort_index()
ret._set_attributes()
if not inplace:
return ret
def pivot_table(
self,
index,
columns,
values="value",
aggfunc="count",
fill_value=None,
style=None,
):
"""Returns a pivot table
Parameters
----------
index : str or list of str
rows for Pivot table
columns : str or list of str
columns for Pivot table
values : str, default 'value'
dataframe column to aggregate or count
aggfunc : str or function, default 'count'
function used for aggregation,
accepts 'count', 'mean', and 'sum'
fill_value : scalar, default None
value to replace missing values with
style : str, default None
output style for pivot table formatting
accepts 'highlight_not_max', 'heatmap'
"""
index = [index] if isstr(index) else index
columns = [columns] if isstr(columns) else columns
if values != "value":
raise ValueError("This method only supports `values='value'`!")
df = self._data
# allow 'aggfunc' to be passed as string for easier user interface
if isstr(aggfunc):
if aggfunc == "count":
df = self._data.groupby(index + columns).count()
fill_value = 0
elif aggfunc == "mean":
df = self._data.groupby(index + columns).mean().round(2)
fill_value = 0 if style == "heatmap" else ""
elif aggfunc == "sum":
df = self._data.groupby(index + columns).sum()
fill_value = 0 if style == "heatmap" else ""
df = df.unstack(level=columns, fill_value=fill_value)
return df
def interpolate(self, time, inplace=False, **kwargs):
"""Interpolate missing values in the timeseries data
This method uses :meth:`pandas.DataFrame.interpolate`,
which applies linear interpolation by default
Parameters
----------
time : int or datetime, or list-like thereof
Year or :class:`datetime.datetime` to be interpolated.
This must match the datetime/year format of `self`.
inplace : bool, optional
if True, do operation inplace and return None
kwargs
passed to :meth:`pandas.DataFrame.interpolate`
"""
ret = self.copy() if not inplace else self
interp_kwargs = dict(method="slinear", axis=1)
interp_kwargs.update(kwargs)
time = to_list(time)
# TODO - have to explicitly cast to numpy datetime to sort later,
# could enforce as we do for year below
if self.time_col == "time":
time = list(map(np.datetime64, time))
elif not all(is_integer(x) for x in time):
raise ValueError(f"The `time` argument {time} contains non-integers")
old_cols = list(ret[ret.time_col].unique())
columns = np.unique(np.concatenate([old_cols, time]))
# calculate a separate dataframe with full interpolation
df = ret.timeseries()
newdf = df.reindex(columns=columns).interpolate(**interp_kwargs)
# replace only columns asked for
for col in time:
df[col] = newdf[col]
# replace underlying data object
# TODO naming time_col could be done in timeseries()
df.columns.name = ret.time_col
df = df.stack() # long-data to pd.Series
df.name = "value"
ret._data = df.sort_index()
ret._set_attributes()
if not inplace:
return ret
def swap_time_for_year(self, subannual=False, inplace=False):
"""Convert the `time` dimension to `year` (as integer).
Parameters
----------
subannual : bool, str or func, optional
Merge non-year components of the "time" domain as new column "subannual".
Apply :meth:`strftime() <datetime.date.strftime>` on the values of the
"time" domain using `subannual` (if a string) or "%m-%d %H:%M%z" (if True).
If it is a function, apply the function on the values of the "time" domain.
inplace : bool, optional
If True, do operation inplace and return None.
Returns
-------
:class:`IamDataFrame` or **None**
Object with altered time domain or None if `inplace=True`.
Raises
------
ValueError
"time" is not a column of `self.data`
See Also
--------
swap_year_for_time
"""
return swap_time_for_year(self, subannual=subannual, inplace=inplace)
def swap_year_for_time(self, inplace=False):
"""Convert the `year` and `subannual` dimensions to `time` (as datetime).
The method applies :meth:`dateutil.parser.parse` on the combined columns
`year` and `subannual`:
.. code-block:: python
dateutil.parser.parse([f"{y}-{s}" for y, s in zip(year, subannual)])
Parameters
----------
inplace : bool, optional
If True, do operation inplace and return None.
Returns
-------
:class:`IamDataFrame` or **None**
Object with altered time domain or None if `inplace=True`.
Raises
------
ValueError
"year" or "subannual" are not a column of `self.data`
See Also
--------
swap_time_for_year
"""
return swap_year_for_time(self, inplace=inplace)
def as_pandas(self, meta_cols=True):
"""Return object as a pandas.DataFrame
Parameters
----------
meta_cols : list, default None
join `data` with all `meta` columns if True (default)
or only with columns in list, or return copy of `data` if False
"""
# merge data and (downselected) meta, or return copy of data
if meta_cols:
meta_cols = self.meta.columns if meta_cols is True else meta_cols
return (
self.data.set_index(META_IDX).join(self.meta[meta_cols]).reset_index()
)
else:
return self.data.copy()
def timeseries(self, iamc_index=False):
"""Returns `data` as :class:`pandas.DataFrame` in wide format
Parameters
----------
iamc_index : bool, optional
if True, use `['model', 'scenario', 'region', 'variable', 'unit']`;
else, use all 'data' columns
Raises
------
ValueError
`IamDataFrame` is empty
ValueError
reducing to IAMC-index yields an index with duplicates
"""
if self.empty:
raise ValueError("This IamDataFrame is empty!")
s = self._data
if iamc_index:
if self.time_col == "time":
raise ValueError(
"Cannot use `iamc_index=True` with 'datetime' time-domain!"
)
s = s.droplevel(self.extra_cols)
return s.unstack(level=self.time_col).rename_axis(None, axis=1)
def reset_exclude(self):
"""Reset exclusion assignment for all scenarios to `exclude: False`"""
self.meta["exclude"] = False
def set_meta(self, meta, name=None, index=None):
"""Add meta indicators as pandas.Series, list or value (int/float/str)
Parameters
----------
meta : pandas.DataFrame, pandas.Series, list, int, float or str
column to be added to 'meta'
(by `['model', 'scenario']` index if possible)
name : str, optional
meta column name (defaults to meta `pandas.Series.name`);
either `meta.name` or the name kwarg must be defined
index : IamDataFrame, pandas.DataFrame or pandas.MultiIndex, optional
index to be used for setting meta column (`['model', 'scenario']`)
"""
if isinstance(meta, pd.DataFrame):
if meta.index.names != self.meta.index.names:
# catch Model, Scenario instead of model, scenario
meta = meta.rename(
columns={i.capitalize(): i for i in META_IDX}
).set_index(self.meta.index.names)
meta = meta.loc[self.meta.index.intersection(meta.index)]
meta.index = meta.index.remove_unused_levels()
self.meta = merge_meta(meta, self.meta, ignore_conflict=True)
return
# check that name is valid and doesn't conflict with data columns
if (name or (hasattr(meta, "name") and meta.name)) in [None, False]:
raise ValueError("Must pass a name or use a named pd.Series")
name = name or meta.name
if name in self.dimensions:
raise ValueError(f"Column {name} already exists in `data`!")
if name in ILLEGAL_COLS:
raise ValueError(f"Name {name} is illegal for meta indicators!")
# check if meta has a valid index and use it for further workflow
if (
hasattr(meta, "index")
and hasattr(meta.index, "names")
and set(META_IDX).issubset(meta.index.names)
):
index = meta.index
# if no valid index is provided, add meta as new column `name` and exit
if index is None:
self.meta[name] = list(meta) if islistable(meta) else meta
return
# use meta.index if index arg is an IamDataFrame
if isinstance(index, IamDataFrame):
index = index.meta.index
# turn dataframe to index if index arg is a DataFrame
if isinstance(index, pd.DataFrame):
index = index.set_index(META_IDX).index
if not isinstance(index, pd.MultiIndex):
raise ValueError("Index cannot be coerced to pd.MultiIndex")
# raise error if index is not unique
if index.duplicated().any():
raise ValueError("Non-unique ['model', 'scenario'] index!")
# create pd.Series from meta, index and name if provided
meta = pd.Series(data=meta, index=index, name=name)
# reduce index dimensions to model-scenario only
meta = meta.reset_index().reindex(columns=META_IDX + [name]).set_index(META_IDX)
# check if trying to add model-scenario index not existing in self
diff = meta.index.difference(self.meta.index)
if not diff.empty:
raise ValueError(f"Adding meta for non-existing scenarios:\n{diff}")
self._new_meta_column(name)
self.meta[name] = meta[name].combine_first(self.meta[name])
def set_meta_from_data(self, name, method=None, column="value", **kwargs):
"""Add meta indicators from downselected timeseries data of self
Parameters
----------
name : str
column name of the 'meta' table
method : function, optional
method for aggregation
(e.g., :func:`numpy.max <numpy.ndarray.max>`);
required if downselected data do not yield unique values
column : str, optional
the column from `data` to be used to derive the indicator
kwargs
passed to :meth:`filter` for downselected data
"""
_data = self.filter(**kwargs).data
if method is None:
meta = _data.set_index(META_IDX)[column]
else:
meta = _data.groupby(META_IDX)[column].apply(method)
self.set_meta(meta, name)
def categorize(
self, name, value, criteria, color=None, marker=None, linestyle=None
):
"""Assign scenarios to a category according to specific criteria
Parameters
----------
name : str
column name of the 'meta' table
value : str
category identifier
criteria : dict
dictionary with variables mapped to applicable checks
('up' and 'lo' for respective bounds, 'year' for years - optional)
color : str, optional
assign a color to this category for plotting
marker : str, optional
assign a marker to this category for plotting
linestyle : str, optional
assign a linestyle to this category for plotting
"""
# add plotting run control
for kind, arg in [
("color", color),
("marker", marker),
("linestyle", linestyle),
]:
if arg:
run_control().update({kind: {name: {value: arg}}})
# find all data that matches categorization
rows = _apply_criteria(self._data, criteria, in_range=True, return_test="all")
idx = _make_index(rows, cols=self.index.names)
if len(idx) == 0:
logger.info("No scenarios satisfy the criteria")
return
# update meta dataframe
self._new_meta_column(name)
self.meta.loc[idx, name] = value
msg = "{} scenario{} categorized as `{}: {}`"
logger.info(msg.format(len(idx), "" if len(idx) == 1 else "s", name, value))
def _new_meta_column(self, name):
"""Add a column to meta if it doesn't exist, set value to nan"""
if name is None:
raise ValueError(f"Cannot add a meta column {name}")
if name not in self.meta:
self.meta[name] = np.nan
def require_data(
self, region=None, variable=None, unit=None, year=None, exclude_on_fail=False
):
"""Check whether scenarios have values for all combinations of given elements
Parameters
----------
region : str or list of str, optional
Required region(s).
variable : str or list of str, optional
Required variable(s).
unit : str or list of str, optional
Required unit(s).
year : int or list of int, optional
Required year(s).
exclude_on_fail : bool, optional
Set *meta* indicator for scenarios failing validation as `exclude: True`.
Returns
-------
pd.DataFrame
A dataframe of the *index* of scenarios not satisfying the cr
"""
# TODO: option to require values in certain ranges, see `_apply_criteria()`
# create mapping of required dimensions
required = {}
n = 1 # expected number of rows per scenario
for dim, value in [
("region", region),
("variable", variable),
("unit", unit),
("year", year),
]:
if value is not None:
required[dim] = value
n *= len(to_list(value))
# fast exit if no arguments values are given
if not required:
return
# downselect to relevant rows
keep = self._apply_filters(**required)
rows = self._data.index[keep]
# identify scenarios that have none of the required values
index_none = self.index.difference(
rows.droplevel(level=self.coordinates).drop_duplicates()
).to_frame(index=False)
# identify scenarios that have some but not all required values
columns = [i for i in self.coordinates if i not in required]
rows = rows.droplevel(level=columns).drop_duplicates()
data = (
pd.DataFrame(index=rows)
.reset_index(level=list(required))
.groupby(self.index.names)
)
index_incomplete = pd.DataFrame(
[idx for idx, df in data if len(df) != n], columns=self.index.names
)