Publishing 2019 R1 content
[platform/upstream/dldt.git] / model-optimizer / mo / front / onnx / extractors / utils.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.graph.graph import Node
20 from mo.utils.error import Error
21
22
23 def onnx_attr(node: Node, name: str, field: str, default=None, dst_type=None):
24     """ Retrieves ONNX attribute with name `name` from ONNX protobuf `node.pb`.
25         The final value is casted to dst_type if attribute really exists.
26         The function returns `default` otherwise.
27     """
28     attrs = [a for a in node.pb.attribute if a.name == name]
29     if len(attrs) == 0:
30         # there is no requested attribute in the protobuf message
31         return default
32     elif len(attrs) > 1:
33         raise Error('Found multiple entries for attribute name {} when at most one is expected. Protobuf message with '
34                     'the issue: {}.', name, node.pb)
35     else:
36         res = getattr(attrs[0], field)
37         if dst_type is not None:
38             return dst_type(res)
39         else:
40             return res
41
42
43 def get_backend_pad(pads, spatial_dims, axis):
44     return [x[axis] for x in pads[spatial_dims]]
45
46
47 def get_onnx_autopad(auto_pad):
48     auto_pad = auto_pad.decode().lower()
49     if auto_pad == 'notset':
50         auto_pad = None
51     return auto_pad
52
53
54 def get_onnx_datatype_as_numpy(value):
55     datatype_to_numpy = {
56                          1: np.float32,
57                          9: np.bool,
58                          11: np.double,
59                          10: np.float16,
60                          5: np.int16,
61                          6: np.int32,
62                          7: np.int64,
63                          3: np.int8,
64                          8: np.ubyte,
65                          4: np.uint16,
66                          12: np.uint32,
67                          13: np.uint64,
68                          2: np.uint8,
69                          }
70     try:
71         return datatype_to_numpy[value]
72     except KeyError:
73         raise Error("Incorrect value {} for Datatype enum".format(value))