Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / ops / flatten_onnx.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.graph.graph import Graph
22 from mo.ops.op import Op
23
24
25 class FlattenONNX(Op):
26     op = 'FlattenONNX'
27     enabled = True
28
29     def __init__(self, graph: Graph, attrs: dict):
30         super().__init__(graph, {
31             'type': 'Reshape',
32             'op': __class__.op,
33             'infer': __class__.infer,
34             'in_ports_count': 2,
35             'out_ports_count': 1,
36         }, attrs)
37
38     @staticmethod
39     def infer(node):
40         """
41         Infers shape of flatten node as it is done in onnx.
42         Args:
43             node: graph flatten node
44         """
45         if not node.has_valid('axis'):
46             log.debug('Can\'t calculate output shape for {} node due to missing axis attribute'.format(node.name))
47             return
48
49         if node.in_node(0).shape is None:
50             log.debug('Can\'t calculate output shape for {} node due to shape for input node is None'.format(node.name))
51             return
52
53         if len(node.in_nodes()) != 1:
54             log.debug(
55                 'Can\'t calculate output shape for {} node. Number of input nodes should be equal 1 instead of {}'.format(
56                     node.name, len(node.in_nodes())))
57             return
58
59         axis = node.axis
60         shape = node.in_node(0).shape
61         dim = [np.prod(shape[0:axis]), np.prod(shape[axis:])]
62         node['dim'] = np.array(dim)
63         node.out_node().shape = np.array(dim)
64         if node.in_node(0).has_valid('value'):
65             node.out_node().value = np.reshape(node.in_node(0).value, dim)