Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / ops / select.py
1 """
2  Copyright (c) 2018-2019 Intel Corporation
3
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 """
16
17 import networkx as nx
18 import numpy as np
19
20 from mo.graph.graph import Node, Graph
21 from mo.ops.op import Op
22 from mo.utils.error import Error
23
24
25 class Select(Op):
26     op = 'Select'
27
28     def __init__(self, graph: Graph, attrs: dict):
29         mandatory_props = {
30             'op': __class__.op,
31             'in_ports_count': 3,
32             'out_ports_count': 1,
33             'infer': __class__.infer,
34         }
35         super().__init__(graph, mandatory_props, attrs)
36
37     @staticmethod
38     def infer(node: Node):
39         assert len(node.in_nodes()) == 3, "Select operation must have 3 inputs by TensorFlow reference:" \
40                                           " \'condition\', \'then\' and \'else\' tensors"
41         condition_node = node.in_node(0)
42         resulting_tensors = [node.in_node(1), node.in_node(2)]
43
44         assert np.array_equal(resulting_tensors[0].shape, resulting_tensors[1].shape), \
45             "TensorFlow \'Select\' operation has 3 inputs: \'condition\', \'then\' and \'else\' tensors." \
46             "\'then\' and \'else\' tensors must have the same shape by TensorFlow reference"
47         output_shape = resulting_tensors[0].shape
48
49         # Case with unknown condition
50         if not condition_node.has_valid('value'):
51             # infer only shapes
52             for out in node.out_nodes():
53                 node.out_node(out).shape = np.array(output_shape)
54             return
55
56         condition_value = condition_node.value[0]
57
58         assert isinstance(condition_value, np.bool_), \
59             "TensorFlow \'Select\' operation has 3 inputs: \'condition\', \'then\' and \'else\' tensors. " \
60             "Value of \'condition\' tensor must be boolen by TensorFlow reference"
61
62         output_value = resulting_tensors[not condition_value].value
63         for _, out_node in node.graph.out_edges(node.id):
64             node.graph.node[out_node]['shape'] = np.array(output_shape)
65             node.graph.node[out_node]['value'] = None if output_value is None else np.array(output_value)