Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
model_builder_numbers.py
Go to the documentation of this file.
1# Copyright 2010-2024 Google LLC
2# Licensed under the Apache License, Version 2.0 (the "License");
3# you may not use this file except in compliance with the License.
4# You may obtain a copy of the License at
5#
6# http://www.apache.org/licenses/LICENSE-2.0
7#
8# Unless required by applicable law or agreed to in writing, software
9# distributed under the License is distributed on an "AS IS" BASIS,
10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11# See the License for the specific language governing permissions and
12# limitations under the License.
13
14"""helpers methods for the cp_model_builder module on numbers."""
15
16import numbers
17from typing import Any, Sequence, Union
18import numpy as np
19import numpy.typing as npt
20
21# Custom types.
22NumberT = Union[numbers.Number, np.number]
23
24
25def is_integral(x: Any) -> bool:
26 """Checks if x has either a number.Integral or a np.integer type."""
27 return isinstance(x, numbers.Integral) or isinstance(x, np.integer)
28
29
30def is_a_number(x: Any) -> bool:
31 """Checks if x has either a number.Number or a np.double type."""
32 return (
33 isinstance(x, numbers.Number)
34 or isinstance(x, np.double)
35 or isinstance(x, np.integer)
36 )
37
38
39def is_zero(x: Any) -> bool:
40 """Checks if the x is 0 or 0.0."""
41 return (is_integral(x) and int(x) == 0) or (is_a_number(x) and float(x) == 0.0)
42
43
44def is_one(x: Any) -> bool:
45 """Checks if x is 1 or 1.0."""
46 return (is_integral(x) and int(x) == 1) or (is_a_number(x) and float(x) == 1.0)
47
48
49def is_minus_one(x: Any) -> bool:
50 """Checks if x is -1 or -1.0."""
51 return (is_integral(x) and int(x) == -1) or (is_a_number(x) and float(x) == -1.0)
52
53
54def assert_is_a_number(x: NumberT) -> np.double:
55 """Asserts that x is a number and converts to a np.double."""
56 if not is_a_number(x):
57 raise TypeError("Not a number: %s" % x)
58 return np.double(x)
59
60
61def assert_is_a_number_array(x: Sequence[NumberT]) -> npt.NDArray[np.double]:
62 """Asserts x is a list of numbers and converts it to np.array(np.double)."""
63 result = np.empty(len(x), dtype=np.double)
64 pos = 0
65 for c in x:
66 result[pos] = assert_is_a_number(c)
67 pos += 1
68 assert pos == len(x)
69 return result
npt.NDArray[np.double] assert_is_a_number_array(Sequence[NumberT] x)