block.py 9.61 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
118
119
120
121
122
123
124
125
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
157
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
from collections import namedtuple

from .experiment import Experiment
from .toolchain import Toolchain

_Node = namedtuple("Node", ["block", "name", "dataformat"])


class _Edge:
    """An edge of a BEAT experiment/toolchain graph
    """

    def __init__(self, block, name, dataformat, channel, **kwargs):
        super().__init__(**kwargs)
        self.before = _Node(block, name, dataformat)
        self.channel = channel

    def connect_to(self, block, name, dataformat):
        after = _Node(block, name, dataformat)
        if dataformat != self.before[-1]:
            raise RuntimeError(f"Cannot connect the output of {self.before} to {after}")
        self.after = after

    def __repr__(self):
        return f"{self.before} -> {self.after} in {self.channel}"


class _Block:
    """A block of a BEAT experiment/toolchain.
    It holds information about its input/output connections.
    """

    def __init__(self, component, name=None, **kwargs):
        super().__init__(**kwargs)
        self._component = component
        self._edges = []
        self._name = name or component.name.replace("/", "_")


class DatasetBlock(_Block):
    def __init__(self, database, protocol, set, name=None, **kwargs):
        super().__init__(component=database, name=name, **kwargs)

        if protocol not in database.protocol_names:
            raise ValueError(
                f"Unknown protocol name ({protocol}) for database: {database}"
            )
        self._protocol = protocol

        if set not in database.set_names(protocol):
            raise ValueError(
                f"Unknown set name ({set}) for "
                f"database: {database} and protocol: {protocol}"
            )
        self._set = set
        self._channel = f"{self._component.name}_{self._protocol}_{self._set}"
        self._channel = self._channel.replace("/", "_")
        if name is None:
            self._name = self._channel

    def __getattr__(self, name):
        # check if name is in the set outputs
        _set = self._component.set(self._protocol, self._set)
        if name not in _set["outputs"]:
            raise AttributeError
        edge = _Edge(
            block=self,
            name=name,
            dataformat=_set["outputs"][name],
            channel=self._channel,
        )
        # keep the edge
        setattr(self, name, edge)
        self._edges.append(edge)
        return edge


class _AlgorithmAnalyzerBlock(_Block):
    def validate_inputs(self, **kwargs):
        input_names = set(kwargs.keys())
        valid_input_names = set(self._component.input_map.keys())
        if input_names != valid_input_names:
            raise ValueError(
                f"Inputs {input_names} do not match "
                f"algorithm's inputs: {valid_input_names}"
            )
        # set channel based on inputs if not set already
        if self.channel is None:
            edge_channels = set(v.channel for v in kwargs.values())
            if not len(edge_channels) == 1:
                raise ValueError(
                    f"The inputs are coming from more than 1 synchronization channel "
                    f"({edge_channels}). During the initialization of {self}, specify "
                    f"the dataset responsible for the main synchronization channel "
                    "of this block."
                )
            self.channel = edge_channels.pop()

    def connect_inputs(self, **kwargs):
        self.input_edges = []
        # connect input edges to inputs
        for input_name, edge in kwargs.items():
            edge.connect_to(self, input_name, self._component.input_map[input_name])
            self.input_edges.append(edge)


class AlgorithmBlock(_AlgorithmAnalyzerBlock):
    def __init__(self, algorithm, sync_with=None, parameters=None, name=None, **kwargs):
        super().__init__(component=algorithm, name=name, **kwargs)
        self.channel = None if sync_with is None else sync_with._channel
        self.parameters = parameters

    def __call__(self, **kwargs):
        self.validate_inputs(**kwargs)
        self.connect_inputs(**kwargs)

        # find the channel of output through inputs
        grp = self._component.output_group
        for input_name, edge in kwargs.items():
            if input_name in grp["inputs"]:
                output_channel = edge.channel
                break

        # construct output edges
        output_edges = []
        for output_name, dataformat in self._component.output_map.items():
            edge = _Edge(
                block=self,
                name=output_name,
                dataformat=dataformat,
                channel=output_channel,
            )
            output_edges.append(edge)

        self._edges.extend(output_edges)
        if len(output_edges) == 1:
            return output_edges[0]
        return output_edges


class AnalyzerBlock(_AlgorithmAnalyzerBlock):
    def __init__(
        self, analyzer, name=None, toolchain_name=None, experiment_name=None, **kwargs
    ):
        super().__init__(component=analyzer, name=name, **kwargs)
        self.channel = None
        self.toolchain_name = toolchain_name
        self.experiment_name = experiment_name

    def __call__(self, **kwargs):
        self.validate_inputs(**kwargs)
        self.connect_inputs(**kwargs)


def create_experiment(*analyzers, experiment_name, toolchain_name=None):
    # construct the toolchain and experiment
    toolchain_name = toolchain_name or experiment_name
    experiment = _create_experiment(
        [edge for analyzer in analyzers for edge in analyzer.input_edges],
        toolchain_name=toolchain_name,
        experiment_name=experiment_name,
    )
    return experiment


def _get_all_edges(edges, all_edges=None):
    if all_edges is None:
        all_edges = set()
    for edge in edges:
        all_edges.add(edge)
        new_edges = [
            e for e in getattr(edge.before.block, "input_edges", []) if e not in edges
        ]
        all_edges.update(_get_all_edges(new_edges, all_edges))
    return all_edges


def _create_experiment(edges, toolchain_name, experiment_name):
    all_edges = list(_get_all_edges(edges))

    # find all blocks
    datasets = set()
    algorithms = set()
    analyzers = set()
    for edge in all_edges:

        before_block = edge.before.block
        if isinstance(before_block, DatasetBlock):
            datasets.add(before_block)

        after_block = edge.after.block
        if isinstance(after_block, AlgorithmBlock):
            algorithms.add(after_block)
        elif isinstance(after_block, AnalyzerBlock):
            analyzers.add(after_block)

    # create unique names for all blocks
    all_blocks = list(datasets) + list(algorithms) + list(analyzers)
    names, names_map = list(), dict()
    for block in all_blocks:
        name = block._name
        # if the name already exists
        while name in names:
            name += "_2"
        names.append(name)
        names_map[block] = name

    # find all connections
    connections = []
    for edge in all_edges:
        before_name = names_map[edge.before.block]
        after_name = names_map[edge.after.block]
        connections.append(
            {
                "channel": edge.channel,
                "from": f"{before_name}.{edge.before.name}",
                "to": f"{after_name}.{edge.after.name}",
            }
        )

    # create datasets
    toolchain_datasets, experiment_datasets = list(), dict()
    for block in datasets:
        name = names_map[block]
        outputs = [edge.before.name for edge in block._edges]
        toolchain_datasets.append(dict(name=name, outputs=outputs))
        experiment_datasets[name] = dict(
            database=block._component.name, protocol=block._protocol, set=block._set,
        )

    # create blocks (algorithms)
    toolchain_blocks, experiment_blocks = list(), dict()
    for block in algorithms:
        name = names_map[block]
        channel = block.channel
        inputs = [edge.after.name for edge in block.input_edges]
        outputs = [edge.before.name for edge in block._edges]
        toolchain_blocks.append(
            dict(
                name=name, synchronized_channel=channel, inputs=inputs, outputs=outputs
            )
        )
        experiment_blocks[name] = dict(
            algorithm=block._component.name,
            inputs={edge.after.name: edge.before.name for edge in block.input_edges},
            outputs={edge.before.name: edge.after.name for edge in block._edges},
        )

    # create analyzers
    toolchain_analyzers, experiment_analyzers = list(), dict()
    for block in analyzers:
        name = names_map[block]
        channel = block.channel
        inputs = [edge.after.name for edge in block.input_edges]
        toolchain_analyzers.append(
            dict(name=name, synchronized_channel=channel, inputs=inputs)
        )
        experiment_analyzers[name] = dict(
            algorithm=block._component.name,
            inputs={edge.after.name: edge.before.name for edge in block.input_edges},
        )

    # create toolchain
    data = dict(
        analyzers=toolchain_analyzers,
        blocks=toolchain_blocks,
        datasets=toolchain_datasets,
        connections=connections,
        representation={"blocks": {}, "channel_colors": {}, "connections": {}},
    )
    toolchain = Toolchain.new(data=data, name=toolchain_name)

    data = dict(
        analyzers=experiment_analyzers,
        blocks=experiment_blocks,
        datasets=experiment_datasets,
        schema_version=1,
        globals={
            "environment": {"name": "dummy", "version": "0.0.0"},
            "queue": "queue",
        },
    )

    experiment = Experiment.new(data=data, toolchain=toolchain, label=experiment_name,)
    return experiment