Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / extensions / front / image_scaler.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 numpy as np
18
19 from mo.front.common.replacement import FrontReplacementOp
20 from mo.graph.graph import Graph
21 from mo.ops.const import Const
22 from mo.ops.lin_op import Mul, Add
23
24
25 class ImageScaler(FrontReplacementOp):
26     op = "ImageScaler"
27     enabled = True
28
29     def replace_sub_graph(self, graph: Graph, match: dict):
30         # This replacer replace ImageScalar operation to Mul->Add sequence
31         # Also it check that weights and biases are good
32         op = match['op']
33
34         # Check that weights and biases are not useless
35         has_bias, has_weights = True, True
36         if all([x == 1 for x in np.nditer(op.scale)]):
37             has_weights = False
38         if all([x == 0 for x in np.nditer(op.bias)]):
39             has_bias = False
40
41         assert len(op.in_ports()) == 1
42
43         last_port = op.in_port(0).get_source()
44
45         # Create Mul & Add nodes
46         if has_weights:
47             mul_weights = Const(graph, dict(value=op.scale, shape=op.scale.shape)).create_node()
48             mul_op = Mul(graph, dict(name=op.id + '/mul_')).create_node()
49             op.in_port(0).get_connection().set_destination(mul_op.in_port(0))
50             mul_weights.out_port(0).connect(mul_op.in_port(1))
51             last_port = mul_op.out_port(0)
52
53         if has_bias:
54             add_bias = Const(graph, dict(value=op.bias, shape=op.bias.shape)).create_node()
55             add_op = Add(graph, dict(name=op.id + '/add_')).create_node()
56             last_port.get_connection().set_destination(add_op.in_port(0))
57             add_bias.out_port(0).connect(add_op.in_port(1))
58             last_port = add_op.out_port(0)
59
60         op.in_port(0).disconnect()
61         op.out_port(0).get_connection().set_source(last_port)