Passed
Pull Request — master (#206)
by Grega
02:08
created

NiaPy.util.utility.wangRepair()   A

Complexity

Conditions 1

Size

Total Lines 19
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nop 4
dl 0
loc 19
rs 10
c 0
b 0
f 0
1
# encoding=utf8
2
3
"""Implementation of various utility functions."""
4
5
import logging
6
7
from numpy import (
8
    ndarray,
9
    asarray,
10
    full,
11
    empty,
12
    where,
13
    random as rand,
14
    ceil,
15
    amin,
16
    amax
17
)
18
19
logging.basicConfig()
20
logger = logging.getLogger("NiaPy.util.utility")
21
logger.setLevel("INFO")
22
23
__all__ = [
24
    "limit_repair",
25
    "limitInversRepair",
26
    "objects2array",
27
    "wangRepair",
28
    "randRepair",
29
    "fullArray",
30
    "reflectRepair"
31
]
32
33
34
def limit_repair(x, Lower, Upper, **kwargs):
35
    r"""Repair solution and put the solution in the random position inside of the bounds of problem.
36
37
    Arguments:
38
            x (numpy.ndarray): Solution to check and repair if needed.
39
            Lower (numpy.ndarray): Lower bounds of search space.
40
            Upper (numpy.ndarray): Upper bounds of search space.
41
            kwargs (Dict[str, Any]): Additional arguments.
42
43
    Returns:
44
            numpy.ndarray: Solution in search space.
45
46
    """
47
48
    ir = where(x < Lower)
49
    x[ir] = Lower[ir]
50
    ir = where(x > Upper)
51
    x[ir] = Upper[ir]
52
    return x
53
54
55
def limitInversRepair(x, Lower, Upper, **kwargs):
56
    r"""Repair solution and put the solution in the random position inside of the bounds of problem.
57
58
    Arguments:
59
            x (numpy.ndarray): Solution to check and repair if needed.
60
            Lower (numpy.ndarray): Lower bounds of search space.
61
            Upper (numpy.ndarray): Upper bounds of search space.
62
            kwargs (Dict[str, Any]): Additional arguments.
63
64
    Returns:
65
            numpy.ndarray: Solution in search space.
66
67
    """
68
69
    ir = where(x < Lower)
70
    x[ir] = Upper[ir]
71
    ir = where(x > Upper)
72
    x[ir] = Lower[ir]
73
    return x
74
75
76
def wangRepair(x, Lower, Upper, **kwargs):
77
    r"""Repair solution and put the solution in the random position inside of the bounds of problem.
78
79
    Arguments:
80
            x (numpy.ndarray): Solution to check and repair if needed.
81
            Lower (numpy.ndarray): Lower bounds of search space.
82
            Upper (numpy.ndarray): Upper bounds of search space.
83
            kwargs (Dict[str, Any]): Additional arguments.
84
85
    Returns:
86
            numpy.ndarray: Solution in search space.
87
88
    """
89
90
    ir = where(x < Lower)
91
    x[ir] = amin([Upper[ir], 2 * Lower[ir] - x[ir]], axis=0)
92
    ir = where(x > Upper)
93
    x[ir] = amax([Lower[ir], 2 * Upper[ir] - x[ir]], axis=0)
94
    return x
95
96
97
def randRepair(x, Lower, Upper, rnd=rand, **kwargs):
98
    r"""Repair solution and put the solution in the random position inside of the bounds of problem.
99
100
    Arguments:
101
            x (numpy.ndarray): Solution to check and repair if needed.
102
            Lower (numpy.ndarray): Lower bounds of search space.
103
            Upper (numpy.ndarray): Upper bounds of search space.
104
            rnd (mtrand.RandomState): Random generator.
105
            kwargs (Dict[str, Any]): Additional arguments.
106
107
    Returns:
108
            numpy.ndarray: Fixed solution.
109
110
    """
111
112
    ir = where(x < Lower)
113
    x[ir] = rnd.uniform(Lower[ir], Upper[ir])
114
    ir = where(x > Upper)
115
    x[ir] = rnd.uniform(Lower[ir], Upper[ir])
116
    return x
117
118
119
def reflectRepair(x, Lower, Upper, **kwargs):
120
    r"""Repair solution and put the solution in search space with reflection of how much the solution violates a bound.
121
122
    Args:
123
            x (numpy.ndarray): Solution to be fixed.
124
            Lower (numpy.ndarray): Lower bounds of search space.
125
            Upper (numpy.ndarray): Upper bounds of search space.
126
            kwargs (Dict[str, Any]): Additional arguments.
127
128
    Returns:
129
            numpy.ndarray: Fix solution.
130
131
    """
132
133
    ir = where(x > Upper)
134
    x[ir] = Lower[ir] + x[ir] % (Upper[ir] - Lower[ir])
135
    ir = where(x < Lower)
136
    x[ir] = Lower[ir] + x[ir] % (Upper[ir] - Lower[ir])
137
    return x
138
139
140
def fullArray(a, D):
141
    r"""Fill or create array of length D, from value or value form a.
142
143
    Arguments:
144
        a (Union[int, float, numpy.ndarray], Iterable[Any]): Input values for fill.
145
        D (int): Length of new array.
146
147
    Returns:
148
        numpy.ndarray: Array filled with passed values or value.
149
150
    """
151
152
    A = []
153
154
    if isinstance(a, (int, float)):
155
        A = full(D, a)
156
    elif isinstance(a, (ndarray, list, tuple)):
157
        if len(a) == D:
158
            A = a if isinstance(a, ndarray) else asarray(a)
159
        elif len(a) > D:
160
            A = a[:D] if isinstance(a, ndarray) else asarray(a[:D])
161
        else:
162
            for i in range(int(ceil(float(D) / len(a)))):
163
                A.extend(a[:D if (D - i * len(a)) >= len(a) else D - i * len(a)])
164
            A = asarray(A)
165
    return A
166
167
168
def objects2array(objs):
169
    r"""Convert `Iterable` array or list to `NumPy` array.
170
171
    Args:
172
        objs (Iterable[Any]): Array or list to convert.
173
174
    Returns:
175
        numpy.ndarray: Array of objects.
176
177
    """
178
179
    a = empty(len(objs), dtype=object)
180
    for i, e in enumerate(objs):
181
        a[i] = e
182
    return a
183