task.py 8.51 KB
Newer Older
1
from collections.abc import Mapping
2
from typing import Optional, Union
3
4

from .hashing import UniversalHashable
5
6
7
8
9
10
from .variable import VariableContainer
from .variable import VariableContainerNamespace
from .variable import ReadOnlyVariableContainerNamespace
from .registration import Registered


11
class TaskInputError(ValueError):
12
13
14
    pass


15
class Task(Registered, UniversalHashable, register=False):
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
    """Node in a task Graph with named inputs and outputs.

    The universal hash of the task is equal to the universal
    hash of the output. The universal hash of the output is
    equal to the hash of the inputs and the task nonce.

    A task is done when its output exists.

    This is an abstract class. Instantiating a `Task` should be
    done with `ewokscore.inittask.instantiate_task`.
    """

    _INPUT_NAMES = set()
    _OPTIONAL_INPUT_NAMES = set()
    _OUTPUT_NAMES = set()
    _N_REQUIRED_POSITIONAL_INPUTS = 0

33
    def __init__(self, inputs=None, varinfo=None, label=None):
34
35
36
37
38
39
40
41
42
        """The named arguments are inputs and Variable configuration"""
        if inputs is None:
            inputs = dict()
        elif not isinstance(inputs, Mapping):
            raise TypeError(inputs, type(inputs))

        # Check required inputs
        missing_required = set(self._INPUT_NAMES) - set(inputs.keys())
        if missing_required:
43
            raise TaskInputError(f"Missing inputs for {type(self)}: {missing_required}")
44
45
46
47
48

        # Check required positional inputs
        nrequiredargs = self._N_REQUIRED_POSITIONAL_INPUTS
        for i in range(nrequiredargs):
            if i not in inputs and str(i) not in inputs:
49
                raise TaskInputError(
50
51
52
53
54
                    f"Missing inputs for {type(self)}: positional argument #{i}"
                )

        # Init missing optional inputs
        missing_optional = set(self._OPTIONAL_INPUT_NAMES) - set(inputs.keys())
55
56
        for varname in missing_optional:
            inputs[varname] = self.MISSING_DATA
57
58

        # Required outputs for the task to be "done"
59
        ovars = {varname: self.MISSING_DATA for varname in self._OUTPUT_NAMES}
60
61
62
63

        # Misc
        self._exception = None
        self._done = None
64
        self.__label = label
65
66
67
68
69
70

        # The output hash will update dynamically if any of the input
        # variables change
        self._inputs = VariableContainer(value=inputs, varinfo=varinfo)
        self._outputs = VariableContainer(
            value=ovars,
71
            pre_uhash=self._inputs,
72
73
74
75
            instance_nonce=self.class_nonce(),
            varinfo=varinfo,
        )

76
77
        self._public_inputs = ReadOnlyVariableContainerNamespace(self._inputs)
        self._public_outputs = VariableContainerNamespace(self._outputs)
78
79

        # The task class has the same hash as its output
80
        super().__init__(pre_uhash=self._outputs)
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117

    def __init_subclass__(
        subclass,
        input_names=tuple(),
        optional_input_names=tuple(),
        output_names=tuple(),
        n_required_positional_inputs=0,
        **kwargs,
    ):
        super().__init_subclass__(**kwargs)
        input_names = set(input_names)
        optional_input_names = set(optional_input_names)
        output_names = set(output_names)

        reserved = subclass._reserved_variable_names()
        forbidden = input_names & reserved
        forbidden |= optional_input_names & reserved
        forbidden |= output_names & reserved
        if forbidden:
            raise RuntimeError(
                "The following names cannot be used a variable names: "
                + str(list(forbidden))
            )

        # Ensures that each subclass has their own sets:
        subclass._INPUT_NAMES = subclass._INPUT_NAMES | set(input_names)
        subclass._OPTIONAL_INPUT_NAMES = subclass._OPTIONAL_INPUT_NAMES | set(
            optional_input_names
        )
        subclass._OUTPUT_NAMES = subclass._OUTPUT_NAMES | set(output_names)
        subclass._N_REQUIRED_POSITIONAL_INPUTS = n_required_positional_inputs

    @staticmethod
    def _reserved_variable_names():
        return VariableContainerNamespace._reserved_variable_names()

    @classmethod
118
    def instantiate(cls, registry_name: str, **kw):
119
120
        """Factory method for instantiating a derived class.

121
        :param str registry_name: for example "tasklib.tasks.MyTask" or "MyTask"
122
123
124
        :param **kw: `Task` constructor arguments
        :returns Task:
        """
125
        return cls.get_subclass(registry_name)(**kw)
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156

    @classmethod
    def required_input_names(cls):
        return cls._INPUT_NAMES

    @classmethod
    def optional_input_names(cls):
        return cls._OPTIONAL_INPUT_NAMES

    @classmethod
    def input_names(cls):
        return cls._INPUT_NAMES | cls._OPTIONAL_INPUT_NAMES

    @classmethod
    def output_names(cls):
        return cls._OUTPUT_NAMES

    @classmethod
    def class_nonce_data(cls):
        return super().class_nonce_data() + (
            sorted(cls.input_names()),
            sorted(cls.output_names()),
            cls._N_REQUIRED_POSITIONAL_INPUTS,
        )

    @property
    def input_variables(self):
        return self._inputs

    @property
    def inputs(self):
157
        return self._public_inputs
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184

    @property
    def input_uhashes(self):
        return self._inputs.variable_uhashes

    @property
    def input_values(self):
        return self._inputs.variable_values

    @property
    def named_input_values(self):
        return self._inputs.named_variable_values

    @property
    def positional_input_values(self):
        return self._inputs.positional_variable_values

    @property
    def npositional_inputs(self):
        return self._inputs.n_positional_variables

    @property
    def output_variables(self):
        return self._outputs

    @property
    def outputs(self):
185
        return self._public_outputs
186
187
188
189
190
191
192
193
194

    @property
    def output_uhashes(self):
        return self._outputs.variable_uhashes

    @property
    def output_values(self):
        return self._outputs.variable_values

195
196
    @property
    def output_transfer_data(self):
197
        """The values are either `DataUri` or `Variable`"""
198
199
        return self._outputs.variable_transfer_data

200
201
202
203
204
205
206
207
    @property
    def output_metadata(self) -> Union[dict, None]:
        return self._outputs.metadata

    def _update_output_metadata(self):
        metadata = self.output_metadata
        if metadata is None:
            return
208
209
        if self.__label:
            metadata.setdefault("title", self.__label)
210

211
212
213
    @property
    def done(self):
        """Completed (with or without exception)"""
214
215
216
217
218
        return self.failed or self.succeeded

    @property
    def succeeded(self):
        """Completed without exception and with output values"""
219
        if self._OUTPUT_NAMES:
220
            return self._outputs.has_value
221
        else:
222
            return self._done
223
224
225

    @property
    def failed(self):
226
        """Completed with exception"""
227
228
        return self._exception is not None

Wout De Nolf's avatar
Wout De Nolf committed
229
230
231
232
233
234
235
    def _get_repr_data(self):
        data = super()._get_repr_data()
        if self.__label:
            data["label"] = repr(str(self.__label))
        else:
            data["label"] = None

Wout De Nolf's avatar
Wout De Nolf committed
236
237
238
239
240
241
242
    @property
    def label(self):
        if self.__label:
            return self.__label
        else:
            return str(self)

243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
    def _iter_missing_input_values(self):
        for iname in self._INPUT_NAMES:
            var = self._inputs.get(iname)
            if var is None or not var.has_value:
                yield iname

    @property
    def is_ready_to_execute(self):
        try:
            next(iter(self._iter_missing_input_values()))
        except StopIteration:
            return True
        return False

    def assert_ready_to_execute(self):
        lst = list(self._iter_missing_input_values())
        if lst:
            raise TaskInputError(
                "The following inputs could not be loaded: " + str(lst)
            )

264
265
266
    def execute(
        self, force_rerun: Optional[bool] = False, raise_on_error: Optional[bool] = True
    ):
267
268
269
270
271
272
273
274
        try:
            if force_rerun:
                # Rerun a task which is already done
                self._outputs.force_non_existing()
            if self.done:
                return
            self.assert_ready_to_execute()
            self.run()
275
            self._update_output_metadata()
276
277
278
279
            self._outputs.dump()
        except Exception as e:
            self._exception = e
            if raise_on_error:
Wout De Nolf's avatar
Wout De Nolf committed
280
                raise RuntimeError(f"Task '{self.label}' failed") from e
281
282
283
284
285
286
        else:
            self._done = True

    def run(self):
        """To be implemented by the derived classes"""
        raise NotImplementedError