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,776 |
easul.visual.element.element
|
start_element
| null |
def start_element(self, tag, attrs=None):
if attrs:
attrs = [k + "=\"" + (v if v else "") +"\"" for k,v in attrs.items()]
else:
attrs = []
attr_list = " ".join(attrs)
self._elements.append(f"<{tag} {attr_list}>")
|
(self, tag, attrs=None)
|
45,777 |
easul.process
|
IfElseTest
|
Returns 'true_value' or 'false_value' in 'output_field' depending on whether expression evaluates to true or false
when supplied with the record.
|
class IfElseTest:
"""
Returns 'true_value' or 'false_value' in 'output_field' depending on whether expression evaluates to true or false
when supplied with the record.
"""
expression = field()
output_field = field()
true_value = field()
false_value = field()
def __call__(self, record):
record[self.output_field] = self.true_value if self.expression.evaluate(record) else self.false_value
return record
|
(*, expression, output_field, true_value, false_value) -> None
|
45,778 |
easul.process
|
__call__
| null |
def __call__(self, record):
record[self.output_field] = self.true_value if self.expression.evaluate(record) else self.false_value
return record
|
(self, record)
|
45,779 |
easul.process
|
__eq__
|
Method generated by attrs for class IfElseTest.
|
# 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,782 |
easul.process
|
__ne__
|
Method generated by attrs for class IfElseTest.
| null |
(self, other)
|
45,785 |
easul.action
|
IgnoreMissingData
|
Action which handles missing data and sets an outcome with a default value.
|
class IgnoreMissingData(Action):
"""
Action which handles missing data and sets an outcome with a default value.
"""
default_value = field()
next_step = field()
def missing_data(self, event):
event.outcome = ResultOutcome(outcome_step=event.step, input_data=event.data, next_step = self.next_step, reason="Missing data", result=DefaultResult(value=None, data=self.default_value), value=self.default_value)
|
(*, default_value, next_step) -> None
|
45,786 |
easul.action
|
__eq__
|
Method generated by attrs for class IgnoreMissingData.
|
"""
"""
import logging
from easul.algorithm.result import DefaultResult
from easul.outcome import ResultOutcome
LOG = logging.getLogger(__name__)
from attrs import define, field
class StopFlow(Exception):
pass
|
(self, other)
|
45,789 |
easul.action
|
__ne__
|
Method generated by attrs for class IgnoreMissingData.
| null |
(self, other)
|
45,797 |
easul.action
|
missing_data
| null |
def missing_data(self, event):
event.outcome = ResultOutcome(outcome_step=event.step, input_data=event.data, next_step = self.next_step, reason="Missing data", result=DefaultResult(value=None, data=self.default_value), value=self.default_value)
|
(self, event)
|
45,798 |
easul.action
|
IgnoreMissingTimebasedData
|
Action which handles missing data and sets a timestamp in the outcome.
|
class IgnoreMissingTimebasedData(IgnoreMissingData):
"""
Action which handles missing data and sets a timestamp in the outcome.
"""
timestamp_field = field()
def missing_data(self, event):
values = self.default_value
values[self.timestamp_field] = event.driver.clock.timestamp
event.outcome = ResultOutcome(outcome_step=event.step, input_data=event.data, next_step = self.next_step, reason="Missing data", result=DefaultResult(value=None, data=values), value=values)
|
(*, default_value, next_step, timestamp_field) -> None
|
45,799 |
easul.action
|
__eq__
|
Method generated by attrs for class IgnoreMissingTimebasedData.
|
"""
"""
import logging
from easul.algorithm.result import DefaultResult
from easul.outcome import ResultOutcome
LOG = logging.getLogger(__name__)
from attrs import define, field
class StopFlow(Exception):
pass
|
(self, other)
|
45,802 |
easul.action
|
__ne__
|
Method generated by attrs for class IgnoreMissingTimebasedData.
| null |
(self, other)
|
45,810 |
easul.action
|
missing_data
| null |
def missing_data(self, event):
values = self.default_value
values[self.timestamp_field] = event.driver.clock.timestamp
event.outcome = ResultOutcome(outcome_step=event.step, input_data=event.data, next_step = self.next_step, reason="Missing data", result=DefaultResult(value=None, data=values), value=values)
|
(self, event)
|
45,811 |
easul.data
|
InputEncoder
|
Base encoder which encodes input data according to supplied encoding functions for each field.
|
class InputEncoder:
"""
Base encoder which encodes input data according to supplied encoding functions for each field.
"""
def __init__(self, encodings):
self.encodings = encodings
def encode_input(self, dinput):
for field_name,encoder_fn in self.encodings.items():
col = encoder_fn(field_name, dinput)
dinput.data[field_name] = col
def encode_field(self, field_name, dinput):
encoder_fn = self.encodings.get(field_name)
if not encoder_fn:
return dinput[field_name]
return encoder_fn(field_name, dinput)
def is_field_encoded(self, field_name):
return field_name in self.encodings
|
(encodings)
|
45,812 |
easul.data
|
__init__
| null |
def __init__(self, encodings):
self.encodings = encodings
|
(self, encodings)
|
45,813 |
easul.data
|
encode_field
| null |
def encode_field(self, field_name, dinput):
encoder_fn = self.encodings.get(field_name)
if not encoder_fn:
return dinput[field_name]
return encoder_fn(field_name, dinput)
|
(self, field_name, dinput)
|
45,814 |
easul.data
|
encode_input
| null |
def encode_input(self, dinput):
for field_name,encoder_fn in self.encodings.items():
col = encoder_fn(field_name, dinput)
dinput.data[field_name] = col
|
(self, dinput)
|
45,815 |
easul.data
|
is_field_encoded
| null |
def is_field_encoded(self, field_name):
return field_name in self.encodings
|
(self, field_name)
|
45,816 |
easul.outcome
|
InvalidDataOutcome
|
Decision failed because of invalid data.
|
class InvalidDataOutcome(FailedOutcome):
"""
Decision failed because of invalid data.
"""
next_step = field(default=None)
|
(*, outcome_step, reason, context=None, input_data=None, next_step=None) -> None
|
45,817 |
easul.outcome
|
__eq__
|
Method generated by attrs for class InvalidDataOutcome.
|
from attrs import define, field
@define(kw_only=True)
class Outcome:
"""
Base Outcome class. Output by Decision classes and contains information on the next step (based on the decision),
the reason for the outcome/decision and context related to the result.
"""
outcome_step = field()
next_step = field()
reason = field()
context = field(default=None)
input_data = field(default=None)
def asdict(self):
return {
"outcome_step":self.outcome_step.name,
"next_step":self.next_step.name if self.next_step else None,
"reason":self.reason,
"context":self.context if self.context else {},
"input_data": self.input_data if type(self.input_data) is dict else self.input_data.asdict() if self.input_data else {}
}
def __repr__(self):
return f"<{self.__class__.__name__ } {self.asdict()}>"
|
(self, other)
|
45,820 |
easul.outcome
|
__ne__
|
Method generated by attrs for class InvalidDataOutcome.
| null |
(self, other)
|
45,823 |
easul.outcome
|
asdict
| null |
def asdict(self):
return {
"outcome_step":self.outcome_step.name,
"next_step":self.next_step.name if self.next_step else None,
"reason":self.reason,
"context":self.context if self.context else {},
"input_data": self.input_data if type(self.input_data) is dict else self.input_data.asdict() if self.input_data else {}
}
|
(self)
|
45,824 |
easul.error
|
InvalidStepData
|
Error thrown when data is invalid. Should result in step status changing to 'ERROR'
|
class InvalidStepData(StepDataError):
"""
Error thrown when data is invalid. Should result in step status changing to 'ERROR'
"""
@property
def _message(self):
return f"Data invalid in step {self.step_name}"
|
(journey, step_name, exception=None, message=None, **kwargs)
|
45,825 |
easul.error
|
__init__
| null |
def __init__(self, journey, step_name, exception=None, message=None, **kwargs):
self.step_name = step_name
self.journey = journey
self.kwargs = kwargs
if not message:
message = self._message
if exception:
message+=f" [exception:{exception}]"
super().__init__(message)
|
(self, journey, step_name, exception=None, message=None, **kwargs)
|
45,826 |
easul.visual.draw.flowchart
|
JourneyChartSettings
| null |
class JourneyChartSettings:
route_only:bool
data_sources:bool
after_route:bool
|
(*, route_only: bool, data_sources: bool, after_route: bool) -> None
|
45,827 |
easul.visual.draw.flowchart
|
__eq__
|
Method generated by attrs for class JourneyChartSettings.
|
from typing import List
from attrs import define, field
from easul.step import Step
import uuid
@define(kw_only=True)
class JourneyChartSettings:
route_only:bool
data_sources:bool
after_route:bool
|
(self, other)
|
45,830 |
easul.visual.draw.flowchart
|
__ne__
|
Method generated by attrs for class JourneyChartSettings.
| null |
(self, other)
|
45,833 |
easul.visual.element.journey
|
JourneyMap
| null |
class JourneyMap(Element):
route_only:bool = field(default=False, metadata={"help": "Only show map elements which are in route"})
data_sources:bool = field(default=False, metadata={"help":"Show possible routes following current step"} )
start_step:str = field(metadata={"help":"Start step for logic map"}, default=None)
after_route:bool = field(default=False, metadata = {"help": "Show possible routes following current step"})
help = "Journey map showing what step and stage journey is currently at"
flowchart_cls = field(default=MermaidCLIFlowChart)
def create(self, *args, steps, step, driver, **kwargs):
route = driver.get_route()
start_step = steps[self.start_step] if self.start_step else get_start_step(steps)
settings = JourneyChartSettings(route_only=self.route_only,
data_sources=self.data_sources,
after_route=self.after_route)
chart = self.flowchart_cls(steps=steps, start_step=start_step, route=route, settings=settings)
return chart.generate()
|
(*, name='untitled', help='', title='Untitled', fill_container=False, style=None, html_class='', html_tag='h5', route_only: bool = False, data_sources: bool = False, start_step: str = None, after_route: bool = False, flowchart_cls=<class 'easul.visual.draw.flowchart.MermaidCLIFlowChart'>) -> None
|
45,834 |
easul.visual.element.journey
|
__eq__
|
Method generated by attrs for class JourneyMap.
|
from attr import field, define
from easul.util import get_start_step
from easul.visual.draw.flowchart import JourneyChartSettings, MermaidCLIFlowChart
from easul.visual.element import Element
@define(kw_only=True)
class JourneyMap(Element):
route_only:bool = field(default=False, metadata={"help": "Only show map elements which are in route"})
data_sources:bool = field(default=False, metadata={"help":"Show possible routes following current step"} )
start_step:str = field(metadata={"help":"Start step for logic map"}, default=None)
after_route:bool = field(default=False, metadata = {"help": "Show possible routes following current step"})
help = "Journey map showing what step and stage journey is currently at"
flowchart_cls = field(default=MermaidCLIFlowChart)
def create(self, *args, steps, step, driver, **kwargs):
route = driver.get_route()
start_step = steps[self.start_step] if self.start_step else get_start_step(steps)
settings = JourneyChartSettings(route_only=self.route_only,
data_sources=self.data_sources,
after_route=self.after_route)
chart = self.flowchart_cls(steps=steps, start_step=start_step, route=route, settings=settings)
return chart.generate()
|
(self, other)
|
45,837 |
easul.visual.element.journey
|
__ne__
|
Method generated by attrs for class JourneyMap.
| null |
(self, other)
|
45,841 |
easul.visual.element.journey
|
create
| null |
def create(self, *args, steps, step, driver, **kwargs):
route = driver.get_route()
start_step = steps[self.start_step] if self.start_step else get_start_step(steps)
settings = JourneyChartSettings(route_only=self.route_only,
data_sources=self.data_sources,
after_route=self.after_route)
chart = self.flowchart_cls(steps=steps, start_step=start_step, route=route, settings=settings)
return chart.generate()
|
(self, *args, steps, step, driver, **kwargs)
|
45,848 |
easul.process
|
MapDataItems
|
Uses a dictionary of source->target 'field_map'-pings and places the result in the 'field' of the original
record.
|
class MapDataItems:
"""
Uses a dictionary of source->target 'field_map'-pings and places the result in the 'field' of the original
record.
"""
field_map:Dict[str,str] = field()
field:str = field()
def __call__(self, record):
final_row = {}
for src, value in record.items():
tgt = self.field_map.get(src)
if tgt is None:
continue
final_row[tgt] = value
record[self.field] = final_row
return record
|
(*, field_map: Dict[str, str], field: str) -> None
|
45,849 |
easul.process
|
__call__
| null |
def __call__(self, record):
final_row = {}
for src, value in record.items():
tgt = self.field_map.get(src)
if tgt is None:
continue
final_row[tgt] = value
record[self.field] = final_row
return record
|
(self, record)
|
45,850 |
easul.process
|
__eq__
|
Method generated by attrs for class MapDataItems.
|
# 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,853 |
easul.process
|
__ne__
|
Method generated by attrs for class MapDataItems.
| null |
(self, other)
|
45,856 |
easul.process
|
MapValues
|
Maps values for a particular 'field' according to a 'mappings' dictionary (option value -> mapped value).
For example this can be used to remap character-based option keys to numbers (e.g. Male -> 0, Female -> 1,
Other -> 2)
|
class MapValues:
"""
Maps values for a particular 'field' according to a 'mappings' dictionary (option value -> mapped value).
For example this can be used to remap character-based option keys to numbers (e.g. Male -> 0, Female -> 1,
Other -> 2)
"""
mappings = field()
field = field()
def __call__(self, record):
record[self.field] = self.mappings.get(record[self.field])
return record
|
(*, mappings, field) -> None
|
45,857 |
easul.process
|
__call__
| null |
def __call__(self, record):
record[self.field] = self.mappings.get(record[self.field])
return record
|
(self, record)
|
45,858 |
easul.process
|
__eq__
|
Method generated by attrs for class MapValues.
|
# 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,861 |
easul.process
|
__ne__
|
Method generated by attrs for class MapValues.
| null |
(self, other)
|
45,864 |
easul.visual.draw.flowchart
|
MermaidCLIFlowChart
|
Draw Mermaid flowchart using locally installed CLI (mermaid-cli). Requires NodeJS to be installed.
|
class MermaidCLIFlowChart:
"""
Draw Mermaid flowchart using locally installed CLI (mermaid-cli). Requires NodeJS to be installed.
"""
steps = field(factory=list)
start_step:Step = field()
route:List = field(factory=list)
settings = field()
current_step: Step = field(default=None)
def __attrs_post_init__(self):
if self.current_step is None:
if len(self.route)==0:
self.current_step = list(self.steps.values())[0]
else:
self.current_step = self.steps.get(self.route[-1])
def generate(self):
chart = self.create_chart()
filename = self._write_file(chart)
return self._read_file(filename)
def create_chart(self):
checked = []
chart_lines = self._generate_chart_lines(self.start_step, checked, self.settings)
chart_lines.append(self.start_step.name + "[" + self.start_step.title + "]")
chart_lines.append("classDef current fill:#0ae,stroke:#333,stroke-width:4px,color:white;")
chart_lines.append("classDef journey fill:#9cf,stroke:#88d,stroke-width:2px,color:#88d;")
chart_lines.append("classDef non_journey fill:#eee,stroke:#ccc,stroke-width:1px,color:#aaaaaa;")
for j in self.route:
if j == self.current_step.name:
continue
chart_lines.append("class " + j + " journey;")
chart_lines.append("class " + self.current_step.name + " current;")
return "flowchart TD\n" + "\n".join(["\t" + l for l in chart_lines])
def _generate_chart_lines(self, step, checked, settings):
if step.exclude_from_chart:
return []
lines = []
if step.name in checked:
return []
checked.append(step.name)
lines.append(step.name + "[" + step.title + "]")
if step.name not in self.route and step != self.start_step:
lines.append("class " + step.name + " non_journey;")
if settings.data_sources is True:
if step.data_sources:
for idx, data_source in enumerate(step.data_sources):
lines.append(f"ds{idx}_{step.name}[({data_source})]")
lines.append(f"ds{idx}_{step.name}.->{step.name}")
for reason, possible_step in step.possible_links.items():
pre_arrow = "-. "
post_arrow = ".->"
in_route = False
try:
step_idx = self.route.index(step.name)
if step_idx < len(self.route) - 1:
if self.route[step_idx + 1] == possible_step.name:
pre_arrow = "== "
post_arrow = "==>"
in_route = True
except ValueError:
pass
if settings.route_only is True and in_route is False:
continue
lines.append(step.name + pre_arrow + "\"" + reason + "\"" + post_arrow + possible_step.name)
lines.extend(
self._generate_chart_lines(possible_step, checked, settings)
)
return lines
def _write_file(self, mjs_chart):
import tempfile
import os
mmd = tempfile.NamedTemporaryFile(mode="w", suffix=".mmd", delete=False)
svg = tempfile.NamedTemporaryFile(suffix=".svg", delete=False)
svg.close()
mmd.write(mjs_chart)
mmd.close()
cmd = "mmdc -i " + str(mmd.name) + " -o " + str(svg.name)
os.system(cmd)
return svg.name
def _read_file(self, filename):
with open(filename, "r") as svg_file:
value = svg_file.read()
return str(value)
|
(*, steps=NOTHING, start_step: easul.step.Step, route: List = NOTHING, settings, current_step: easul.step.Step = None) -> None
|
45,865 |
easul.visual.draw.flowchart
|
__attrs_post_init__
| null |
def __attrs_post_init__(self):
if self.current_step is None:
if len(self.route)==0:
self.current_step = list(self.steps.values())[0]
else:
self.current_step = self.steps.get(self.route[-1])
|
(self)
|
45,866 |
easul.visual.draw.flowchart
|
__eq__
|
Method generated by attrs for class MermaidCLIFlowChart.
|
from typing import List
from attrs import define, field
from easul.step import Step
import uuid
@define(kw_only=True)
class JourneyChartSettings:
route_only:bool
data_sources:bool
after_route:bool
|
(self, other)
|
45,869 |
easul.visual.draw.flowchart
|
__ne__
|
Method generated by attrs for class MermaidCLIFlowChart.
| null |
(self, other)
|
45,872 |
easul.visual.draw.flowchart
|
_generate_chart_lines
| null |
def _generate_chart_lines(self, step, checked, settings):
if step.exclude_from_chart:
return []
lines = []
if step.name in checked:
return []
checked.append(step.name)
lines.append(step.name + "[" + step.title + "]")
if step.name not in self.route and step != self.start_step:
lines.append("class " + step.name + " non_journey;")
if settings.data_sources is True:
if step.data_sources:
for idx, data_source in enumerate(step.data_sources):
lines.append(f"ds{idx}_{step.name}[({data_source})]")
lines.append(f"ds{idx}_{step.name}.->{step.name}")
for reason, possible_step in step.possible_links.items():
pre_arrow = "-. "
post_arrow = ".->"
in_route = False
try:
step_idx = self.route.index(step.name)
if step_idx < len(self.route) - 1:
if self.route[step_idx + 1] == possible_step.name:
pre_arrow = "== "
post_arrow = "==>"
in_route = True
except ValueError:
pass
if settings.route_only is True and in_route is False:
continue
lines.append(step.name + pre_arrow + "\"" + reason + "\"" + post_arrow + possible_step.name)
lines.extend(
self._generate_chart_lines(possible_step, checked, settings)
)
return lines
|
(self, step, checked, settings)
|
45,873 |
easul.visual.draw.flowchart
|
_read_file
| null |
def _read_file(self, filename):
with open(filename, "r") as svg_file:
value = svg_file.read()
return str(value)
|
(self, filename)
|
45,874 |
easul.visual.draw.flowchart
|
_write_file
| null |
def _write_file(self, mjs_chart):
import tempfile
import os
mmd = tempfile.NamedTemporaryFile(mode="w", suffix=".mmd", delete=False)
svg = tempfile.NamedTemporaryFile(suffix=".svg", delete=False)
svg.close()
mmd.write(mjs_chart)
mmd.close()
cmd = "mmdc -i " + str(mmd.name) + " -o " + str(svg.name)
os.system(cmd)
return svg.name
|
(self, mjs_chart)
|
45,875 |
easul.visual.draw.flowchart
|
create_chart
| null |
def create_chart(self):
checked = []
chart_lines = self._generate_chart_lines(self.start_step, checked, self.settings)
chart_lines.append(self.start_step.name + "[" + self.start_step.title + "]")
chart_lines.append("classDef current fill:#0ae,stroke:#333,stroke-width:4px,color:white;")
chart_lines.append("classDef journey fill:#9cf,stroke:#88d,stroke-width:2px,color:#88d;")
chart_lines.append("classDef non_journey fill:#eee,stroke:#ccc,stroke-width:1px,color:#aaaaaa;")
for j in self.route:
if j == self.current_step.name:
continue
chart_lines.append("class " + j + " journey;")
chart_lines.append("class " + self.current_step.name + " current;")
return "flowchart TD\n" + "\n".join(["\t" + l for l in chart_lines])
|
(self)
|
45,876 |
easul.visual.draw.flowchart
|
generate
| null |
def generate(self):
chart = self.create_chart()
filename = self._write_file(chart)
return self._read_file(filename)
|
(self)
|
45,877 |
easul.visual.visual
|
Metadata
| null |
class Metadata(UserDict):
def __init__(self, algorithm=None, visual=None):
super().__init__({})
self.visual = visual
self.algorithm = algorithm
self.init = False
def calculate(self, dataset):
if not self.visual:
raise AttributeError("Cannot calculate metadata as instance has not been called with Visual object")
metadata = {}
for element in self.visual.elements:
element_metadata = element.generate_metadata(algorithm=self.algorithm, dataset=dataset)
if element_metadata:
metadata.update(element_metadata)
metadata["algorithm_digest"] = self.algorithm.unique_digest
self.init = True
self.data.update(metadata)
|
(algorithm=None, visual=None)
|
45,883 |
easul.visual.visual
|
__init__
| null |
def __init__(self, algorithm=None, visual=None):
super().__init__({})
self.visual = visual
self.algorithm = algorithm
self.init = False
|
(self, algorithm=None, visual=None)
|
45,902 |
easul.outcome
|
MissingDataOutcome
|
Decision failed because of missing data.
|
class MissingDataOutcome(FailedOutcome):
"""
Decision failed because of missing data.
"""
next_step = field(default=None)
|
(*, outcome_step, reason, context=None, input_data=None, next_step=None) -> None
|
45,903 |
easul.outcome
|
__eq__
|
Method generated by attrs for class MissingDataOutcome.
|
from attrs import define, field
@define(kw_only=True)
class Outcome:
"""
Base Outcome class. Output by Decision classes and contains information on the next step (based on the decision),
the reason for the outcome/decision and context related to the result.
"""
outcome_step = field()
next_step = field()
reason = field()
context = field(default=None)
input_data = field(default=None)
def asdict(self):
return {
"outcome_step":self.outcome_step.name,
"next_step":self.next_step.name if self.next_step else None,
"reason":self.reason,
"context":self.context if self.context else {},
"input_data": self.input_data if type(self.input_data) is dict else self.input_data.asdict() if self.input_data else {}
}
def __repr__(self):
return f"<{self.__class__.__name__ } {self.asdict()}>"
|
(self, other)
|
45,906 |
easul.outcome
|
__ne__
|
Method generated by attrs for class MissingDataOutcome.
| null |
(self, other)
|
45,910 |
easul.error
|
MissingValue
|
A value is missing from the supplied data.
|
class MissingValue(InvalidData):
"""
A value is missing from the supplied data.
"""
pass
| null |
45,911 |
easul.data
|
MultiDataInput
|
Data input containing multiple rows (e.g. list or DataFrame) which follow the schema.
This is used to handle multiple element predictions/interpretations from user supplied values.
|
class MultiDataInput(DataInput):
"""
Data input containing multiple rows (e.g. list or DataFrame) which follow the schema.
This is used to handle multiple element predictions/interpretations from user supplied values.
"""
def _init_data(self, data):
if isinstance(data, list):
data = pd.DataFrame(data=data, index=[0])
self._data = self._convert_data(data, self.schema.x)
@property
def Y(self):
raise ValueError("Y values are not available in MultiInputDataSet")
@property
def Y_scalar(self):
raise ValueError("Y scalar values are not available in MultiInputDataSet")
@property
def X_data(self):
return self.data
@property
def Y_data(self):
raise ValueError("Y data is not available in MultiInputDataSet")
|
(data, schema: easul.data.DataSchema, convert: bool = True, validate: bool = True, encoded_with=None, encoder=None)
|
45,916 |
easul.data
|
_init_data
| null |
def _init_data(self, data):
if isinstance(data, list):
data = pd.DataFrame(data=data, index=[0])
self._data = self._convert_data(data, self.schema.x)
|
(self, data)
|
45,925 |
easul.expression
|
MultiExpression
|
Base class for an expression which tests multiple expressions according to a multi-logic function (e.g. or)
|
class MultiExpression:
"""
Base class for an expression which tests multiple expressions according to a multi-logic function (e.g. or)
"""
expressions = field()
title:str = field(default=None)
logic = None
join_label = ""
def evaluate(self, data):
return bool(self.logic(*[c.evaluate(data) for c in self.expressions]))
@property
def label(self):
return (" " + self.join_label + " ").join([c.label for c in self.expressions])
|
(*, expressions, title: str = None) -> None
|
45,926 |
easul.expression
|
__eq__
|
Method generated by attrs for class MultiExpression.
|
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,929 |
easul.expression
|
__ne__
|
Method generated by attrs for class MultiExpression.
| null |
(self, other)
|
45,932 |
easul.expression
|
evaluate
| null |
def evaluate(self, data):
return bool(self.logic(*[c.evaluate(data) for c in self.expressions]))
|
(self, data)
|
45,933 |
easul.process
|
MultiRowProcess
|
Process which requires input data as a list and processes each using the supplied 'processes' functions.
|
class MultiRowProcess:
"""
Process which requires input data as a list and processes each using the supplied 'processes' functions.
"""
processes = field()
def __call__(self, records):
new_records = []
for record in records:
for process in self.processes:
record = process(record)
new_records.append(record)
return new_records
|
(*, processes) -> None
|
45,934 |
easul.process
|
__call__
| null |
def __call__(self, records):
new_records = []
for record in records:
for process in self.processes:
record = process(record)
new_records.append(record)
return new_records
|
(self, records)
|
45,935 |
easul.process
|
__eq__
|
Method generated by attrs for class MultiRowProcess.
|
# 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,938 |
easul.process
|
__ne__
|
Method generated by attrs for class MultiRowProcess.
| null |
(self, other)
|
45,941 |
easul.expression
|
NullExpression
|
Expression which determines if a field value is None.
If it does not exist in the input data then it is replaced by a defined 'value' and tested against this.
|
class NullExpression(FieldExpression):
"""
Expression which determines if a field value is None.
If it does not exist in the input data then it is replaced by a defined 'value' and tested against this.
"""
def evaluate(self, data):
try:
item = data[self.input_field]
except TypeError:
item = data.value
return item is None
@property
def label(self):
return self.input_field + " is null"
|
(*, input_field: str, ignore_empty: bool = False) -> None
|
45,942 |
easul.expression
|
__eq__
|
Method generated by attrs for class NullExpression.
|
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,945 |
easul.expression
|
__ne__
|
Method generated by attrs for class NullExpression.
| null |
(self, other)
|
45,948 |
easul.expression
|
evaluate
| null |
def evaluate(self, data):
try:
item = data[self.input_field]
except TypeError:
item = data.value
return item is None
|
(self, data)
|
45,949 |
easul.expression
|
OperatorExpression
|
Expression which utilises a function (e.g. from Python operators) to perform its test on a particular field.
The operator function is passed the field value and a defined value to compare it against.
|
class OperatorExpression(FieldExpression):
"""
Expression which utilises a function (e.g. from Python operators) to perform its test on a particular field.
The operator function is passed the field value and a defined value to compare it against.
"""
operator: Callable = field()
value: int = field()
def _test(self, item):
return bool(self.operator(item,self.value))
@property
def label(self):
docstring = str(self.operator.__doc__)
docstring = docstring.replace("Same as ", "")
label = docstring.replace("a","[a]").replace("b","[b]")
label = label.replace("[a]", self.input_field).replace("[b]", str(self.value)).replace(".","")
return label
|
(*, input_field: str, ignore_empty: bool = False, operator: Callable, value: int) -> None
|
45,950 |
easul.expression
|
__eq__
|
Method generated by attrs for class OperatorExpression.
|
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,953 |
easul.expression
|
__ne__
|
Method generated by attrs for class OperatorExpression.
| null |
(self, other)
|
45,956 |
easul.expression
|
_test
| null |
def _test(self, item):
return bool(self.operator(item,self.value))
|
(self, item)
|
45,958 |
easul.expression
|
OrExpression
|
Expression which tests whether one expression OR another is true
|
class OrExpression(MultiExpression):
"""
Expression which tests whether one expression OR another is true
"""
logic = operator.or_
join_label = "or"
|
(*, expressions, title: str = None) -> None
|
45,959 |
easul.expression
|
__eq__
|
Method generated by attrs for class OrExpression.
|
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,962 |
easul.expression
|
__ne__
|
Method generated by attrs for class OrExpression.
| null |
(self, other)
|
45,966 |
easul.outcome
|
Outcome
|
Base Outcome class. Output by Decision classes and contains information on the next step (based on the decision),
the reason for the outcome/decision and context related to the result.
|
class Outcome:
"""
Base Outcome class. Output by Decision classes and contains information on the next step (based on the decision),
the reason for the outcome/decision and context related to the result.
"""
outcome_step = field()
next_step = field()
reason = field()
context = field(default=None)
input_data = field(default=None)
def asdict(self):
return {
"outcome_step":self.outcome_step.name,
"next_step":self.next_step.name if self.next_step else None,
"reason":self.reason,
"context":self.context if self.context else {},
"input_data": self.input_data if type(self.input_data) is dict else self.input_data.asdict() if self.input_data else {}
}
def __repr__(self):
return f"<{self.__class__.__name__ } {self.asdict()}>"
|
(*, outcome_step, next_step, reason, context=None, input_data=None) -> None
|
45,967 |
easul.outcome
|
__eq__
|
Method generated by attrs for class Outcome.
|
from attrs import define, field
@define(kw_only=True)
class Outcome:
"""
Base Outcome class. Output by Decision classes and contains information on the next step (based on the decision),
the reason for the outcome/decision and context related to the result.
"""
outcome_step = field()
next_step = field()
reason = field()
context = field(default=None)
input_data = field(default=None)
def asdict(self):
return {
"outcome_step":self.outcome_step.name,
"next_step":self.next_step.name if self.next_step else None,
"reason":self.reason,
"context":self.context if self.context else {},
"input_data": self.input_data if type(self.input_data) is dict else self.input_data.asdict() if self.input_data else {}
}
def __repr__(self):
return f"<{self.__class__.__name__ } {self.asdict()}>"
|
(self, other)
|
45,970 |
easul.outcome
|
__ne__
|
Method generated by attrs for class Outcome.
| null |
(self, other)
|
45,971 |
easul.outcome
|
__repr__
| null |
def __repr__(self):
return f"<{self.__class__.__name__ } {self.asdict()}>"
|
(self)
|
45,974 |
easul.process
|
ParseDate
|
Parse 'field_name' string value according to 'format' and return a date object.
If value does not meet format it is updated with None
|
class ParseDate(ParseDateTime):
"""
Parse 'field_name' string value according to 'format' and return a date object.
If value does not meet format it is updated with None
"""
def _parse_value(self, value):
if isinstance(value, date):
return value
if isinstance(value, datetime):
return value.date()
try:
return datetime.strptime(str(value), self.format).date()
except AttributeError:
return self.default_value
|
(*, field_name: str, format: str, default_value: Optional[datetime.datetime] = None) -> None
|
45,975 |
easul.process
|
__call__
| null |
def __call__(self, record):
if self.field_name not in record:
raise AttributeError(f"{self.__class__.__name__} '{self.field_name}' is not present in the input data")
date_value = record.get(self.field_name)
if date_value is None:
record[self.field_name] = None
return record
try:
dt = self._parse_value(date_value)
record[self.field_name] = dt
except ValueError:
record[self.field_name] = None
return record
|
(self, record)
|
45,976 |
easul.process
|
__eq__
|
Method generated by attrs for class ParseDate.
|
# 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,979 |
easul.process
|
__ne__
|
Method generated by attrs for class ParseDate.
| null |
(self, other)
|
45,982 |
easul.process
|
_parse_value
| null |
def _parse_value(self, value):
if isinstance(value, date):
return value
if isinstance(value, datetime):
return value.date()
try:
return datetime.strptime(str(value), self.format).date()
except AttributeError:
return self.default_value
|
(self, value)
|
45,983 |
easul.process
|
ParseDateTime
|
Parse 'field_name' string value according to 'format' into a datetime object.
If value does not meet format it is updated with the 'default_value' which is None unless defined.
|
class ParseDateTime:
"""
Parse 'field_name' string value according to 'format' into a datetime object.
If value does not meet format it is updated with the 'default_value' which is None unless defined.
"""
field_name:str = field()
format:str = field()
default_value:Optional[datetime] = field(default=None)
def _parse_value(self, value):
return value if isinstance(value, datetime) else datetime.strptime(value,self.format)
def __call__(self, record):
if self.field_name not in record:
raise AttributeError(f"{self.__class__.__name__} '{self.field_name}' is not present in the input data")
date_value = record.get(self.field_name)
if date_value is None:
record[self.field_name] = None
return record
try:
dt = self._parse_value(date_value)
record[self.field_name] = dt
except ValueError:
record[self.field_name] = None
return record
|
(*, field_name: str, format: str, default_value: Optional[datetime.datetime] = None) -> None
|
45,985 |
easul.process
|
__eq__
|
Method generated by attrs for class ParseDateTime.
|
# 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,988 |
easul.process
|
__ne__
|
Method generated by attrs for class ParseDateTime.
| null |
(self, other)
|
45,991 |
easul.process
|
_parse_value
| null |
def _parse_value(self, value):
return value if isinstance(value, datetime) else datetime.strptime(value,self.format)
|
(self, value)
|
45,992 |
easul.process
|
ParseTime
|
Parse 'field_name' string value according to 'format' and return a time object.
If value does not meet format it is updated with None
|
class ParseTime(ParseDateTime):
"""
Parse 'field_name' string value according to 'format' and return a time object.
If value does not meet format it is updated with None
"""
def _parse_value(self, value):
if isinstance(value, time):
return value
if isinstance(value, datetime):
return value.time()
try:
return datetime.strptime(str(value), self.format).time()
except AttributeError:
return self.default_value
|
(*, field_name: str, format: str, default_value: Optional[datetime.datetime] = None) -> None
|
45,994 |
easul.process
|
__eq__
|
Method generated by attrs for class ParseTime.
|
# 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,997 |
easul.process
|
__ne__
|
Method generated by attrs for class ParseTime.
| null |
(self, other)
|
46,000 |
easul.process
|
_parse_value
| null |
def _parse_value(self, value):
if isinstance(value, time):
return value
if isinstance(value, datetime):
return value.time()
try:
return datetime.strptime(str(value), self.format).time()
except AttributeError:
return self.default_value
|
(self, value)
|
46,001 |
easul.action
|
PassPreviousResultAction
|
Action which puts the previous outcome value into the input data.
|
class PassPreviousResultAction(Action):
"""
Action which puts the previous outcome value into the input data.
"""
as_field = field()
def after_data(self, event):
if event.previous_outcome:
event.data[self.as_field] = event.previous_outcome.value
|
(*, as_field) -> None
|
46,002 |
easul.action
|
__eq__
|
Method generated by attrs for class PassPreviousResultAction.
|
"""
"""
import logging
from easul.algorithm.result import DefaultResult
from easul.outcome import ResultOutcome
LOG = logging.getLogger(__name__)
from attrs import define, field
class StopFlow(Exception):
pass
|
(self, other)
|
46,005 |
easul.action
|
__ne__
|
Method generated by attrs for class PassPreviousResultAction.
| null |
(self, other)
|
46,008 |
easul.action
|
after_data
| null |
def after_data(self, event):
if event.previous_outcome:
event.data[self.as_field] = event.previous_outcome.value
|
(self, event)
|
46,014 |
easul.decision
|
PassThruDecision
|
class PassThruDecision(Decision):
"""
"""
next_step = field()
def describe(self):
desc = super().describe()
desc.update({
"next_step": self.next_step.title + "(" + self.next_step.name + ")",
})
return desc
def decide_outcome(self, result, context, data, step):
return ResultOutcome(
outcome_step=step,
next_step=self.next_step,
value=result.value,
result=result,
context=context,
input_data=data,
reason="next"
)
@property
def possible_links(self):
return {"next":self.next_step}
|
(*, next_step) -> None
|
|
46,015 |
easul.decision
|
__eq__
|
Method generated by attrs for class PassThruDecision.
|
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)
|
46,018 |
easul.decision
|
__ne__
|
Method generated by attrs for class PassThruDecision.
| null |
(self, other)
|
46,021 |
easul.decision
|
decide_outcome
| null |
def decide_outcome(self, result, context, data, step):
return ResultOutcome(
outcome_step=step,
next_step=self.next_step,
value=result.value,
result=result,
context=context,
input_data=data,
reason="next"
)
|
(self, result, context, data, step)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.