Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / common / partial_infer / expand_dims.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 logging as log
18
19 import numpy as np
20
21 from mo.ops.op import PermuteAttrs
22
23
24 def tf_expand_dims_infer(node):
25     input_node = node.in_nodes()[0]
26     output_node = node.out_node()
27     if input_node.shape is None:
28         return
29
30     # TensorFlow style with dynamic input
31     if len(node.in_nodes()) > 1:
32         axis_node = node.in_nodes()[1]
33         if isinstance(axis_node.value, np.ndarray) and axis_node.value.size > 1:
34             log.error("ExpandDims operation : axis should be scalar")
35             return
36         expand_axis = axis_node.value.item()
37         node.graph.remove_edge(axis_node.id, node.id)
38     else:
39         if not node.has_valid('expand_axis'):
40             log.error("ExpandDims axis is not defined")
41             return
42         expand_axis = node.expand_axis
43
44     if expand_axis is None:
45         return
46
47     # expand_axis is a position where the new axis is placed
48     # so expand_dims works for negative axis in a different way
49     # not as insert operation
50     if expand_axis < 0:
51         expand_axis += len(input_node.shape) + 1
52
53     output_node.shape = np.insert(input_node.shape, expand_axis, [1])
54     # convert data type of the shape to int64 explicitly
55     output_node.shape = output_node.shape.astype(np.int64)
56     if input_node.value is not None:
57         output_node.value = np.array(np.reshape(input_node.value, output_node.shape))
58
59     node['dim'] = output_node.shape
60
61     PermuteAttrs.create_permute_attrs(node, attrs=[('dim', 'output:0')])
62