Skip to content

Use math instead of numpy in some places #6765

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jul 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion xarray/coding/cftimeindex.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from __future__ import annotations

import math
import re
import warnings
from datetime import timedelta
Expand Down Expand Up @@ -249,7 +250,7 @@ def format_times(
):
"""Format values of cftimeindex as pd.Index."""
n_per_row = max(max_width // (CFTIME_REPR_LENGTH + len(separator)), 1)
n_rows = int(np.ceil(len(index) / n_per_row))
n_rows = math.ceil(len(index) / n_per_row)

representation = ""
for row in range(n_rows):
Expand Down
5 changes: 3 additions & 2 deletions xarray/core/dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import datetime
import inspect
import itertools
import math
import sys
import warnings
from collections import defaultdict
Expand Down Expand Up @@ -5187,7 +5188,7 @@ def dropna(
if dim in array.dims:
dims = [d for d in array.dims if d != dim]
count += np.asarray(array.count(dims)) # type: ignore[attr-defined]
size += np.prod([self.dims[d] for d in dims])
size += math.prod([self.dims[d] for d in dims])

if thresh is not None:
mask = count >= thresh
Expand Down Expand Up @@ -5945,7 +5946,7 @@ def _set_numpy_data_from_dataframe(
# We already verified that the MultiIndex has all unique values, so
# there are missing values if and only if the size of output arrays is
# larger that the index.
missing_values = np.prod(shape) > idx.shape[0]
missing_values = math.prod(shape) > idx.shape[0]

for name, values in arrays:
# NumPy indexing is much faster than using DataFrame.reindex() to
Expand Down
9 changes: 4 additions & 5 deletions xarray/core/formatting.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

import contextlib
import functools
import math
from collections import defaultdict
from datetime import datetime, timedelta
from itertools import chain, zip_longest
Expand Down Expand Up @@ -44,10 +45,10 @@ def wrap_indent(text, start="", length=None):


def _get_indexer_at_least_n_items(shape, n_desired, from_end):
assert 0 < n_desired <= np.prod(shape)
assert 0 < n_desired <= math.prod(shape)
cum_items = np.cumprod(shape[::-1])
n_steps = np.argmax(cum_items >= n_desired)
stop = int(np.ceil(float(n_desired) / np.r_[1, cum_items][n_steps]))
stop = math.ceil(float(n_desired) / np.r_[1, cum_items][n_steps])
indexer = (
((-1 if from_end else 0),) * (len(shape) - 1 - n_steps)
+ ((slice(-stop, None) if from_end else slice(stop)),)
Expand Down Expand Up @@ -185,9 +186,7 @@ def format_array_flat(array, max_width: int):
"""
# every item will take up at least two characters, but we always want to
# print at least first and last items
max_possibly_relevant = min(
max(array.size, 1), max(int(np.ceil(max_width / 2.0)), 2)
)
max_possibly_relevant = min(max(array.size, 1), max(math.ceil(max_width / 2.0), 2))
relevant_front_items = format_items(
first_n_items(array, (max_possibly_relevant + 1) // 2)
)
Expand Down
4 changes: 2 additions & 2 deletions xarray/core/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import functools
import io
import itertools
import math
import os
import re
import sys
Expand Down Expand Up @@ -555,8 +556,7 @@ def ndim(self: Any) -> int:

@property
def size(self: Any) -> int:
# cast to int so that shape = () gives size = 1
return int(np.prod(self.shape))
return math.prod(self.shape)

def __len__(self: Any) -> int:
try:
Expand Down
5 changes: 3 additions & 2 deletions xarray/core/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import copy
import itertools
import math
import numbers
import warnings
from datetime import timedelta
Expand Down Expand Up @@ -1644,7 +1645,7 @@ def _unstack_once_full(
"name as an existing dimension"
)

if np.prod(new_dim_sizes) != self.sizes[old_dim]:
if math.prod(new_dim_sizes) != self.sizes[old_dim]:
raise ValueError(
"the product of the new dimension sizes must "
"equal the size of the old dimension"
Expand Down Expand Up @@ -1684,7 +1685,7 @@ def _unstack_once(
new_dims = reordered.dims[: len(other_dims)] + new_dim_names

if fill_value is dtypes.NA:
is_missing_values = np.prod(new_shape) > np.prod(self.shape)
is_missing_values = math.prod(new_shape) > math.prod(self.shape)
if is_missing_values:
dtype, fill_value = dtypes.maybe_promote(self.dtype)
else:
Expand Down
2 changes: 1 addition & 1 deletion xarray/testing.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def _format_message(x, y, err_msg, verbose):
abs_diff = max(abs(diff))
rel_diff = "not implemented"

n_diff = int(np.count_nonzero(diff))
n_diff = np.count_nonzero(diff)
n_total = diff.size

fraction = f"{n_diff} / {n_total}"
Expand Down
3 changes: 2 additions & 1 deletion xarray/tests/test_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import contextlib
import inspect
import math
from copy import copy
from datetime import datetime
from typing import Any
Expand Down Expand Up @@ -117,7 +118,7 @@ def easy_array(shape, start=0, stop=1):

shape is a tuple like (2, 3)
"""
a = np.linspace(start, stop, num=np.prod(shape))
a = np.linspace(start, stop, num=math.prod(shape))
return a.reshape(shape)


Expand Down
3 changes: 2 additions & 1 deletion xarray/tests/test_sparse.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import math
import pickle
from textwrap import dedent

Expand Down Expand Up @@ -28,7 +29,7 @@ def assert_sparse_equal(a, b):


def make_ndarray(shape):
return np.arange(np.prod(shape)).reshape(shape)
return np.arange(math.prod(shape)).reshape(shape)


def make_sparray(shape):
Expand Down