Google OR-Tools v9.15
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#!/usr/bin/env python3
2# Copyright 2010-2025 Google LLC
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"""helpers methods for the cp_model_builder module on numbers."""
16
17from collections.abc import Sequence
18import numbers
19from typing import Any, Union
20import numpy as np
21import numpy.typing as npt
22
23# Custom types.
24NumberT = Union[numbers.Number, np.number]
25
26
27def is_integral(x: Any) -> bool:
28 """Checks if x has either a number.Integral or a np.integer type."""
29 return isinstance(x, numbers.Integral) or isinstance(x, np.integer)
30
31
32def is_a_number(x: Any) -> bool:
33 """Checks if x has either a number.Number or a np.double type."""
34 return (
35 isinstance(x, numbers.Number)
36 or isinstance(x, np.double)
37 or isinstance(x, np.integer)
38 )
39
40
41def is_zero(x: Any) -> bool:
42 """Checks if the x is 0 or 0.0."""
43 return (is_integral(x) and int(x) == 0) or (is_a_number(x) and float(x) == 0.0)
44
45
46def is_one(x: Any) -> bool:
47 """Checks if x is 1 or 1.0."""
48 return (is_integral(x) and int(x) == 1) or (is_a_number(x) and float(x) == 1.0)
49
50
51def is_minus_one(x: Any) -> bool:
52 """Checks if x is -1 or -1.0."""
53 return (is_integral(x) and int(x) == -1) or (is_a_number(x) and float(x) == -1.0)
54
55
56def assert_is_a_number(x: NumberT) -> np.double:
57 """Asserts that x is a number and converts to a np.double."""
58 if not is_a_number(x):
59 raise TypeError("Not a number: %s" % x)
60 return np.double(x)
61
62
63def assert_is_a_number_array(x: Sequence[NumberT]) -> npt.NDArray[np.double]:
64 """Asserts x is a list of numbers and converts it to np.array(np.double)."""
65 result = np.empty(len(x), dtype=np.double)
66 pos = 0
67 for c in x:
68 result[pos] = assert_is_a_number(c)
69 pos += 1
70 assert pos == len(x)
71 return result
npt.NDArray[np.double] assert_is_a_number_array(Sequence[NumberT] x)