Skip to content

graph

Graph.

AbstractSerializable dataclass

Bases: ABC

An abstract serializable container.

Source code in client/ayon_workflow/workflow_editor/graph.py
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
@dataclass
class AbstractSerializable(abc.ABC):
    """An abstract serializable container."""

    name: str = field(default_factory=str)
    description: str = field(default_factory=str)

    def export_to_file(self, filepath: str):
        with open(filepath, "w", encoding="utf-8") as file_handler:
            file_handler.write(self.to_json())

    def to_json(self, sorted_keys: Optional[bool] = False) -> str:
        as_primitive = serialization.serialize_to_primitive(self)
        return json.dumps(as_primitive, indent=4, sort_keys=sorted_keys)

    @classmethod
    def import_from_file(cls, filepath: str) -> Self:
        data = pathlib.Path(filepath).read_text(encoding="utf-8")
        return cls.from_json(data)

    @classmethod
    def from_json(cls, json_str: str) -> Self:
        data = json.loads(json_str)
        return cls.from_dict(data)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> Any:
        return serialization.deserialize_from_primitive(data)

DispatchGraph dataclass

Bases: Graph

A Graph that only stores dispatch nodes for submission.

Source code in client/ayon_workflow/workflow_editor/graph.py
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@dataclass
class DispatchGraph(Graph):
    """A Graph that only stores dispatch nodes for submission."""

    all_nodes: List[AbstractDispatchTask] = field(default_factory=list)
    default_task_cls: str = field(default_factory=str)  # Store class name

    def get_associated_manager(self) -> str:
        managers = {
            node.get_associated_manager()
            for node in self.all_nodes
        }
        if len(managers) == 1:
            return managers.pop()

        # Either no value or multiple values for custom managers
        # within the dispatch graph. This is unexpected.
        raise RuntimeError(
            "Ambiguous dispatch graph, cannot"
            f"identify render manager from {managers}."
        )

    def create_node(
        self,
        dispatch_node_type: str,
        label: Optional[str] = None
    ) -> AbstractDispatchTask:
        """Create a container from a specific metadata container type."""
        meta_types = {
            klass.__name__: klass
            for klass in get_dispatch_node_types()
        }

        # Initialize new metadata container.
        if dispatch_node_type not in meta_types:
            raise ValueError(
                f"Invalid dispatch node type {dispatch_node_type}. "
                f"Available types are: {meta_types}."
            )

        meta_type = meta_types[dispatch_node_type]
        new_container_name = self._get_new_name(dispatch_node_type)
        new_container = meta_type(
            name=new_container_name,
            label=label,
            class_name=dispatch_node_type,
        )
        self.all_nodes.append(new_container)
        return new_container

    def delete_node(
        self,
        dispatch_node: AbstractDispatchTask,
    ):
        """Delete a dispatch node from the graph."""
        if not isinstance(dispatch_node, AbstractDispatchTask):
            raise TypeError(f"Invalid node provided {dispatch_node}")

        if dispatch_node not in self.all_nodes:
            raise ValueError(
                f"Invalid item to remove. {dispatch_node} "
                "is not part of the graph."
            )

        self.all_nodes.remove(dispatch_node)

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "DispatchGraph":
        data = serialization.deserialize_from_primitive(data)

        # Backward compatible with previous serialization method.
        # TODO remove legacy serialization format support in a future version.
        if isinstance(data, dict):
            logger.warning(
                "DispatchGraph.from_dict: using legacy serialization format"
            )
            dispatch_type_map = {
                klass.__name__: klass
                for klass in get_dispatch_node_types()
            }
            all_nodes = []
            for meta_node_data in data.get("all_nodes", []):
                class_name = meta_node_data.get("class_name") or next(
                    (name for name in dispatch_type_map
                     if name in meta_node_data["name"]),
                    None
                )
                klass = (
                    dispatch_type_map.get(class_name)
                    if class_name else None
                )
                if klass is None:
                    raise ValueError(
                        f"Unsupported node data: {meta_node_data}."
                    )
                all_nodes.append(klass.from_dict(meta_node_data))

            return cls(
                name=data.get("name"),
                description=data.get("description"),
                all_nodes=all_nodes,
                default_task_cls=data.get("default_task_cls", ""),
                ui=data.get("ui"),
            )

        return data

create_node(dispatch_node_type, label=None)

Create a container from a specific metadata container type.

Source code in client/ayon_workflow/workflow_editor/graph.py
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
def create_node(
    self,
    dispatch_node_type: str,
    label: Optional[str] = None
) -> AbstractDispatchTask:
    """Create a container from a specific metadata container type."""
    meta_types = {
        klass.__name__: klass
        for klass in get_dispatch_node_types()
    }

    # Initialize new metadata container.
    if dispatch_node_type not in meta_types:
        raise ValueError(
            f"Invalid dispatch node type {dispatch_node_type}. "
            f"Available types are: {meta_types}."
        )

    meta_type = meta_types[dispatch_node_type]
    new_container_name = self._get_new_name(dispatch_node_type)
    new_container = meta_type(
        name=new_container_name,
        label=label,
        class_name=dispatch_node_type,
    )
    self.all_nodes.append(new_container)
    return new_container

delete_node(dispatch_node)

Delete a dispatch node from the graph.

Source code in client/ayon_workflow/workflow_editor/graph.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def delete_node(
    self,
    dispatch_node: AbstractDispatchTask,
):
    """Delete a dispatch node from the graph."""
    if not isinstance(dispatch_node, AbstractDispatchTask):
        raise TypeError(f"Invalid node provided {dispatch_node}")

    if dispatch_node not in self.all_nodes:
        raise ValueError(
            f"Invalid item to remove. {dispatch_node} "
            "is not part of the graph."
        )

    self.all_nodes.remove(dispatch_node)

Graph dataclass

Bases: AbstractSerializable

A container of nodes.

Source code in client/ayon_workflow/workflow_editor/graph.py
 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
@dataclass
class Graph(AbstractSerializable):
    """A container of nodes."""

    all_nodes: List[Node] = field(default_factory=list)

    ui: Optional[ui_utils.UiGraphMetadata] = None
    metadata: Dict[str, Any] = field(default_factory=dict)

    def __str__(self) -> str:
        return f"<Graph {self.name} {len(self.all_nodes)} node(s)>"

    def get_nodes(
        self,
        node_types: Union[None, List[str]] = None,
    ) -> List[Node]:
        """Return all nodes with potential filter on type."""
        if node_types:
            return [
                node for node in self.all_nodes if node.node_type in node_types
            ]

        return copy.copy(self.all_nodes)

    def get_node_by_name(self, name: str) -> Node:
        for node in self.all_nodes:
            if node.name == name:
                return node
        raise ValueError(f"No node named {name} in graph.")

    def create_node(
            self,
            node_type: str,
            label: Optional[str] = None
        ) -> Node:
        """Create a node from a specific node type."""
        plugins = PluginRegistry().plugin_list()

        # Initialize new node from plugin desc.
        if node_type not in plugins:
            raise ValueError(
                f"Invalid node type {node_type}. "
                f"Available types are: {tuple(plugins)}"
            )

        new_node_name = self._get_new_name(node_type)
        new_node = Node(
            name=new_node_name,
            plugin_ref=PluginRef(
                name=node_type,
                version=plugins[node_type].version,
            ),
            label=label,
        )
        self.all_nodes.append(new_node)
        return new_node

    def delete_node(self, node: Node):
        """Delete a node from the graph."""
        if not isinstance(node, Node):
            raise TypeError(f"Invalid node provided {node}")

        # Check that node is present.
        elif node not in self.all_nodes:
            raise ValueError(
                f"Invalid node to remove. {node} is not part of the graph."
            )

        # Execution node: remove and adjust graph connections.
        to_remove = self.all_nodes.pop(self.all_nodes.index(node))

        # Remove potential broken connections.
        for other_node in self.all_nodes:
            for input_name in other_node.inputs:
                # Skip if to_remove is not connected this other node.
                conn_values = other_node[input_name]
                if not isinstance(conn_values, list):
                    conn_values = [conn_values]

                if (
                    conn_values == []
                    or not isinstance(conn_values[0], NodeConnection)
                ):
                    continue

                for conn in conn_values:
                    connected_node_name = conn.origin_node_name
                    if connected_node_name == to_remove.name:
                        other_node.disconnect_input(input_name)

        # Delete node.
        del to_remove

    def _get_new_name(self, item_type: str) -> str:
        """Compute a new meaningful yet unique item name."""
        similar_nodes = self.get_nodes(node_types=[item_type])

        if similar_nodes:
            regex = r"\D*(?P<index>\d*)"
            indexes = [
                re.match(regex, node.name).groupdict()["index"]
                for node in similar_nodes
            ]
            node_idx = max(map(int, indexes)) + 1

        else:
            node_idx = 1

        # Technically node name just have to be unique, stuff such
        # as "NodeType3" makes it easier to troubleshoot.
        return f"{item_type}{node_idx}"

    def duplicate_nodes(self, nodes: List[Node]) -> List[Node]:
        """ Duplicate provided nodes in the graph.
        """
        new_nodes = []
        node_names = []
        graph_node_names = {node.name for node in self.all_nodes}

        # duplicate nodes
        for node in nodes:
            node_names.append(node.name)
            new_node = copy.deepcopy(node)
            new_node.name = self._get_new_name(node.node_type)
            self.all_nodes.append(new_node)
            new_nodes.append(new_node)

        node_idx_by_name = {name: idx for idx, name in enumerate(node_names)}

        # duplicate connections
        for new_node in new_nodes:
            for input_name, conns in new_node.input_connections.items():
                is_multi_input = True
                if not isinstance(conns, list):  # handle non-multi inputs
                    is_multi_input = False
                    conns = [conns]

                idx = 0
                for input_conn in conns:
                    if (
                        isinstance(input_conn, NodeConnection)
                        and input_conn.origin_node_name not in graph_node_names
                    ):
                        if is_multi_input:
                            new_node.input_connections[input_name].pop(idx)
                            continue
                        else:
                            new_node.input_connections[input_name] = None
                            break

                    new_conn = copy.copy(input_conn)
                    if (
                        isinstance(input_conn, NodeConnection)
                        and input_conn.origin_node_name in node_idx_by_name
                    ):
                        node_idx = node_idx_by_name[
                            input_conn.origin_node_name
                        ]
                        new_conn.origin_node_name = new_nodes[node_idx].name

                    if not is_multi_input:
                        new_node.input_connections[input_name] = new_conn
                        break
                    new_node.input_connections[input_name][idx] = new_conn
                    idx += 1

        return new_nodes

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Graph":
        data = super().from_dict(data)

        # Backward compatible with previous serialization method.
        # TODO remove legacy serialization format support in a future version.
        if isinstance(data, dict):
            logger.warning(
                "Graph.from_dict: using legacy serialization format"
            )
            all_nodes = []
            for node_data in data.get("all_nodes", []):
                try:
                    all_nodes.append(Node.from_dict(node_data))

                except TypeError as error:
                    raise ValueError(
                        f"Unsupported node data: {node_data}."
                    ) from error

            return cls(
                name=data.get("name"),
                description=data.get("description"),
                all_nodes=all_nodes,
                ui=data.get("ui"),
            )

        return data

create_node(node_type, label=None)

Create a node from a specific node type.

Source code in client/ayon_workflow/workflow_editor/graph.py
 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
def create_node(
        self,
        node_type: str,
        label: Optional[str] = None
    ) -> Node:
    """Create a node from a specific node type."""
    plugins = PluginRegistry().plugin_list()

    # Initialize new node from plugin desc.
    if node_type not in plugins:
        raise ValueError(
            f"Invalid node type {node_type}. "
            f"Available types are: {tuple(plugins)}"
        )

    new_node_name = self._get_new_name(node_type)
    new_node = Node(
        name=new_node_name,
        plugin_ref=PluginRef(
            name=node_type,
            version=plugins[node_type].version,
        ),
        label=label,
    )
    self.all_nodes.append(new_node)
    return new_node

delete_node(node)

Delete a node from the graph.

Source code in client/ayon_workflow/workflow_editor/graph.py
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
def delete_node(self, node: Node):
    """Delete a node from the graph."""
    if not isinstance(node, Node):
        raise TypeError(f"Invalid node provided {node}")

    # Check that node is present.
    elif node not in self.all_nodes:
        raise ValueError(
            f"Invalid node to remove. {node} is not part of the graph."
        )

    # Execution node: remove and adjust graph connections.
    to_remove = self.all_nodes.pop(self.all_nodes.index(node))

    # Remove potential broken connections.
    for other_node in self.all_nodes:
        for input_name in other_node.inputs:
            # Skip if to_remove is not connected this other node.
            conn_values = other_node[input_name]
            if not isinstance(conn_values, list):
                conn_values = [conn_values]

            if (
                conn_values == []
                or not isinstance(conn_values[0], NodeConnection)
            ):
                continue

            for conn in conn_values:
                connected_node_name = conn.origin_node_name
                if connected_node_name == to_remove.name:
                    other_node.disconnect_input(input_name)

    # Delete node.
    del to_remove

duplicate_nodes(nodes)

Duplicate provided nodes in the graph.

Source code in client/ayon_workflow/workflow_editor/graph.py
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
def duplicate_nodes(self, nodes: List[Node]) -> List[Node]:
    """ Duplicate provided nodes in the graph.
    """
    new_nodes = []
    node_names = []
    graph_node_names = {node.name for node in self.all_nodes}

    # duplicate nodes
    for node in nodes:
        node_names.append(node.name)
        new_node = copy.deepcopy(node)
        new_node.name = self._get_new_name(node.node_type)
        self.all_nodes.append(new_node)
        new_nodes.append(new_node)

    node_idx_by_name = {name: idx for idx, name in enumerate(node_names)}

    # duplicate connections
    for new_node in new_nodes:
        for input_name, conns in new_node.input_connections.items():
            is_multi_input = True
            if not isinstance(conns, list):  # handle non-multi inputs
                is_multi_input = False
                conns = [conns]

            idx = 0
            for input_conn in conns:
                if (
                    isinstance(input_conn, NodeConnection)
                    and input_conn.origin_node_name not in graph_node_names
                ):
                    if is_multi_input:
                        new_node.input_connections[input_name].pop(idx)
                        continue
                    else:
                        new_node.input_connections[input_name] = None
                        break

                new_conn = copy.copy(input_conn)
                if (
                    isinstance(input_conn, NodeConnection)
                    and input_conn.origin_node_name in node_idx_by_name
                ):
                    node_idx = node_idx_by_name[
                        input_conn.origin_node_name
                    ]
                    new_conn.origin_node_name = new_nodes[node_idx].name

                if not is_multi_input:
                    new_node.input_connections[input_name] = new_conn
                    break
                new_node.input_connections[input_name][idx] = new_conn
                idx += 1

    return new_nodes

get_nodes(node_types=None)

Return all nodes with potential filter on type.

Source code in client/ayon_workflow/workflow_editor/graph.py
76
77
78
79
80
81
82
83
84
85
86
def get_nodes(
    self,
    node_types: Union[None, List[str]] = None,
) -> List[Node]:
    """Return all nodes with potential filter on type."""
    if node_types:
        return [
            node for node in self.all_nodes if node.node_type in node_types
        ]

    return copy.copy(self.all_nodes)