Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / ops / gather.py
1 """
2  Copyright (c) 2017-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 logging as log
18
19 import networkx as nx
20 import numpy as np
21
22 from mo.graph.graph import Node, Graph
23 from mo.ops.op import Op
24
25
26 class Gather(Op):
27     op = 'Gather'
28
29     def __init__(self, graph: Graph, attrs: dict):
30         mandatory_props = {
31             'type': __class__.op,
32             'op': __class__.op,
33             'axis': 0,
34             'in_ports_count': 3,
35             'out_ports_count': 1,
36             'infer': __class__.infer,
37         }
38         super().__init__(graph, mandatory_props, attrs)
39
40     def supported_attrs(self):
41         return [
42             'axis',
43         ]
44
45     @staticmethod
46     def infer(node: Node):
47         assert len(node.in_nodes()) == 2 or len(node.in_nodes()) == 3
48
49         # There may be three inputs in TensorFlow. The third input is axis
50         if len(node.in_nodes()) == 3:
51             if node.in_node(2).value is None:
52                 log.error("Gather is supported only with constant axis value")
53                 return
54             node.axis = node.in_node(2).value.item()
55             node.graph.remove_edge(node.in_node(2).id, node.id)
56
57         axis = node.axis
58         data = node.in_node(0)
59         indices = node.in_node(1)
60
61         # both inputs are constant
62         if data.value is not None and indices.value is not None:
63             node.out_node(0).value = np.take(data.value, indices.value, axis)
64             node.out_node(0).shape = np.array(node.out_node(0).value.shape, dtype=np.int64)
65             return
66
67         shape = np.concatenate((data.shape[:axis], indices.shape))
68         if axis < len(data.shape) - 1:
69             shape = np.concatenate((shape, data.shape[axis + 1:]))
70
71         node.out_node(0).shape = np.array(shape, dtype=np.int64)