|
1
|
|
|
from abc import ABC, abstractmethod |
|
2
|
|
|
from functools import reduce |
|
3
|
|
|
import attr |
|
4
|
|
|
import pandas as pd |
|
5
|
|
|
|
|
6
|
|
|
from so_magic.utils import SubclassRegistry |
|
7
|
|
|
|
|
8
|
|
|
|
|
9
|
|
|
class FillerInterface(ABC): |
|
10
|
|
|
@abstractmethod |
|
11
|
|
|
def fill(self, *args, **kwargs): |
|
12
|
|
|
raise NotImplementedError |
|
13
|
|
|
|
|
14
|
|
|
|
|
15
|
|
|
class FillerFactoryType(type): |
|
16
|
|
|
|
|
17
|
|
|
@classmethod |
|
18
|
|
|
def create(mcs, *args, **kwargs) -> FillerInterface: |
|
19
|
|
|
raise NotImplementedError |
|
20
|
|
|
|
|
21
|
|
|
|
|
22
|
|
|
class FillerFactoryClassRegistry(metaclass=SubclassRegistry): pass |
|
23
|
|
|
|
|
24
|
|
|
|
|
25
|
|
|
@FillerFactoryClassRegistry.register_as_subclass('static') |
|
26
|
|
|
class StaticDataFiller(FillerInterface): |
|
27
|
|
|
def __init__(self, *args, **kwargs) -> None: |
|
28
|
|
|
self._variable = args[1] |
|
29
|
|
|
if callable(kwargs.get('value')): |
|
30
|
|
|
self._fct = kwargs['value'] |
|
31
|
|
|
else: |
|
32
|
|
|
self._fct = self._variable.data_type |
|
33
|
|
|
print('\n----->', self._fct, type(self._fct)) |
|
34
|
|
|
|
|
35
|
|
|
def replace_missing_with_true_zero(self, value, true_zero): |
|
36
|
|
|
try: |
|
37
|
|
|
if pd.isnull(value): # True for both np.nan and None |
|
38
|
|
|
return true_zero |
|
39
|
|
|
except ValueError: |
|
40
|
|
|
pass |
|
41
|
|
|
return value |
|
42
|
|
|
|
|
43
|
|
|
def fill(self, *args, **kwargs): |
|
44
|
|
|
datapoints = args[0] |
|
45
|
|
|
datapoints.observations[str(self._variable)] = datapoints.observations[str(self._variable)].map(lambda a: self.replace_missing_with_true_zero(a, self._fct())) |
|
|
|
|
|
|
46
|
|
|
|
|
47
|
|
|
|
|
48
|
|
|
@attr.s |
|
49
|
|
|
class FillerFactory: |
|
50
|
|
|
filler_factory_classes_registry = attr.ib(default=attr.Factory(lambda: FillerFactoryClassRegistry)) |
|
51
|
|
|
def create(self, datapoints, variable, value=None): |
|
52
|
|
|
key = 'static' |
|
53
|
|
|
return self.filler_factory_classes_registry.create(key, datapoints, variable, value=value) |
|
54
|
|
|
|
|
55
|
|
|
|
|
56
|
|
|
@attr.s |
|
57
|
|
|
class MagicFillerFactory: |
|
58
|
|
|
filler_factory = attr.ib(init=False, default=attr.Factory(FillerFactory)) |
|
59
|
|
|
|
|
60
|
|
|
def create(self, datapoints, variable, value=None): |
|
61
|
|
|
return self.filler_factory.create(datapoints, variable, value=value) |
|
62
|
|
|
|