id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
19,500
geometalab/pyGeoTile
pygeotile/tile.py
Tile.google
def google(self): """Gets the tile in the Google format, converted from TMS""" tms_x, tms_y = self.tms return tms_x, (2 ** self.zoom - 1) - tms_y
python
def google(self): tms_x, tms_y = self.tms return tms_x, (2 ** self.zoom - 1) - tms_y
[ "def", "google", "(", "self", ")", ":", "tms_x", ",", "tms_y", "=", "self", ".", "tms", "return", "tms_x", ",", "(", "2", "**", "self", ".", "zoom", "-", "1", ")", "-", "tms_y" ]
Gets the tile in the Google format, converted from TMS
[ "Gets", "the", "tile", "in", "the", "Google", "format", "converted", "from", "TMS" ]
b1f44271698f5fc4d18c2add935797ed43254aa6
https://github.com/geometalab/pyGeoTile/blob/b1f44271698f5fc4d18c2add935797ed43254aa6/pygeotile/tile.py#L91-L94
19,501
geometalab/pyGeoTile
pygeotile/tile.py
Tile.bounds
def bounds(self): """Gets the bounds of a tile represented as the most west and south point and the most east and north point""" google_x, google_y = self.google pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE pixel_x_east, pixel_y_south = (google_x + 1) * TILE_SIZE, (google_y + 1) * TILE_SIZE point_min = Point.from_pixel(pixel_x=pixel_x_west, pixel_y=pixel_y_south, zoom=self.zoom) point_max = Point.from_pixel(pixel_x=pixel_x_east, pixel_y=pixel_y_north, zoom=self.zoom) return point_min, point_max
python
def bounds(self): google_x, google_y = self.google pixel_x_west, pixel_y_north = google_x * TILE_SIZE, google_y * TILE_SIZE pixel_x_east, pixel_y_south = (google_x + 1) * TILE_SIZE, (google_y + 1) * TILE_SIZE point_min = Point.from_pixel(pixel_x=pixel_x_west, pixel_y=pixel_y_south, zoom=self.zoom) point_max = Point.from_pixel(pixel_x=pixel_x_east, pixel_y=pixel_y_north, zoom=self.zoom) return point_min, point_max
[ "def", "bounds", "(", "self", ")", ":", "google_x", ",", "google_y", "=", "self", ".", "google", "pixel_x_west", ",", "pixel_y_north", "=", "google_x", "*", "TILE_SIZE", ",", "google_y", "*", "TILE_SIZE", "pixel_x_east", ",", "pixel_y_south", "=", "(", "goog...
Gets the bounds of a tile represented as the most west and south point and the most east and north point
[ "Gets", "the", "bounds", "of", "a", "tile", "represented", "as", "the", "most", "west", "and", "south", "point", "and", "the", "most", "east", "and", "north", "point" ]
b1f44271698f5fc4d18c2add935797ed43254aa6
https://github.com/geometalab/pyGeoTile/blob/b1f44271698f5fc4d18c2add935797ed43254aa6/pygeotile/tile.py#L97-L105
19,502
IAMconsortium/pyam
pyam/read_ixmp.py
read_ix
def read_ix(ix, **kwargs): """Read timeseries data from an ixmp object Parameters ---------- ix: ixmp.TimeSeries or ixmp.Scenario this option requires the ixmp package as a dependency kwargs: arguments passed to ixmp.TimeSeries.timeseries() """ 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.scenario return df, 'year', []
python
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.scenario return df, 'year', []
[ "def", "read_ix", "(", "ix", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "ix", ",", "ixmp", ".", "TimeSeries", ")", ":", "error", "=", "'not recognized as valid ixmp class: {}'", ".", "format", "(", "ix", ")", "raise", "ValueError", ...
Read timeseries data from an ixmp object Parameters ---------- ix: ixmp.TimeSeries or ixmp.Scenario this option requires the ixmp package as a dependency kwargs: arguments passed to ixmp.TimeSeries.timeseries()
[ "Read", "timeseries", "data", "from", "an", "ixmp", "object" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/read_ixmp.py#L8-L24
19,503
IAMconsortium/pyam
pyam/utils.py
requires_package
def requires_package(pkg, msg, error_type=ImportError): """Decorator when a function requires an optional dependency Parameters ---------- pkg : imported package object msg : string Message to show to user with error_type error_type : python error class """ def _requires_package(func): def wrapper(*args, **kwargs): if pkg is None: raise error_type(msg) return func(*args, **kwargs) return wrapper return _requires_package
python
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 _requires_package
[ "def", "requires_package", "(", "pkg", ",", "msg", ",", "error_type", "=", "ImportError", ")", ":", "def", "_requires_package", "(", "func", ")", ":", "def", "wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "pkg", "is", "None", "...
Decorator when a function requires an optional dependency Parameters ---------- pkg : imported package object msg : string Message to show to user with error_type error_type : python error class
[ "Decorator", "when", "a", "function", "requires", "an", "optional", "dependency" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L36-L52
19,504
IAMconsortium/pyam
pyam/utils.py
write_sheet
def write_sheet(writer, name, df, index=False): """Write a pandas DataFrame to an ExcelWriter, auto-formatting column width depending on maxwidth of data and colum header Parameters ---------- writer: pandas.ExcelWriter an instance of a pandas ExcelWriter name: string name of the sheet to be written df: pandas.DataFrame a pandas DataFrame to be written to the sheet index: boolean, default False flag whether index should be written to the sheet """ 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')): width = len(str(col)) + 2 else: width = max([df[col].map(lambda x: len(str(x or 'None'))).max(), len(col)]) + 2 xls_col = '{c}:{c}'.format(c=NUMERIC_TO_STR[i]) worksheet.set_column(xls_col, width)
python
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')): width = len(str(col)) + 2 else: width = max([df[col].map(lambda x: len(str(x or 'None'))).max(), len(col)]) + 2 xls_col = '{c}:{c}'.format(c=NUMERIC_TO_STR[i]) worksheet.set_column(xls_col, width)
[ "def", "write_sheet", "(", "writer", ",", "name", ",", "df", ",", "index", "=", "False", ")", ":", "if", "index", ":", "df", "=", "df", ".", "reset_index", "(", ")", "df", ".", "to_excel", "(", "writer", ",", "name", ",", "index", "=", "False", "...
Write a pandas DataFrame to an ExcelWriter, auto-formatting column width depending on maxwidth of data and colum header Parameters ---------- writer: pandas.ExcelWriter an instance of a pandas ExcelWriter name: string name of the sheet to be written df: pandas.DataFrame a pandas DataFrame to be written to the sheet index: boolean, default False flag whether index should be written to the sheet
[ "Write", "a", "pandas", "DataFrame", "to", "an", "ExcelWriter", "auto", "-", "formatting", "column", "width", "depending", "on", "maxwidth", "of", "data", "and", "colum", "header" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L70-L96
19,505
IAMconsortium/pyam
pyam/utils.py
read_pandas
def read_pandas(fname, *args, **kwargs): """Read a file and return a pd.DataFrame""" 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) if len(xl.sheet_names) > 1 and 'sheet_name' not in kwargs: kwargs['sheet_name'] = 'data' df = pd.read_excel(fname, *args, **kwargs) return df
python
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) if len(xl.sheet_names) > 1 and 'sheet_name' not in kwargs: kwargs['sheet_name'] = 'data' df = pd.read_excel(fname, *args, **kwargs) return df
[ "def", "read_pandas", "(", "fname", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fname", ")", ":", "raise", "ValueError", "(", "'no data file `{}` found!'", ".", "format", "(", "fname", ")", ...
Read a file and return a pd.DataFrame
[ "Read", "a", "file", "and", "return", "a", "pd", ".", "DataFrame" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L99-L110
19,506
IAMconsortium/pyam
pyam/utils.py
sort_data
def sort_data(data, cols): """Sort `data` rows and order columns""" return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)
python
def sort_data(data, cols): return data.sort_values(cols)[cols + ['value']].reset_index(drop=True)
[ "def", "sort_data", "(", "data", ",", "cols", ")", ":", "return", "data", ".", "sort_values", "(", "cols", ")", "[", "cols", "+", "[", "'value'", "]", "]", ".", "reset_index", "(", "drop", "=", "True", ")" ]
Sort `data` rows and order columns
[ "Sort", "data", "rows", "and", "order", "columns" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L258-L260
19,507
IAMconsortium/pyam
pyam/utils.py
_escape_regexp
def _escape_regexp(s): """escape characters with specific regexp use""" return ( str(s) .replace('|', '\\|') .replace('.', '\.') # `.` has to be replaced before `*` .replace('*', '.*') .replace('+', '\+') .replace('(', '\(') .replace(')', '\)') .replace('$', '\\$') )
python
def _escape_regexp(s): return ( str(s) .replace('|', '\\|') .replace('.', '\.') # `.` has to be replaced before `*` .replace('*', '.*') .replace('+', '\+') .replace('(', '\(') .replace(')', '\)') .replace('$', '\\$') )
[ "def", "_escape_regexp", "(", "s", ")", ":", "return", "(", "str", "(", "s", ")", ".", "replace", "(", "'|'", ",", "'\\\\|'", ")", ".", "replace", "(", "'.'", ",", "'\\.'", ")", "# `.` has to be replaced before `*`", ".", "replace", "(", "'*'", ",", "'...
escape characters with specific regexp use
[ "escape", "characters", "with", "specific", "regexp", "use" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L332-L343
19,508
IAMconsortium/pyam
pyam/utils.py
years_match
def years_match(data, years): """ matching of year columns for data filtering """ 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 TypeError(error_msg) return data.isin(years)
python
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 TypeError(error_msg) return data.isin(years)
[ "def", "years_match", "(", "data", ",", "years", ")", ":", "years", "=", "[", "years", "]", "if", "isinstance", "(", "years", ",", "int", ")", "else", "years", "dt", "=", "datetime", ".", "datetime", "if", "isinstance", "(", "years", ",", "dt", ")", ...
matching of year columns for data filtering
[ "matching", "of", "year", "columns", "for", "data", "filtering" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L346-L355
19,509
IAMconsortium/pyam
pyam/utils.py
hour_match
def hour_match(data, hours): """ matching of days in time columns for data filtering """ hours = [hours] if isinstance(hours, int) else hours return data.isin(hours)
python
def hour_match(data, hours): hours = [hours] if isinstance(hours, int) else hours return data.isin(hours)
[ "def", "hour_match", "(", "data", ",", "hours", ")", ":", "hours", "=", "[", "hours", "]", "if", "isinstance", "(", "hours", ",", "int", ")", "else", "hours", "return", "data", ".", "isin", "(", "hours", ")" ]
matching of days in time columns for data filtering
[ "matching", "of", "days", "in", "time", "columns", "for", "data", "filtering" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L372-L377
19,510
IAMconsortium/pyam
pyam/utils.py
datetime_match
def datetime_match(data, dts): """ matching of datetimes in time columns for data filtering """ 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) return data.isin(dts)
python
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) return data.isin(dts)
[ "def", "datetime_match", "(", "data", ",", "dts", ")", ":", "dts", "=", "dts", "if", "islistable", "(", "dts", ")", "else", "[", "dts", "]", "if", "any", "(", "[", "not", "isinstance", "(", "i", ",", "datetime", ".", "datetime", ")", "for", "i", ...
matching of datetimes in time columns for data filtering
[ "matching", "of", "datetimes", "in", "time", "columns", "for", "data", "filtering" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L422-L432
19,511
IAMconsortium/pyam
pyam/utils.py
to_int
def to_int(x, index=False): """Formatting series or timeseries columns to int and checking validity. If `index=False`, the function works on the `pd.Series x`; else, the function casts the index of `x` to int and returns x with a new index. """ _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 else: return _x
python
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 else: return _x
[ "def", "to_int", "(", "x", ",", "index", "=", "False", ")", ":", "_x", "=", "x", ".", "index", "if", "index", "else", "x", "cols", "=", "list", "(", "map", "(", "int", ",", "_x", ")", ")", "error", "=", "_x", "[", "cols", "!=", "_x", "]", "...
Formatting series or timeseries columns to int and checking validity. If `index=False`, the function works on the `pd.Series x`; else, the function casts the index of `x` to int and returns x with a new index.
[ "Formatting", "series", "or", "timeseries", "columns", "to", "int", "and", "checking", "validity", ".", "If", "index", "=", "False", "the", "function", "works", "on", "the", "pd", ".", "Series", "x", ";", "else", "the", "function", "casts", "the", "index",...
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L435-L449
19,512
IAMconsortium/pyam
pyam/utils.py
concat_with_pipe
def concat_with_pipe(x, cols=None): """Concatenate a `pd.Series` separated by `|`, drop `None` or `np.nan`""" cols = cols or x.index return '|'.join([x[i] for i in cols if x[i] not in [None, np.nan]])
python
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]])
[ "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"...
Concatenate a `pd.Series` separated by `|`, drop `None` or `np.nan`
[ "Concatenate", "a", "pd", ".", "Series", "separated", "by", "|", "drop", "None", "or", "np", ".", "nan" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/utils.py#L452-L455
19,513
IAMconsortium/pyam
pyam/core.py
_make_index
def _make_index(df, cols=META_IDX): """Create an index from the columns of a dataframe""" return pd.MultiIndex.from_tuples( pd.unique(list(zip(*[df[col] for col in cols]))), names=tuple(cols))
python
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))
[ "def", "_make_index", "(", "df", ",", "cols", "=", "META_IDX", ")", ":", "return", "pd", ".", "MultiIndex", ".", "from_tuples", "(", "pd", ".", "unique", "(", "list", "(", "zip", "(", "*", "[", "df", "[", "col", "]", "for", "col", "in", "cols", "...
Create an index from the columns of a dataframe
[ "Create", "an", "index", "from", "the", "columns", "of", "a", "dataframe" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1400-L1403
19,514
IAMconsortium/pyam
pyam/core.py
check_aggregate
def check_aggregate(df, variable, components=None, exclude_on_fail=False, multiplier=1, **kwargs): """Check whether the timeseries values match the aggregation of sub-categories Parameters ---------- df: IamDataFrame instance args: see IamDataFrame.check_aggregate() for details kwargs: passed to `df.filter()` """ fdf = df.filter(**kwargs) if len(fdf.data) > 0: vdf = fdf.check_aggregate(variable=variable, components=components, exclude_on_fail=exclude_on_fail, multiplier=multiplier) df.meta['exclude'] |= fdf.meta['exclude'] # update if any excluded return vdf
python
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, exclude_on_fail=exclude_on_fail, multiplier=multiplier) df.meta['exclude'] |= fdf.meta['exclude'] # update if any excluded return vdf
[ "def", "check_aggregate", "(", "df", ",", "variable", ",", "components", "=", "None", ",", "exclude_on_fail", "=", "False", ",", "multiplier", "=", "1", ",", "*", "*", "kwargs", ")", ":", "fdf", "=", "df", ".", "filter", "(", "*", "*", "kwargs", ")",...
Check whether the timeseries values match the aggregation of sub-categories Parameters ---------- df: IamDataFrame instance args: see IamDataFrame.check_aggregate() for details kwargs: passed to `df.filter()`
[ "Check", "whether", "the", "timeseries", "values", "match", "the", "aggregation", "of", "sub", "-", "categories" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1462-L1479
19,515
IAMconsortium/pyam
pyam/core.py
filter_by_meta
def filter_by_meta(data, df, join_meta=False, **kwargs): """Filter by and join meta columns from an IamDataFrame to a pd.DataFrame Parameters ---------- data: pd.DataFrame instance DataFrame to which meta columns are to be joined, index or columns must include `['model', 'scenario']` df: IamDataFrame instance IamDataFrame from which meta columns are filtered and joined (optional) join_meta: bool, default False join selected columns from `df.meta` on `data` kwargs: meta columns to be filtered/joined, where `col=...` applies filters by the given arguments (using `utils.pattern_match()`) and `col=None` joins the column without filtering (setting col to `np.nan` if `(model, scenario) not in df.meta.index`) """ 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))].copy()) # filter meta by columns keep = np.array([True] * len(meta)) apply_filter = False for col, values in kwargs.items(): if col in META_IDX and values is not None: _col = meta.index.get_level_values(0 if col is 'model' else 1) keep &= pattern_match(_col, values, has_nan=False) apply_filter = True elif values is not None: keep &= pattern_match(meta[col], values) apply_filter |= values is not None meta = meta[keep] # set the data index to META_IDX and apply filtered meta index data = data.copy() idx = list(data.index.names) if not data.index.names == [None] else None data = data.reset_index().set_index(META_IDX) meta = meta.loc[meta.index.intersection(data.index)] meta.index.names = META_IDX if apply_filter: data = data.loc[meta.index] data.index.names = META_IDX # join meta (optional), reset index to format as input arg data = data.join(meta) if join_meta else data data = data.reset_index().set_index(idx or 'index') if idx is None: data.index.name = None return data
python
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))].copy()) # filter meta by columns keep = np.array([True] * len(meta)) apply_filter = False for col, values in kwargs.items(): if col in META_IDX and values is not None: _col = meta.index.get_level_values(0 if col is 'model' else 1) keep &= pattern_match(_col, values, has_nan=False) apply_filter = True elif values is not None: keep &= pattern_match(meta[col], values) apply_filter |= values is not None meta = meta[keep] # set the data index to META_IDX and apply filtered meta index data = data.copy() idx = list(data.index.names) if not data.index.names == [None] else None data = data.reset_index().set_index(META_IDX) meta = meta.loc[meta.index.intersection(data.index)] meta.index.names = META_IDX if apply_filter: data = data.loc[meta.index] data.index.names = META_IDX # join meta (optional), reset index to format as input arg data = data.join(meta) if join_meta else data data = data.reset_index().set_index(idx or 'index') if idx is None: data.index.name = None return data
[ "def", "filter_by_meta", "(", "data", ",", "df", ",", "join_meta", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "set", "(", "META_IDX", ")", ".", "issubset", "(", "data", ".", "index", ".", "names", "+", "list", "(", "data", ".", ...
Filter by and join meta columns from an IamDataFrame to a pd.DataFrame Parameters ---------- data: pd.DataFrame instance DataFrame to which meta columns are to be joined, index or columns must include `['model', 'scenario']` df: IamDataFrame instance IamDataFrame from which meta columns are filtered and joined (optional) join_meta: bool, default False join selected columns from `df.meta` on `data` kwargs: meta columns to be filtered/joined, where `col=...` applies filters by the given arguments (using `utils.pattern_match()`) and `col=None` joins the column without filtering (setting col to `np.nan` if `(model, scenario) not in df.meta.index`)
[ "Filter", "by", "and", "join", "meta", "columns", "from", "an", "IamDataFrame", "to", "a", "pd", ".", "DataFrame" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1482-L1534
19,516
IAMconsortium/pyam
pyam/core.py
compare
def compare(left, right, left_label='left', right_label='right', drop_close=True, **kwargs): """Compare the data in two IamDataFrames and return a pd.DataFrame Parameters ---------- left, right: IamDataFrames the IamDataFrames to be compared left_label, right_label: str, default `left`, `right` column names of the returned dataframe drop_close: bool, default True remove all data where `left` and `right` are close kwargs: passed to `np.isclose()` """ ret = pd.concat({right_label: right.data.set_index(right._LONG_IDX), left_label: left.data.set_index(left._LONG_IDX)}, axis=1) ret.columns = ret.columns.droplevel(1) if drop_close: ret = ret[~np.isclose(ret[left_label], ret[right_label], **kwargs)] return ret[[right_label, left_label]]
python
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.columns = ret.columns.droplevel(1) if drop_close: ret = ret[~np.isclose(ret[left_label], ret[right_label], **kwargs)] return ret[[right_label, left_label]]
[ "def", "compare", "(", "left", ",", "right", ",", "left_label", "=", "'left'", ",", "right_label", "=", "'right'", ",", "drop_close", "=", "True", ",", "*", "*", "kwargs", ")", ":", "ret", "=", "pd", ".", "concat", "(", "{", "right_label", ":", "righ...
Compare the data in two IamDataFrames and return a pd.DataFrame Parameters ---------- left, right: IamDataFrames the IamDataFrames to be compared left_label, right_label: str, default `left`, `right` column names of the returned dataframe drop_close: bool, default True remove all data where `left` and `right` are close kwargs: passed to `np.isclose()`
[ "Compare", "the", "data", "in", "two", "IamDataFrames", "and", "return", "a", "pd", ".", "DataFrame" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1537-L1556
19,517
IAMconsortium/pyam
pyam/core.py
concat
def concat(dfs): """Concatenate a series of `pyam.IamDataFrame`-like objects together""" 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 IamDataFrame(df) if _df is None: _df = copy.deepcopy(df) else: _df.append(df, inplace=True) return _df
python
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 IamDataFrame(df) if _df is None: _df = copy.deepcopy(df) else: _df.append(df, inplace=True) return _df
[ "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", ...
Concatenate a series of `pyam.IamDataFrame`-like objects together
[ "Concatenate", "a", "series", "of", "pyam", ".", "IamDataFrame", "-", "like", "objects", "together" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1559-L1572
19,518
IAMconsortium/pyam
pyam/core.py
IamDataFrame.variables
def variables(self, include_units=False): """Get a list of variables Parameters ---------- include_units: boolean, default False include the units """ if include_units: return self.data[['variable', 'unit']].drop_duplicates()\ .reset_index(drop=True).sort_values('variable') else: return pd.Series(self.data.variable.unique(), name='variable')
python
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.unique(), name='variable')
[ "def", "variables", "(", "self", ",", "include_units", "=", "False", ")", ":", "if", "include_units", ":", "return", "self", ".", "data", "[", "[", "'variable'", ",", "'unit'", "]", "]", ".", "drop_duplicates", "(", ")", ".", "reset_index", "(", "drop", ...
Get a list of variables Parameters ---------- include_units: boolean, default False include the units
[ "Get", "a", "list", "of", "variables" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L161-L173
19,519
IAMconsortium/pyam
pyam/core.py
IamDataFrame.append
def append(self, other, ignore_meta_conflict=False, inplace=False, **kwargs): """Append any castable object to this IamDataFrame. Columns in `other.meta` that are not in `self.meta` are always merged, duplicate region-variable-unit-year rows raise a ValueError. Parameters ---------- other: pyam.IamDataFrame, ixmp.TimeSeries, ixmp.Scenario, pd.DataFrame or data file An IamDataFrame, TimeSeries or Scenario (requires `ixmp`), pandas.DataFrame or data file with IAMC-format data columns ignore_meta_conflict : bool, default False If False and `other` is an IamDataFrame, raise an error if any meta columns present in `self` and `other` are not identical. inplace : bool, default False If True, do operation inplace and return None kwargs are passed through to `IamDataFrame(other, **kwargs)` """ if not isinstance(other, IamDataFrame): other = IamDataFrame(other, **kwargs) ignore_meta_conflict = True if self.time_col is not other.time_col: raise ValueError('incompatible time format (years vs. datetime)!') ret = copy.deepcopy(self) if not inplace else self diff = other.meta.index.difference(ret.meta.index) intersect = other.meta.index.intersection(ret.meta.index) # merge other.meta columns not in self.meta for existing scenarios if not intersect.empty: # if not ignored, check that overlapping meta dataframes are equal if not ignore_meta_conflict: cols = [i for i in other.meta.columns if i in ret.meta.columns] if not ret.meta.loc[intersect, cols].equals( other.meta.loc[intersect, cols]): conflict_idx = ( pd.concat([ret.meta.loc[intersect, cols], other.meta.loc[intersect, cols]] ).drop_duplicates() .index.drop_duplicates() ) msg = 'conflict in `meta` for scenarios {}'.format( [i for i in pd.DataFrame(index=conflict_idx).index]) raise ValueError(msg) cols = [i for i in other.meta.columns if i not in ret.meta.columns] _meta = other.meta.loc[intersect, cols] ret.meta = ret.meta.merge(_meta, how='outer', left_index=True, right_index=True) # join other.meta for new scenarios if not diff.empty: # sorting not supported by ` pd.append()` prior to version 23 sort_kwarg = {} if int(pd.__version__.split('.')[1]) < 23 \ else dict(sort=False) ret.meta = ret.meta.append(other.meta.loc[diff, :], **sort_kwarg) # append other.data (verify integrity for no duplicates) _data = ret.data.set_index(ret._LONG_IDX).append( other.data.set_index(other._LONG_IDX), verify_integrity=True) # merge extra columns in `data` and set `LONG_IDX` ret.extra_cols += [i for i in other.extra_cols if i not in ret.extra_cols] ret._LONG_IDX = IAMC_IDX + [ret.time_col] + ret.extra_cols ret.data = sort_data(_data.reset_index(), ret._LONG_IDX) if not inplace: return ret
python
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 other.time_col: raise ValueError('incompatible time format (years vs. datetime)!') ret = copy.deepcopy(self) if not inplace else self diff = other.meta.index.difference(ret.meta.index) intersect = other.meta.index.intersection(ret.meta.index) # merge other.meta columns not in self.meta for existing scenarios if not intersect.empty: # if not ignored, check that overlapping meta dataframes are equal if not ignore_meta_conflict: cols = [i for i in other.meta.columns if i in ret.meta.columns] if not ret.meta.loc[intersect, cols].equals( other.meta.loc[intersect, cols]): conflict_idx = ( pd.concat([ret.meta.loc[intersect, cols], other.meta.loc[intersect, cols]] ).drop_duplicates() .index.drop_duplicates() ) msg = 'conflict in `meta` for scenarios {}'.format( [i for i in pd.DataFrame(index=conflict_idx).index]) raise ValueError(msg) cols = [i for i in other.meta.columns if i not in ret.meta.columns] _meta = other.meta.loc[intersect, cols] ret.meta = ret.meta.merge(_meta, how='outer', left_index=True, right_index=True) # join other.meta for new scenarios if not diff.empty: # sorting not supported by ` pd.append()` prior to version 23 sort_kwarg = {} if int(pd.__version__.split('.')[1]) < 23 \ else dict(sort=False) ret.meta = ret.meta.append(other.meta.loc[diff, :], **sort_kwarg) # append other.data (verify integrity for no duplicates) _data = ret.data.set_index(ret._LONG_IDX).append( other.data.set_index(other._LONG_IDX), verify_integrity=True) # merge extra columns in `data` and set `LONG_IDX` ret.extra_cols += [i for i in other.extra_cols if i not in ret.extra_cols] ret._LONG_IDX = IAMC_IDX + [ret.time_col] + ret.extra_cols ret.data = sort_data(_data.reset_index(), ret._LONG_IDX) if not inplace: return ret
[ "def", "append", "(", "self", ",", "other", ",", "ignore_meta_conflict", "=", "False", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "other", ",", "IamDataFrame", ")", ":", "other", "=", "IamDataFrame", ...
Append any castable object to this IamDataFrame. Columns in `other.meta` that are not in `self.meta` are always merged, duplicate region-variable-unit-year rows raise a ValueError. Parameters ---------- other: pyam.IamDataFrame, ixmp.TimeSeries, ixmp.Scenario, pd.DataFrame or data file An IamDataFrame, TimeSeries or Scenario (requires `ixmp`), pandas.DataFrame or data file with IAMC-format data columns ignore_meta_conflict : bool, default False If False and `other` is an IamDataFrame, raise an error if any meta columns present in `self` and `other` are not identical. inplace : bool, default False If True, do operation inplace and return None kwargs are passed through to `IamDataFrame(other, **kwargs)`
[ "Append", "any", "castable", "object", "to", "this", "IamDataFrame", ".", "Columns", "in", "other", ".", "meta", "that", "are", "not", "in", "self", ".", "meta", "are", "always", "merged", "duplicate", "region", "-", "variable", "-", "unit", "-", "year", ...
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L175-L246
19,520
IAMconsortium/pyam
pyam/core.py
IamDataFrame.pivot_table
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 strings rows for Pivot table columns: str or list of strings 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 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, as_index=False).count() fill_value = 0 elif aggfunc == 'mean': df = self.data.groupby(index + columns, as_index=False).mean()\ .round(2) aggfunc = np.sum fill_value = 0 if style == 'heatmap' else "" elif aggfunc == 'sum': aggfunc = np.sum fill_value = 0 if style == 'heatmap' else "" df = df.pivot_table(values=values, index=index, columns=columns, aggfunc=aggfunc, fill_value=fill_value) return df
python
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 # allow 'aggfunc' to be passed as string for easier user interface if isstr(aggfunc): if aggfunc == 'count': df = self.data.groupby(index + columns, as_index=False).count() fill_value = 0 elif aggfunc == 'mean': df = self.data.groupby(index + columns, as_index=False).mean()\ .round(2) aggfunc = np.sum fill_value = 0 if style == 'heatmap' else "" elif aggfunc == 'sum': aggfunc = np.sum fill_value = 0 if style == 'heatmap' else "" df = df.pivot_table(values=values, index=index, columns=columns, aggfunc=aggfunc, fill_value=fill_value) return df
[ "def", "pivot_table", "(", "self", ",", "index", ",", "columns", ",", "values", "=", "'value'", ",", "aggfunc", "=", "'count'", ",", "fill_value", "=", "None", ",", "style", "=", "None", ")", ":", "index", "=", "[", "index", "]", "if", "isstr", "(", ...
Returns a pivot table Parameters ---------- index: str or list of strings rows for Pivot table columns: str or list of strings 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'
[ "Returns", "a", "pivot", "table" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L248-L290
19,521
IAMconsortium/pyam
pyam/core.py
IamDataFrame.as_pandas
def as_pandas(self, with_metadata=False): """Return this as a pd.DataFrame Parameters ---------- with_metadata : bool, default False or dict if True, join data with all meta columns; if a dict, discover meaningful meta columns from values (in key-value) """ if with_metadata: cols = self._discover_meta_cols(**with_metadata) \ if isinstance(with_metadata, dict) else self.meta.columns return ( self.data .set_index(META_IDX) .join(self.meta[cols]) .reset_index() ) else: return self.data.copy()
python
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 .set_index(META_IDX) .join(self.meta[cols]) .reset_index() ) else: return self.data.copy()
[ "def", "as_pandas", "(", "self", ",", "with_metadata", "=", "False", ")", ":", "if", "with_metadata", ":", "cols", "=", "self", ".", "_discover_meta_cols", "(", "*", "*", "with_metadata", ")", "if", "isinstance", "(", "with_metadata", ",", "dict", ")", "el...
Return this as a pd.DataFrame Parameters ---------- with_metadata : bool, default False or dict if True, join data with all meta columns; if a dict, discover meaningful meta columns from values (in key-value)
[ "Return", "this", "as", "a", "pd", ".", "DataFrame" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L312-L331
19,522
IAMconsortium/pyam
pyam/core.py
IamDataFrame._new_meta_column
def _new_meta_column(self, name): """Add a column to meta if it doesn't exist, set to value `np.nan`""" if name is None: raise ValueError('cannot add a meta column `{}`'.format(name)) if name not in self.meta: self.meta[name] = np.nan
python
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
[ "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", ":", "sel...
Add a column to meta if it doesn't exist, set to value `np.nan`
[ "Add", "a", "column", "to", "meta", "if", "it", "doesn", "t", "exist", "set", "to", "value", "np", ".", "nan" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L474-L479
19,523
IAMconsortium/pyam
pyam/core.py
IamDataFrame.convert_unit
def convert_unit(self, conversion_mapping, inplace=False): """Converts units based on provided unit conversion factors Parameters ---------- conversion_mapping: dict for each unit for which a conversion should be carried out, provide current unit and target unit and conversion factor {<current unit>: [<target unit>, <conversion factor>]} inplace: bool, default False if True, do operation inplace and return None """ 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['unit'] == current_unit ret.data.loc[where, 'value'] *= factor ret.data.loc[where, 'unit'] = new_unit if not inplace: return ret
python
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['unit'] == current_unit ret.data.loc[where, 'value'] *= factor ret.data.loc[where, 'unit'] = new_unit if not inplace: return ret
[ "def", "convert_unit", "(", "self", ",", "conversion_mapping", ",", "inplace", "=", "False", ")", ":", "ret", "=", "copy", ".", "deepcopy", "(", "self", ")", "if", "not", "inplace", "else", "self", "for", "current_unit", ",", "(", "new_unit", ",", "facto...
Converts units based on provided unit conversion factors Parameters ---------- conversion_mapping: dict for each unit for which a conversion should be carried out, provide current unit and target unit and conversion factor {<current unit>: [<target unit>, <conversion factor>]} inplace: bool, default False if True, do operation inplace and return None
[ "Converts", "units", "based", "on", "provided", "unit", "conversion", "factors" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L635-L654
19,524
IAMconsortium/pyam
pyam/core.py
IamDataFrame.normalize
def normalize(self, inplace=False, **kwargs): """Normalize data to a given value. Currently only supports normalizing to a specific time. Parameters ---------- inplace: bool, default False if True, do operation inplace and return None kwargs: the values on which to normalize (e.g., `year=2005`) """ 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 # change all below if supporting more in the future cols = self.time_col value = kwargs[self.time_col] x = df.set_index(IAMC_IDX) x['value'] /= x[x[cols] == value]['value'] ret.data = x.reset_index() if not inplace: return ret
python
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 # change all below if supporting more in the future cols = self.time_col value = kwargs[self.time_col] x = df.set_index(IAMC_IDX) x['value'] /= x[x[cols] == value]['value'] ret.data = x.reset_index() if not inplace: return ret
[ "def", "normalize", "(", "self", ",", "inplace", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "kwargs", ")", ">", "1", "or", "self", ".", "time_col", "not", "in", "kwargs", ":", "raise", "ValueError", "(", "'Only time(year)-based ...
Normalize data to a given value. Currently only supports normalizing to a specific time. Parameters ---------- inplace: bool, default False if True, do operation inplace and return None kwargs: the values on which to normalize (e.g., `year=2005`)
[ "Normalize", "data", "to", "a", "given", "value", ".", "Currently", "only", "supports", "normalizing", "to", "a", "specific", "time", "." ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L656-L677
19,525
IAMconsortium/pyam
pyam/core.py
IamDataFrame.aggregate
def aggregate(self, variable, components=None, append=False): """Compute the aggregate of timeseries components or sub-categories Parameters ---------- variable: str variable for which the aggregate should be computed components: list of str, default None list of variables, defaults to all sub-categories of `variable` append: bool, default False append the aggregate timeseries to `data` and return None, else return aggregate timeseries """ # default components to all variables one level below `variable` components = components or self._variable_components(variable) if not len(components): msg = 'cannot aggregate variable `{}` because it has no components' logger().info(msg.format(variable)) return rows = self._apply_filters(variable=components) _data = _aggregate(self.data[rows], 'variable') if append is True: self.append(_data, variable=variable, inplace=True) else: return _data
python
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 aggregate variable `{}` because it has no components' logger().info(msg.format(variable)) return rows = self._apply_filters(variable=components) _data = _aggregate(self.data[rows], 'variable') if append is True: self.append(_data, variable=variable, inplace=True) else: return _data
[ "def", "aggregate", "(", "self", ",", "variable", ",", "components", "=", "None", ",", "append", "=", "False", ")", ":", "# default components to all variables one level below `variable`", "components", "=", "components", "or", "self", ".", "_variable_components", "("...
Compute the aggregate of timeseries components or sub-categories Parameters ---------- variable: str variable for which the aggregate should be computed components: list of str, default None list of variables, defaults to all sub-categories of `variable` append: bool, default False append the aggregate timeseries to `data` and return None, else return aggregate timeseries
[ "Compute", "the", "aggregate", "of", "timeseries", "components", "or", "sub", "-", "categories" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L679-L707
19,526
IAMconsortium/pyam
pyam/core.py
IamDataFrame.check_aggregate
def check_aggregate(self, variable, components=None, exclude_on_fail=False, multiplier=1, **kwargs): """Check whether a timeseries matches the aggregation of its components Parameters ---------- variable: str variable to be checked for matching aggregation of sub-categories components: list of str, default None list of variables, defaults to all sub-categories of `variable` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` multiplier: number, default 1 factor when comparing variable and sum of components kwargs: passed to `np.isclose()` """ # compute aggregate from components, return None if no components df_components = self.aggregate(variable, components) if df_components is None: return # filter and groupby data, use `pd.Series.align` for matching index rows = self._apply_filters(variable=variable) df_variable, df_components = ( _aggregate(self.data[rows], 'variable').align(df_components) ) # use `np.isclose` for checking match diff = df_variable[~np.isclose(df_variable, multiplier * df_components, **kwargs)] if len(diff): msg = '`{}` - {} of {} rows are not aggregates of components' logger().info(msg.format(variable, len(diff), len(df_variable))) if exclude_on_fail: self._exclude_on_fail(diff.index.droplevel([2, 3, 4])) return IamDataFrame(diff, variable=variable).timeseries()
python
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) if df_components is None: return # filter and groupby data, use `pd.Series.align` for matching index rows = self._apply_filters(variable=variable) df_variable, df_components = ( _aggregate(self.data[rows], 'variable').align(df_components) ) # use `np.isclose` for checking match diff = df_variable[~np.isclose(df_variable, multiplier * df_components, **kwargs)] if len(diff): msg = '`{}` - {} of {} rows are not aggregates of components' logger().info(msg.format(variable, len(diff), len(df_variable))) if exclude_on_fail: self._exclude_on_fail(diff.index.droplevel([2, 3, 4])) return IamDataFrame(diff, variable=variable).timeseries()
[ "def", "check_aggregate", "(", "self", ",", "variable", ",", "components", "=", "None", ",", "exclude_on_fail", "=", "False", ",", "multiplier", "=", "1", ",", "*", "*", "kwargs", ")", ":", "# compute aggregate from components, return None if no components", "df_com...
Check whether a timeseries matches the aggregation of its components Parameters ---------- variable: str variable to be checked for matching aggregation of sub-categories components: list of str, default None list of variables, defaults to all sub-categories of `variable` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` multiplier: number, default 1 factor when comparing variable and sum of components kwargs: passed to `np.isclose()`
[ "Check", "whether", "a", "timeseries", "matches", "the", "aggregation", "of", "its", "components" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L709-L747
19,527
IAMconsortium/pyam
pyam/core.py
IamDataFrame.aggregate_region
def aggregate_region(self, variable, region='World', subregions=None, components=None, append=False): """Compute the aggregate of timeseries over a number of regions including variable components only defined at the `region` level Parameters ---------- variable: str variable for which the aggregate should be computed region: str, default 'World' dimension subregions: list of str list of subregions, defaults to all regions other than `region` components: list of str list of variables, defaults to all sub-categories of `variable` included in `region` but not in any of `subregions` append: bool, default False append the aggregate timeseries to `data` and return None, else return aggregate timeseries """ # default subregions to all regions other than `region` if subregions is None: rows = self._apply_filters(variable=variable) subregions = set(self.data[rows].region) - set([region]) if not len(subregions): msg = 'cannot aggregate variable `{}` to `{}` because it does not'\ ' exist in any subregion' logger().info(msg.format(variable, region)) return # compute aggregate over all subregions subregion_df = self.filter(region=subregions) cols = ['region', 'variable'] _data = _aggregate(subregion_df.filter(variable=variable).data, cols) # add components at the `region` level, defaults to all variables one # level below `variable` that are only present in `region` region_df = self.filter(region=region) components = components or ( set(region_df._variable_components(variable)).difference( subregion_df._variable_components(variable))) if len(components): rows = region_df._apply_filters(variable=components) _data = _data.add(_aggregate(region_df.data[rows], cols), fill_value=0) if append is True: self.append(_data, region=region, variable=variable, inplace=True) else: return _data
python
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(variable=variable) subregions = set(self.data[rows].region) - set([region]) if not len(subregions): msg = 'cannot aggregate variable `{}` to `{}` because it does not'\ ' exist in any subregion' logger().info(msg.format(variable, region)) return # compute aggregate over all subregions subregion_df = self.filter(region=subregions) cols = ['region', 'variable'] _data = _aggregate(subregion_df.filter(variable=variable).data, cols) # add components at the `region` level, defaults to all variables one # level below `variable` that are only present in `region` region_df = self.filter(region=region) components = components or ( set(region_df._variable_components(variable)).difference( subregion_df._variable_components(variable))) if len(components): rows = region_df._apply_filters(variable=components) _data = _data.add(_aggregate(region_df.data[rows], cols), fill_value=0) if append is True: self.append(_data, region=region, variable=variable, inplace=True) else: return _data
[ "def", "aggregate_region", "(", "self", ",", "variable", ",", "region", "=", "'World'", ",", "subregions", "=", "None", ",", "components", "=", "None", ",", "append", "=", "False", ")", ":", "# default subregions to all regions other than `region`", "if", "subregi...
Compute the aggregate of timeseries over a number of regions including variable components only defined at the `region` level Parameters ---------- variable: str variable for which the aggregate should be computed region: str, default 'World' dimension subregions: list of str list of subregions, defaults to all regions other than `region` components: list of str list of variables, defaults to all sub-categories of `variable` included in `region` but not in any of `subregions` append: bool, default False append the aggregate timeseries to `data` and return None, else return aggregate timeseries
[ "Compute", "the", "aggregate", "of", "timeseries", "over", "a", "number", "of", "regions", "including", "variable", "components", "only", "defined", "at", "the", "region", "level" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L749-L801
19,528
IAMconsortium/pyam
pyam/core.py
IamDataFrame.check_aggregate_region
def check_aggregate_region(self, variable, region='World', subregions=None, components=None, exclude_on_fail=False, **kwargs): """Check whether the region timeseries data match the aggregation of components Parameters ---------- variable: str variable to be checked for matching aggregation of subregions region: str, default 'World' region to be checked for matching aggregation of subregions subregions: list of str list of subregions, defaults to all regions other than `region` components: list of str, default None list of variables, defaults to all sub-categories of `variable` included in `region` but not in any of `subregions` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` kwargs: passed to `np.isclose()` """ # compute aggregate from subregions, return None if no subregions df_subregions = self.aggregate_region(variable, region, subregions, components) if df_subregions is None: return # filter and groupby data, use `pd.Series.align` for matching index rows = self._apply_filters(region=region, variable=variable) df_region, df_subregions = ( _aggregate(self.data[rows], ['region', 'variable']) .align(df_subregions) ) # use `np.isclose` for checking match diff = df_region[~np.isclose(df_region, df_subregions, **kwargs)] if len(diff): msg = ( '`{}` - {} of {} rows are not aggregates of subregions' ) logger().info(msg.format(variable, len(diff), len(df_region))) if exclude_on_fail: self._exclude_on_fail(diff.index.droplevel([2, 3])) col_args = dict(region=region, variable=variable) return IamDataFrame(diff, **col_args).timeseries()
python
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 df_subregions = self.aggregate_region(variable, region, subregions, components) if df_subregions is None: return # filter and groupby data, use `pd.Series.align` for matching index rows = self._apply_filters(region=region, variable=variable) df_region, df_subregions = ( _aggregate(self.data[rows], ['region', 'variable']) .align(df_subregions) ) # use `np.isclose` for checking match diff = df_region[~np.isclose(df_region, df_subregions, **kwargs)] if len(diff): msg = ( '`{}` - {} of {} rows are not aggregates of subregions' ) logger().info(msg.format(variable, len(diff), len(df_region))) if exclude_on_fail: self._exclude_on_fail(diff.index.droplevel([2, 3])) col_args = dict(region=region, variable=variable) return IamDataFrame(diff, **col_args).timeseries()
[ "def", "check_aggregate_region", "(", "self", ",", "variable", ",", "region", "=", "'World'", ",", "subregions", "=", "None", ",", "components", "=", "None", ",", "exclude_on_fail", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# compute aggregate from sub...
Check whether the region timeseries data match the aggregation of components Parameters ---------- variable: str variable to be checked for matching aggregation of subregions region: str, default 'World' region to be checked for matching aggregation of subregions subregions: list of str list of subregions, defaults to all regions other than `region` components: list of str, default None list of variables, defaults to all sub-categories of `variable` included in `region` but not in any of `subregions` exclude_on_fail: boolean, default False flag scenarios failing validation as `exclude: True` kwargs: passed to `np.isclose()`
[ "Check", "whether", "the", "region", "timeseries", "data", "match", "the", "aggregation", "of", "components" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L803-L850
19,529
IAMconsortium/pyam
pyam/core.py
IamDataFrame.check_internal_consistency
def check_internal_consistency(self, **kwargs): """Check whether the database is internally consistent We check that all variables are equal to the sum of their sectoral components and that all the regions add up to the World total. If the check is passed, None is returned, otherwise a dictionary of inconsistent variables is returned. Note: at the moment, this method's regional checking is limited to checking that all the regions sum to the World region. We cannot make this more automatic unless we start to store how the regions relate, see [this issue](https://github.com/IAMconsortium/pyam/issues/106). Parameters ---------- kwargs: passed to `np.isclose()` """ inconsistent_vars = {} for variable in self.variables(): diff_agg = self.check_aggregate(variable, **kwargs) if diff_agg is not None: inconsistent_vars[variable + "-aggregate"] = diff_agg diff_regional = self.check_aggregate_region(variable, **kwargs) if diff_regional is not None: inconsistent_vars[variable + "-regional"] = diff_regional return inconsistent_vars if inconsistent_vars else None
python
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 + "-aggregate"] = diff_agg diff_regional = self.check_aggregate_region(variable, **kwargs) if diff_regional is not None: inconsistent_vars[variable + "-regional"] = diff_regional return inconsistent_vars if inconsistent_vars else None
[ "def", "check_internal_consistency", "(", "self", ",", "*", "*", "kwargs", ")", ":", "inconsistent_vars", "=", "{", "}", "for", "variable", "in", "self", ".", "variables", "(", ")", ":", "diff_agg", "=", "self", ".", "check_aggregate", "(", "variable", ","...
Check whether the database is internally consistent We check that all variables are equal to the sum of their sectoral components and that all the regions add up to the World total. If the check is passed, None is returned, otherwise a dictionary of inconsistent variables is returned. Note: at the moment, this method's regional checking is limited to checking that all the regions sum to the World region. We cannot make this more automatic unless we start to store how the regions relate, see [this issue](https://github.com/IAMconsortium/pyam/issues/106). Parameters ---------- kwargs: passed to `np.isclose()`
[ "Check", "whether", "the", "database", "is", "internally", "consistent" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L860-L888
19,530
IAMconsortium/pyam
pyam/core.py
IamDataFrame._apply_filters
def _apply_filters(self, **filters): """Determine rows to keep in data for given set of filters Parameters ---------- filters: dict dictionary of filters ({col: values}}); uses a pseudo-regexp syntax by default, but accepts `regexp: True` to use regexp directly """ 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=None)` as no filter applied if values is None: continue if col in self.meta.columns: matches = pattern_match(self.meta[col], values, regexp=regexp) cat_idx = self.meta[matches].index keep_col = (self.data[META_IDX].set_index(META_IDX) .index.isin(cat_idx)) elif col == 'variable': level = filters['level'] if 'level' in filters else None keep_col = pattern_match(self.data[col], values, level, regexp) elif col == 'year': _data = self.data[col] if self.time_col is not 'time' \ else self.data['time'].apply(lambda x: x.year) keep_col = years_match(_data, values) elif col == 'month' and self.time_col is 'time': keep_col = month_match(self.data['time'] .apply(lambda x: x.month), values) elif col == 'day' and self.time_col is 'time': if isinstance(values, str): wday = True elif isinstance(values, list) and isinstance(values[0], str): wday = True else: wday = False if wday: days = self.data['time'].apply(lambda x: x.weekday()) else: # ints or list of ints days = self.data['time'].apply(lambda x: x.day) keep_col = day_match(days, values) elif col == 'hour' and self.time_col is 'time': keep_col = hour_match(self.data['time'] .apply(lambda x: x.hour), values) elif col == 'time' and self.time_col is 'time': keep_col = datetime_match(self.data[col], values) elif col == 'level': if 'variable' not in filters.keys(): keep_col = find_depth(self.data['variable'], level=values) else: continue elif col in self.data.columns: keep_col = pattern_match(self.data[col], values, regexp=regexp) else: _raise_filter_error(col) keep &= keep_col return keep
python
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=None)` as no filter applied if values is None: continue if col in self.meta.columns: matches = pattern_match(self.meta[col], values, regexp=regexp) cat_idx = self.meta[matches].index keep_col = (self.data[META_IDX].set_index(META_IDX) .index.isin(cat_idx)) elif col == 'variable': level = filters['level'] if 'level' in filters else None keep_col = pattern_match(self.data[col], values, level, regexp) elif col == 'year': _data = self.data[col] if self.time_col is not 'time' \ else self.data['time'].apply(lambda x: x.year) keep_col = years_match(_data, values) elif col == 'month' and self.time_col is 'time': keep_col = month_match(self.data['time'] .apply(lambda x: x.month), values) elif col == 'day' and self.time_col is 'time': if isinstance(values, str): wday = True elif isinstance(values, list) and isinstance(values[0], str): wday = True else: wday = False if wday: days = self.data['time'].apply(lambda x: x.weekday()) else: # ints or list of ints days = self.data['time'].apply(lambda x: x.day) keep_col = day_match(days, values) elif col == 'hour' and self.time_col is 'time': keep_col = hour_match(self.data['time'] .apply(lambda x: x.hour), values) elif col == 'time' and self.time_col is 'time': keep_col = datetime_match(self.data[col], values) elif col == 'level': if 'variable' not in filters.keys(): keep_col = find_depth(self.data['variable'], level=values) else: continue elif col in self.data.columns: keep_col = pattern_match(self.data[col], values, regexp=regexp) else: _raise_filter_error(col) keep &= keep_col return keep
[ "def", "_apply_filters", "(", "self", ",", "*", "*", "filters", ")", ":", "regexp", "=", "filters", ".", "pop", "(", "'regexp'", ",", "False", ")", "keep", "=", "np", ".", "array", "(", "[", "True", "]", "*", "len", "(", "self", ".", "data", ")",...
Determine rows to keep in data for given set of filters Parameters ---------- filters: dict dictionary of filters ({col: values}}); uses a pseudo-regexp syntax by default, but accepts `regexp: True` to use regexp directly
[ "Determine", "rows", "to", "keep", "in", "data", "for", "given", "set", "of", "filters" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L938-L1013
19,531
IAMconsortium/pyam
pyam/core.py
IamDataFrame.col_apply
def col_apply(self, col, func, *args, **kwargs): """Apply a function to a column Parameters ---------- col: string column in either data or metadata func: functional function to apply """ 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)
python
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)
[ "def", "col_apply", "(", "self", ",", "col", ",", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "col", "in", "self", ".", "data", ":", "self", ".", "data", "[", "col", "]", "=", "self", ".", "data", "[", "col", "]", ".", ...
Apply a function to a column Parameters ---------- col: string column in either data or metadata func: functional function to apply
[ "Apply", "a", "function", "to", "a", "column" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1015-L1028
19,532
IAMconsortium/pyam
pyam/core.py
IamDataFrame._to_file_format
def _to_file_format(self, iamc_index): """Return a dataframe suitable for writing to a file""" df = self.timeseries(iamc_index=iamc_index).reset_index() df = df.rename(columns={c: str(c).title() for c in df.columns}) return df
python
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
[ "def", "_to_file_format", "(", "self", ",", "iamc_index", ")", ":", "df", "=", "self", ".", "timeseries", "(", "iamc_index", "=", "iamc_index", ")", ".", "reset_index", "(", ")", "df", "=", "df", ".", "rename", "(", "columns", "=", "{", "c", ":", "st...
Return a dataframe suitable for writing to a file
[ "Return", "a", "dataframe", "suitable", "for", "writing", "to", "a", "file" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1030-L1034
19,533
IAMconsortium/pyam
pyam/core.py
IamDataFrame.to_csv
def to_csv(self, path, iamc_index=False, **kwargs): """Write timeseries data to a csv file Parameters ---------- path: string file path iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns """ self._to_file_format(iamc_index).to_csv(path, index=False, **kwargs)
python
def to_csv(self, path, iamc_index=False, **kwargs): self._to_file_format(iamc_index).to_csv(path, index=False, **kwargs)
[ "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 Parameters ---------- path: string file path iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns
[ "Write", "timeseries", "data", "to", "a", "csv", "file" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1036-L1047
19,534
IAMconsortium/pyam
pyam/core.py
IamDataFrame.to_excel
def to_excel(self, excel_writer, sheet_name='data', iamc_index=False, **kwargs): """Write timeseries data to Excel format Parameters ---------- excel_writer: string or ExcelWriter object file path or existing ExcelWriter sheet_name: string, default 'data' name of sheet which will contain `IamDataFrame.timeseries()` data iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns """ if not isinstance(excel_writer, pd.ExcelWriter): close = True excel_writer = pd.ExcelWriter(excel_writer) self._to_file_format(iamc_index)\ .to_excel(excel_writer, sheet_name=sheet_name, index=False, **kwargs) if close: excel_writer.close()
python
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(iamc_index)\ .to_excel(excel_writer, sheet_name=sheet_name, index=False, **kwargs) if close: excel_writer.close()
[ "def", "to_excel", "(", "self", ",", "excel_writer", ",", "sheet_name", "=", "'data'", ",", "iamc_index", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "excel_writer", ",", "pd", ".", "ExcelWriter", ")", ":", "close", ...
Write timeseries data to Excel format Parameters ---------- excel_writer: string or ExcelWriter object file path or existing ExcelWriter sheet_name: string, default 'data' name of sheet which will contain `IamDataFrame.timeseries()` data iamc_index: bool, default False if True, use `['model', 'scenario', 'region', 'variable', 'unit']`; else, use all `data` columns
[ "Write", "timeseries", "data", "to", "Excel", "format" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1049-L1070
19,535
IAMconsortium/pyam
pyam/core.py
IamDataFrame.export_metadata
def export_metadata(self, path): """Export metadata to Excel Parameters ---------- path: string path/filename for xlsx file of metadata export """ writer = pd.ExcelWriter(path) write_sheet(writer, 'meta', self.meta, index=True) writer.save()
python
def export_metadata(self, path): writer = pd.ExcelWriter(path) write_sheet(writer, 'meta', self.meta, index=True) writer.save()
[ "def", "export_metadata", "(", "self", ",", "path", ")", ":", "writer", "=", "pd", ".", "ExcelWriter", "(", "path", ")", "write_sheet", "(", "writer", ",", "'meta'", ",", "self", ".", "meta", ",", "index", "=", "True", ")", "writer", ".", "save", "("...
Export metadata to Excel Parameters ---------- path: string path/filename for xlsx file of metadata export
[ "Export", "metadata", "to", "Excel" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1072-L1082
19,536
IAMconsortium/pyam
pyam/core.py
IamDataFrame.load_metadata
def load_metadata(self, path, *args, **kwargs): """Load metadata exported from `pyam.IamDataFrame` instance Parameters ---------- path: string xlsx file with metadata exported from `pyam.IamDataFrame` instance """ 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: xl = pd.ExcelFile(path) if len(xl.sheet_names) > 1 and 'sheet_name' not in kwargs: kwargs['sheet_name'] = 'meta' df = pd.read_excel(path, *args, **kwargs) req_cols = ['model', 'scenario', 'exclude'] if not set(req_cols).issubset(set(df.columns)): e = 'File `{}` does not have required columns ({})!' raise ValueError(e.format(path, req_cols)) # set index, filter to relevant scenarios from imported metadata file df.set_index(META_IDX, inplace=True) idx = self.meta.index.intersection(df.index) n_invalid = len(df) - len(idx) if n_invalid > 0: msg = 'Ignoring {} scenario{} from imported metadata' logger().info(msg.format(n_invalid, 's' if n_invalid > 1 else '')) if idx.empty: raise ValueError('No valid scenarios in imported metadata file!') df = df.loc[idx] # Merge in imported metadata msg = 'Importing metadata for {} scenario{} (for total of {})' logger().info(msg.format(len(df), 's' if len(df) > 1 else '', len(self.meta))) for col in df.columns: self._new_meta_column(col) self.meta[col] = df[col].combine_first(self.meta[col]) # set column `exclude` to bool self.meta.exclude = self.meta.exclude.astype('bool')
python
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: xl = pd.ExcelFile(path) if len(xl.sheet_names) > 1 and 'sheet_name' not in kwargs: kwargs['sheet_name'] = 'meta' df = pd.read_excel(path, *args, **kwargs) req_cols = ['model', 'scenario', 'exclude'] if not set(req_cols).issubset(set(df.columns)): e = 'File `{}` does not have required columns ({})!' raise ValueError(e.format(path, req_cols)) # set index, filter to relevant scenarios from imported metadata file df.set_index(META_IDX, inplace=True) idx = self.meta.index.intersection(df.index) n_invalid = len(df) - len(idx) if n_invalid > 0: msg = 'Ignoring {} scenario{} from imported metadata' logger().info(msg.format(n_invalid, 's' if n_invalid > 1 else '')) if idx.empty: raise ValueError('No valid scenarios in imported metadata file!') df = df.loc[idx] # Merge in imported metadata msg = 'Importing metadata for {} scenario{} (for total of {})' logger().info(msg.format(len(df), 's' if len(df) > 1 else '', len(self.meta))) for col in df.columns: self._new_meta_column(col) self.meta[col] = df[col].combine_first(self.meta[col]) # set column `exclude` to bool self.meta.exclude = self.meta.exclude.astype('bool')
[ "def", "load_metadata", "(", "self", ",", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "\"no metadata file '\"", "+", "path", "+", "\"' ...
Load metadata exported from `pyam.IamDataFrame` instance Parameters ---------- path: string xlsx file with metadata exported from `pyam.IamDataFrame` instance
[ "Load", "metadata", "exported", "from", "pyam", ".", "IamDataFrame", "instance" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1084-L1131
19,537
IAMconsortium/pyam
pyam/core.py
IamDataFrame.line_plot
def line_plot(self, x='year', y='value', **kwargs): """Plot timeseries lines of existing data see pyam.plotting.line_plot() for all available options """ 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_vars = set([x, y]) & set(variables) df = df[df['variable'].isin(keep_vars)] idx = list(set(df.columns) - set(['value'])) df = (df .reset_index() .set_index(idx) .value # df -> series .unstack(level='variable') # keep_vars are columns .rename_axis(None, axis=1) # rm column index name .reset_index() .set_index(META_IDX) ) if x != 'year' and y != 'year': df = df.drop('year', axis=1) # years causes NaNs ax, handles, labels = plotting.line_plot( df.dropna(), x=x, y=y, **kwargs) return ax
python
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_vars = set([x, y]) & set(variables) df = df[df['variable'].isin(keep_vars)] idx = list(set(df.columns) - set(['value'])) df = (df .reset_index() .set_index(idx) .value # df -> series .unstack(level='variable') # keep_vars are columns .rename_axis(None, axis=1) # rm column index name .reset_index() .set_index(META_IDX) ) if x != 'year' and y != 'year': df = df.drop('year', axis=1) # years causes NaNs ax, handles, labels = plotting.line_plot( df.dropna(), x=x, y=y, **kwargs) return ax
[ "def", "line_plot", "(", "self", ",", "x", "=", "'year'", ",", "y", "=", "'value'", ",", "*", "*", "kwargs", ")", ":", "df", "=", "self", ".", "as_pandas", "(", "with_metadata", "=", "kwargs", ")", "# pivot data if asked for explicit variable name", "variabl...
Plot timeseries lines of existing data see pyam.plotting.line_plot() for all available options
[ "Plot", "timeseries", "lines", "of", "existing", "data" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1133-L1160
19,538
IAMconsortium/pyam
pyam/core.py
IamDataFrame.stack_plot
def stack_plot(self, *args, **kwargs): """Plot timeseries stacks of existing data see pyam.plotting.stack_plot() for all available options """ df = self.as_pandas(with_metadata=True) ax = plotting.stack_plot(df, *args, **kwargs) return ax
python
def stack_plot(self, *args, **kwargs): df = self.as_pandas(with_metadata=True) ax = plotting.stack_plot(df, *args, **kwargs) return ax
[ "def", "stack_plot", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "df", "=", "self", ".", "as_pandas", "(", "with_metadata", "=", "True", ")", "ax", "=", "plotting", ".", "stack_plot", "(", "df", ",", "*", "args", ",", "*", "...
Plot timeseries stacks of existing data see pyam.plotting.stack_plot() for all available options
[ "Plot", "timeseries", "stacks", "of", "existing", "data" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1162-L1169
19,539
IAMconsortium/pyam
pyam/core.py
IamDataFrame.scatter
def scatter(self, x, y, **kwargs): """Plot a scatter chart using metadata columns see pyam.plotting.scatter() for all available options """ 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 = self.meta[cols].reset_index() elif xisvar and yisvar: # filter pivot both and rename dfx = ( self .filter(variable=x) .as_pandas(with_metadata=kwargs) .rename(columns={'value': x, 'unit': 'xunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) dfy = ( self .filter(variable=y) .as_pandas(with_metadata=kwargs) .rename(columns={'value': y, 'unit': 'yunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) df = dfx.join(dfy, lsuffix='_left', rsuffix='').reset_index() else: # filter, merge with meta, and rename value column to match var var = x if xisvar else y df = ( self .filter(variable=var) .as_pandas(with_metadata=kwargs) .rename(columns={'value': var}) ) ax = plotting.scatter(df.dropna(), x, y, **kwargs) return ax
python
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 = self.meta[cols].reset_index() elif xisvar and yisvar: # filter pivot both and rename dfx = ( self .filter(variable=x) .as_pandas(with_metadata=kwargs) .rename(columns={'value': x, 'unit': 'xunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) dfy = ( self .filter(variable=y) .as_pandas(with_metadata=kwargs) .rename(columns={'value': y, 'unit': 'yunit'}) .set_index(YEAR_IDX) .drop('variable', axis=1) ) df = dfx.join(dfy, lsuffix='_left', rsuffix='').reset_index() else: # filter, merge with meta, and rename value column to match var var = x if xisvar else y df = ( self .filter(variable=var) .as_pandas(with_metadata=kwargs) .rename(columns={'value': var}) ) ax = plotting.scatter(df.dropna(), x, y, **kwargs) return ax
[ "def", "scatter", "(", "self", ",", "x", ",", "y", ",", "*", "*", "kwargs", ")", ":", "variables", "=", "self", ".", "data", "[", "'variable'", "]", ".", "unique", "(", ")", "xisvar", "=", "x", "in", "variables", "yisvar", "=", "y", "in", "variab...
Plot a scatter chart using metadata columns see pyam.plotting.scatter() for all available options
[ "Plot", "a", "scatter", "chart", "using", "metadata", "columns" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/core.py#L1189-L1229
19,540
IAMconsortium/pyam
pyam/run_control.py
RunControl.update
def update(self, rc): """Add additional run control parameters Parameters ---------- rc : string, file, dictionary, optional a path to a YAML file, a file handle for a YAML file, or a dictionary describing run control configuration """ rc = self._load_yaml(rc) self.store = _recursive_update(self.store, rc)
python
def update(self, rc): rc = self._load_yaml(rc) self.store = _recursive_update(self.store, rc)
[ "def", "update", "(", "self", ",", "rc", ")", ":", "rc", "=", "self", ".", "_load_yaml", "(", "rc", ")", "self", ".", "store", "=", "_recursive_update", "(", "self", ".", "store", ",", "rc", ")" ]
Add additional run control parameters Parameters ---------- rc : string, file, dictionary, optional a path to a YAML file, a file handle for a YAML file, or a dictionary describing run control configuration
[ "Add", "additional", "run", "control", "parameters" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/run_control.py#L75-L85
19,541
IAMconsortium/pyam
pyam/run_control.py
RunControl.recursive_update
def recursive_update(self, k, d): """Recursively update a top-level option in the run control Parameters ---------- k : string the top-level key d : dictionary or similar the dictionary to use for updating """ u = self.__getitem__(k) self.store[k] = _recursive_update(u, d)
python
def recursive_update(self, k, d): u = self.__getitem__(k) self.store[k] = _recursive_update(u, d)
[ "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 Parameters ---------- k : string the top-level key d : dictionary or similar the dictionary to use for updating
[ "Recursively", "update", "a", "top", "-", "level", "option", "in", "the", "run", "control" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/run_control.py#L125-L136
19,542
IAMconsortium/pyam
pyam/iiasa.py
Connection.available_metadata
def available_metadata(self): """ List all scenario metadata indicators available in the connected data source """ 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']
python
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']
[ "def", "available_metadata", "(", "self", ")", ":", "url", "=", "self", ".", "base_url", "+", "'metadata/types'", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "self", ".", "auth", "(", ")", ")", "}", "r", "=", "requests...
List all scenario metadata indicators available in the connected data source
[ "List", "all", "scenario", "metadata", "indicators", "available", "in", "the", "connected", "data", "source" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L87-L95
19,543
IAMconsortium/pyam
pyam/iiasa.py
Connection.metadata
def metadata(self, default=True): """ Metadata of scenarios in the connected data source Parameter --------- default : bool, optional, default True Return *only* the default version of each Scenario. Any (`model`, `scenario`) without a default version is omitted. If :obj:`False`, return all versions. """ # 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={}&includeMetadata=true' url = self.base_url + add_url.format(default) headers = {'Authorization': 'Bearer {}'.format(self.auth())} r = requests.get(url, headers=headers) df = pd.read_json(r.content, orient='records') def extract(row): return ( pd.concat([row[['model', 'scenario']], pd.Series(row.metadata)]) .to_frame() .T .set_index(['model', 'scenario']) ) return pd.concat([extract(row) for idx, row in df.iterrows()], sort=False).reset_index()
python
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={}&includeMetadata=true' url = self.base_url + add_url.format(default) headers = {'Authorization': 'Bearer {}'.format(self.auth())} r = requests.get(url, headers=headers) df = pd.read_json(r.content, orient='records') def extract(row): return ( pd.concat([row[['model', 'scenario']], pd.Series(row.metadata)]) .to_frame() .T .set_index(['model', 'scenario']) ) return pd.concat([extract(row) for idx, row in df.iterrows()], sort=False).reset_index()
[ "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", "=", "'r...
Metadata of scenarios in the connected data source Parameter --------- default : bool, optional, default True Return *only* the default version of each Scenario. Any (`model`, `scenario`) without a default version is omitted. If :obj:`False`, return all versions.
[ "Metadata", "of", "scenarios", "in", "the", "connected", "data", "source" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L98-L128
19,544
IAMconsortium/pyam
pyam/iiasa.py
Connection.variables
def variables(self): """All variables in the connected data source""" 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'].unique(), name='variable')
python
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'].unique(), name='variable')
[ "def", "variables", "(", "self", ")", ":", "url", "=", "self", ".", "base_url", "+", "'ts'", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "self", ".", "auth", "(", ")", ")", "}", "r", "=", "requests", ".", "get", ...
All variables in the connected data source
[ "All", "variables", "in", "the", "connected", "data", "source" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L141-L147
19,545
IAMconsortium/pyam
pyam/iiasa.py
Connection.query
def query(self, **kwargs): """ Query the data source, subselecting data. Available keyword arguments include - model - scenario - region - variable Example ------- ``` Connection.query(model='MESSAGE', scenario='SSP2*', variable=['Emissions|CO2', 'Primary Energy']) ``` """ headers = { 'Authorization': 'Bearer {}'.format(self.auth()), 'Content-Type': 'application/json', } data = json.dumps(self._query_post_data(**kwargs)) url = self.base_url + 'runs/bulk/ts' r = requests.post(url, headers=headers, data=data) # refactor returned json object to be castable to an IamDataFrame df = ( pd.read_json(r.content, orient='records') .drop(columns='runId') .rename(columns={'time': 'subannual'}) ) # check if returned dataframe has subannual disaggregation, drop if not if pd.Series([i in [-1, 'year'] for i in df.subannual]).all(): df.drop(columns='subannual', inplace=True) # check if there are multiple version for any model/scenario lst = ( df[META_IDX + ['version']].drop_duplicates() .groupby(META_IDX).count().version ) if max(lst) > 1: raise ValueError('multiple versions for {}'.format( lst[lst > 1].index.to_list())) df.drop(columns='version', inplace=True) return df
python
def query(self, **kwargs): headers = { 'Authorization': 'Bearer {}'.format(self.auth()), 'Content-Type': 'application/json', } data = json.dumps(self._query_post_data(**kwargs)) url = self.base_url + 'runs/bulk/ts' r = requests.post(url, headers=headers, data=data) # refactor returned json object to be castable to an IamDataFrame df = ( pd.read_json(r.content, orient='records') .drop(columns='runId') .rename(columns={'time': 'subannual'}) ) # check if returned dataframe has subannual disaggregation, drop if not if pd.Series([i in [-1, 'year'] for i in df.subannual]).all(): df.drop(columns='subannual', inplace=True) # check if there are multiple version for any model/scenario lst = ( df[META_IDX + ['version']].drop_duplicates() .groupby(META_IDX).count().version ) if max(lst) > 1: raise ValueError('multiple versions for {}'.format( lst[lst > 1].index.to_list())) df.drop(columns='version', inplace=True) return df
[ "def", "query", "(", "self", ",", "*", "*", "kwargs", ")", ":", "headers", "=", "{", "'Authorization'", ":", "'Bearer {}'", ".", "format", "(", "self", ".", "auth", "(", ")", ")", ",", "'Content-Type'", ":", "'application/json'", ",", "}", "data", "=",...
Query the data source, subselecting data. Available keyword arguments include - model - scenario - region - variable Example ------- ``` Connection.query(model='MESSAGE', scenario='SSP2*', variable=['Emissions|CO2', 'Primary Energy']) ```
[ "Query", "the", "data", "source", "subselecting", "data", ".", "Available", "keyword", "arguments", "include" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/iiasa.py#L209-L253
19,546
IAMconsortium/pyam
pyam/statistics.py
Statistics.reindex
def reindex(self, copy=True): """Reindex the summary statistics dataframe""" 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 not None: ret.stats = ret.stats.reindex(index=ret.rows, level=ret.idx_depth) ret.stats = ret.stats.reindex(columns=ret._headers, level=0) ret.stats = ret.stats.reindex(columns=ret._subheaders, level=1) ret.stats = ret.stats.reindex(columns=ret._describe_cols, level=2) if copy: return ret
python
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 not None: ret.stats = ret.stats.reindex(index=ret.rows, level=ret.idx_depth) ret.stats = ret.stats.reindex(columns=ret._headers, level=0) ret.stats = ret.stats.reindex(columns=ret._subheaders, level=1) ret.stats = ret.stats.reindex(columns=ret._describe_cols, level=2) if copy: return ret
[ "def", "reindex", "(", "self", ",", "copy", "=", "True", ")", ":", "ret", "=", "deepcopy", "(", "self", ")", "if", "copy", "else", "self", "ret", ".", "stats", "=", "ret", ".", "stats", ".", "reindex", "(", "index", "=", "ret", ".", "_idx", ",", ...
Reindex the summary statistics dataframe
[ "Reindex", "the", "summary", "statistics", "dataframe" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/statistics.py#L198-L213
19,547
IAMconsortium/pyam
pyam/statistics.py
Statistics.summarize
def summarize(self, center='mean', fullrange=None, interquartile=None, custom_format='{:.2f}'): """Format the compiled statistics to a concise string output Parameter --------- center : str, default `mean` what to return as 'center' of the summary: `mean`, `50%`, `median` fullrange : bool, default None return full range of data if True or `fullrange`, `interquartile` and `format_spec` are None interquartile : bool, default None return interquartile range if True custom_format : formatting specifications """ # call `reindex()` to reorder index and columns self.reindex(copy=False) center = 'median' if center == '50%' else center if fullrange is None and interquartile is None: fullrange = True return self.stats.apply(format_rows, center=center, fullrange=fullrange, interquartile=interquartile, custom_format=custom_format, axis=1, raw=False)
python
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 if fullrange is None and interquartile is None: fullrange = True return self.stats.apply(format_rows, center=center, fullrange=fullrange, interquartile=interquartile, custom_format=custom_format, axis=1, raw=False)
[ "def", "summarize", "(", "self", ",", "center", "=", "'mean'", ",", "fullrange", "=", "None", ",", "interquartile", "=", "None", ",", "custom_format", "=", "'{:.2f}'", ")", ":", "# call `reindex()` to reorder index and columns", "self", ".", "reindex", "(", "cop...
Format the compiled statistics to a concise string output Parameter --------- center : str, default `mean` what to return as 'center' of the summary: `mean`, `50%`, `median` fullrange : bool, default None return full range of data if True or `fullrange`, `interquartile` and `format_spec` are None interquartile : bool, default None return interquartile range if True custom_format : formatting specifications
[ "Format", "the", "compiled", "statistics", "to", "a", "concise", "string", "output" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/statistics.py#L215-L240
19,548
IAMconsortium/pyam
pyam/plotting.py
reset_default_props
def reset_default_props(**kwargs): """Reset properties to initial cycle point""" 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]), 'marker': itertools.cycle(['o', 'x', '.', '+', '*']), 'linestyle': itertools.cycle(['-', '--', '-.', ':']), }
python
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]), 'marker': itertools.cycle(['o', 'x', '.', '+', '*']), 'linestyle': itertools.cycle(['-', '--', '-.', ':']), }
[ "def", "reset_default_props", "(", "*", "*", "kwargs", ")", ":", "global", "_DEFAULT_PROPS", "pcycle", "=", "plt", ".", "rcParams", "[", "'axes.prop_cycle'", "]", "_DEFAULT_PROPS", "=", "{", "'color'", ":", "itertools", ".", "cycle", "(", "_get_standard_colors",...
Reset properties to initial cycle point
[ "Reset", "properties", "to", "initial", "cycle", "point" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L75-L84
19,549
IAMconsortium/pyam
pyam/plotting.py
default_props
def default_props(reset=False, **kwargs): """Return current default properties Parameters ---------- reset : bool if True, reset properties and return default: False """ global _DEFAULT_PROPS if _DEFAULT_PROPS is None or reset: reset_default_props(**kwargs) return _DEFAULT_PROPS
python
def default_props(reset=False, **kwargs): global _DEFAULT_PROPS if _DEFAULT_PROPS is None or reset: reset_default_props(**kwargs) return _DEFAULT_PROPS
[ "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 Parameters ---------- reset : bool if True, reset properties and return default: False
[ "Return", "current", "default", "properties" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L87-L99
19,550
IAMconsortium/pyam
pyam/plotting.py
assign_style_props
def assign_style_props(df, color=None, marker=None, linestyle=None, cmap=None): """Assign the style properties for a plot Parameters ---------- df : pd.DataFrame data to be used for style properties """ if color is None and cmap is not None: raise ValueError('`cmap` must be provided with the `color` argument') # determine color, marker, and linestyle for each line n = len(df[color].unique()) if color in df.columns else \ len(df[list(set(df.columns) & set(IAMC_IDX))].drop_duplicates()) defaults = default_props(reset=True, num_colors=n, colormap=cmap) props = {} rc = run_control() kinds = [('color', color), ('marker', marker), ('linestyle', linestyle)] for kind, var in kinds: rc_has_kind = kind in rc if var in df.columns: rc_has_var = rc_has_kind and var in rc[kind] props_for_kind = {} for val in df[var].unique(): if rc_has_var and val in rc[kind][var]: props_for_kind[val] = rc[kind][var][val] # cycle any way to keep defaults the same next(defaults[kind]) else: props_for_kind[val] = next(defaults[kind]) props[kind] = props_for_kind # update for special properties only if they exist in props if 'color' in props: d = props['color'] values = list(d.values()) # find if any colors in our properties corresponds with special colors # we know about overlap_idx = np.in1d(values, list(PYAM_COLORS.keys())) if overlap_idx.any(): # some exist in our special set keys = np.array(list(d.keys()))[overlap_idx] values = np.array(values)[overlap_idx] # translate each from pyam name, like AR6-SSP2-45 to proper color # designation for k, v in zip(keys, values): d[k] = PYAM_COLORS[v] # replace props with updated dict without special colors props['color'] = d return props
python
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 for each line n = len(df[color].unique()) if color in df.columns else \ len(df[list(set(df.columns) & set(IAMC_IDX))].drop_duplicates()) defaults = default_props(reset=True, num_colors=n, colormap=cmap) props = {} rc = run_control() kinds = [('color', color), ('marker', marker), ('linestyle', linestyle)] for kind, var in kinds: rc_has_kind = kind in rc if var in df.columns: rc_has_var = rc_has_kind and var in rc[kind] props_for_kind = {} for val in df[var].unique(): if rc_has_var and val in rc[kind][var]: props_for_kind[val] = rc[kind][var][val] # cycle any way to keep defaults the same next(defaults[kind]) else: props_for_kind[val] = next(defaults[kind]) props[kind] = props_for_kind # update for special properties only if they exist in props if 'color' in props: d = props['color'] values = list(d.values()) # find if any colors in our properties corresponds with special colors # we know about overlap_idx = np.in1d(values, list(PYAM_COLORS.keys())) if overlap_idx.any(): # some exist in our special set keys = np.array(list(d.keys()))[overlap_idx] values = np.array(values)[overlap_idx] # translate each from pyam name, like AR6-SSP2-45 to proper color # designation for k, v in zip(keys, values): d[k] = PYAM_COLORS[v] # replace props with updated dict without special colors props['color'] = d return props
[ "def", "assign_style_props", "(", "df", ",", "color", "=", "None", ",", "marker", "=", "None", ",", "linestyle", "=", "None", ",", "cmap", "=", "None", ")", ":", "if", "color", "is", "None", "and", "cmap", "is", "not", "None", ":", "raise", "ValueErr...
Assign the style properties for a plot Parameters ---------- df : pd.DataFrame data to be used for style properties
[ "Assign", "the", "style", "properties", "for", "a", "plot" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L102-L155
19,551
IAMconsortium/pyam
pyam/plotting.py
reshape_line_plot
def reshape_line_plot(df, x, y): """Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers. """ 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
python
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
[ "def", "reshape_line_plot", "(", "df", ",", "x", ",", "y", ")", ":", "idx", "=", "list", "(", "df", ".", "columns", ".", "drop", "(", "y", ")", ")", "if", "df", ".", "duplicated", "(", "idx", ")", ".", "any", "(", ")", ":", "warnings", ".", "...
Reshape data from long form to "line plot form". Line plot form has x value as the index with one column for each line. Each column has data points as values and all metadata as column headers.
[ "Reshape", "data", "from", "long", "form", "to", "line", "plot", "form", "." ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L158-L169
19,552
IAMconsortium/pyam
pyam/plotting.py
reshape_bar_plot
def reshape_bar_plot(df, x, y, bars): """Reshape data from long form to "bar plot form". Bar plot form has x value as the index with one column for bar grouping. Table values come from y values. """ 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
python
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
[ "def", "reshape_bar_plot", "(", "df", ",", "x", ",", "y", ",", "bars", ")", ":", "idx", "=", "[", "bars", ",", "x", "]", "if", "df", ".", "duplicated", "(", "idx", ")", ".", "any", "(", ")", ":", "warnings", ".", "warn", "(", "'Duplicated index f...
Reshape data from long form to "bar plot form". Bar plot form has x value as the index with one column for bar grouping. Table values come from y values.
[ "Reshape", "data", "from", "long", "form", "to", "bar", "plot", "form", "." ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L172-L183
19,553
IAMconsortium/pyam
pyam/plotting.py
read_shapefile
def read_shapefile(fname, region_col=None, **kwargs): """Read a shapefile for use in regional plots. Shapefiles must have a column denoted as "region". Parameters ---------- fname : string path to shapefile to be read by geopandas region_col : string, default None if provided, rename a column in the shapefile to "region" """ 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') gdf['region'] = gdf['region'].str.upper() return gdf
python
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') gdf['region'] = gdf['region'].str.upper() return gdf
[ "def", "read_shapefile", "(", "fname", ",", "region_col", "=", "None", ",", "*", "*", "kwargs", ")", ":", "gdf", "=", "gpd", ".", "read_file", "(", "fname", ",", "*", "*", "kwargs", ")", "if", "region_col", "is", "not", "None", ":", "gdf", "=", "gd...
Read a shapefile for use in regional plots. Shapefiles must have a column denoted as "region". Parameters ---------- fname : string path to shapefile to be read by geopandas region_col : string, default None if provided, rename a column in the shapefile to "region"
[ "Read", "a", "shapefile", "for", "use", "in", "regional", "plots", ".", "Shapefiles", "must", "have", "a", "column", "denoted", "as", "region", "." ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L188-L205
19,554
IAMconsortium/pyam
pyam/plotting.py
add_net_values_to_bar_plot
def add_net_values_to_bar_plot(axs, color='k'): """Add net values next to an existing vertical stacked bar chart Parameters ---------- axs : matplotlib.Axes or list thereof color : str, optional, default: black the color of the bars to add """ 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.add_patch(rect)
python
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.add_patch(rect)
[ "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", "(", ...
Add net values next to an existing vertical stacked bar chart Parameters ---------- axs : matplotlib.Axes or list thereof color : str, optional, default: black the color of the bars to add
[ "Add", "net", "values", "next", "to", "an", "existing", "vertical", "stacked", "bar", "chart" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L650-L664
19,555
IAMconsortium/pyam
pyam/plotting.py
scatter
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): """Plot data as a scatter chart. Parameters ---------- df : pd.DataFrame Data to plot as a long-form data frame x : str column to be plotted on the x-axis y : str column to be plotted on the y-axis ax : matplotlib.Axes, optional legend : bool, optional Include a legend (`None` displays legend only if less than 13 entries) default: None title : bool or string, optional Display a custom title. color : string, optional A valid matplotlib color or column name. If a column name, common values will be provided the same color. default: None marker : string A valid matplotlib marker or column name. If a column name, common values will be provided the same marker. default: 'o' linestyle : string, optional A valid matplotlib linestyle or column name. If a column name, common values will be provided the same linestyle. default: None cmap : string, optional A colormap to use. default: None groupby : list-like, optional Data grouping for plotting. default: ['model', 'scenario'] with_lines : bool, optional Make the scatter plot with lines connecting common data. default: False kwargs : Additional arguments to pass to the pd.DataFrame.plot() function """ if ax is None: fig, ax = plt.subplots() # assign styling properties props = assign_style_props(df, color=color, marker=marker, linestyle=linestyle, cmap=cmap) # group data groups = df.groupby(groupby) # loop over grouped dataframe, plot data legend_data = [] for name, group in groups: pargs = {} labels = [] for key, kind, var in [('c', 'color', color), ('marker', 'marker', marker), ('linestyle', 'linestyle', linestyle)]: if kind in props: label = group[var].values[0] pargs[key] = props[kind][group[var].values[0]] labels.append(repr(label).lstrip("u'").strip("'")) else: pargs[key] = var if len(labels) > 0: legend_data.append(' '.join(labels)) else: legend_data.append(' '.join(name)) kwargs.update(pargs) if with_lines: ax.plot(group[x], group[y], **kwargs) else: kwargs.pop('linestyle') # scatter() can't take a linestyle ax.scatter(group[x], group[y], **kwargs) # build legend handles and labels handles, labels = ax.get_legend_handles_labels() if legend_data != [''] * len(legend_data): labels = sorted(list(set(tuple(legend_data)))) idxs = [legend_data.index(d) for d in labels] handles = [handles[i] for i in idxs] if legend is None and len(labels) < 13 or legend is not False: _add_legend(ax, handles, labels, legend) # add labels and title ax.set_xlabel(x) ax.set_ylabel(y) if title: ax.set_title(title) return ax
python
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 properties props = assign_style_props(df, color=color, marker=marker, linestyle=linestyle, cmap=cmap) # group data groups = df.groupby(groupby) # loop over grouped dataframe, plot data legend_data = [] for name, group in groups: pargs = {} labels = [] for key, kind, var in [('c', 'color', color), ('marker', 'marker', marker), ('linestyle', 'linestyle', linestyle)]: if kind in props: label = group[var].values[0] pargs[key] = props[kind][group[var].values[0]] labels.append(repr(label).lstrip("u'").strip("'")) else: pargs[key] = var if len(labels) > 0: legend_data.append(' '.join(labels)) else: legend_data.append(' '.join(name)) kwargs.update(pargs) if with_lines: ax.plot(group[x], group[y], **kwargs) else: kwargs.pop('linestyle') # scatter() can't take a linestyle ax.scatter(group[x], group[y], **kwargs) # build legend handles and labels handles, labels = ax.get_legend_handles_labels() if legend_data != [''] * len(legend_data): labels = sorted(list(set(tuple(legend_data)))) idxs = [legend_data.index(d) for d in labels] handles = [handles[i] for i in idxs] if legend is None and len(labels) < 13 or legend is not False: _add_legend(ax, handles, labels, legend) # add labels and title ax.set_xlabel(x) ax.set_ylabel(y) if title: ax.set_title(title) return ax
[ "def", "scatter", "(", "df", ",", "x", ",", "y", ",", "ax", "=", "None", ",", "legend", "=", "None", ",", "title", "=", "None", ",", "color", "=", "None", ",", "marker", "=", "'o'", ",", "linestyle", "=", "None", ",", "cmap", "=", "None", ",", ...
Plot data as a scatter chart. Parameters ---------- df : pd.DataFrame Data to plot as a long-form data frame x : str column to be plotted on the x-axis y : str column to be plotted on the y-axis ax : matplotlib.Axes, optional legend : bool, optional Include a legend (`None` displays legend only if less than 13 entries) default: None title : bool or string, optional Display a custom title. color : string, optional A valid matplotlib color or column name. If a column name, common values will be provided the same color. default: None marker : string A valid matplotlib marker or column name. If a column name, common values will be provided the same marker. default: 'o' linestyle : string, optional A valid matplotlib linestyle or column name. If a column name, common values will be provided the same linestyle. default: None cmap : string, optional A colormap to use. default: None groupby : list-like, optional Data grouping for plotting. default: ['model', 'scenario'] with_lines : bool, optional Make the scatter plot with lines connecting common data. default: False kwargs : Additional arguments to pass to the pd.DataFrame.plot() function
[ "Plot", "data", "as", "a", "scatter", "chart", "." ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/plotting.py#L667-L760
19,556
IAMconsortium/pyam
pyam/logger.py
logger
def logger(): """Access global logger""" global _LOGGER if _LOGGER is None: logging.basicConfig() _LOGGER = logging.getLogger() _LOGGER.setLevel('INFO') return _LOGGER
python
def logger(): global _LOGGER if _LOGGER is None: logging.basicConfig() _LOGGER = logging.getLogger() _LOGGER.setLevel('INFO') return _LOGGER
[ "def", "logger", "(", ")", ":", "global", "_LOGGER", "if", "_LOGGER", "is", "None", ":", "logging", ".", "basicConfig", "(", ")", "_LOGGER", "=", "logging", ".", "getLogger", "(", ")", "_LOGGER", ".", "setLevel", "(", "'INFO'", ")", "return", "_LOGGER" ]
Access global logger
[ "Access", "global", "logger" ]
4077929ca6e7be63a0e3ecf882c5f1da97b287bf
https://github.com/IAMconsortium/pyam/blob/4077929ca6e7be63a0e3ecf882c5f1da97b287bf/pyam/logger.py#L7-L14
19,557
linode/linode_api4-python
linode_api4/objects/nodebalancer.py
NodeBalancerConfig.nodes
def nodes(self): """ This is a special derived_class relationship because NodeBalancerNode is the only api object that requires two parent_ids """ if not hasattr(self, '_nodes'): base_url = "{}/{}".format(NodeBalancerConfig.api_endpoint, NodeBalancerNode.derived_url_path) result = self._client._get_objects(base_url, NodeBalancerNode, model=self, parent_id=(self.id, self.nodebalancer_id)) self._set('_nodes', result) return self._nodes
python
def nodes(self): if not hasattr(self, '_nodes'): base_url = "{}/{}".format(NodeBalancerConfig.api_endpoint, NodeBalancerNode.derived_url_path) result = self._client._get_objects(base_url, NodeBalancerNode, model=self, parent_id=(self.id, self.nodebalancer_id)) self._set('_nodes', result) return self._nodes
[ "def", "nodes", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_nodes'", ")", ":", "base_url", "=", "\"{}/{}\"", ".", "format", "(", "NodeBalancerConfig", ".", "api_endpoint", ",", "NodeBalancerNode", ".", "derived_url_path", ")", "result...
This is a special derived_class relationship because NodeBalancerNode is the only api object that requires two parent_ids
[ "This", "is", "a", "special", "derived_class", "relationship", "because", "NodeBalancerNode", "is", "the", "only", "api", "object", "that", "requires", "two", "parent_ids" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/nodebalancer.py#L73-L84
19,558
linode/linode_api4-python
linode_api4/objects/volume.py
Volume.attach
def attach(self, to_linode, config=None): """ Attaches this Volume to the given Linode """ result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self, data={ "linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode, "config": None if not config else config.id if issubclass(type(config), Base) else config, }) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when attaching volume!', json=result) self._populate(result) return True
python
def attach(self, to_linode, config=None): result = self._client.post('{}/attach'.format(Volume.api_endpoint), model=self, data={ "linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode, "config": None if not config else config.id if issubclass(type(config), Base) else config, }) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when attaching volume!', json=result) self._populate(result) return True
[ "def", "attach", "(", "self", ",", "to_linode", ",", "config", "=", "None", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "'{}/attach'", ".", "format", "(", "Volume", ".", "api_endpoint", ")", ",", "model", "=", "self", ",", "dat...
Attaches this Volume to the given Linode
[ "Attaches", "this", "Volume", "to", "the", "given", "Linode" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/volume.py#L22-L36
19,559
linode/linode_api4-python
linode_api4/objects/volume.py
Volume.detach
def detach(self): """ Detaches this Volume if it is attached """ self._client.post('{}/detach'.format(Volume.api_endpoint), model=self) return True
python
def detach(self): self._client.post('{}/detach'.format(Volume.api_endpoint), model=self) return True
[ "def", "detach", "(", "self", ")", ":", "self", ".", "_client", ".", "post", "(", "'{}/detach'", ".", "format", "(", "Volume", ".", "api_endpoint", ")", ",", "model", "=", "self", ")", "return", "True" ]
Detaches this Volume if it is attached
[ "Detaches", "this", "Volume", "if", "it", "is", "attached" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/volume.py#L38-L44
19,560
linode/linode_api4-python
linode_api4/objects/volume.py
Volume.resize
def resize(self, size): """ Resizes this Volume """ result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self, data={ "size": size })) self._populate(result.json) return True
python
def resize(self, size): result = self._client.post('{}/resize'.format(Volume.api_endpoint, model=self, data={ "size": size })) self._populate(result.json) return True
[ "def", "resize", "(", "self", ",", "size", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "'{}/resize'", ".", "format", "(", "Volume", ".", "api_endpoint", ",", "model", "=", "self", ",", "data", "=", "{", "\"size\"", ":", "size",...
Resizes this Volume
[ "Resizes", "this", "Volume" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/volume.py#L46-L55
19,561
linode/linode_api4-python
linode_api4/objects/volume.py
Volume.clone
def clone(self, label): """ Clones this volume to a new volume in the same region with the given label :param label: The label for the new volume. :returns: The new volume object. """ result = self._client.post('{}/clone'.format(Volume.api_endpoint), model=self, data={'label': label}) if not 'id' in result: raise UnexpectedResponseError('Unexpected response cloning volume!') return Volume(self._client, result['id'], result)
python
def clone(self, label): result = self._client.post('{}/clone'.format(Volume.api_endpoint), model=self, data={'label': label}) if not 'id' in result: raise UnexpectedResponseError('Unexpected response cloning volume!') return Volume(self._client, result['id'], result)
[ "def", "clone", "(", "self", ",", "label", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "'{}/clone'", ".", "format", "(", "Volume", ".", "api_endpoint", ")", ",", "model", "=", "self", ",", "data", "=", "{", "'label'", ":", "l...
Clones this volume to a new volume in the same region with the given label :param label: The label for the new volume. :returns: The new volume object.
[ "Clones", "this", "volume", "to", "a", "new", "volume", "in", "the", "same", "region", "with", "the", "given", "label" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/volume.py#L57-L71
19,562
linode/linode_api4-python
linode_api4/objects/tag.py
Tag._get_raw_objects
def _get_raw_objects(self): """ Helper function to populate the first page of raw objects for this tag. This has the side effect of creating the ``_raw_objects`` attribute of this object. """ if not hasattr(self, '_raw_objects'): result = self._client.get(type(self).api_endpoint, model=self) # I want to cache this to avoid making duplicate requests, but I don't # want it in the __init__ self._raw_objects = result # pylint: disable=attribute-defined-outside-init return self._raw_objects
python
def _get_raw_objects(self): if not hasattr(self, '_raw_objects'): result = self._client.get(type(self).api_endpoint, model=self) # I want to cache this to avoid making duplicate requests, but I don't # want it in the __init__ self._raw_objects = result # pylint: disable=attribute-defined-outside-init return self._raw_objects
[ "def", "_get_raw_objects", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_raw_objects'", ")", ":", "result", "=", "self", ".", "_client", ".", "get", "(", "type", "(", "self", ")", ".", "api_endpoint", ",", "model", "=", "self", ...
Helper function to populate the first page of raw objects for this tag. This has the side effect of creating the ``_raw_objects`` attribute of this object.
[ "Helper", "function", "to", "populate", "the", "first", "page", "of", "raw", "objects", "for", "this", "tag", ".", "This", "has", "the", "side", "effect", "of", "creating", "the", "_raw_objects", "attribute", "of", "this", "object", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/tag.py#L32-L45
19,563
linode/linode_api4-python
linode_api4/objects/tag.py
Tag.objects
def objects(self): """ Returns a list of objects with this Tag. This list may contain any taggable object type. """ data = self._get_raw_objects() return PaginatedList.make_paginated_list(data, self._client, TaggedObjectProxy, page_url=type(self).api_endpoint.format(**vars(self)))
python
def objects(self): data = self._get_raw_objects() return PaginatedList.make_paginated_list(data, self._client, TaggedObjectProxy, page_url=type(self).api_endpoint.format(**vars(self)))
[ "def", "objects", "(", "self", ")", ":", "data", "=", "self", ".", "_get_raw_objects", "(", ")", "return", "PaginatedList", ".", "make_paginated_list", "(", "data", ",", "self", ".", "_client", ",", "TaggedObjectProxy", ",", "page_url", "=", "type", "(", "...
Returns a list of objects with this Tag. This list may contain any taggable object type.
[ "Returns", "a", "list", "of", "objects", "with", "this", "Tag", ".", "This", "list", "may", "contain", "any", "taggable", "object", "type", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/tag.py#L60-L68
19,564
linode/linode_api4-python
linode_api4/objects/tag.py
TaggedObjectProxy.make_instance
def make_instance(cls, id, client, parent_id=None, json=None): """ Overrides Base's ``make_instance`` to allow dynamic creation of objects based on the defined type in the response json. :param cls: The class this was called on :param id: The id of the instance to create :param client: The client to use for this instance :param parent_id: The parent id for derived classes :param json: The JSON to populate the instance with :returns: A new instance of this type, populated with json """ make_cls = CLASS_MAP.get(id) # in this case, ID is coming in as the type if make_cls is None: # we don't recognize this entity type - do nothing? return None # discard the envelope real_json = json['data'] real_id = real_json['id'] # make the real object type return Base.make(real_id, client, make_cls, parent_id=None, json=real_json)
python
def make_instance(cls, id, client, parent_id=None, json=None): make_cls = CLASS_MAP.get(id) # in this case, ID is coming in as the type if make_cls is None: # we don't recognize this entity type - do nothing? return None # discard the envelope real_json = json['data'] real_id = real_json['id'] # make the real object type return Base.make(real_id, client, make_cls, parent_id=None, json=real_json)
[ "def", "make_instance", "(", "cls", ",", "id", ",", "client", ",", "parent_id", "=", "None", ",", "json", "=", "None", ")", ":", "make_cls", "=", "CLASS_MAP", ".", "get", "(", "id", ")", "# in this case, ID is coming in as the type", "if", "make_cls", "is", ...
Overrides Base's ``make_instance`` to allow dynamic creation of objects based on the defined type in the response json. :param cls: The class this was called on :param id: The id of the instance to create :param client: The client to use for this instance :param parent_id: The parent id for derived classes :param json: The JSON to populate the instance with :returns: A new instance of this type, populated with json
[ "Overrides", "Base", "s", "make_instance", "to", "allow", "dynamic", "creation", "of", "objects", "based", "on", "the", "defined", "type", "in", "the", "response", "json", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/tag.py#L89-L113
19,565
linode/linode_api4-python
linode_api4/objects/linode.py
Disk.resize
def resize(self, new_size): """ Resizes this disk. The Linode Instance this disk belongs to must have sufficient space available to accommodate the new size, and must be offline. **NOTE** If resizing a disk down, the filesystem on the disk must still fit on the new disk size. You may need to resize the filesystem on the disk first before performing this action. :param new_size: The intended new size of the disk, in MB :type new_size: int :returns: True if the resize was initiated successfully. :rtype: bool """ self._client.post('{}/resize'.format(Disk.api_endpoint), model=self, data={"size": new_size}) return True
python
def resize(self, new_size): self._client.post('{}/resize'.format(Disk.api_endpoint), model=self, data={"size": new_size}) return True
[ "def", "resize", "(", "self", ",", "new_size", ")", ":", "self", ".", "_client", ".", "post", "(", "'{}/resize'", ".", "format", "(", "Disk", ".", "api_endpoint", ")", ",", "model", "=", "self", ",", "data", "=", "{", "\"size\"", ":", "new_size", "}"...
Resizes this disk. The Linode Instance this disk belongs to must have sufficient space available to accommodate the new size, and must be offline. **NOTE** If resizing a disk down, the filesystem on the disk must still fit on the new disk size. You may need to resize the filesystem on the disk first before performing this action. :param new_size: The intended new size of the disk, in MB :type new_size: int :returns: True if the resize was initiated successfully. :rtype: bool
[ "Resizes", "this", "disk", ".", "The", "Linode", "Instance", "this", "disk", "belongs", "to", "must", "have", "sufficient", "space", "available", "to", "accommodate", "the", "new", "size", "and", "must", "be", "offline", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L98-L116
19,566
linode/linode_api4-python
linode_api4/objects/linode.py
Config._populate
def _populate(self, json): """ Map devices more nicely while populating. """ from .volume import Volume DerivedBase._populate(self, json) devices = {} for device_index, device in json['devices'].items(): if not device: devices[device_index] = None continue dev = None if 'disk_id' in device and device['disk_id']: # this is a disk dev = Disk.make_instance(device['disk_id'], self._client, parent_id=self.linode_id) else: dev = Volume.make_instance(device['volume_id'], self._client, parent_id=self.linode_id) devices[device_index] = dev self._set('devices', MappedObject(**devices))
python
def _populate(self, json): from .volume import Volume DerivedBase._populate(self, json) devices = {} for device_index, device in json['devices'].items(): if not device: devices[device_index] = None continue dev = None if 'disk_id' in device and device['disk_id']: # this is a disk dev = Disk.make_instance(device['disk_id'], self._client, parent_id=self.linode_id) else: dev = Volume.make_instance(device['volume_id'], self._client, parent_id=self.linode_id) devices[device_index] = dev self._set('devices', MappedObject(**devices))
[ "def", "_populate", "(", "self", ",", "json", ")", ":", "from", ".", "volume", "import", "Volume", "DerivedBase", ".", "_populate", "(", "self", ",", "json", ")", "devices", "=", "{", "}", "for", "device_index", ",", "device", "in", "json", "[", "'devi...
Map devices more nicely while populating.
[ "Map", "devices", "more", "nicely", "while", "populating", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L172-L195
19,567
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.ips
def ips(self): """ The ips related collection is not normalized like the others, so we have to make an ad-hoc object to return for its response """ if not hasattr(self, '_ips'): result = self._client.get("{}/ips".format(Instance.api_endpoint), model=self) if not "ipv4" in result: raise UnexpectedResponseError('Unexpected response loading IPs', json=result) v4pub = [] for c in result['ipv4']['public']: i = IPAddress(self._client, c['address'], c) v4pub.append(i) v4pri = [] for c in result['ipv4']['private']: i = IPAddress(self._client, c['address'], c) v4pri.append(i) shared_ips = [] for c in result['ipv4']['shared']: i = IPAddress(self._client, c['address'], c) shared_ips.append(i) slaac = IPAddress(self._client, result['ipv6']['slaac']['address'], result['ipv6']['slaac']) link_local = IPAddress(self._client, result['ipv6']['link_local']['address'], result['ipv6']['link_local']) pools = [] for p in result['ipv6']['global']: pools.append(IPv6Pool(self._client, p['range'])) ips = MappedObject(**{ "ipv4": { "public": v4pub, "private": v4pri, "shared": shared_ips, }, "ipv6": { "slaac": slaac, "link_local": link_local, "pools": pools, }, }) self._set('_ips', ips) return self._ips
python
def ips(self): if not hasattr(self, '_ips'): result = self._client.get("{}/ips".format(Instance.api_endpoint), model=self) if not "ipv4" in result: raise UnexpectedResponseError('Unexpected response loading IPs', json=result) v4pub = [] for c in result['ipv4']['public']: i = IPAddress(self._client, c['address'], c) v4pub.append(i) v4pri = [] for c in result['ipv4']['private']: i = IPAddress(self._client, c['address'], c) v4pri.append(i) shared_ips = [] for c in result['ipv4']['shared']: i = IPAddress(self._client, c['address'], c) shared_ips.append(i) slaac = IPAddress(self._client, result['ipv6']['slaac']['address'], result['ipv6']['slaac']) link_local = IPAddress(self._client, result['ipv6']['link_local']['address'], result['ipv6']['link_local']) pools = [] for p in result['ipv6']['global']: pools.append(IPv6Pool(self._client, p['range'])) ips = MappedObject(**{ "ipv4": { "public": v4pub, "private": v4pri, "shared": shared_ips, }, "ipv6": { "slaac": slaac, "link_local": link_local, "pools": pools, }, }) self._set('_ips', ips) return self._ips
[ "def", "ips", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_ips'", ")", ":", "result", "=", "self", ".", "_client", ".", "get", "(", "\"{}/ips\"", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ",", "model", "=", "s...
The ips related collection is not normalized like the others, so we have to make an ad-hoc object to return for its response
[ "The", "ips", "related", "collection", "is", "not", "normalized", "like", "the", "others", "so", "we", "have", "to", "make", "an", "ad", "-", "hoc", "object", "to", "return", "for", "its", "response" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L222-L272
19,568
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.available_backups
def available_backups(self): """ The backups response contains what backups are available to be restored. """ if not hasattr(self, '_avail_backups'): result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self) if not 'automatic' in result: raise UnexpectedResponseError('Unexpected response loading available backups!', json=result) automatic = [] for a in result['automatic']: cur = Backup(self._client, a['id'], self.id, a) automatic.append(cur) snap = None if result['snapshot']['current']: snap = Backup(self._client, result['snapshot']['current']['id'], self.id, result['snapshot']['current']) psnap = None if result['snapshot']['in_progress']: psnap = Backup(self._client, result['snapshot']['in_progress']['id'], self.id, result['snapshot']['in_progress']) self._set('_avail_backups', MappedObject(**{ "automatic": automatic, "snapshot": { "current": snap, "in_progress": psnap, } })) return self._avail_backups
python
def available_backups(self): if not hasattr(self, '_avail_backups'): result = self._client.get("{}/backups".format(Instance.api_endpoint), model=self) if not 'automatic' in result: raise UnexpectedResponseError('Unexpected response loading available backups!', json=result) automatic = [] for a in result['automatic']: cur = Backup(self._client, a['id'], self.id, a) automatic.append(cur) snap = None if result['snapshot']['current']: snap = Backup(self._client, result['snapshot']['current']['id'], self.id, result['snapshot']['current']) psnap = None if result['snapshot']['in_progress']: psnap = Backup(self._client, result['snapshot']['in_progress']['id'], self.id, result['snapshot']['in_progress']) self._set('_avail_backups', MappedObject(**{ "automatic": automatic, "snapshot": { "current": snap, "in_progress": psnap, } })) return self._avail_backups
[ "def", "available_backups", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_avail_backups'", ")", ":", "result", "=", "self", ".", "_client", ".", "get", "(", "\"{}/backups\"", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ...
The backups response contains what backups are available to be restored.
[ "The", "backups", "response", "contains", "what", "backups", "are", "available", "to", "be", "restored", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L275-L308
19,569
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.invalidate
def invalidate(self): """ Clear out cached properties """ if hasattr(self, '_avail_backups'): del self._avail_backups if hasattr(self, '_ips'): del self._ips Base.invalidate(self)
python
def invalidate(self): if hasattr(self, '_avail_backups'): del self._avail_backups if hasattr(self, '_ips'): del self._ips Base.invalidate(self)
[ "def", "invalidate", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'_avail_backups'", ")", ":", "del", "self", ".", "_avail_backups", "if", "hasattr", "(", "self", ",", "'_ips'", ")", ":", "del", "self", ".", "_ips", "Base", ".", "invalida...
Clear out cached properties
[ "Clear", "out", "cached", "properties" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L321-L328
19,570
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.config_create
def config_create(self, kernel=None, label=None, devices=[], disks=[], volumes=[], **kwargs): """ Creates a Linode Config with the given attributes. :param kernel: The kernel to boot with. :param label: The config label :param disks: The list of disks, starting at sda, to map to this config. :param volumes: The volumes, starting after the last disk, to map to this config :param devices: A list of devices to assign to this config, in device index order. Values must be of type Disk or Volume. If this is given, you may not include disks or volumes. :param **kwargs: Any other arguments accepted by the api. :returns: A new Linode Config """ from .volume import Volume hypervisor_prefix = 'sd' if self.hypervisor == 'kvm' else 'xvd' device_names = [hypervisor_prefix + string.ascii_lowercase[i] for i in range(0, 8)] device_map = {device_names[i]: None for i in range(0, len(device_names))} if devices and (disks or volumes): raise ValueError('You may not call config_create with "devices" and ' 'either of "disks" or "volumes" specified!') if not devices: if not isinstance(disks, list): disks = [disks] if not isinstance(volumes, list): volumes = [volumes] devices = [] for d in disks: if d is None: devices.append(None) elif isinstance(d, Disk): devices.append(d) else: devices.append(Disk(self._client, int(d), self.id)) for v in volumes: if v is None: devices.append(None) elif isinstance(v, Volume): devices.append(v) else: devices.append(Volume(self._client, int(v))) if not devices: raise ValueError('Must include at least one disk or volume!') for i, d in enumerate(devices): if d is None: pass elif isinstance(d, Disk): device_map[device_names[i]] = {'disk_id': d.id } elif isinstance(d, Volume): device_map[device_names[i]] = {'volume_id': d.id } else: raise TypeError('Disk or Volume expected!') params = { 'kernel': kernel.id if issubclass(type(kernel), Base) else kernel, 'label': label if label else "{}_config_{}".format(self.label, len(self.configs)), 'devices': device_map, } params.update(kwargs) result = self._client.post("{}/configs".format(Instance.api_endpoint), model=self, data=params) self.invalidate() if not 'id' in result: raise UnexpectedResponseError('Unexpected response creating config!', json=result) c = Config(self._client, result['id'], self.id, result) return c
python
def config_create(self, kernel=None, label=None, devices=[], disks=[], volumes=[], **kwargs): from .volume import Volume hypervisor_prefix = 'sd' if self.hypervisor == 'kvm' else 'xvd' device_names = [hypervisor_prefix + string.ascii_lowercase[i] for i in range(0, 8)] device_map = {device_names[i]: None for i in range(0, len(device_names))} if devices and (disks or volumes): raise ValueError('You may not call config_create with "devices" and ' 'either of "disks" or "volumes" specified!') if not devices: if not isinstance(disks, list): disks = [disks] if not isinstance(volumes, list): volumes = [volumes] devices = [] for d in disks: if d is None: devices.append(None) elif isinstance(d, Disk): devices.append(d) else: devices.append(Disk(self._client, int(d), self.id)) for v in volumes: if v is None: devices.append(None) elif isinstance(v, Volume): devices.append(v) else: devices.append(Volume(self._client, int(v))) if not devices: raise ValueError('Must include at least one disk or volume!') for i, d in enumerate(devices): if d is None: pass elif isinstance(d, Disk): device_map[device_names[i]] = {'disk_id': d.id } elif isinstance(d, Volume): device_map[device_names[i]] = {'volume_id': d.id } else: raise TypeError('Disk or Volume expected!') params = { 'kernel': kernel.id if issubclass(type(kernel), Base) else kernel, 'label': label if label else "{}_config_{}".format(self.label, len(self.configs)), 'devices': device_map, } params.update(kwargs) result = self._client.post("{}/configs".format(Instance.api_endpoint), model=self, data=params) self.invalidate() if not 'id' in result: raise UnexpectedResponseError('Unexpected response creating config!', json=result) c = Config(self._client, result['id'], self.id, result) return c
[ "def", "config_create", "(", "self", ",", "kernel", "=", "None", ",", "label", "=", "None", ",", "devices", "=", "[", "]", ",", "disks", "=", "[", "]", ",", "volumes", "=", "[", "]", ",", "*", "*", "kwargs", ")", ":", "from", ".", "volume", "im...
Creates a Linode Config with the given attributes. :param kernel: The kernel to boot with. :param label: The config label :param disks: The list of disks, starting at sda, to map to this config. :param volumes: The volumes, starting after the last disk, to map to this config :param devices: A list of devices to assign to this config, in device index order. Values must be of type Disk or Volume. If this is given, you may not include disks or volumes. :param **kwargs: Any other arguments accepted by the api. :returns: A new Linode Config
[ "Creates", "a", "Linode", "Config", "with", "the", "given", "attributes", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L378-L456
19,571
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.enable_backups
def enable_backups(self): """ Enable Backups for this Instance. When enabled, we will automatically backup your Instance's data so that it can be restored at a later date. For more information on Instance's Backups service and pricing, see our `Backups Page`_ .. _Backups Page: https://www.linode.com/backups """ self._client.post("{}/backups/enable".format(Instance.api_endpoint), model=self) self.invalidate() return True
python
def enable_backups(self): self._client.post("{}/backups/enable".format(Instance.api_endpoint), model=self) self.invalidate() return True
[ "def", "enable_backups", "(", "self", ")", ":", "self", ".", "_client", ".", "post", "(", "\"{}/backups/enable\"", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ",", "model", "=", "self", ")", "self", ".", "invalidate", "(", ")", "return", "T...
Enable Backups for this Instance. When enabled, we will automatically backup your Instance's data so that it can be restored at a later date. For more information on Instance's Backups service and pricing, see our `Backups Page`_ .. _Backups Page: https://www.linode.com/backups
[ "Enable", "Backups", "for", "this", "Instance", ".", "When", "enabled", "we", "will", "automatically", "backup", "your", "Instance", "s", "data", "so", "that", "it", "can", "be", "restored", "at", "a", "later", "date", ".", "For", "more", "information", "o...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L502-L513
19,572
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.mutate
def mutate(self): """ Upgrades this Instance to the latest generation type """ self._client.post('{}/mutate'.format(Instance.api_endpoint), model=self) return True
python
def mutate(self): self._client.post('{}/mutate'.format(Instance.api_endpoint), model=self) return True
[ "def", "mutate", "(", "self", ")", ":", "self", ".", "_client", ".", "post", "(", "'{}/mutate'", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ",", "model", "=", "self", ")", "return", "True" ]
Upgrades this Instance to the latest generation type
[ "Upgrades", "this", "Instance", "to", "the", "latest", "generation", "type" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L635-L641
19,573
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.initiate_migration
def initiate_migration(self): """ Initiates a pending migration that is already scheduled for this Linode Instance """ self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self)
python
def initiate_migration(self): self._client.post('{}/migrate'.format(Instance.api_endpoint), model=self)
[ "def", "initiate_migration", "(", "self", ")", ":", "self", ".", "_client", ".", "post", "(", "'{}/migrate'", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ",", "model", "=", "self", ")" ]
Initiates a pending migration that is already scheduled for this Linode Instance
[ "Initiates", "a", "pending", "migration", "that", "is", "already", "scheduled", "for", "this", "Linode", "Instance" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L643-L648
19,574
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.clone
def clone(self, to_linode=None, region=None, service=None, configs=[], disks=[], label=None, group=None, with_backups=None): """ Clones this linode into a new linode or into a new linode in the given region """ if to_linode and region: raise ValueError('You may only specify one of "to_linode" and "region"') if region and not service: raise ValueError('Specifying a region requires a "service" as well') if not isinstance(configs, list) and not isinstance(configs, PaginatedList): configs = [configs] if not isinstance(disks, list) and not isinstance(disks, PaginatedList): disks = [disks] cids = [ c.id if issubclass(type(c), Base) else c for c in configs ] dids = [ d.id if issubclass(type(d), Base) else d for d in disks ] params = { "linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode, "region": region.id if issubclass(type(region), Base) else region, "type": service.id if issubclass(type(service), Base) else service, "configs": cids if cids else None, "disks": dids if dids else None, "label": label, "group": group, "with_backups": with_backups, } result = self._client.post('{}/clone'.format(Instance.api_endpoint), model=self, data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response cloning Instance!', json=result) l = Instance(self._client, result['id'], result) return l
python
def clone(self, to_linode=None, region=None, service=None, configs=[], disks=[], label=None, group=None, with_backups=None): if to_linode and region: raise ValueError('You may only specify one of "to_linode" and "region"') if region and not service: raise ValueError('Specifying a region requires a "service" as well') if not isinstance(configs, list) and not isinstance(configs, PaginatedList): configs = [configs] if not isinstance(disks, list) and not isinstance(disks, PaginatedList): disks = [disks] cids = [ c.id if issubclass(type(c), Base) else c for c in configs ] dids = [ d.id if issubclass(type(d), Base) else d for d in disks ] params = { "linode_id": to_linode.id if issubclass(type(to_linode), Base) else to_linode, "region": region.id if issubclass(type(region), Base) else region, "type": service.id if issubclass(type(service), Base) else service, "configs": cids if cids else None, "disks": dids if dids else None, "label": label, "group": group, "with_backups": with_backups, } result = self._client.post('{}/clone'.format(Instance.api_endpoint), model=self, data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response cloning Instance!', json=result) l = Instance(self._client, result['id'], result) return l
[ "def", "clone", "(", "self", ",", "to_linode", "=", "None", ",", "region", "=", "None", ",", "service", "=", "None", ",", "configs", "=", "[", "]", ",", "disks", "=", "[", "]", ",", "label", "=", "None", ",", "group", "=", "None", ",", "with_back...
Clones this linode into a new linode or into a new linode in the given region
[ "Clones", "this", "linode", "into", "a", "new", "linode", "or", "into", "a", "new", "linode", "in", "the", "given", "region" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L650-L684
19,575
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.stats
def stats(self): """ Returns the JSON stats for this Instance """ # TODO - this would be nicer if we formatted the stats return self._client.get('{}/stats'.format(Instance.api_endpoint), model=self)
python
def stats(self): # TODO - this would be nicer if we formatted the stats return self._client.get('{}/stats'.format(Instance.api_endpoint), model=self)
[ "def", "stats", "(", "self", ")", ":", "# TODO - this would be nicer if we formatted the stats", "return", "self", ".", "_client", ".", "get", "(", "'{}/stats'", ".", "format", "(", "Instance", ".", "api_endpoint", ")", ",", "model", "=", "self", ")" ]
Returns the JSON stats for this Instance
[ "Returns", "the", "JSON", "stats", "for", "this", "Instance" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L687-L692
19,576
linode/linode_api4-python
linode_api4/objects/linode.py
Instance.stats_for
def stats_for(self, dt): """ Returns stats for the month containing the given datetime """ # TODO - this would be nicer if we formatted the stats if not isinstance(dt, datetime): raise TypeError('stats_for requires a datetime object!') return self._client.get('{}/stats/'.format(dt.strftime('%Y/%m')))
python
def stats_for(self, dt): # TODO - this would be nicer if we formatted the stats if not isinstance(dt, datetime): raise TypeError('stats_for requires a datetime object!') return self._client.get('{}/stats/'.format(dt.strftime('%Y/%m')))
[ "def", "stats_for", "(", "self", ",", "dt", ")", ":", "# TODO - this would be nicer if we formatted the stats", "if", "not", "isinstance", "(", "dt", ",", "datetime", ")", ":", "raise", "TypeError", "(", "'stats_for requires a datetime object!'", ")", "return", "self"...
Returns stats for the month containing the given datetime
[ "Returns", "stats", "for", "the", "month", "containing", "the", "given", "datetime" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L694-L701
19,577
linode/linode_api4-python
linode_api4/objects/linode.py
StackScript._populate
def _populate(self, json): """ Override the populate method to map user_defined_fields to fancy values """ Base._populate(self, json) mapped_udfs = [] for udf in self.user_defined_fields: t = UserDefinedFieldType.text choices = None if hasattr(udf, 'oneof'): t = UserDefinedFieldType.select_one choices = udf.oneof.split(',') elif hasattr(udf, 'manyof'): t = UserDefinedFieldType.select_many choices = udf.manyof.split(',') mapped_udfs.append(UserDefinedField(udf.name, udf.label if hasattr(udf, 'label') else None, udf.example if hasattr(udf, 'example') else None, t, choices=choices)) self._set('user_defined_fields', mapped_udfs) ndist = [ Image(self._client, d) for d in self.images ] self._set('images', ndist)
python
def _populate(self, json): Base._populate(self, json) mapped_udfs = [] for udf in self.user_defined_fields: t = UserDefinedFieldType.text choices = None if hasattr(udf, 'oneof'): t = UserDefinedFieldType.select_one choices = udf.oneof.split(',') elif hasattr(udf, 'manyof'): t = UserDefinedFieldType.select_many choices = udf.manyof.split(',') mapped_udfs.append(UserDefinedField(udf.name, udf.label if hasattr(udf, 'label') else None, udf.example if hasattr(udf, 'example') else None, t, choices=choices)) self._set('user_defined_fields', mapped_udfs) ndist = [ Image(self._client, d) for d in self.images ] self._set('images', ndist)
[ "def", "_populate", "(", "self", ",", "json", ")", ":", "Base", ".", "_populate", "(", "self", ",", "json", ")", "mapped_udfs", "=", "[", "]", "for", "udf", "in", "self", ".", "user_defined_fields", ":", "t", "=", "UserDefinedFieldType", ".", "text", "...
Override the populate method to map user_defined_fields to fancy values
[ "Override", "the", "populate", "method", "to", "map", "user_defined_fields", "to", "fancy", "values" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/linode.py#L738-L763
19,578
linode/linode_api4-python
linode_api4/objects/account.py
InvoiceItem._populate
def _populate(self, json): """ Allows population of "from_date" from the returned "from" attribute which is a reserved word in python. Also populates "to_date" to be complete. """ super(InvoiceItem, self)._populate(json) self.from_date = datetime.strptime(json['from'], DATE_FORMAT) self.to_date = datetime.strptime(json['to'], DATE_FORMAT)
python
def _populate(self, json): super(InvoiceItem, self)._populate(json) self.from_date = datetime.strptime(json['from'], DATE_FORMAT) self.to_date = datetime.strptime(json['to'], DATE_FORMAT)
[ "def", "_populate", "(", "self", ",", "json", ")", ":", "super", "(", "InvoiceItem", ",", "self", ")", ".", "_populate", "(", "json", ")", "self", ".", "from_date", "=", "datetime", ".", "strptime", "(", "json", "[", "'from'", "]", ",", "DATE_FORMAT", ...
Allows population of "from_date" from the returned "from" attribute which is a reserved word in python. Also populates "to_date" to be complete.
[ "Allows", "population", "of", "from_date", "from", "the", "returned", "from", "attribute", "which", "is", "a", "reserved", "word", "in", "python", ".", "Also", "populates", "to_date", "to", "be", "complete", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/account.py#L128-L136
19,579
linode/linode_api4-python
linode_api4/objects/account.py
OAuthClient.reset_secret
def reset_secret(self): """ Resets the client secret for this client. """ result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when resetting secret!', json=result) self._populate(result) return self.secret
python
def reset_secret(self): result = self._client.post("{}/reset_secret".format(OAuthClient.api_endpoint), model=self) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when resetting secret!', json=result) self._populate(result) return self.secret
[ "def", "reset_secret", "(", "self", ")", ":", "result", "=", "self", ".", "_client", ".", "post", "(", "\"{}/reset_secret\"", ".", "format", "(", "OAuthClient", ".", "api_endpoint", ")", ",", "model", "=", "self", ")", "if", "not", "'id'", "in", "result"...
Resets the client secret for this client.
[ "Resets", "the", "client", "secret", "for", "this", "client", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/account.py#L163-L173
19,580
linode/linode_api4-python
linode_api4/objects/account.py
OAuthClient.thumbnail
def thumbnail(self, dump_to=None): """ This returns binary data that represents a 128x128 image. If dump_to is given, attempts to write the image to a file at the given location. """ headers = { "Authorization": "token {}".format(self._client.token) } result = requests.get('{}/{}/thumbnail'.format(self._client.base_url, OAuthClient.api_endpoint.format(id=self.id)), headers=headers) if not result.status_code == 200: raise ApiError('No thumbnail found for OAuthClient {}'.format(self.id)) if dump_to: with open(dump_to, 'wb+') as f: f.write(result.content) return result.content
python
def thumbnail(self, dump_to=None): headers = { "Authorization": "token {}".format(self._client.token) } result = requests.get('{}/{}/thumbnail'.format(self._client.base_url, OAuthClient.api_endpoint.format(id=self.id)), headers=headers) if not result.status_code == 200: raise ApiError('No thumbnail found for OAuthClient {}'.format(self.id)) if dump_to: with open(dump_to, 'wb+') as f: f.write(result.content) return result.content
[ "def", "thumbnail", "(", "self", ",", "dump_to", "=", "None", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "\"token {}\"", ".", "format", "(", "self", ".", "_client", ".", "token", ")", "}", "result", "=", "requests", ".", "get", "(", "'{}/...
This returns binary data that represents a 128x128 image. If dump_to is given, attempts to write the image to a file at the given location.
[ "This", "returns", "binary", "data", "that", "represents", "a", "128x128", "image", ".", "If", "dump_to", "is", "given", "attempts", "to", "write", "the", "image", "to", "a", "file", "at", "the", "given", "location", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/account.py#L175-L195
19,581
linode/linode_api4-python
linode_api4/objects/account.py
OAuthClient.set_thumbnail
def set_thumbnail(self, thumbnail): """ Sets the thumbnail for this OAuth Client. If thumbnail is bytes, uploads it as a png. Otherwise, assumes thumbnail is a path to the thumbnail and reads it in as bytes before uploading. """ headers = { "Authorization": "token {}".format(self._client.token), "Content-type": "image/png", } # TODO this check needs to be smarter - python2 doesn't do it right if not isinstance(thumbnail, bytes): with open(thumbnail, 'rb') as f: thumbnail = f.read() result = requests.put('{}/{}/thumbnail'.format(self._client.base_url, OAuthClient.api_endpoint.format(id=self.id)), headers=headers, data=thumbnail) if not result.status_code == 200: errors = [] j = result.json() if 'errors' in j: errors = [ e['reason'] for e in j['errors'] ] raise ApiError('{}: {}'.format(result.status_code, errors), json=j) return True
python
def set_thumbnail(self, thumbnail): headers = { "Authorization": "token {}".format(self._client.token), "Content-type": "image/png", } # TODO this check needs to be smarter - python2 doesn't do it right if not isinstance(thumbnail, bytes): with open(thumbnail, 'rb') as f: thumbnail = f.read() result = requests.put('{}/{}/thumbnail'.format(self._client.base_url, OAuthClient.api_endpoint.format(id=self.id)), headers=headers, data=thumbnail) if not result.status_code == 200: errors = [] j = result.json() if 'errors' in j: errors = [ e['reason'] for e in j['errors'] ] raise ApiError('{}: {}'.format(result.status_code, errors), json=j) return True
[ "def", "set_thumbnail", "(", "self", ",", "thumbnail", ")", ":", "headers", "=", "{", "\"Authorization\"", ":", "\"token {}\"", ".", "format", "(", "self", ".", "_client", ".", "token", ")", ",", "\"Content-type\"", ":", "\"image/png\"", ",", "}", "# TODO th...
Sets the thumbnail for this OAuth Client. If thumbnail is bytes, uploads it as a png. Otherwise, assumes thumbnail is a path to the thumbnail and reads it in as bytes before uploading.
[ "Sets", "the", "thumbnail", "for", "this", "OAuth", "Client", ".", "If", "thumbnail", "is", "bytes", "uploads", "it", "as", "a", "png", ".", "Otherwise", "assumes", "thumbnail", "is", "a", "path", "to", "the", "thumbnail", "and", "reads", "it", "in", "as...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/account.py#L197-L224
19,582
linode/linode_api4-python
linode_api4/objects/account.py
User.grants
def grants(self): """ Retrieves the grants for this user. If the user is unrestricted, this will result in an ApiError. This is smart, and will only fetch from the api once unless the object is invalidated. :returns: The grants for this user. :rtype: linode.objects.account.UserGrants """ from linode_api4.objects.account import UserGrants if not hasattr(self, '_grants'): resp = self._client.get(UserGrants.api_endpoint.format(username=self.username)) grants = UserGrants(self._client, self.username, resp) self._set('_grants', grants) return self._grants
python
def grants(self): from linode_api4.objects.account import UserGrants if not hasattr(self, '_grants'): resp = self._client.get(UserGrants.api_endpoint.format(username=self.username)) grants = UserGrants(self._client, self.username, resp) self._set('_grants', grants) return self._grants
[ "def", "grants", "(", "self", ")", ":", "from", "linode_api4", ".", "objects", ".", "account", "import", "UserGrants", "if", "not", "hasattr", "(", "self", ",", "'_grants'", ")", ":", "resp", "=", "self", ".", "_client", ".", "get", "(", "UserGrants", ...
Retrieves the grants for this user. If the user is unrestricted, this will result in an ApiError. This is smart, and will only fetch from the api once unless the object is invalidated. :returns: The grants for this user. :rtype: linode.objects.account.UserGrants
[ "Retrieves", "the", "grants", "for", "this", "user", ".", "If", "the", "user", "is", "unrestricted", "this", "will", "result", "in", "an", "ApiError", ".", "This", "is", "smart", "and", "will", "only", "fetch", "from", "the", "api", "once", "unless", "th...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/account.py#L248-L264
19,583
linode/linode_api4-python
linode_api4/objects/base.py
Base.save
def save(self): """ Send this object's mutable values to the server in a PUT request """ resp = self._client.put(type(self).api_endpoint, model=self, data=self._serialize()) if 'error' in resp: return False return True
python
def save(self): resp = self._client.put(type(self).api_endpoint, model=self, data=self._serialize()) if 'error' in resp: return False return True
[ "def", "save", "(", "self", ")", ":", "resp", "=", "self", ".", "_client", ".", "put", "(", "type", "(", "self", ")", ".", "api_endpoint", ",", "model", "=", "self", ",", "data", "=", "self", ".", "_serialize", "(", ")", ")", "if", "'error'", "in...
Send this object's mutable values to the server in a PUT request
[ "Send", "this", "object", "s", "mutable", "values", "to", "the", "server", "in", "a", "PUT", "request" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L150-L159
19,584
linode/linode_api4-python
linode_api4/objects/base.py
Base.delete
def delete(self): """ Sends a DELETE request for this object """ resp = self._client.delete(type(self).api_endpoint, model=self) if 'error' in resp: return False self.invalidate() return True
python
def delete(self): resp = self._client.delete(type(self).api_endpoint, model=self) if 'error' in resp: return False self.invalidate() return True
[ "def", "delete", "(", "self", ")", ":", "resp", "=", "self", ".", "_client", ".", "delete", "(", "type", "(", "self", ")", ".", "api_endpoint", ",", "model", "=", "self", ")", "if", "'error'", "in", "resp", ":", "return", "False", "self", ".", "inv...
Sends a DELETE request for this object
[ "Sends", "a", "DELETE", "request", "for", "this", "object" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L161-L170
19,585
linode/linode_api4-python
linode_api4/objects/base.py
Base.invalidate
def invalidate(self): """ Invalidates all non-identifier Properties this object has locally, causing the next access to re-fetch them from the server """ for key in [k for k in type(self).properties.keys() if not type(self).properties[k].identifier]: self._set(key, None) self._set('_populated', False)
python
def invalidate(self): for key in [k for k in type(self).properties.keys() if not type(self).properties[k].identifier]: self._set(key, None) self._set('_populated', False)
[ "def", "invalidate", "(", "self", ")", ":", "for", "key", "in", "[", "k", "for", "k", "in", "type", "(", "self", ")", ".", "properties", ".", "keys", "(", ")", "if", "not", "type", "(", "self", ")", ".", "properties", "[", "k", "]", ".", "ident...
Invalidates all non-identifier Properties this object has locally, causing the next access to re-fetch them from the server
[ "Invalidates", "all", "non", "-", "identifier", "Properties", "this", "object", "has", "locally", "causing", "the", "next", "access", "to", "re", "-", "fetch", "them", "from", "the", "server" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L172-L181
19,586
linode/linode_api4-python
linode_api4/objects/base.py
Base._serialize
def _serialize(self): """ A helper method to build a dict of all mutable Properties of this object """ result = { a: getattr(self, a) for a in type(self).properties if type(self).properties[a].mutable } for k, v in result.items(): if isinstance(v, Base): result[k] = v.id return result
python
def _serialize(self): result = { a: getattr(self, a) for a in type(self).properties if type(self).properties[a].mutable } for k, v in result.items(): if isinstance(v, Base): result[k] = v.id return result
[ "def", "_serialize", "(", "self", ")", ":", "result", "=", "{", "a", ":", "getattr", "(", "self", ",", "a", ")", "for", "a", "in", "type", "(", "self", ")", ".", "properties", "if", "type", "(", "self", ")", ".", "properties", "[", "a", "]", "....
A helper method to build a dict of all mutable Properties of this object
[ "A", "helper", "method", "to", "build", "a", "dict", "of", "all", "mutable", "Properties", "of", "this", "object" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L183-L195
19,587
linode/linode_api4-python
linode_api4/objects/base.py
Base._api_get
def _api_get(self): """ A helper method to GET this object from the server """ json = self._client.get(type(self).api_endpoint, model=self) self._populate(json)
python
def _api_get(self): json = self._client.get(type(self).api_endpoint, model=self) self._populate(json)
[ "def", "_api_get", "(", "self", ")", ":", "json", "=", "self", ".", "_client", ".", "get", "(", "type", "(", "self", ")", ".", "api_endpoint", ",", "model", "=", "self", ")", "self", ".", "_populate", "(", "json", ")" ]
A helper method to GET this object from the server
[ "A", "helper", "method", "to", "GET", "this", "object", "from", "the", "server" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L197-L202
19,588
linode/linode_api4-python
linode_api4/objects/base.py
Base._populate
def _populate(self, json): """ A helper method that, given a JSON object representing this object, assigns values based on the properties dict and the attributes of its Properties. """ if not json: return # hide the raw JSON away in case someone needs it self._set('_raw_json', json) for key in json: if key in (k for k in type(self).properties.keys() if not type(self).properties[k].identifier): if type(self).properties[key].relationship \ and not json[key] is None: if isinstance(json[key], list): objs = [] for d in json[key]: if not 'id' in d: continue new_class = type(self).properties[key].relationship obj = new_class.make_instance(d['id'], getattr(self,'_client')) if obj: obj._populate(d) objs.append(obj) self._set(key, objs) else: if isinstance(json[key], dict): related_id = json[key]['id'] else: related_id = json[key] new_class = type(self).properties[key].relationship obj = new_class.make_instance(related_id, getattr(self,'_client')) if obj and isinstance(json[key], dict): obj._populate(json[key]) self._set(key, obj) elif type(self).properties[key].slug_relationship \ and not json[key] is None: # create an object of the expected type with the given slug self._set(key, type(self).properties[key].slug_relationship(self._client, json[key])) elif type(json[key]) is dict: self._set(key, MappedObject(**json[key])) elif type(json[key]) is list: # we're going to use MappedObject's behavior with lists to # expand these, then grab the resulting value to set mapping = MappedObject(_list=json[key]) self._set(key, mapping._list) # pylint: disable=no-member elif type(self).properties[key].is_datetime: try: t = time.strptime(json[key], DATE_FORMAT) self._set(key, datetime.fromtimestamp(time.mktime(t))) except: #TODO - handle this better (or log it?) self._set(key, json[key]) else: self._set(key, json[key]) self._set('_populated', True) self._set('_last_updated', datetime.now())
python
def _populate(self, json): if not json: return # hide the raw JSON away in case someone needs it self._set('_raw_json', json) for key in json: if key in (k for k in type(self).properties.keys() if not type(self).properties[k].identifier): if type(self).properties[key].relationship \ and not json[key] is None: if isinstance(json[key], list): objs = [] for d in json[key]: if not 'id' in d: continue new_class = type(self).properties[key].relationship obj = new_class.make_instance(d['id'], getattr(self,'_client')) if obj: obj._populate(d) objs.append(obj) self._set(key, objs) else: if isinstance(json[key], dict): related_id = json[key]['id'] else: related_id = json[key] new_class = type(self).properties[key].relationship obj = new_class.make_instance(related_id, getattr(self,'_client')) if obj and isinstance(json[key], dict): obj._populate(json[key]) self._set(key, obj) elif type(self).properties[key].slug_relationship \ and not json[key] is None: # create an object of the expected type with the given slug self._set(key, type(self).properties[key].slug_relationship(self._client, json[key])) elif type(json[key]) is dict: self._set(key, MappedObject(**json[key])) elif type(json[key]) is list: # we're going to use MappedObject's behavior with lists to # expand these, then grab the resulting value to set mapping = MappedObject(_list=json[key]) self._set(key, mapping._list) # pylint: disable=no-member elif type(self).properties[key].is_datetime: try: t = time.strptime(json[key], DATE_FORMAT) self._set(key, datetime.fromtimestamp(time.mktime(t))) except: #TODO - handle this better (or log it?) self._set(key, json[key]) else: self._set(key, json[key]) self._set('_populated', True) self._set('_last_updated', datetime.now())
[ "def", "_populate", "(", "self", ",", "json", ")", ":", "if", "not", "json", ":", "return", "# hide the raw JSON away in case someone needs it", "self", ".", "_set", "(", "'_raw_json'", ",", "json", ")", "for", "key", "in", "json", ":", "if", "key", "in", ...
A helper method that, given a JSON object representing this object, assigns values based on the properties dict and the attributes of its Properties.
[ "A", "helper", "method", "that", "given", "a", "JSON", "object", "representing", "this", "object", "assigns", "values", "based", "on", "the", "properties", "dict", "and", "the", "attributes", "of", "its", "Properties", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L204-L265
19,589
linode/linode_api4-python
linode_api4/objects/base.py
Base.make
def make(id, client, cls, parent_id=None, json=None): """ Makes an api object based on an id and class. :param id: The id of the object to create :param client: The LinodeClient to give the new object :param cls: The class type to instantiate :param parent_id: The parent id for derived classes :param json: The JSON to use to populate the new class :returns: An instance of cls with the given id """ from .dbase import DerivedBase if issubclass(cls, DerivedBase): return cls(client, id, parent_id, json) else: return cls(client, id, json)
python
def make(id, client, cls, parent_id=None, json=None): from .dbase import DerivedBase if issubclass(cls, DerivedBase): return cls(client, id, parent_id, json) else: return cls(client, id, json)
[ "def", "make", "(", "id", ",", "client", ",", "cls", ",", "parent_id", "=", "None", ",", "json", "=", "None", ")", ":", "from", ".", "dbase", "import", "DerivedBase", "if", "issubclass", "(", "cls", ",", "DerivedBase", ")", ":", "return", "cls", "(",...
Makes an api object based on an id and class. :param id: The id of the object to create :param client: The LinodeClient to give the new object :param cls: The class type to instantiate :param parent_id: The parent id for derived classes :param json: The JSON to use to populate the new class :returns: An instance of cls with the given id
[ "Makes", "an", "api", "object", "based", "on", "an", "id", "and", "class", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L283-L300
19,590
linode/linode_api4-python
linode_api4/objects/base.py
Base.make_instance
def make_instance(cls, id, client, parent_id=None, json=None): """ Makes an instance of the class this is called on and returns it. The intended usage is: instance = Linode.make_instance(123, client, json=response) :param cls: The class this was called on. :param id: The id of the instance to create :param client: The client to use for this instance :param parent_id: The parent id for derived classes :param json: The JSON to populate the instance with :returns: A new instance of this type, populated with json """ return Base.make(id, client, cls, parent_id=parent_id, json=json)
python
def make_instance(cls, id, client, parent_id=None, json=None): return Base.make(id, client, cls, parent_id=parent_id, json=json)
[ "def", "make_instance", "(", "cls", ",", "id", ",", "client", ",", "parent_id", "=", "None", ",", "json", "=", "None", ")", ":", "return", "Base", ".", "make", "(", "id", ",", "client", ",", "cls", ",", "parent_id", "=", "parent_id", ",", "json", "...
Makes an instance of the class this is called on and returns it. The intended usage is: instance = Linode.make_instance(123, client, json=response) :param cls: The class this was called on. :param id: The id of the instance to create :param client: The client to use for this instance :param parent_id: The parent id for derived classes :param json: The JSON to populate the instance with :returns: A new instance of this type, populated with json
[ "Makes", "an", "instance", "of", "the", "class", "this", "is", "called", "on", "and", "returns", "it", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/base.py#L303-L318
19,591
linode/linode_api4-python
linode_api4/objects/networking.py
IPAddress.to
def to(self, linode): """ This is a helper method for ip-assign, and should not be used outside of that context. It's used to cleanly build an IP Assign request with pretty python syntax. """ from .linode import Instance if not isinstance(linode, Instance): raise ValueError("IP Address can only be assigned to a Linode!") return { "address": self.address, "linode_id": linode.id }
python
def to(self, linode): from .linode import Instance if not isinstance(linode, Instance): raise ValueError("IP Address can only be assigned to a Linode!") return { "address": self.address, "linode_id": linode.id }
[ "def", "to", "(", "self", ",", "linode", ")", ":", "from", ".", "linode", "import", "Instance", "if", "not", "isinstance", "(", "linode", ",", "Instance", ")", ":", "raise", "ValueError", "(", "\"IP Address can only be assigned to a Linode!\"", ")", "return", ...
This is a helper method for ip-assign, and should not be used outside of that context. It's used to cleanly build an IP Assign request with pretty python syntax.
[ "This", "is", "a", "helper", "method", "for", "ip", "-", "assign", "and", "should", "not", "be", "used", "outside", "of", "that", "context", ".", "It", "s", "used", "to", "cleanly", "build", "an", "IP", "Assign", "request", "with", "pretty", "python", ...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/objects/networking.py#L49-L58
19,592
linode/linode_api4-python
linode_api4/linode_client.py
ProfileGroup.token_create
def token_create(self, label=None, expiry=None, scopes=None, **kwargs): """ Creates and returns a new Personal Access Token """ if label: kwargs['label'] = label if expiry: if isinstance(expiry, datetime): expiry = datetime.strftime(expiry, "%Y-%m-%dT%H:%M:%S") kwargs['expiry'] = expiry if scopes: kwargs['scopes'] = scopes result = self.client.post('/profile/tokens', data=kwargs) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Personal Access ' 'Token!', json=result) token = PersonalAccessToken(self.client, result['id'], result) return token
python
def token_create(self, label=None, expiry=None, scopes=None, **kwargs): if label: kwargs['label'] = label if expiry: if isinstance(expiry, datetime): expiry = datetime.strftime(expiry, "%Y-%m-%dT%H:%M:%S") kwargs['expiry'] = expiry if scopes: kwargs['scopes'] = scopes result = self.client.post('/profile/tokens', data=kwargs) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Personal Access ' 'Token!', json=result) token = PersonalAccessToken(self.client, result['id'], result) return token
[ "def", "token_create", "(", "self", ",", "label", "=", "None", ",", "expiry", "=", "None", ",", "scopes", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "label", ":", "kwargs", "[", "'label'", "]", "=", "label", "if", "expiry", ":", "if", ...
Creates and returns a new Personal Access Token
[ "Creates", "and", "returns", "a", "new", "Personal", "Access", "Token" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L358-L378
19,593
linode/linode_api4-python
linode_api4/linode_client.py
ProfileGroup.ssh_key_upload
def ssh_key_upload(self, key, label): """ Uploads a new SSH Public Key to your profile This key can be used in later Linode deployments. :param key: The ssh key, or a path to the ssh key. If a path is provided, the file at the path must exist and be readable or an exception will be thrown. :type key: str :param label: The name to give this key. This is purely aesthetic. :type label: str :returns: The newly uploaded SSH Key :rtype: SSHKey :raises ValueError: If the key provided does not appear to be valid, and does not appear to be a path to a valid key. """ if not key.startswith(SSH_KEY_TYPES): # this might be a file path - look for it path = os.path.expanduser(key) if os.path.isfile(path): with open(path) as f: key = f.read().strip() if not key.startswith(SSH_KEY_TYPES): raise ValueError('Invalid SSH Public Key') params = { 'ssh_key': key, 'label': label, } result = self.client.post('/profile/sshkeys', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when uploading SSH Key!', json=result) ssh_key = SSHKey(self.client, result['id'], result) return ssh_key
python
def ssh_key_upload(self, key, label): if not key.startswith(SSH_KEY_TYPES): # this might be a file path - look for it path = os.path.expanduser(key) if os.path.isfile(path): with open(path) as f: key = f.read().strip() if not key.startswith(SSH_KEY_TYPES): raise ValueError('Invalid SSH Public Key') params = { 'ssh_key': key, 'label': label, } result = self.client.post('/profile/sshkeys', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when uploading SSH Key!', json=result) ssh_key = SSHKey(self.client, result['id'], result) return ssh_key
[ "def", "ssh_key_upload", "(", "self", ",", "key", ",", "label", ")", ":", "if", "not", "key", ".", "startswith", "(", "SSH_KEY_TYPES", ")", ":", "# this might be a file path - look for it", "path", "=", "os", ".", "path", ".", "expanduser", "(", "key", ")", ...
Uploads a new SSH Public Key to your profile This key can be used in later Linode deployments. :param key: The ssh key, or a path to the ssh key. If a path is provided, the file at the path must exist and be readable or an exception will be thrown. :type key: str :param label: The name to give this key. This is purely aesthetic. :type label: str :returns: The newly uploaded SSH Key :rtype: SSHKey :raises ValueError: If the key provided does not appear to be valid, and does not appear to be a path to a valid key.
[ "Uploads", "a", "new", "SSH", "Public", "Key", "to", "your", "profile", "This", "key", "can", "be", "used", "in", "later", "Linode", "deployments", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L392-L430
19,594
linode/linode_api4-python
linode_api4/linode_client.py
LongviewGroup.client_create
def client_create(self, label=None): """ Creates a new LongviewClient, optionally with a given label. :param label: The label for the new client. If None, a default label based on the new client's ID will be used. :returns: A new LongviewClient :raises ApiError: If a non-200 status code is returned :raises UnexpectedResponseError: If the returned data from the api does not look as expected. """ result = self.client.post('/longview/clients', data={ "label": label }) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Longivew ' 'Client!', json=result) c = LongviewClient(self.client, result['id'], result) return c
python
def client_create(self, label=None): result = self.client.post('/longview/clients', data={ "label": label }) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating Longivew ' 'Client!', json=result) c = LongviewClient(self.client, result['id'], result) return c
[ "def", "client_create", "(", "self", ",", "label", "=", "None", ")", ":", "result", "=", "self", ".", "client", ".", "post", "(", "'/longview/clients'", ",", "data", "=", "{", "\"label\"", ":", "label", "}", ")", "if", "not", "'id'", "in", "result", ...
Creates a new LongviewClient, optionally with a given label. :param label: The label for the new client. If None, a default label based on the new client's ID will be used. :returns: A new LongviewClient :raises ApiError: If a non-200 status code is returned :raises UnexpectedResponseError: If the returned data from the api does not look as expected.
[ "Creates", "a", "new", "LongviewClient", "optionally", "with", "a", "given", "label", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L441-L463
19,595
linode/linode_api4-python
linode_api4/linode_client.py
AccountGroup.events_mark_seen
def events_mark_seen(self, event): """ Marks event as the last event we have seen. If event is an int, it is treated as an event_id, otherwise it should be an event object whose id will be used. """ last_seen = event if isinstance(event, int) else event.id self.client.post('{}/seen'.format(Event.api_endpoint), model=Event(self.client, last_seen))
python
def events_mark_seen(self, event): last_seen = event if isinstance(event, int) else event.id self.client.post('{}/seen'.format(Event.api_endpoint), model=Event(self.client, last_seen))
[ "def", "events_mark_seen", "(", "self", ",", "event", ")", ":", "last_seen", "=", "event", "if", "isinstance", "(", "event", ",", "int", ")", "else", "event", ".", "id", "self", ".", "client", ".", "post", "(", "'{}/seen'", ".", "format", "(", "Event",...
Marks event as the last event we have seen. If event is an int, it is treated as an event_id, otherwise it should be an event object whose id will be used.
[ "Marks", "event", "as", "the", "last", "event", "we", "have", "seen", ".", "If", "event", "is", "an", "int", "it", "is", "treated", "as", "an", "event_id", "otherwise", "it", "should", "be", "an", "event", "object", "whose", "id", "will", "be", "used",...
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L495-L501
19,596
linode/linode_api4-python
linode_api4/linode_client.py
AccountGroup.settings
def settings(self): """ Resturns the account settings data for this acocunt. This is not a listing endpoint. """ result = self.client.get('/account/settings') if not 'managed' in result: raise UnexpectedResponseError('Unexpected response when getting account settings!', json=result) s = AccountSettings(self.client, result['managed'], result) return s
python
def settings(self): result = self.client.get('/account/settings') if not 'managed' in result: raise UnexpectedResponseError('Unexpected response when getting account settings!', json=result) s = AccountSettings(self.client, result['managed'], result) return s
[ "def", "settings", "(", "self", ")", ":", "result", "=", "self", ".", "client", ".", "get", "(", "'/account/settings'", ")", "if", "not", "'managed'", "in", "result", ":", "raise", "UnexpectedResponseError", "(", "'Unexpected response when getting account settings!'...
Resturns the account settings data for this acocunt. This is not a listing endpoint.
[ "Resturns", "the", "account", "settings", "data", "for", "this", "acocunt", ".", "This", "is", "not", "a", "listing", "endpoint", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L503-L515
19,597
linode/linode_api4-python
linode_api4/linode_client.py
AccountGroup.oauth_client_create
def oauth_client_create(self, name, redirect_uri, **kwargs): """ Make a new OAuth Client and return it """ params = { "label": name, "redirect_uri": redirect_uri, } params.update(kwargs) result = self.client.post('/account/oauth-clients', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating OAuth Client!', json=result) c = OAuthClient(self.client, result['id'], result) return c
python
def oauth_client_create(self, name, redirect_uri, **kwargs): params = { "label": name, "redirect_uri": redirect_uri, } params.update(kwargs) result = self.client.post('/account/oauth-clients', data=params) if not 'id' in result: raise UnexpectedResponseError('Unexpected response when creating OAuth Client!', json=result) c = OAuthClient(self.client, result['id'], result) return c
[ "def", "oauth_client_create", "(", "self", ",", "name", ",", "redirect_uri", ",", "*", "*", "kwargs", ")", ":", "params", "=", "{", "\"label\"", ":", "name", ",", "\"redirect_uri\"", ":", "redirect_uri", ",", "}", "params", ".", "update", "(", "kwargs", ...
Make a new OAuth Client and return it
[ "Make", "a", "new", "OAuth", "Client", "and", "return", "it" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L535-L552
19,598
linode/linode_api4-python
linode_api4/linode_client.py
AccountGroup.transfer
def transfer(self): """ Returns a MappedObject containing the account's transfer pool data """ result = self.client.get('/account/transfer') if not 'used' in result: raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!') return MappedObject(**result)
python
def transfer(self): result = self.client.get('/account/transfer') if not 'used' in result: raise UnexpectedResponseError('Unexpected response when getting Transfer Pool!') return MappedObject(**result)
[ "def", "transfer", "(", "self", ")", ":", "result", "=", "self", ".", "client", ".", "get", "(", "'/account/transfer'", ")", "if", "not", "'used'", "in", "result", ":", "raise", "UnexpectedResponseError", "(", "'Unexpected response when getting Transfer Pool!'", "...
Returns a MappedObject containing the account's transfer pool data
[ "Returns", "a", "MappedObject", "containing", "the", "account", "s", "transfer", "pool", "data" ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L560-L569
19,599
linode/linode_api4-python
linode_api4/linode_client.py
NetworkingGroup.ip_allocate
def ip_allocate(self, linode, public=True): """ Allocates an IP to a Instance you own. Additional IPs must be requested by opening a support ticket first. :param linode: The Instance to allocate the new IP for. :type linode: Instance or int :param public: If True, allocate a public IP address. Defaults to True. :type public: bool :returns: The new IPAddress :rtype: IPAddress """ result = self.client.post('/networking/ipv4/', data={ "linode_id": linode.id if isinstance(linode, Base) else linode, "type": "ipv4", "public": public, }) if not 'address' in result: raise UnexpectedResponseError('Unexpected response when adding IPv4 address!', json=result) ip = IPAddress(self.client, result['address'], result) return ip
python
def ip_allocate(self, linode, public=True): result = self.client.post('/networking/ipv4/', data={ "linode_id": linode.id if isinstance(linode, Base) else linode, "type": "ipv4", "public": public, }) if not 'address' in result: raise UnexpectedResponseError('Unexpected response when adding IPv4 address!', json=result) ip = IPAddress(self.client, result['address'], result) return ip
[ "def", "ip_allocate", "(", "self", ",", "linode", ",", "public", "=", "True", ")", ":", "result", "=", "self", ".", "client", ".", "post", "(", "'/networking/ipv4/'", ",", "data", "=", "{", "\"linode_id\"", ":", "linode", ".", "id", "if", "isinstance", ...
Allocates an IP to a Instance you own. Additional IPs must be requested by opening a support ticket first. :param linode: The Instance to allocate the new IP for. :type linode: Instance or int :param public: If True, allocate a public IP address. Defaults to True. :type public: bool :returns: The new IPAddress :rtype: IPAddress
[ "Allocates", "an", "IP", "to", "a", "Instance", "you", "own", ".", "Additional", "IPs", "must", "be", "requested", "by", "opening", "a", "support", "ticket", "first", "." ]
1dd7318d2aed014c746d48c7957464c57af883ca
https://github.com/linode/linode_api4-python/blob/1dd7318d2aed014c746d48c7957464c57af883ca/linode_api4/linode_client.py#L658-L682