Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def decision_function(self, X, method='most-wins'):
X = _check_2d_inp(X, reshape = True)
if method == 'most-wins':
return self._decision_function_winners(X)
elif method == 'goodness':
return self._decision_function_goo... | [
"\n Calculate a 'goodness' distribution over labels\n \n Note\n ----\n Predictions can be calculated either by counting which class wins the most\n pairwise comparisons (as in [1] and [2]), or - for classifiers with a 'predict_proba'\n method - by taking into account... |
Please provide a description of the function:def predict(self, X, method = 'most-wins'):
X = _check_2d_inp(X, reshape = True)
if method == 'most-wins':
return self._predict_winners(X)
elif method == 'goodness':
goodness = self._decision_function_goodness(X)
... | [
"\n Predict the less costly class for a given observation\n \n Note\n ----\n Predictions can be calculated either by counting which class wins the most\n pairwise comparisons (as in [1] and [2]), or - for classifiers with a 'predict_proba'\n method - by taking into a... |
Please provide a description of the function:def fit(self, X, C):
X,C = _check_fit_input(X,C)
C = np.asfortranarray(C)
nclasses=C.shape[1]
self.tree=_BinTree(nclasses)
self.classifiers=[deepcopy(self.base_classifier) for c in range(nclasses-1)]
classifier_queue=s... | [
"\n Fit a filter tree classifier\n \n Note\n ----\n Shifting the order of the classes within the cost array will produce different\n results, as it will build a different binary tree comparing different classes\n at each node.\n \n Parameters\n -... |
Please provide a description of the function:def predict(self, X):
X = _check_2d_inp(X, reshape = True)
if X.shape[0] == 1:
return self._predict(X)
else:
shape_single = list(X.shape)
shape_single[0] = 1
pred = np.empty(X.shape[0], dtype = ... | [
"\n Predict the less costly class for a given observation\n \n Note\n ----\n The implementation here happens in a Python loop rather than in some\n NumPy array operations, thus it will be slower than the other algorithms\n here, even though in theory it implies fewer... |
Please provide a description of the function:def fit(self, X, y, sample_weight=None):
assert self.extra_rej_const >= 0
if sample_weight is None:
sample_weight = np.ones(y.shape[0])
else:
if isinstance(sample_weight, list):
sample_weight = np.array... | [
"\n Fit a binary classifier with sample weights to data.\n \n Note\n ----\n Examples at each sample are accepted with probability = weight/Z,\n where Z = max(weight) + extra_rej_const.\n Larger values for extra_rej_const ensure that no example gets selected in\n ... |
Please provide a description of the function:def decision_function(self, X, aggregation = 'raw'):
if aggregation == 'weighted':
if 'predict_proba' not in dir(self.classifiers[0]):
raise Exception("'aggregation='weighted'' is only available for classifiers with 'predict_proba... | [
"\n Calculate how preferred is positive class according to classifiers\n \n Note\n ----\n If passing aggregation = 'raw', it will output the proportion of the classifiers\n that voted for the positive class.\n If passing aggregation = 'weighted', it will output the a... |
Please provide a description of the function:def fit(self, X, C):
X, C = _check_fit_input(X, C)
C = np.asfortranarray(C)
self.nclasses = C.shape[1]
self.classifiers = [deepcopy(self.base_classifier) for i in range(self.nclasses)]
if not self.weight_simple_diff:
... | [
"\n Fit one weighted classifier per class\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n The data on which to fit a cost-sensitive classifier.\n C : array (n_samples, n_classes)\n The cost of predicting each label for each observati... |
Please provide a description of the function:def decision_function(self, X):
X = _check_2d_inp(X)
preds = np.empty((X.shape[0], self.nclasses))
available_methods = dir(self.classifiers[0])
if "decision_function" in available_methods:
Parallel(n_jobs=self.njobs, verb... | [
"\n Calculate a 'goodness' distribution over labels\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n Data for which to predict the cost of each label.\n \n Returns\n -------\n pred : array (n_samples, n_classes)\n ... |
Please provide a description of the function:def predict(self, X):
X = _check_2d_inp(X)
return np.argmax(self.decision_function(X), axis=1) | [
"\n Predict the less costly class for a given observation\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n Data for which to predict minimum cost label.\n \n Returns\n -------\n y_hat : array (n_samples,)\n Label ... |
Please provide a description of the function:def fit(self, X, C):
X, C = _check_fit_input(X, C)
C = np.asfortranarray(C)
self.nclasses = C.shape[1]
self.regressors = [deepcopy(self.base_regressor) for i in range(self.nclasses)]
Parallel(n_jobs=self.njobs, verbose=0, requ... | [
"\n Fit one regressor per class\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n The data on which to fit a cost-sensitive classifier.\n C : array (n_samples, n_classes)\n The cost of predicting each label for each observation (more m... |
Please provide a description of the function:def decision_function(self, X, apply_softmax = True):
X = _check_2d_inp(X, reshape = True)
preds = np.empty((X.shape[0], self.nclasses), dtype = "float64")
Parallel(n_jobs=self.njobs, verbose=0, require="sharedmem")(delayed(self._decision_fun... | [
"\n Get cost estimates for each observation\n \n Note\n ----\n If called with apply_softmax = False, this will output the predicted\n COST rather than the 'goodness' - meaning, more is worse.\n \n If called with apply_softmax = True, it will output one minus t... |
Please provide a description of the function:def predict(self, X):
X = _check_2d_inp(X)
return np.argmin(self.decision_function(X, False), axis=1) | [
"\n Predict the less costly class for a given observation\n \n Parameters\n ----------\n X : array (n_samples, n_features)\n Data for which to predict minimum cost labels.\n \n Returns\n -------\n y_hat : array (n_samples,)\n Label... |
Please provide a description of the function:def read_ix(ix, **kwargs):
if not isinstance(ix, ixmp.TimeSeries):
error = 'not recognized as valid ixmp class: {}'.format(ix)
raise ValueError(error)
df = ix.timeseries(iamc=False, **kwargs)
df['model'] = ix.model
df['scenario'] = ix.sc... | [
"Read timeseries data from an ixmp object\n\n Parameters\n ----------\n ix: ixmp.TimeSeries or ixmp.Scenario\n this option requires the ixmp package as a dependency\n kwargs: arguments passed to ixmp.TimeSeries.timeseries()\n "
] |
Please provide a description of the function:def requires_package(pkg, msg, error_type=ImportError):
def _requires_package(func):
def wrapper(*args, **kwargs):
if pkg is None:
raise error_type(msg)
return func(*args, **kwargs)
return wrapper
return _r... | [
"Decorator when a function requires an optional dependency\n\n Parameters\n ----------\n pkg : imported package object\n msg : string\n Message to show to user with error_type\n error_type : python error class\n "
] |
Please provide a description of the function:def write_sheet(writer, name, df, index=False):
if index:
df = df.reset_index()
df.to_excel(writer, name, index=False)
worksheet = writer.sheets[name]
for i, col in enumerate(df.columns):
if df.dtypes[col].name.startswith(('float', 'int')... | [
"Write a pandas DataFrame to an ExcelWriter,\n auto-formatting column width depending on maxwidth of data and colum header\n\n Parameters\n ----------\n writer: pandas.ExcelWriter\n an instance of a pandas ExcelWriter\n name: string\n name of the sheet to be written\n df: pandas.Data... |
Please provide a description of the function:def read_pandas(fname, *args, **kwargs):
if not os.path.exists(fname):
raise ValueError('no data file `{}` found!'.format(fname))
if fname.endswith('csv'):
df = pd.read_csv(fname, *args, **kwargs)
else:
xl = pd.ExcelFile(fname)
... | [
"Read a file and return a pd.DataFrame"
] |
Please provide a description of the function:def read_file(fname, *args, **kwargs):
if not isstr(fname):
raise ValueError('reading multiple files not supported, '
'please use `pyam.IamDataFrame.append()`')
logger().info('Reading `{}`'.format(fname))
format_kwargs = {}
... | [
"Read data from a file saved in the standard IAMC format\n or a table with year/value columns\n "
] |
Please provide a description of the function:def format_data(df, **kwargs):
if isinstance(df, pd.Series):
df = df.to_frame()
# Check for R-style year columns, converting where necessary
def convert_r_columns(c):
try:
first = c[0]
second = c[1:]
if fi... | [
"Convert a `pd.Dataframe` or `pd.Series` to the required format"
] |
Please provide a description of the function:def sort_data(data, cols):
return data.sort_values(cols)[cols + ['value']].reset_index(drop=True) | [
"Sort `data` rows and order columns"
] |
Please provide a description of the function:def find_depth(data, s='', level=None):
# remove wildcard as last character from string, escape regex characters
_s = re.compile('^' + _escape_regexp(s.rstrip('*')))
_p = re.compile('\\|')
# find depth
def _count_pipes(val):
return len(_p.fi... | [
"\n return or assert the depth (number of `|`) of variables\n\n Parameters\n ----------\n data : pd.Series of strings\n IAMC-style variables\n s : str, default ''\n remove leading `s` from any variable in `data`\n level : int or str, default None\n if None, return depth (numbe... |
Please provide a description of the function:def pattern_match(data, values, level=None, regexp=False, has_nan=True):
matches = np.array([False] * len(data))
if not isinstance(values, collections.Iterable) or isstr(values):
values = [values]
# issue (#40) with string-to-nan comparison, replace... | [
"\n matching of model/scenario names, variables, regions, and meta columns to\n pseudo-regex (if `regexp == False`) for filtering (str, int, bool)\n "
] |
Please provide a description of the function:def _escape_regexp(s):
return (
str(s)
.replace('|', '\\|')
.replace('.', '\.') # `.` has to be replaced before `*`
.replace('*', '.*')
.replace('+', '\+')
.replace('(', '\(')
.replace(')', '\)')
.repl... | [
"escape characters with specific regexp use"
] |
Please provide a description of the function:def years_match(data, years):
years = [years] if isinstance(years, int) else years
dt = datetime.datetime
if isinstance(years, dt) or isinstance(years[0], dt):
error_msg = "`year` can only be filtered with ints or lists of ints"
raise TypeErr... | [
"\n matching of year columns for data filtering\n "
] |
Please provide a description of the function:def hour_match(data, hours):
hours = [hours] if isinstance(hours, int) else hours
return data.isin(hours) | [
"\n matching of days in time columns for data filtering\n "
] |
Please provide a description of the function:def datetime_match(data, dts):
dts = dts if islistable(dts) else [dts]
if any([not isinstance(i, datetime.datetime) for i in dts]):
error_msg = (
"`time` can only be filtered by datetimes"
)
raise TypeError(error_msg)
retu... | [
"\n matching of datetimes in time columns for data filtering\n "
] |
Please provide a description of the function:def to_int(x, index=False):
_x = x.index if index else x
cols = list(map(int, _x))
error = _x[cols != _x]
if not error.empty:
raise ValueError('invalid values `{}`'.format(list(error)))
if index:
x.index = cols
return x
el... | [
"Formatting series or timeseries columns to int and checking validity.\n If `index=False`, the function works on the `pd.Series x`; else,\n the function casts the index of `x` to int and returns x with a new index.\n "
] |
Please provide a description of the function:def concat_with_pipe(x, cols=None):
cols = cols or x.index
return '|'.join([x[i] for i in cols if x[i] not in [None, np.nan]]) | [
"Concatenate a `pd.Series` separated by `|`, drop `None` or `np.nan`"
] |
Please provide a description of the function:def reduce_hierarchy(x, depth):
_x = x.split('|')
depth = len(_x) + depth - 1 if depth < 0 else depth
return '|'.join(_x[0:(depth + 1)]) | [
"Reduce the hierarchy (depth by `|`) string to the specified level"
] |
Please provide a description of the function:def _aggregate(df, by):
by = [by] if isstr(by) else by
cols = [c for c in list(df.columns) if c not in ['value'] + by]
return df.groupby(cols).sum()['value'] | [
"Aggregate `df` by specified column(s), return indexed `pd.Series`"
] |
Please provide a description of the function:def _check_rows(rows, check, in_range=True, return_test='any'):
valid_checks = set(['up', 'lo', 'year'])
if not set(check.keys()).issubset(valid_checks):
msg = 'Unknown checking type: {}'
raise ValueError(msg.format(check.keys() - valid_checks))
... | [
"Check all rows to be in/out of a certain range and provide testing on\n return values based on provided conditions\n\n Parameters\n ----------\n rows: pd.DataFrame\n data rows\n check: dict\n dictionary with possible values of 'up', 'lo', and 'year'\n in_range: bool, optional\n ... |
Please provide a description of the function:def _apply_criteria(df, criteria, **kwargs):
idxs = []
for var, check in criteria.items():
_df = df[df['variable'] == var]
for group in _df.groupby(META_IDX):
grp_idxs = _check_rows(group[-1], check, **kwargs)
idxs.append(... | [
"Apply criteria individually to every model/scenario instance"
] |
Please provide a description of the function:def _make_index(df, cols=META_IDX):
return pd.MultiIndex.from_tuples(
pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols)) | [
"Create an index from the columns of a dataframe"
] |
Please provide a description of the function:def validate(df, criteria={}, exclude_on_fail=False, **kwargs):
fdf = df.filter(**kwargs)
if len(fdf.data) > 0:
vdf = fdf.validate(criteria=criteria, exclude_on_fail=exclude_on_fail)
df.meta['exclude'] |= fdf.meta['exclude'] # update if any excl... | [
"Validate scenarios using criteria on timeseries values\n\n Parameters\n ----------\n df: IamDataFrame instance\n args: see `IamDataFrame.validate()` for details\n kwargs: passed to `df.filter()`\n "
] |
Please provide a description of the function:def require_variable(df, variable, unit=None, year=None, exclude_on_fail=False,
**kwargs):
fdf = df.filter(**kwargs)
if len(fdf.data) > 0:
vdf = fdf.require_variable(variable=variable, unit=unit, year=year,
... | [
"Check whether all scenarios have a required variable\n\n Parameters\n ----------\n df: IamDataFrame instance\n args: see `IamDataFrame.require_variable()` for details\n kwargs: passed to `df.filter()`\n "
] |
Please provide a description of the function:def categorize(df, name, value, criteria,
color=None, marker=None, linestyle=None, **kwargs):
fdf = df.filter(**kwargs)
fdf.categorize(name=name, value=value, criteria=criteria, color=color,
marker=marker, linestyle=linestyle)
... | [
"Assign scenarios to a category according to specific criteria\n or display the category assignment\n\n Parameters\n ----------\n df: IamDataFrame instance\n args: see `IamDataFrame.categorize()` for details\n kwargs: passed to `df.filter()`\n "
] |
Please provide a description of the function:def check_aggregate(df, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
fdf = df.filter(**kwargs)
if len(fdf.data) > 0:
vdf = fdf.check_aggregate(variable=variable, components=components,
... | [
"Check whether the timeseries values match the aggregation\n of sub-categories\n\n Parameters\n ----------\n df: IamDataFrame instance\n args: see IamDataFrame.check_aggregate() for details\n kwargs: passed to `df.filter()`\n "
] |
Please provide a description of the function:def filter_by_meta(data, df, join_meta=False, **kwargs):
if not set(META_IDX).issubset(data.index.names + list(data.columns)):
raise ValueError('missing required index dimensions or columns!')
meta = pd.DataFrame(df.meta[list(set(kwargs) - set(META_IDX)... | [
"Filter by and join meta columns from an IamDataFrame to a pd.DataFrame\n\n Parameters\n ----------\n data: pd.DataFrame instance\n DataFrame to which meta columns are to be joined,\n index or columns must include `['model', 'scenario']`\n df: IamDataFrame instance\n IamDataFrame fr... |
Please provide a description of the function:def compare(left, right, left_label='left', right_label='right',
drop_close=True, **kwargs):
ret = pd.concat({right_label: right.data.set_index(right._LONG_IDX),
left_label: left.data.set_index(left._LONG_IDX)}, axis=1)
ret.colum... | [
"Compare the data in two IamDataFrames and return a pd.DataFrame\n\n Parameters\n ----------\n left, right: IamDataFrames\n the IamDataFrames to be compared\n left_label, right_label: str, default `left`, `right`\n column names of the returned dataframe\n drop_close: bool, default True\... |
Please provide a description of the function:def concat(dfs):
if isstr(dfs) or not hasattr(dfs, '__iter__'):
msg = 'Argument must be a non-string iterable (e.g., list or tuple)'
raise TypeError(msg)
_df = None
for df in dfs:
df = df if isinstance(df, IamDataFrame) else IamDataF... | [
"Concatenate a series of `pyam.IamDataFrame`-like objects together"
] |
Please provide a description of the function:def variables(self, include_units=False):
if include_units:
return self.data[['variable', 'unit']].drop_duplicates()\
.reset_index(drop=True).sort_values('variable')
else:
return pd.Series(self.data.variable.un... | [
"Get a list of variables\n\n Parameters\n ----------\n include_units: boolean, default False\n include the units\n "
] |
Please provide a description of the function:def append(self, other, ignore_meta_conflict=False, inplace=False,
**kwargs):
if not isinstance(other, IamDataFrame):
other = IamDataFrame(other, **kwargs)
ignore_meta_conflict = True
if self.time_col is not ot... | [
"Append any castable object to this IamDataFrame.\n Columns in `other.meta` that are not in `self.meta` are always merged,\n duplicate region-variable-unit-year rows raise a ValueError.\n\n Parameters\n ----------\n other: pyam.IamDataFrame, ixmp.TimeSeries, ixmp.Scenario,\n ... |
Please provide a description of the function:def pivot_table(self, index, columns, values='value',
aggfunc='count', fill_value=None, style=None):
index = [index] if isstr(index) else index
columns = [columns] if isstr(columns) else columns
df = self.data
# ... | [
"Returns a pivot table\n\n Parameters\n ----------\n index: str or list of strings\n rows for Pivot table\n columns: str or list of strings\n columns for Pivot table\n values: str, default 'value'\n dataframe column to aggregate or count\n a... |
Please provide a description of the function:def interpolate(self, year):
df = self.pivot_table(index=IAMC_IDX, columns=['year'],
values='value', aggfunc=np.sum)
# drop year-rows where values are already defined
if year in df.columns:
df = df[np... | [
"Interpolate missing values in timeseries (linear interpolation)\n\n Parameters\n ----------\n year: int\n year to be interpolated\n "
] |
Please provide a description of the function:def as_pandas(self, with_metadata=False):
if with_metadata:
cols = self._discover_meta_cols(**with_metadata) \
if isinstance(with_metadata, dict) else self.meta.columns
return (
self.data
... | [
"Return this as a pd.DataFrame\n\n Parameters\n ----------\n with_metadata : bool, default False or dict\n if True, join data with all meta columns; if a dict, discover\n meaningful meta columns from values (in key-value)\n "
] |
Please provide a description of the function:def _discover_meta_cols(self, **kwargs):
cols = set(['exclude'])
for arg, value in kwargs.items():
if isstr(value) and value in self.meta.columns:
cols.add(value)
return list(cols) | [
"Return the subset of `kwargs` values (not keys!) matching\n a `meta` column name"
] |
Please provide a description of the function:def timeseries(self, iamc_index=False):
index = IAMC_IDX if iamc_index else IAMC_IDX + self.extra_cols
df = (
self.data
.pivot_table(index=index, columns=self.time_col)
.value # column name
.rename_axi... | [
"Returns a pd.DataFrame in wide format (years or timedate as columns)\n\n Parameters\n ----------\n iamc_index: bool, default False\n if True, use `['model', 'scenario', 'region', 'variable', 'unit']`;\n else, use all `data` columns\n "
] |
Please provide a description of the function:def set_meta(self, meta, name=None, index=None):
# 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.S... | [
"Add metadata columns as pd.Series, list or value (int/float/str)\n\n Parameters\n ----------\n meta: pd.Series, list, int, float or str\n column to be added to metadata\n (by `['model', 'scenario']` index if possible)\n name: str, optional\n meta column ... |
Please provide a description of the function:def categorize(self, name, value, criteria,
color=None, marker=None, linestyle=None):
# add plotting run control
for kind, arg in [('color', color), ('marker', marker),
('linestyle', linestyle)]:
... | [
"Assign scenarios to a category according to specific criteria\n or display the category assignment\n\n Parameters\n ----------\n name: str\n category column name\n value: str\n category identifier\n criteria: dict\n dictionary with variable... |
Please provide a description of the function:def _new_meta_column(self, name):
if name is None:
raise ValueError('cannot add a meta column `{}`'.format(name))
if name not in self.meta:
self.meta[name] = np.nan | [
"Add a column to meta if it doesn't exist, set to value `np.nan`"
] |
Please provide a description of the function:def require_variable(self, variable, unit=None, year=None,
exclude_on_fail=False):
criteria = {'variable': variable}
if unit:
criteria.update({'unit': unit})
if year:
criteria.update({'year': y... | [
"Check whether all scenarios have a required variable\n\n Parameters\n ----------\n variable: str\n required variable\n unit: str, default None\n name of unit (optional)\n year: int or list, default None\n years (optional)\n exclude_on_fail:... |
Please provide a description of the function:def validate(self, criteria={}, exclude_on_fail=False):
df = _apply_criteria(self.data, criteria, in_range=False)
if not df.empty:
msg = '{} of {} data points to not satisfy the criteria'
logger().info(msg.format(len(df), len... | [
"Validate scenarios using criteria on timeseries values\n\n Parameters\n ----------\n criteria: dict\n dictionary with variable keys and check values\n ('up' and 'lo' for respective bounds, 'year' for years)\n exclude_on_fail: bool, default False\n flag sc... |
Please provide a description of the function:def rename(self, mapping=None, inplace=False, append=False,
check_duplicates=True, **kwargs):
# combine `mapping` arg and mapping kwargs, ensure no rename conflicts
mapping = mapping or {}
duplicate = set(mapping).intersection(... | [
"Rename and aggregate column entries using `groupby.sum()` on values.\n When renaming models or scenarios, the uniqueness of the index must be\n maintained, and the function will raise an error otherwise.\n\n Renaming is only applied to any data where a filter matches for all\n columns g... |
Please provide a description of the function:def convert_unit(self, conversion_mapping, inplace=False):
ret = copy.deepcopy(self) if not inplace else self
for current_unit, (new_unit, factor) in conversion_mapping.items():
factor = pd.to_numeric(factor)
where = ret.data[... | [
"Converts units based on provided unit conversion factors\n\n Parameters\n ----------\n conversion_mapping: dict\n for each unit for which a conversion should be carried out,\n provide current unit and target unit and conversion factor\n {<current unit>: [<targe... |
Please provide a description of the function:def normalize(self, inplace=False, **kwargs):
if len(kwargs) > 1 or self.time_col not in kwargs:
raise ValueError('Only time(year)-based normalization supported')
ret = copy.deepcopy(self) if not inplace else self
df = ret.data
... | [
"Normalize data to a given value. Currently only supports normalizing\n to a specific time.\n\n Parameters\n ----------\n inplace: bool, default False\n if True, do operation inplace and return None\n kwargs: the values on which to normalize (e.g., `year=2005`)\n ... |
Please provide a description of the function:def aggregate(self, variable, components=None, append=False):
# default components to all variables one level below `variable`
components = components or self._variable_components(variable)
if not len(components):
msg = 'cannot a... | [
"Compute the aggregate of timeseries components or sub-categories\n\n Parameters\n ----------\n variable: str\n variable for which the aggregate should be computed\n components: list of str, default None\n list of variables, defaults to all sub-categories of `variab... |
Please provide a description of the function:def check_aggregate(self, variable, components=None, exclude_on_fail=False,
multiplier=1, **kwargs):
# compute aggregate from components, return None if no components
df_components = self.aggregate(variable, components)
... | [
"Check whether a timeseries matches the aggregation of its components\n\n Parameters\n ----------\n variable: str\n variable to be checked for matching aggregation of sub-categories\n components: list of str, default None\n list of variables, defaults to all sub-cat... |
Please provide a description of the function:def aggregate_region(self, variable, region='World', subregions=None,
components=None, append=False):
# default subregions to all regions other than `region`
if subregions is None:
rows = self._apply_filters(varia... | [
"Compute the aggregate of timeseries over a number of regions\n including variable components only defined at the `region` level\n\n Parameters\n ----------\n variable: str\n variable for which the aggregate should be computed\n region: str, default 'World'\n ... |
Please provide a description of the function:def check_aggregate_region(self, variable, region='World', subregions=None,
components=None, exclude_on_fail=False,
**kwargs):
# compute aggregate from subregions, return None if no subregions
... | [
"Check whether the region timeseries data match the aggregation\n of components\n\n Parameters\n ----------\n variable: str\n variable to be checked for matching aggregation of subregions\n region: str, default 'World'\n region to be checked for matching aggr... |
Please provide a description of the function:def _variable_components(self, variable):
var_list = pd.Series(self.data.variable.unique())
return var_list[pattern_match(var_list, '{}|*'.format(variable), 0)] | [
"Get all components (sub-categories) of a variable\n\n For `variable='foo'`, return `['foo|bar']`, but don't include\n `'foo|bar|baz'`, which is a sub-sub-category"
] |
Please provide a description of the function:def check_internal_consistency(self, **kwargs):
inconsistent_vars = {}
for variable in self.variables():
diff_agg = self.check_aggregate(variable, **kwargs)
if diff_agg is not None:
inconsistent_vars[variable +... | [
"Check whether the database is internally consistent\n\n We check that all variables are equal to the sum of their sectoral\n components and that all the regions add up to the World total. If\n the check is passed, None is returned, otherwise a dictionary of\n inconsistent variables is r... |
Please provide a description of the function:def _exclude_on_fail(self, df):
idx = df if isinstance(df, pd.MultiIndex) else _meta_idx(df)
self.meta.loc[idx, 'exclude'] = True
logger().info('{} non-valid scenario{} will be excluded'
.format(len(idx), '' if len(idx) ... | [
"Assign a selection of scenarios as `exclude: True` in meta"
] |
Please provide a description of the function:def filter(self, filters=None, keep=True, inplace=False, **kwargs):
if filters is not None:
msg = '`filters` keyword argument in `filter()` is deprecated ' + \
'and will be removed in the next release'
warnings.warn(ms... | [
"Return a filtered IamDataFrame (i.e., a subset of current data)\n\n Parameters\n ----------\n keep: bool, default True\n keep all scenarios satisfying the filters (if True) or the inverse\n inplace: bool, default False\n if True, do operation inplace and return Non... |
Please provide a description of the function:def _apply_filters(self, **filters):
regexp = filters.pop('regexp', False)
keep = np.array([True] * len(self.data))
# filter by columns and list of values
for col, values in filters.items():
# treat `_apply_filters(col=No... | [
"Determine rows to keep in data for given set of filters\n\n Parameters\n ----------\n filters: dict\n dictionary of filters ({col: values}}); uses a pseudo-regexp syntax\n by default, but accepts `regexp: True` to use regexp directly\n "
] |
Please provide a description of the function:def col_apply(self, col, func, *args, **kwargs):
if col in self.data:
self.data[col] = self.data[col].apply(func, *args, **kwargs)
else:
self.meta[col] = self.meta[col].apply(func, *args, **kwargs) | [
"Apply a function to a column\n\n Parameters\n ----------\n col: string\n column in either data or metadata\n func: functional\n function to apply\n "
] |
Please provide a description of the function:def _to_file_format(self, iamc_index):
df = self.timeseries(iamc_index=iamc_index).reset_index()
df = df.rename(columns={c: str(c).title() for c in df.columns})
return df | [
"Return a dataframe suitable for writing to a file"
] |
Please provide a description of the function:def to_csv(self, path, iamc_index=False, **kwargs):
self._to_file_format(iamc_index).to_csv(path, index=False, **kwargs) | [
"Write timeseries data to a csv file\n\n Parameters\n ----------\n path: string\n file path\n iamc_index: bool, default False\n if True, use `['model', 'scenario', 'region', 'variable', 'unit']`;\n else, use all `data` columns\n "
] |
Please provide a description of the function:def to_excel(self, excel_writer, sheet_name='data',
iamc_index=False, **kwargs):
if not isinstance(excel_writer, pd.ExcelWriter):
close = True
excel_writer = pd.ExcelWriter(excel_writer)
self._to_file_format(i... | [
"Write timeseries data to Excel format\n\n Parameters\n ----------\n excel_writer: string or ExcelWriter object\n file path or existing ExcelWriter\n sheet_name: string, default 'data'\n name of sheet which will contain `IamDataFrame.timeseries()` data\n iamc... |
Please provide a description of the function:def export_metadata(self, path):
writer = pd.ExcelWriter(path)
write_sheet(writer, 'meta', self.meta, index=True)
writer.save() | [
"Export metadata to Excel\n\n Parameters\n ----------\n path: string\n path/filename for xlsx file of metadata export\n "
] |
Please provide a description of the function:def load_metadata(self, path, *args, **kwargs):
if not os.path.exists(path):
raise ValueError("no metadata file '" + path + "' found!")
if path.endswith('csv'):
df = pd.read_csv(path, *args, **kwargs)
else:
... | [
"Load metadata exported from `pyam.IamDataFrame` instance\n\n Parameters\n ----------\n path: string\n xlsx file with metadata exported from `pyam.IamDataFrame` instance\n "
] |
Please provide a description of the function:def line_plot(self, x='year', y='value', **kwargs):
df = self.as_pandas(with_metadata=kwargs)
# pivot data if asked for explicit variable name
variables = df['variable'].unique()
if x in variables or y in variables:
keep_... | [
"Plot timeseries lines of existing data\n\n see pyam.plotting.line_plot() for all available options\n "
] |
Please provide a description of the function:def stack_plot(self, *args, **kwargs):
df = self.as_pandas(with_metadata=True)
ax = plotting.stack_plot(df, *args, **kwargs)
return ax | [
"Plot timeseries stacks of existing data\n\n see pyam.plotting.stack_plot() for all available options\n "
] |
Please provide a description of the function:def scatter(self, x, y, **kwargs):
variables = self.data['variable'].unique()
xisvar = x in variables
yisvar = y in variables
if not xisvar and not yisvar:
cols = [x, y] + self._discover_meta_cols(**kwargs)
df ... | [
"Plot a scatter chart using metadata columns\n\n see pyam.plotting.scatter() for all available options\n "
] |
Please provide a description of the function:def map_regions(self, map_col, agg=None, copy_col=None, fname=None,
region_col=None, remove_duplicates=False, inplace=False):
models = self.meta.index.get_level_values('model').unique()
fname = fname or run_control()['region_mappi... | [
"Plot regional data for a single model, scenario, variable, and year\n\n see pyam.plotting.region_plot() for all available options\n\n Parameters\n ----------\n map_col: string\n The column used to map new regions to. Common examples include\n iso and 5_region.\n ... |
Please provide a description of the function:def region_plot(self, **kwargs):
df = self.as_pandas(with_metadata=True)
ax = plotting.region_plot(df, **kwargs)
return ax | [
"Plot regional data for a single model, scenario, variable, and year\n\n see pyam.plotting.region_plot() for all available options\n "
] |
Please provide a description of the function:def update(self, rc):
rc = self._load_yaml(rc)
self.store = _recursive_update(self.store, rc) | [
"Add additional run control parameters\n\n Parameters\n ----------\n rc : string, file, dictionary, optional\n a path to a YAML file, a file handle for a YAML file, or a\n dictionary describing run control configuration\n "
] |
Please provide a description of the function:def recursive_update(self, k, d):
u = self.__getitem__(k)
self.store[k] = _recursive_update(u, d) | [
"Recursively update a top-level option in the run control\n\n Parameters\n ----------\n k : string\n the top-level key\n d : dictionary or similar\n the dictionary to use for updating\n "
] |
Please provide a description of the function:def fill_series(x, year):
x = x.dropna()
if year in x.index and not np.isnan(x[year]):
return x[year]
else:
prev = [i for i in x.index if i < year]
nxt = [i for i in x.index if i > year]
if prev and nxt:
p = max(pr... | [
"Returns the value of a timeseries (indexed over years) for a year\n by linear interpolation.\n\n Parameters\n ----------\n x: pandas.Series\n a timeseries to be interpolated\n year: int\n year of interpolation\n "
] |
Please provide a description of the function:def cumulative(x, first_year, last_year):
# if the timeseries does not cover the range `[first_year, last_year]`,
# return nan to avoid erroneous aggregation
if min(x.index) > first_year:
logger().warning('the timeseries `{}` does not start by {}'.fo... | [
"Returns the cumulative sum of a timeseries (indexed over years),\n implements linear interpolation between years, ignores nan's in the range.\n The function includes the last-year value of the series, and\n raises a warning if start_year or last_year is outside of\n the timeseries range and returns nan... |
Please provide a description of the function:def cross_threshold(x, threshold=0, direction=['from above', 'from below']):
prev_yr, prev_val = None, None
years = []
direction = [direction] if isstr(direction) else list(direction)
if not set(direction).issubset(set(['from above', 'from below'])):
... | [
"Returns a list of the years in which a timeseries (indexed over years)\n crosses a given threshold\n\n Parameters\n ----------\n x: pandas.Series\n a timeseries indexed over years\n threshold: float, default 0\n the threshold that the timeseries is checked against\n direction: str, ... |
Please provide a description of the function:def read_iiasa(name, meta=False, **kwargs):
conn = Connection(name)
# data
df = conn.query(**kwargs)
df = IamDataFrame(df)
# metadata
if meta:
mdf = conn.metadata()
# only data for models/scenarios in df
mdf = mdf[mdf.mode... | [
"\n Query an IIASA database. See Connection.query() for more documentation\n\n Parameters\n ----------\n name : str\n A valid IIASA database name, see pyam.iiasa.valid_connection_names()\n meta : bool or list of strings\n If not False, also include metadata indicators (or subset if prov... |
Please provide a description of the function:def scenario_list(self, default=True):
default = 'true' if default else 'false'
add_url = 'runs?getOnlyDefaultRuns={}'
url = self.base_url + add_url.format(default)
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
... | [
"\n Metadata regarding the list of scenarios (e.g., models, scenarios,\n run identifier, etc.) in the connected data source.\n\n Parameter\n ---------\n default : bool, optional, default True\n Return *only* the default version of each Scenario.\n Any (`model... |
Please provide a description of the function:def available_metadata(self):
url = self.base_url + 'metadata/types'
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
r = requests.get(url, headers=headers)
return pd.read_json(r.content, orient='records')['name'] | [
"\n List all scenario metadata indicators available in the connected\n data source\n "
] |
Please provide a description of the function:def metadata(self, default=True):
# at present this reads in all data for all scenarios, it could be sped
# up in the future to try to query a subset
default = 'true' if default else 'false'
add_url = 'runs?getOnlyDefaultRuns={}&inclu... | [
"\n Metadata of scenarios in the connected data source\n\n Parameter\n ---------\n default : bool, optional, default True\n Return *only* the default version of each Scenario.\n Any (`model`, `scenario`) without a default version is omitted.\n If :obj:`Fa... |
Please provide a description of the function:def variables(self):
url = self.base_url + 'ts'
headers = {'Authorization': 'Bearer {}'.format(self.auth())}
r = requests.get(url, headers=headers)
df = pd.read_json(r.content, orient='records')
return pd.Series(df['variable']... | [
"All variables in the connected data source"
] |
Please provide a description of the function:def format_rows(row, center, fullrange=None, interquartile=None,
custom_format='{:.2f}'):
if (fullrange or 0) + (interquartile or 0) == 1:
legend = '{} ({})'.format(center, 'max, min' if fullrange is True
els... | [
"Format a row with `describe()` columns to a concise string"
] |
Please provide a description of the function:def add(self, data, header, row=None, subheader=None):
# verify validity of specifications
if self.rows is not None and row is None:
raise ValueError('row specification required')
if self.rows is None and row is not None:
... | [
"Filter `data` by arguments of this SummaryStats instance,\n then apply `pd.describe()` and format the statistics\n\n Parameters\n ----------\n data : pd.DataFrame or pd.Series\n data for which summary statistics should be computed\n header : str\n column nam... |
Please provide a description of the function:def reindex(self, copy=True):
ret = deepcopy(self) if copy else self
ret.stats = ret.stats.reindex(index=ret._idx, level=0)
if ret.idx_depth == 2:
ret.stats = ret.stats.reindex(index=ret._sub_idx, level=1)
if ret.rows is ... | [
"Reindex the summary statistics dataframe"
] |
Please provide a description of the function:def summarize(self, center='mean', fullrange=None, interquartile=None,
custom_format='{:.2f}'):
# call `reindex()` to reorder index and columns
self.reindex(copy=False)
center = 'median' if center == '50%' else center
... | [
"Format the compiled statistics to a concise string output\n\n Parameter\n ---------\n center : str, default `mean`\n what to return as 'center' of the summary: `mean`, `50%`, `median`\n fullrange : bool, default None\n return full range of data if True or `fullrang... |
Please provide a description of the function:def reset_default_props(**kwargs):
global _DEFAULT_PROPS
pcycle = plt.rcParams['axes.prop_cycle']
_DEFAULT_PROPS = {
'color': itertools.cycle(_get_standard_colors(**kwargs))
if len(kwargs) > 0 else itertools.cycle([x['color'] for x in pcycle]... | [
"Reset properties to initial cycle point"
] |
Please provide a description of the function:def default_props(reset=False, **kwargs):
global _DEFAULT_PROPS
if _DEFAULT_PROPS is None or reset:
reset_default_props(**kwargs)
return _DEFAULT_PROPS | [
"Return current default properties\n\n Parameters\n ----------\n reset : bool\n if True, reset properties and return\n default: False\n "
] |
Please provide a description of the function:def assign_style_props(df, color=None, marker=None, linestyle=None,
cmap=None):
if color is None and cmap is not None:
raise ValueError('`cmap` must be provided with the `color` argument')
# determine color, marker, and linestyle ... | [
"Assign the style properties for a plot\n\n Parameters\n ----------\n df : pd.DataFrame\n data to be used for style properties\n "
] |
Please provide a description of the function:def reshape_line_plot(df, x, y):
idx = list(df.columns.drop(y))
if df.duplicated(idx).any():
warnings.warn('Duplicated index found.')
df = df.drop_duplicates(idx, keep='last')
df = df.set_index(idx)[y].unstack(x).T
return df | [
"Reshape data from long form to \"line plot form\".\n\n Line plot form has x value as the index with one column for each line.\n Each column has data points as values and all metadata as column headers.\n "
] |
Please provide a description of the function:def reshape_bar_plot(df, x, y, bars):
idx = [bars, x]
if df.duplicated(idx).any():
warnings.warn('Duplicated index found.')
df = df.drop_duplicates(idx, keep='last')
df = df.set_index(idx)[y].unstack(x).T
return df | [
"Reshape data from long form to \"bar plot form\".\n\n Bar plot form has x value as the index with one column for bar grouping.\n Table values come from y values.\n "
] |
Please provide a description of the function:def read_shapefile(fname, region_col=None, **kwargs):
gdf = gpd.read_file(fname, **kwargs)
if region_col is not None:
gdf = gdf.rename(columns={region_col: 'region'})
if 'region' not in gdf.columns:
raise IOError('Must provide a region column... | [
"Read a shapefile for use in regional plots. Shapefiles must have a\n column denoted as \"region\".\n\n Parameters\n ----------\n fname : string\n path to shapefile to be read by geopandas\n region_col : string, default None\n if provided, rename a column in the shapefile to \"region\"\... |
Please provide a description of the function:def region_plot(df, column='value', ax=None, crs=None, gdf=None,
add_features=True, vmin=None, vmax=None, cmap=None,
cbar=True, legend=False, title=True):
for col in ['model', 'scenario', 'year', 'variable']:
if len(df[col].un... | [
"Plot data on a map.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n column : string, optional, default: 'value'\n The column to use for plotting values\n ax : matplotlib.Axes, optional\n crs : cartopy.crs, optional\n The crs to plot,... |
Please provide a description of the function:def pie_plot(df, value='value', category='variable',
ax=None, legend=False, title=True, cmap=None,
**kwargs):
for col in set(SORT_IDX) - set([category]):
if len(df[col].unique()) > 1:
msg = 'Can not plot multiple {}s in ... | [
"Plot data as a bar chart.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n value : string, optional\n The column to use for data values\n default: value\n category : string, optional\n The column to use for labels\n default... |
Please provide a description of the function:def stack_plot(df, x='year', y='value', stack='variable',
ax=None, legend=True, title=True, cmap=None, total=None,
**kwargs):
for col in set(SORT_IDX) - set([x, stack]):
if len(df[col].unique()) > 1:
msg = 'Can not p... | [
"Plot data as a stack chart.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n x : string, optional\n The column to use for x-axis values\n default: year\n y : string, optional\n The column to use for y-axis values\n default:... |
Please provide a description of the function:def bar_plot(df, x='year', y='value', bars='variable',
ax=None, orient='v', legend=True, title=True, cmap=None,
**kwargs):
for col in set(SORT_IDX) - set([x, bars]):
if len(df[col].unique()) > 1:
msg = 'Can not plot mult... | [
"Plot data as a bar chart.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n x : string, optional\n The column to use for x-axis values\n default: year\n y : string, optional\n The column to use for y-axis values\n default: v... |
Please provide a description of the function:def add_net_values_to_bar_plot(axs, color='k'):
axs = axs if isinstance(axs, Iterable) else [axs]
for ax in axs:
box_args = _get_boxes(ax)
for x, args in box_args.items():
rect = mpatches.Rectangle(*args, color=color)
ax.a... | [
"Add net values next to an existing vertical stacked bar chart\n\n Parameters\n ----------\n axs : matplotlib.Axes or list thereof\n color : str, optional, default: black\n the color of the bars to add\n "
] |
Please provide a description of the function:def scatter(df, x, y, ax=None, legend=None, title=None,
color=None, marker='o', linestyle=None, cmap=None,
groupby=['model', 'scenario'], with_lines=False, **kwargs):
if ax is None:
fig, ax = plt.subplots()
# assign styling prope... | [
"Plot data as a scatter chart.\n\n Parameters\n ----------\n df : pd.DataFrame\n Data to plot as a long-form data frame\n x : str\n column to be plotted on the x-axis\n y : str\n column to be plotted on the y-axis\n ax : matplotlib.Axes, optional\n legend : bool, optional\n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.