• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright 2021 Huawei Technologies Co., Ltd
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14# ==============================================================================
15"""
16General Validator Helper Functions.
17"""
18import os
19import inspect
20
21UINT32_MAX = 4294967295
22UINT32_MIN = 0
23UINT64_MAX = 18446744073709551615
24UINT64_MIN = 0
25
26
27def pad_arg_name(arg_name):
28    if arg_name != "":
29        arg_name = arg_name + " "
30    return arg_name
31
32
33def check_value(arg, valid_range, arg_name=""):
34    arg_name = pad_arg_name(arg_name)
35    if arg < valid_range[0] or arg > valid_range[1]:
36        raise ValueError(
37            "Input {0}is not within the required interval of ({1} to {2}).".format(arg_name,
38                                                                                   valid_range[0], valid_range[1]))
39
40
41def check_uint32(arg, arg_name=""):
42    type_check(arg, (int,), arg_name)
43    check_value(arg, [UINT32_MIN, UINT32_MAX])
44
45
46def check_uint64(arg, arg_name=""):
47    type_check(arg, (int,), arg_name)
48    check_value(arg, [UINT64_MIN, UINT64_MAX])
49
50
51def check_iteration(arg, arg_name=""):
52    type_check(arg, (int,), arg_name)
53    check_value(arg, [-1, UINT64_MAX])
54
55
56def check_dir(dataset_dir):
57    if not os.path.isdir(dataset_dir) or not os.access(dataset_dir, os.R_OK):
58        raise ValueError("The folder {} does not exist or permission denied!".format(dataset_dir))
59
60
61def parse_user_args(method, *args, **kwargs):
62    """
63    Parse user arguments in a function.
64
65    Args:
66        method (method): a callable function.
67        args: user passed args.
68        kwargs: user passed kwargs.
69
70    Returns:
71        user_filled_args (list): values of what the user passed in for the arguments.
72        ba.arguments (Ordered Dict): ordered dict of parameter and argument for what the user has passed.
73    """
74    sig = inspect.signature(method)
75    if 'self' in sig.parameters or 'cls' in sig.parameters:
76        ba = sig.bind(method, *args, **kwargs)
77        ba.apply_defaults()
78        params = list(sig.parameters.keys())[1:]
79    else:
80        ba = sig.bind(*args, **kwargs)
81        ba.apply_defaults()
82        params = list(sig.parameters.keys())
83
84    user_filled_args = [ba.arguments.get(arg_value) for arg_value in params]
85    return user_filled_args, ba.arguments
86
87
88def type_check(arg, types, arg_name):
89    """
90    Check the type of the parameter.
91
92    Args:
93        arg (Any) : any variable.
94        types (tuple): tuple of all valid types for arg.
95        arg_name (str): the name of arg.
96
97    Returns:
98        Exception: when the type is not correct, otherwise nothing.
99    """
100    # handle special case of booleans being a subclass of ints
101    print_value = '\"\"' if repr(arg) == repr('') else arg
102
103    if int in types and bool not in types:
104        if isinstance(arg, bool):
105            raise TypeError("Argument {0} with value {1} is not of type {2}.".format(arg_name, print_value, types))
106    if not isinstance(arg, types):
107        raise TypeError("Argument {0} with value {1} is not of type {2}.".format(arg_name, print_value, types))
108
109
110def type_check_list(args, types, arg_names):
111    """
112    Check the type of each parameter in the list.
113
114    Args:
115        args (Union[list, tuple]): a list or tuple of any variable.
116        types (tuple): tuple of all valid types for arg.
117        arg_names (Union[list, tuple of str]): the names of args.
118
119    Returns:
120        Exception: when the type is not correct, otherwise nothing.
121    """
122    type_check(args, (list, tuple,), arg_names)
123    if len(args) != len(arg_names) and not isinstance(arg_names, str):
124        raise ValueError("List of arguments is not the same length as argument_names.")
125    if isinstance(arg_names, str):
126        arg_names = ["{0}[{1}]".format(arg_names, i) for i in range(len(args))]
127    for arg, arg_name in zip(args, arg_names):
128        type_check(arg, types, arg_name)
129
130
131def replace_minus_one(value):
132    """ replace -1 with a default value """
133    return value if value != -1 else UINT32_MAX
134
135
136def check_param_id(info_param, info_name):
137    """
138    Check the type of info_param.
139
140    Args:
141        info_param (Union[list[int], str]): Info parameters of check_node_list that is either list of ints or *.
142        info_name (str): Info name of check_node_list.
143
144    Raises:
145        ValueError: When the type of info_param is not correct, otherwise nothing.
146    """
147    if isinstance(info_param, str):
148        if info_param not in ["*"]:
149            raise ValueError("Node parameter {} only accepts '*' as string.".format(info_name))
150    else:
151        for param in info_param:
152            check_uint32(param, info_name)
153