index
int64
0
731k
package
stringlengths
2
98
name
stringlengths
1
76
docstring
stringlengths
0
281k
code
stringlengths
4
1.07M
signature
stringlengths
2
42.8k
45,289
easul.visual.element.element
create
Create element container for output :param form: :return:
def create(self, **kwargs): """ Create element container for output :param form: :return: """ output = [] start = self.render_content_start() if start: output.append(start) body = self.render_content_body(**kwargs) if body: output.append(body) end = self.render_content_end() if end: output.append(end) return "".join(output)
(self, **kwargs)
45,290
easul.visual.element.element
generate_context
null
def generate_context(self, algorithm, input_data, visual, **kwargs): ctx = {} for element in self.elements: element_ctx = element.generate_context(algorithm=algorithm, input_data=input_data, visual=visual, **kwargs) if not element_ctx: continue ctx.update(element_ctx) return ctx
(self, algorithm, input_data, visual, **kwargs)
45,291
easul.visual.element.element
generate_metadata
null
def generate_metadata(self, algorithm, dataset, **kwargs): metadata = {} for child_element in self.elements: child_metadata = child_element.generate_metadata(algorithm=algorithm, dataset=dataset, **kwargs) if child_metadata: metadata.update(child_metadata) return metadata
(self, algorithm, dataset, **kwargs)
45,292
easul.visual.element.element
prepare_element
null
def prepare_element(self, **kwargs): return
(self, **kwargs)
45,293
easul.visual.element.element
render_content_body
For each child element renders content using the classes' before_add_child() the child's create function and the classes' after_add_child() :param html: :param form: :return:
def render_content_body(self, **kwargs): """ For each child element renders content using the classes' before_add_child() the child's create function and the classes' after_add_child() :param html: :param form: :return: """ child_elements = self.elements if child_elements is None: return "" content_list = [] for child_element in child_elements: before = self.before_add_child(child_element) if before: content_list.append(before) content = child_element.create(**kwargs) if content: content_list.append(content) after = self.after_add_child(child_element) if after: content_list.append(after) return "".join(content_list)
(self, **kwargs)
45,294
easul.visual.element.element
render_content_end
null
def render_content_end(self, **kwargs): pass
(self, **kwargs)
45,295
easul.visual.element.element
render_content_start
null
def render_content_start(self, **kwargs): pass
(self, **kwargs)
45,296
easul.error
ConversionError
Unable to convert the input data to the correct type due to another exception.
class ConversionError(InvalidData): """ Unable to convert the input data to the correct type due to another exception. """ def __init__(self, message, orig_exception, **kwargs): self.orig_exception = orig_exception kwargs["orig"] = orig_exception super().__init__(message + " [" + ", ".join([k + "=" + str(v) for k,v in kwargs.items()]) + "]") def __repr__(self): return
(message, orig_exception, **kwargs)
45,297
easul.error
__init__
null
def __init__(self, message, orig_exception, **kwargs): self.orig_exception = orig_exception kwargs["orig"] = orig_exception super().__init__(message + " [" + ", ".join([k + "=" + str(v) for k,v in kwargs.items()]) + "]")
(self, message, orig_exception, **kwargs)
45,298
easul.error
__repr__
null
def __repr__(self): return
(self)
45,299
easul.process
ConvertRowsToDictionary
Converts list input to a dictionary containing the 'fields_to_extract' from the first row of the list and puts the input list data into the 'output_field' of the dictionary. If there are no 'fields_to_extract' it will output a dictionary containing just the input list data in the 'output_field' of the dictionary.
class ConvertRowsToDictionary: """ Converts list input to a dictionary containing the 'fields_to_extract' from the first row of the list and puts the input list data into the 'output_field' of the dictionary. If there are no 'fields_to_extract' it will output a dictionary containing just the input list data in the 'output_field' of the dictionary. """ output_field:str = field(default=None) fields_to_extract:List[str] = field(factory=list) def __call__(self, record): if type(record) is not list: raise AttributeError("Input data must be a list") if self.fields_to_extract: first_item = record[0] if len(record)>0 else {} new_record = {field:first_item.get(field) for field in self.fields_to_extract} else: new_record = {} new_record[self.output_field] = record return new_record
(*, output_field: str = None, fields_to_extract: List[str] = NOTHING) -> None
45,300
easul.process
__call__
null
def __call__(self, record): if type(record) is not list: raise AttributeError("Input data must be a list") if self.fields_to_extract: first_item = record[0] if len(record)>0 else {} new_record = {field:first_item.get(field) for field in self.fields_to_extract} else: new_record = {} new_record[self.output_field] = record return new_record
(self, record)
45,301
easul.process
__eq__
Method generated by attrs for class ConvertRowsToDictionary.
# processes are callables which receive a data structure and return a processed version of the data structure # most of the processes defined here are classes but functions can work as well from datetime import datetime, date, time import logging from typing import Callable, List, Dict, Optional LOG = logging.getLogger(__name__) from attrs import define, field @define(kw_only=True) class ExcludeFields: """ Exclude specified fields from the output data """ exclude_fields = field() def __call__(self, record): for exclude_field in self.exclude_fields: if exclude_field in record.keys(): del record[exclude_field] return record
(self, other)
45,304
easul.process
__ne__
Method generated by attrs for class ConvertRowsToDictionary.
null
(self, other)
45,307
easul.process
ConvertToFloat
Convert values in fields to float. If not possible will return None
class ConvertToFloat: """ Convert values in fields to float. If not possible will return None """ fields:List[str] = field() def __call__(self, record): for field in self.fields: try: record[field] = float(record[field]) except TypeError: record[field] = None except ValueError: record[field] = None except KeyError: record[field] = None return record
(*, fields: List[str]) -> None
45,308
easul.process
__call__
null
def __call__(self, record): for field in self.fields: try: record[field] = float(record[field]) except TypeError: record[field] = None except ValueError: record[field] = None except KeyError: record[field] = None return record
(self, record)
45,309
easul.process
__eq__
Method generated by attrs for class ConvertToFloat.
# processes are callables which receive a data structure and return a processed version of the data structure # most of the processes defined here are classes but functions can work as well from datetime import datetime, date, time import logging from typing import Callable, List, Dict, Optional LOG = logging.getLogger(__name__) from attrs import define, field @define(kw_only=True) class ExcludeFields: """ Exclude specified fields from the output data """ exclude_fields = field() def __call__(self, record): for exclude_field in self.exclude_fields: if exclude_field in record.keys(): del record[exclude_field] return record
(self, other)
45,312
easul.process
__ne__
Method generated by attrs for class ConvertToFloat.
null
(self, other)
45,315
easul.process
ConvertToInt
Convert values in fields to int. If not possible will return None. If value is a float it will be rounded to an int.
class ConvertToInt: """ Convert values in fields to int. If not possible will return None. If value is a float it will be rounded to an int. """ fields:List[str] = field() def __call__(self, record): for field in self.fields: try: value = float(record[field]) except TypeError: value = None except ValueError: value = None if value is not None: try: value = round(value) except ValueError: value = None record[field] = value return record
(*, fields: List[str]) -> None
45,316
easul.process
__call__
null
def __call__(self, record): for field in self.fields: try: value = float(record[field]) except TypeError: value = None except ValueError: value = None if value is not None: try: value = round(value) except ValueError: value = None record[field] = value return record
(self, record)
45,317
easul.process
__eq__
Method generated by attrs for class ConvertToInt.
# processes are callables which receive a data structure and return a processed version of the data structure # most of the processes defined here are classes but functions can work as well from datetime import datetime, date, time import logging from typing import Callable, List, Dict, Optional LOG = logging.getLogger(__name__) from attrs import define, field @define(kw_only=True) class ExcludeFields: """ Exclude specified fields from the output data """ exclude_fields = field() def __call__(self, record): for exclude_field in self.exclude_fields: if exclude_field in record.keys(): del record[exclude_field] return record
(self, other)
45,320
easul.process
__ne__
Method generated by attrs for class ConvertToInt.
null
(self, other)
45,323
easul.data
DFDataInput
Data input underpinned by pandas DataFrame inputs.
class DFDataInput(DataInput): """ Data input underpinned by pandas DataFrame inputs. """ convertors = { "number": lambda x, y: x.astype("float"), "float": lambda x,y: DFDataInput.to_float(x), "date": lambda x, y: pd.to_datetime(x, format=y["format"]), "datetime": lambda x, y: pd.to_datetime(x), "category": lambda x, y: x.astype("category"), "integer": lambda x, y: x.astype("int64"), "list": lambda x, y: list(x), "string": lambda x, y: x.astype("string"), "boolean": lambda x,y: DFDataInput.to_boolean(x) } @classmethod def to_boolean(cls,value): if type(value[0]) is str: if value[0] == "": return [None] value = value.astype("int64") return value.astype("boolean") @classmethod def to_float(cls,value): if type(value[0]) and value[0] == "" or value[0] is None: return pd.Series(np.nan() * len(value)) return value.astype("float") def _validate_data(self, data, fields): if len(fields)==0: return for field_name, field_details in fields.items(): if not field_name in data: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") v = self.validator_cls(fields, allow_unknown=False) for idx,row in data.iterrows(): if v.validate(row.to_dict()) is False: raise error.ValidationError(v.errors) def clean(self, data): for column in data.columns: if column in self.schema: continue del data[column] return data def _process_data(self, data): return data
(data, schema: easul.data.DataSchema, convert: bool = True, validate: bool = True, encoded_with=None, encoder=None)
45,324
easul.data
__init__
null
def __init__(self, data, schema: DataSchema, convert:bool=True, validate:bool=True, encoded_with=None, encoder=None): if encoded_with is not None and encoded_with != encoder: raise AttributeError("Data input encoded with different encoder than the defined one") self.schema = schema self._convert = convert self._validate = validate self.encoded_with = encoded_with self.encoder = encoder self._data = None self.data = data
(self, data, schema: easul.data.DataSchema, convert: bool = True, validate: bool = True, encoded_with=None, encoder=None)
45,325
easul.data
__repr__
null
def __repr__(self): data = self.data.to_dict("records") if isinstance(self.data, pd.DataFrame) else self.data return f"<{self.__class__.__name__} data={data}, schema={self.schema}>"
(self)
45,326
easul.data
_convert_data
null
def _convert_data(self, data, fields): if type(data) is list: return [self._convert_data(item, fields) for item in data] for field_name, field_details in fields.items(): try: if field_name not in data: if "required" in field_details: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") else: continue prev_convert = field_details.get("pre_convert") if prev_convert: pre_convert_fn = self.convertors.get(prev_convert) data[field_name] = pre_convert_fn(data[field_name], field_details) field_type = field_details['type'] convert_fn = self.convertors.get(field_type) if not convert_fn: raise error.ConversionError(f"Field conversion function not available to convert '{field_name}' to type '{field_type}'", orig_exception=Exception, data=data) data[field_name] = convert_fn(data[field_name], field_details) except Exception as ex: raise error.ConversionError(f"Unexpected error converting '{field_name}'", orig_exception=ex) return data
(self, data, fields)
45,327
easul.data
_extract_data
null
def _extract_data(self, field_names): data = self.data[field_names].to_numpy() if self.encoder: idx = 0 for field_name in field_names: if self.encoder.is_field_encoded(field_name): col = self.encoder.encode_field(field_name, self) if len(col[0])>1: data = np.concatenate((data[:,range(0,idx)], col, data[:,range(idx+1,data.shape[1])]), axis=1) idx+=col.shape[1] else: data[:idx] = col idx+=1 return data
(self, field_names)
45,328
easul.data
_init_data
null
def _init_data(self, data): try: if self._convert: data = self.convert_data(data) except BaseException as ex: raise error.ConversionError(message="Unable to convert data", orig_exception=ex, data=data) data = self.clean(data) if self._validate: self.validate(data) self._data = self._process_data(data)
(self, data)
45,329
easul.data
_process_data
null
def _process_data(self, data): return data
(self, data)
45,330
easul.data
_validate_data
null
def _validate_data(self, data, fields): if len(fields)==0: return for field_name, field_details in fields.items(): if not field_name in data: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") v = self.validator_cls(fields, allow_unknown=False) for idx,row in data.iterrows(): if v.validate(row.to_dict()) is False: raise error.ValidationError(v.errors)
(self, data, fields)
45,331
easul.data
asdict
null
def asdict(self): return self.data.to_dict("records") if isinstance(self.data, pd.DataFrame) else self.data
(self)
45,332
easul.data
clean
null
def clean(self, data): for column in data.columns: if column in self.schema: continue del data[column] return data
(self, data)
45,333
easul.data
convert_data
null
def convert_data(self, data): return self._convert_data(data, self.schema)
(self, data)
45,334
easul.data
is_matching_encoder
null
def is_matching_encoder(self, encoder): return self.encoded_with == encoder
(self, encoder)
45,335
easul.data
train_test_split
null
def train_test_split(self, train_size=None, test_size=None, splitter=np_random_splitter, **kwargs): if not train_size and not test_size: raise AttributeError("train_size or test_size must be provided") if not train_size: train_size = 1-test_size train, test = splitter(self.data, train_size, **kwargs) data_cls = self.__class__ if isinstance(self.data, pd.DataFrame): data_cls = DFDataInput train_ds = data_cls(data=train,schema=self.schema, convert=False, validate=False) test_ds = data_cls(data=test,schema=self.schema, convert=False, validate=False) return train_ds, test_ds
(self, train_size=None, test_size=None, splitter=<function np_random_splitter at 0x7f4a18cb7d00>, **kwargs)
45,336
easul.data
validate
null
def validate(self, data): if type(data) is list: [self._validate_data(item, self.schema) for item in data] else: self._validate_data(data, self.schema)
(self, data)
45,337
easul.source
DataFrameSource
Source which gets 'data' from a pandas DataFrame utilising an appropriate 'reference_field'. Also can use optional 'timestamp_field' if temporal in nature.
class DataFrameSource(Source): """ Source which gets 'data' from a pandas DataFrame utilising an appropriate 'reference_field'. Also can use optional 'timestamp_field' if temporal in nature. """ data:pd.DataFrame = field(factory=pd.DataFrame) reference_field = field() timestamp_field = field(default=None) def __attrs_post_init__(self): if self.timestamp_field: self.data.sort_values(by=[self.timestamp_field], inplace=True,ascending=False) def _retrieve_raw_data(self, driver, step): data = self.data.query(self.reference_field + " == '" + driver.journey["reference"] + "'") if data.shape[0]==0: raise StepDataNotAvailable(journey=driver.journey, step_name = step.name) return data.to_dict("records")[0] def __iter__(self): for idx, adm in self.data.iterrows(): yield self._process_raw_data(adm)
(*, title: str, processes=NOTHING, data: pandas.core.frame.DataFrame = NOTHING, reference_field, timestamp_field=None) -> None
45,338
easul.source
__attrs_post_init__
null
def __attrs_post_init__(self): if self.timestamp_field: self.data.sort_values(by=[self.timestamp_field], inplace=True,ascending=False)
(self)
45,339
easul.source
__eq__
Method generated by attrs for class DataFrameSource.
import pandas as pd from typing import List, Any, Dict from easul.error import StepDataNotAvailable import logging from abc import abstractmethod from attrs import define, field from functools import partial from easul.util import get_current_result LOG = logging.getLogger(__name__) @define(kw_only=True) class Source: """ Base Source class. Sources provide access to raw data and processing which enables the creation of validated InputData - which can be fed into algorithms. """ title: str = field() processes = field(factory=list) def retrieve(self, driver, step): """ Retrieve data in the form of a Python data structure. Args: driver: step: Returns: """ data = self._retrieve_final_data(driver, step) if not data: raise StepDataNotAvailable(driver.journey, step.name, retry=False, source_title=self.title) return data def _retrieve_final_data(self, driver, step): raw_data = self._retrieve_raw_data(driver, step) return self._process_raw_data(raw_data) @abstractmethod def _retrieve_raw_data(self, driver, step): pass @property def source_titles(self): return [self.title] def describe(self): return { "title":self.title, "type":self.__class__.__name__, } def _process_raw_data(self, raw_data): if raw_data is None: raw_data = {} for process in self.processes: raw_data = process(raw_data) return raw_data
(self, other)
45,342
easul.source
__iter__
null
def __iter__(self): for idx, adm in self.data.iterrows(): yield self._process_raw_data(adm)
(self)
45,343
easul.source
__ne__
Method generated by attrs for class DataFrameSource.
null
(self, other)
45,348
easul.source
_retrieve_raw_data
null
def _retrieve_raw_data(self, driver, step): data = self.data.query(self.reference_field + " == '" + driver.journey["reference"] + "'") if data.shape[0]==0: raise StepDataNotAvailable(journey=driver.journey, step_name = step.name) return data.to_dict("records")[0]
(self, driver, step)
45,351
easul.data
DataInput
Data and schema combined including automatic data conversion and access to data in particular forms. Support for pandas DataFrames and list of dictionaries (which are internally converted).
class DataInput: """ Data and schema combined including automatic data conversion and access to data in particular forms. Support for pandas DataFrames and list of dictionaries (which are internally converted). """ validator_cls = DataValidator convertors = { "number": to_float, "float": to_float, "date": lambda x, y: dt.datetime.strptime(x, y["format"]) if isinstance(x, str) else x, "datetime": lambda x,y: DataInput.to_datetime(x, y) if isinstance(x,str) else x, "time": lambda x, y: DataInput.to_datetime(x, y).time() if isinstance(x, str) else x, "category": lambda x, y: x, "integer": lambda x, y: np.int64(x), "list": lambda x, y: list(x) if x else [], "string": lambda x, y: str(x), "boolean": to_boolean } @classmethod def to_datetime(cls, value, config): if type(value) is dt.datetime: return value return dt.datetime.strptime(value, config.get("format", "%Y-%m-%dT%H:%M:%S")) def __init__(self, data, schema: DataSchema, convert:bool=True, validate:bool=True, encoded_with=None, encoder=None): if encoded_with is not None and encoded_with != encoder: raise AttributeError("Data input encoded with different encoder than the defined one") self.schema = schema self._convert = convert self._validate = validate self.encoded_with = encoded_with self.encoder = encoder self._data = None self.data = data @property def is_encoded(self): return self.encoded_with is not None def is_matching_encoder(self, encoder): return self.encoded_with == encoder @property def data(self): return self._data @data.setter def data(self, value): self._init_data(value) def _init_data(self, data): try: if self._convert: data = self.convert_data(data) except BaseException as ex: raise error.ConversionError(message="Unable to convert data", orig_exception=ex, data=data) data = self.clean(data) if self._validate: self.validate(data) self._data = self._process_data(data) def convert_data(self, data): return self._convert_data(data, self.schema) def validate(self, data): if type(data) is list: [self._validate_data(item, self.schema) for item in data] else: self._validate_data(data, self.schema) def clean(self, data): return data def _convert_data(self, data, fields): if type(data) is list: return [self._convert_data(item, fields) for item in data] for field_name, field_details in fields.items(): try: if field_name not in data: if "required" in field_details: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") else: continue prev_convert = field_details.get("pre_convert") if prev_convert: pre_convert_fn = self.convertors.get(prev_convert) data[field_name] = pre_convert_fn(data[field_name], field_details) field_type = field_details['type'] convert_fn = self.convertors.get(field_type) if not convert_fn: raise error.ConversionError(f"Field conversion function not available to convert '{field_name}' to type '{field_type}'", orig_exception=Exception, data=data) data[field_name] = convert_fn(data[field_name], field_details) except Exception as ex: raise error.ConversionError(f"Unexpected error converting '{field_name}'", orig_exception=ex) return data def _process_data(self, data): if type(data) is dict: return pd.DataFrame(data=[data]) if type(data) is list: return pd.DataFrame(data=data) return data def _validate_data(self, data, fields): if len(fields)==0: return for field_name, field_details in fields.items(): if not field_name in data: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") v = self.validator_cls(fields, allow_unknown=False) if type(data) is list: for row in data: if v.validate(row) is False: raise error.ValidationError(v.errors) else: if v.validate(data) is False: raise error.ValidationError(v.errors) @property def Y_array(self): """ Returns: Y values in the form of an array of np.arrays """ return self.data[self.schema.y_names].to_numpy() @property def Y(self): """ Returns: Y values from the Y array (e.g. the first value) as an np.array """ data = self._extract_data(self.schema.y_names) if self.schema.single_y: return [item[0] for item in data] return data @property def X(self): return self._extract_data(self.schema.x_names) def _extract_data(self, field_names): data = self.data[field_names].to_numpy() if self.encoder: idx = 0 for field_name in field_names: if self.encoder.is_field_encoded(field_name): col = self.encoder.encode_field(field_name, self) if len(col[0])>1: data = np.concatenate((data[:,range(0,idx)], col, data[:,range(idx+1,data.shape[1])]), axis=1) idx+=col.shape[1] else: data[:idx] = col idx+=1 return data @property def X_data(self): """ Returns: A pandas DataFrame containing just X values. """ if len(self.schema.x_names)==0: return [] return self.data[self.schema.x_names] @property def Y_data(self): """ Returns: A pandas DataFrame containing just Y values """ if len(self.schema.y_names)==0: return [] return self.data.loc[:,self.schema.y_names] def train_test_split(self, train_size=None, test_size=None, splitter=np_random_splitter, **kwargs): if not train_size and not test_size: raise AttributeError("train_size or test_size must be provided") if not train_size: train_size = 1-test_size train, test = splitter(self.data, train_size, **kwargs) data_cls = self.__class__ if isinstance(self.data, pd.DataFrame): data_cls = DFDataInput train_ds = data_cls(data=train,schema=self.schema, convert=False, validate=False) test_ds = data_cls(data=test,schema=self.schema, convert=False, validate=False) return train_ds, test_ds def __repr__(self): data = self.data.to_dict("records") if isinstance(self.data, pd.DataFrame) else self.data return f"<{self.__class__.__name__} data={data}, schema={self.schema}>" def asdict(self): return self.data.to_dict("records") if isinstance(self.data, pd.DataFrame) else self.data def clean(self, data): new_data = [] for idx,row in enumerate(data): new_row = {} for column, value in row.items(): if column in self.schema: new_row[column] = value new_data.append(new_row) return new_data
(data, schema: easul.data.DataSchema, convert: bool = True, validate: bool = True, encoded_with=None, encoder=None)
45,357
easul.data
_process_data
null
def _process_data(self, data): if type(data) is dict: return pd.DataFrame(data=[data]) if type(data) is list: return pd.DataFrame(data=data) return data
(self, data)
45,358
easul.data
_validate_data
null
def _validate_data(self, data, fields): if len(fields)==0: return for field_name, field_details in fields.items(): if not field_name in data: raise error.ValidationError(f"Field '{field_name}' is not present in the input data") v = self.validator_cls(fields, allow_unknown=False) if type(data) is list: for row in data: if v.validate(row) is False: raise error.ValidationError(v.errors) else: if v.validate(data) is False: raise error.ValidationError(v.errors)
(self, data, fields)
45,360
easul.data
clean
null
def clean(self, data): new_data = [] for idx,row in enumerate(data): new_row = {} for column, value in row.items(): if column in self.schema: new_row[column] = value new_data.append(new_row) return new_data
(self, data)
45,365
easul.data
DataSchema
Schema used by algorithms to define format of input data. Field definitions utilise 'cerberus' library to validate input data.
class DataSchema(UserDict): """ Schema used by algorithms to define format of input data. Field definitions utilise 'cerberus' library to validate input data. """ def __init__(self, schema:Dict[str,Dict], y_names=None): if not y_names: y_names = [] self.y_names:List[str] = y_names if not all([name in schema for name in y_names]): raise AttributeError(f"Not all y_names {y_names} are in schema definition {list(schema.keys())}") super().__init__(schema) self.refresh() def refresh(self): if self.filter({"type":"category","output":"onehot"},include_x=False,include_y=True): self.single_y = False else: self.single_y = True if len(self.y_names) == 1 else False category_fields = self.filter({"type": "category"}, include_x = True, include_y = True) for category_field_name, category_details in category_fields.items(): if not category_details.get("options"): raise error.ValidationError(f"Field '{category_field_name}' with 'category' type must have 'options' provided") @property def x(self): return {name: self.data[name] for name in filter(lambda x: x in self.x_names, self.data.keys())} @property def y(self): return {name: self.data[name] for name in filter(lambda x: x in self.y_names, self.data.keys())} def to_x_values(self, field_values): return to_np_values(field_values, self.x) def to_y_values(self, field_values): return to_np_values(field_values, self.y) @property def help(self): help_lines = [self._help_line(k,v) for k,v in self.data.items()] help_lines.extend(["* = required field","** = target y value"]) return help_lines def _help_line(self, name, info): return f"- {name}: {info.get('help')}" + ("*" if info.get("required") else " ") + "(" + info.get("type","any") + ")" + ("**" if name in self.y_names else "") def filter(self, criteria=None, include_x=True, include_y=False): filtered = {} for name, info in self.items(): include = True if include_x and include_y and name not in self.data: continue elif include_x and not include_y and name not in self.x_names: continue elif include_y and not include_x and name not in self.y_names: continue if criteria: for filt_k, filt_v in criteria.items(): if filt_k in info and info[filt_k] != filt_v: include = False if include is True: filtered[name] = info return filtered def filter_names(self, **kwargs): filtered = self.filter(**kwargs) return list(filtered.keys()) @property def x_names(self): return list(filter(lambda x: x not in self.y_names, self.data.keys())) @property def unique_digest(self): return "X" def is_categorical(self, name): if self.get(name,{}).get("type") in ["category","list"]: return True return False
(schema: Dict[str, Dict], y_names=None)
45,366
collections
__contains__
null
def __contains__(self, key): return key in self.data
(self, key)
45,367
collections
__copy__
null
def __copy__(self): inst = self.__class__.__new__(self.__class__) inst.__dict__.update(self.__dict__) # Create a copy and avoid triggering descriptors inst.__dict__["data"] = self.__dict__["data"].copy() return inst
(self)
45,368
collections
__delitem__
null
def __delitem__(self, key): del self.data[key]
(self, key)
45,370
collections
__getitem__
null
def __getitem__(self, key): if key in self.data: return self.data[key] if hasattr(self.__class__, "__missing__"): return self.__class__.__missing__(self, key) raise KeyError(key)
(self, key)
45,371
easul.data
__init__
null
def __init__(self, schema:Dict[str,Dict], y_names=None): if not y_names: y_names = [] self.y_names:List[str] = y_names if not all([name in schema for name in y_names]): raise AttributeError(f"Not all y_names {y_names} are in schema definition {list(schema.keys())}") super().__init__(schema) self.refresh()
(self, schema: Dict[str, Dict], y_names=None)
45,372
collections
__ior__
null
def __ior__(self, other): if isinstance(other, UserDict): self.data |= other.data else: self.data |= other return self
(self, other)
45,373
collections
__iter__
null
def __iter__(self): return iter(self.data)
(self)
45,375
collections
__or__
null
def __or__(self, other): if isinstance(other, UserDict): return self.__class__(self.data | other.data) if isinstance(other, dict): return self.__class__(self.data | other) return NotImplemented
(self, other)
45,376
collections
__repr__
null
def __repr__(self): return repr(self.data)
(self)
45,377
collections
__ror__
null
def __ror__(self, other): if isinstance(other, UserDict): return self.__class__(other.data | self.data) if isinstance(other, dict): return self.__class__(other | self.data) return NotImplemented
(self, other)
45,378
collections
__setitem__
null
def __setitem__(self, key, item): self.data[key] = item
(self, key, item)
45,379
easul.data
_help_line
null
def _help_line(self, name, info): return f"- {name}: {info.get('help')}" + ("*" if info.get("required") else " ") + "(" + info.get("type","any") + ")" + ("**" if name in self.y_names else "")
(self, name, info)
45,381
collections
copy
null
def copy(self): if self.__class__ is UserDict: return UserDict(self.data.copy()) import copy data = self.data try: self.data = {} c = copy.copy(self) finally: self.data = data c.update(self) return c
(self)
45,382
easul.data
filter
null
def filter(self, criteria=None, include_x=True, include_y=False): filtered = {} for name, info in self.items(): include = True if include_x and include_y and name not in self.data: continue elif include_x and not include_y and name not in self.x_names: continue elif include_y and not include_x and name not in self.y_names: continue if criteria: for filt_k, filt_v in criteria.items(): if filt_k in info and info[filt_k] != filt_v: include = False if include is True: filtered[name] = info return filtered
(self, criteria=None, include_x=True, include_y=False)
45,383
easul.data
filter_names
null
def filter_names(self, **kwargs): filtered = self.filter(**kwargs) return list(filtered.keys())
(self, **kwargs)
45,385
easul.data
is_categorical
null
def is_categorical(self, name): if self.get(name,{}).get("type") in ["category","list"]: return True return False
(self, name)
45,390
easul.data
refresh
null
def refresh(self): if self.filter({"type":"category","output":"onehot"},include_x=False,include_y=True): self.single_y = False else: self.single_y = True if len(self.y_names) == 1 else False category_fields = self.filter({"type": "category"}, include_x = True, include_y = True) for category_field_name, category_details in category_fields.items(): if not category_details.get("options"): raise error.ValidationError(f"Field '{category_field_name}' with 'category' type must have 'options' provided")
(self)
45,392
easul.data
to_x_values
null
def to_x_values(self, field_values): return to_np_values(field_values, self.x)
(self, field_values)
45,393
easul.data
to_y_values
null
def to_y_values(self, field_values): return to_np_values(field_values, self.y)
(self, field_values)
45,396
easul.data
DataValidator
Cerberus Validator for DataSet schema. Includes additional type mapping for 'time' and additional validation parameters: 'help', 'options', 'output', 'label' and 'pre_convert'
class DataValidator(Validator): """ Cerberus Validator for DataSet schema. Includes additional type mapping for 'time' and additional validation parameters: 'help', 'options', 'output', 'label' and 'pre_convert' """ types_mapping = Validator.types_mapping.copy() types_mapping[CATEGORY_TYPE] = TypeDefinition(CATEGORY_TYPE, (object,), ()) types_mapping["time"] = TypeDefinition('time', (dt.time,), ()) def _validate_help(self, constraint, field, value): """{'type': 'string'}""" pass def _validate_options(self, constraint, field, value): """{'type': 'dict'}""" if value not in constraint: self._error(field, f"Value '" + str(value) + "' is not defined in options") def _validate_output(self, constraint, field, value): """{'type': 'string'}""" pass def _validate_label(self, constraint, field, value): """{'type': 'string'}""" pass def _validate_pre_convert(self, constraint, field, value): """{'type': 'string'}""" pass
(*args, **kwargs)
45,446
easul.data
_validate_help
{'type': 'string'}
def _validate_help(self, constraint, field, value): """{'type': 'string'}""" pass
(self, constraint, field, value)
45,449
easul.data
_validate_label
{'type': 'string'}
def _validate_label(self, constraint, field, value): """{'type': 'string'}""" pass
(self, constraint, field, value)
45,458
easul.data
_validate_options
{'type': 'dict'}
def _validate_options(self, constraint, field, value): """{'type': 'dict'}""" if value not in constraint: self._error(field, f"Value '" + str(value) + "' is not defined in options")
(self, constraint, field, value)
45,459
easul.data
_validate_output
{'type': 'string'}
def _validate_output(self, constraint, field, value): """{'type': 'string'}""" pass
(self, constraint, field, value)
45,460
easul.data
_validate_pre_convert
{'type': 'string'}
def _validate_pre_convert(self, constraint, field, value): """{'type': 'string'}""" pass
(self, constraint, field, value)
45,471
easul.source
DbSource
Source which retrieves data from a database. Currently only supports SQLite.
class DbSource(Source): """ Source which retrieves data from a database. Currently only supports SQLite. """ db:str = field() table_name:str = field(default=None) sql:str = field(default=None) reference_field:str = field() multiple_rows = field(default=False) _cache = field(factory=dict) _data_fn = field() def __attrs_post_init__(self): if self.table_name is None and self.sql is None: raise AttributeError("You must specify 'table_name' or 'sql'") @_data_fn.default def _default_data_fn(self): if self.table_name: return partial(self.db.get_rows, table_name=self.table_name) else: return partial(self.db.get_rows_with_sql, sql=self.sql) def _get_parameters(self, driver): return {self.reference_field:driver.journey["reference"]} def _retrieve_final_data(self, driver, step): if driver.journey["reference"] in self._cache: return self._cache[driver.journey["reference"]] data = super()._retrieve_final_data(driver, step) self._cache[driver.journey["reference"]] = data return data def _retrieve_raw_data(self, driver, step): params = self._get_parameters(driver) data = self._data_fn(values=params) if self.multiple_rows is False and type(data) is list: return data[0] if len(data) > 0 else None return data
(*, title: str, processes=NOTHING, db: str, table_name: str = None, sql: str = None, reference_field: str, multiple_rows=False, cache=NOTHING, data_fn=NOTHING) -> None
45,472
easul.source
__attrs_post_init__
null
def __attrs_post_init__(self): if self.table_name is None and self.sql is None: raise AttributeError("You must specify 'table_name' or 'sql'")
(self)
45,473
easul.source
__eq__
Method generated by attrs for class DbSource.
import pandas as pd from typing import List, Any, Dict from easul.error import StepDataNotAvailable import logging from abc import abstractmethod from attrs import define, field from functools import partial from easul.util import get_current_result LOG = logging.getLogger(__name__) @define(kw_only=True) class Source: """ Base Source class. Sources provide access to raw data and processing which enables the creation of validated InputData - which can be fed into algorithms. """ title: str = field() processes = field(factory=list) def retrieve(self, driver, step): """ Retrieve data in the form of a Python data structure. Args: driver: step: Returns: """ data = self._retrieve_final_data(driver, step) if not data: raise StepDataNotAvailable(driver.journey, step.name, retry=False, source_title=self.title) return data def _retrieve_final_data(self, driver, step): raw_data = self._retrieve_raw_data(driver, step) return self._process_raw_data(raw_data) @abstractmethod def _retrieve_raw_data(self, driver, step): pass @property def source_titles(self): return [self.title] def describe(self): return { "title":self.title, "type":self.__class__.__name__, } def _process_raw_data(self, raw_data): if raw_data is None: raw_data = {} for process in self.processes: raw_data = process(raw_data) return raw_data
(self, other)
45,476
easul.source
__ne__
Method generated by attrs for class DbSource.
null
(self, other)
45,479
easul.source
_default_data_fn
null
@_data_fn.default def _default_data_fn(self): if self.table_name: return partial(self.db.get_rows, table_name=self.table_name) else: return partial(self.db.get_rows_with_sql, sql=self.sql)
(self)
45,480
easul.source
_get_parameters
null
def _get_parameters(self, driver): return {self.reference_field:driver.journey["reference"]}
(self, driver)
45,482
easul.source
_retrieve_final_data
null
def _retrieve_final_data(self, driver, step): if driver.journey["reference"] in self._cache: return self._cache[driver.journey["reference"]] data = super()._retrieve_final_data(driver, step) self._cache[driver.journey["reference"]] = data return data
(self, driver, step)
45,483
easul.source
_retrieve_raw_data
null
def _retrieve_raw_data(self, driver, step): params = self._get_parameters(driver) data = self._data_fn(values=params) if self.multiple_rows is False and type(data) is list: return data[0] if len(data) > 0 else None return data
(self, driver, step)
45,486
easul.decision
Decision
Decides the outcome based on the provided result and the type of decision. The outcome includes the next step, the result and other contextual information.
class Decision: """ Decides the outcome based on the provided result and the type of decision. The outcome includes the next step, the result and other contextual information. """ @abstractmethod def decide_outcome(self, result, context, data, step): pass @property def possible_links(self): return {} def describe(self): return { "type":self.__class__.__name__ }
() -> None
45,487
easul.decision
__eq__
Method generated by attrs for class Decision.
from abc import abstractmethod from attrs import define, field from easul.algorithm import Result from easul.outcome import Outcome, ResultOutcome from easul.expression import DecisionCase @define(kw_only=True) class Decision: """ Decides the outcome based on the provided result and the type of decision. The outcome includes the next step, the result and other contextual information. """ @abstractmethod def decide_outcome(self, result, context, data, step): pass @property def possible_links(self): return {} def describe(self): return { "type":self.__class__.__name__ }
(self, other)
45,490
easul.decision
__ne__
Method generated by attrs for class Decision.
null
(self, other)
45,493
easul.decision
decide_outcome
null
@abstractmethod def decide_outcome(self, result, context, data, step): pass
(self, result, context, data, step)
45,495
easul.expression
DecisionCase
Case class used by Decision classes which instead of a value if true returns a Step.
class DecisionCase: """ Case class used by Decision classes which instead of a value if true returns a Step. """ expression = field() true_step = field(default=None) title = field(default=None) def asdict(self): return { "expression":str(self.expression), "true_step":str(self.true_step.name if self.true_step else "") } def test(self, dset): return self.expression.evaluate(dset)
(*, expression, true_step=None, title=None) -> None
45,496
easul.expression
__eq__
Method generated by attrs for class DecisionCase.
import operator import re from abc import abstractmethod from typing import Callable from attrs import define, field import numpy as np import pandas as pd from easul.error import MissingValue import logging LOG = logging.getLogger(__name__) @define(kw_only=True) class Expression: """ Base Expression class. Derived classes evaluate input data and return a True/False """ label = "" empty_values = [None, np.nan] @abstractmethod def evaluate(self, data): pass @classmethod def is_empty(cls, item): if item in cls.empty_values: return True try: if np.isnan(item): return True except TypeError: pass return False
(self, other)
45,499
easul.expression
__ne__
Method generated by attrs for class DecisionCase.
null
(self, other)
45,502
easul.expression
asdict
null
def asdict(self): return { "expression":str(self.expression), "true_step":str(self.true_step.name if self.true_step else "") }
(self)
45,504
easul.algorithm.result
DefaultResult
Result used when data is missing to output a default result
class DefaultResult(Result): """ Result used when data is missing to output a default result """ label = "Default result"
(*, value, data) -> None
45,505
easul.algorithm.result
__eq__
Method generated by attrs for class DefaultResult.
from collections import namedtuple from typing import Optional from attrs import define, field import logging LOG = logging.getLogger(__name__) Probability = namedtuple("Probability",["probability","label","value"]) @define(kw_only=True, eq=False) class Result: """ Base result class which at a simple level just returns a value. """ value = field() data = field() def asdict(self): """ Dictionary representation of the result used to store the object in databases etc. Returns: """ return { "value": self.value, "data": self.data.asdict() } def __getitem__(self, item): if not hasattr(self, item): return None return getattr(self, item) def __eq__(self, other): return self.asdict() == other.asdict()
(self, other)
45,509
easul.algorithm.result
__ne__
Method generated by attrs for class DefaultResult.
null
(self, other)
45,513
easul.process
DefaultValues
Replaces values in record with default 'values' if they are None. If 'present_flag_field' is set, it will also update this field in the record with a 1 when default values have been added.
class DefaultValues: """ Replaces values in record with default 'values' if they are None. If 'present_flag_field' is set, it will also update this field in the record with a 1 when default values have been added. """ values = field() present_flag_field = field(default=None) def __call__(self, record): if record is None and self.present_flag_field is not None: record = self.values record[self.present_flag_field] = 0 return record if self.present_flag_field is not None: record[self.present_flag_field] = 0 for key, value in self.values.items(): if record.get(key): if self.present_flag_field is not None: record[self.present_flag_field] = 1 continue record[key] = value return record
(*, values, present_flag_field=None) -> None
45,514
easul.process
__call__
null
def __call__(self, record): if record is None and self.present_flag_field is not None: record = self.values record[self.present_flag_field] = 0 return record if self.present_flag_field is not None: record[self.present_flag_field] = 0 for key, value in self.values.items(): if record.get(key): if self.present_flag_field is not None: record[self.present_flag_field] = 1 continue record[key] = value return record
(self, record)
45,515
easul.process
__eq__
Method generated by attrs for class DefaultValues.
# processes are callables which receive a data structure and return a processed version of the data structure # most of the processes defined here are classes but functions can work as well from datetime import datetime, date, time import logging from typing import Callable, List, Dict, Optional LOG = logging.getLogger(__name__) from attrs import define, field @define(kw_only=True) class ExcludeFields: """ Exclude specified fields from the output data """ exclude_fields = field() def __call__(self, record): for exclude_field in self.exclude_fields: if exclude_field in record.keys(): del record[exclude_field] return record
(self, other)
45,518
easul.process
__ne__
Method generated by attrs for class DefaultValues.
null
(self, other)
45,521
easul.util
DeferredCatalog
Extension of dictionary which returns a DeferredItem if
class DeferredCatalog(UserDict): """ Extension of dictionary which returns a DeferredItem if """ # def __getitem__(self, item): # if item not in self.data: # return DeferredItem(item, self) # # return super().__getitem__(item) # def get(self, key): # if key not in self.data: # return DeferredItem(key, self) # # return super().get(key) def update(self, __m, **kwargs): for k,v in __m.items(): if hasattr(v, "name"): v.name = k super().update(__m) def __setitem__(self, key ,value): if hasattr(value, "name"): value.name = key super().__setitem__(key, value)
(dict=None, /, **kwargs)
45,527
collections
__init__
null
def __init__(self, dict=None, /, **kwargs): self.data = {} if dict is not None: self.update(dict) if kwargs: self.update(kwargs)
(self, dict=None, /, **kwargs)
45,534
easul.util
__setitem__
null
def __setitem__(self, key ,value): if hasattr(value, "name"): value.name = key super().__setitem__(key, value)
(self, key, value)
45,543
easul.util
update
null
def update(self, __m, **kwargs): for k,v in __m.items(): if hasattr(v, "name"): v.name = k super().update(__m)
(self, _DeferredCatalog__m, **kwargs)
45,545
easul.util
DeferredItem
Used to refer to an item if it has not been instantiated yet or there is a circular reference between two items (potential for recurrence.
class DeferredItem: """ Used to refer to an item if it has not been instantiated yet or there is a circular reference between two items (potential for recurrence. """ def __init__(self, plan, property, name): self.__dict__['plan'] = plan self.__dict__['property'] = property self.__dict__['name'] = name def __repr__(self): return f"<DeferredItem name={self.name} property={self.property}>" def __getattr__(self, item): return getattr(self.plan.get_property(self.property, self.name), item) def __setattr__(self, key, value): setattr(self.plan.get_property(self.property, self.name), key, value) def __instancecheck__(self, instance): return isinstance(self.plan.get_property(self.property, self.name), instance) def __iter__(self): return iter(self.plan.get_property(self.property)) def __eq__(self, other): return self.plan.get_property(self.property, self.name) == other def replace_plan(self, new_plan): self.__dict__['plan'] = new_plan
(plan, property, name)