Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / middle / RemoveRedundantReshapeAfterCropAndResize.py
1 """
2  Copyright (c) 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.middle.replacement import MiddleReplacementPattern
23
24
25 class RemoveRedundantReshapeAfterCropAndResize(MiddleReplacementPattern):
26     enabled = True
27     force_clean_up = True
28
29     def run_after(self):
30         from extensions.middle.pass_separator import MiddleFinish
31         return [MiddleFinish]
32
33     def run_before(self):
34         return []
35
36     def pattern(self):
37         return dict(
38             nodes=[
39                 ('crop_and_resize', dict(kind='op', op='CropAndResize')),
40                 ('crop_and_resize_data', dict(kind='data')),
41                 ('reshape_1', dict(kind='op', op='Reshape')),
42                 ('reshape_1_data', dict(kind='data')),
43                 ('reshape_2', dict(kind='op', op='Reshape')),
44             ],
45             edges=[
46                 ('crop_and_resize', 'crop_and_resize_data'),
47                 ('crop_and_resize_data', 'reshape_1'),
48                 ('reshape_1', 'reshape_1_data'),
49                 ('reshape_1_data', 'reshape_2'),
50             ]
51         )
52
53     def replace_pattern(self, graph: Graph, match: dict):
54         car_node = match['crop_and_resize']
55         reshape_2_node = match['reshape_2']
56
57         shape_1 = match['crop_and_resize_data'].shape
58         shape_2 = match['reshape_2'].out_node().shape
59         if not np.all(shape_1 == shape_2):
60             log.debug('Cannot remove reshape operations after CropAndResize due to different shapes: {} vs {}'.format(
61                 shape_1, shape_2
62             ))
63             return
64
65         car_node.out_port(0).disconnect()
66         consumer_port_node = reshape_2_node.out_port(0).get_connection().get_destination()
67         consumer_port_node.disconnect()
68         car_node.out_port(0).connect(consumer_port_node)