Skip to content

Commit

Permalink
ENH: inline yt.funcs.is_sequence
Browse files Browse the repository at this point in the history
  • Loading branch information
neutrinoceros committed Sep 5, 2021
1 parent 272a153 commit 7ab33c1
Show file tree
Hide file tree
Showing 29 changed files with 146 additions and 115 deletions.
1 change: 0 additions & 1 deletion doc/source/reference/api/api.rst
Expand Up @@ -729,7 +729,6 @@ Function List
~yt.funcs.humanize_time
~yt.funcs.insert_ipython
~yt.funcs.is_root
~yt.funcs.is_sequence
~yt.funcs.iter_fields
~yt.funcs.just_one
~yt.funcs.only_on_root
Expand Down
13 changes: 7 additions & 6 deletions yt/data_objects/construction_data_containers.py
Expand Up @@ -3,6 +3,7 @@
import os
import warnings
import zipfile
from collections.abc import Sized
from functools import wraps
from re import finditer
from tempfile import NamedTemporaryFile, TemporaryFile
Expand All @@ -20,7 +21,7 @@
)
from yt.fields.field_exceptions import NeedsGridType, NeedsOriginalGrid
from yt.frontends.sph.data_structures import ParticleDataset
from yt.funcs import get_memory_usage, is_sequence, iter_fields, mylog, only_on_root
from yt.funcs import get_memory_usage, iter_fields, mylog, only_on_root
from yt.geometry import particle_deposit as particle_deposit
from yt.geometry.coordinates.cartesian_coordinates import all_data
from yt.loaders import load_uniform_grid
Expand Down Expand Up @@ -752,7 +753,7 @@ def set_field_parameter(self, name, val):
self._data_source.set_field_parameter(name, val)

def _sanitize_dims(self, dims):
if not is_sequence(dims):
if not isinstance(dims, Sized):
dims = [dims] * len(self.ds.domain_left_edge)
if len(dims) != len(self.ds.domain_left_edge):
raise RuntimeError(
Expand All @@ -761,7 +762,7 @@ def _sanitize_dims(self, dims):
return np.array(dims, dtype="int32")

def _sanitize_edge(self, edge):
if not is_sequence(edge):
if not isinstance(edge, Sized):
edge = [edge] * len(self.ds.domain_left_edge)
if len(edge) != len(self.ds.domain_left_edge):
raise RuntimeError(
Expand Down Expand Up @@ -990,7 +991,7 @@ def _fill_fields(self, fields):
"int64"
) * self.ds.relative_refinement(0, self.level)
refine_by = self.ds.refine_by
if not is_sequence(self.ds.refine_by):
if not isinstance(self.ds.refine_by, Sized):
refine_by = [refine_by, refine_by, refine_by]
refine_by = np.array(refine_by, dtype="i8")
for chunk in parallel_objects(self._data_source.chunks(fields, "io")):
Expand Down Expand Up @@ -1376,7 +1377,7 @@ def _fill_fields(self, fields):
# NOTE: This usage of "refine_by" is actually *okay*, because it's
# being used with respect to iref, which is *already* scaled!
refine_by = self.ds.refine_by
if not is_sequence(self.ds.refine_by):
if not isinstance(self.ds.refine_by, Sized):
refine_by = [refine_by, refine_by, refine_by]
refine_by = np.array(refine_by, dtype="i8")

Expand Down Expand Up @@ -2799,7 +2800,7 @@ def _setup_data_source(self):
def _sanitize_edge(self, edge, default):
if edge is None:
return default.copy()
if not is_sequence(edge):
if not isinstance(edge, Sized):
edge = [edge] * len(self.ds.domain_left_edge)
if len(edge) != len(self.ds.domain_left_edge):
raise RuntimeError(
Expand Down
5 changes: 3 additions & 2 deletions yt/data_objects/data_containers.py
@@ -1,5 +1,6 @@
import weakref
from collections import defaultdict
from collections.abc import Sized
from contextlib import contextmanager

import numpy as np
Expand All @@ -8,7 +9,7 @@
from yt.data_objects.profiles import create_profile
from yt.fields.field_exceptions import NeedsGridType
from yt.frontends.ytdata.utilities import save_as_dataset
from yt.funcs import get_output_filename, is_sequence, iter_fields, mylog
from yt.funcs import get_output_filename, iter_fields, mylog
from yt.units.yt_array import YTArray, YTQuantity, uconcatenate
from yt.utilities.amr_kdtree.api import AMRKDTree
from yt.utilities.exceptions import (
Expand Down Expand Up @@ -1390,7 +1391,7 @@ def _tupleize_field(self, field):
except AttributeError:
pass

if is_sequence(field) and not isinstance(field, str):
if isinstance(field, Sized) and not isinstance(field, str):
try:
ftype, fname = field
if not all(isinstance(_, str) for _ in field):
Expand Down
4 changes: 2 additions & 2 deletions yt/data_objects/index_subobjects/grid_patch.py
@@ -1,5 +1,6 @@
import warnings
import weakref
from collections.abc import Sized
from typing import List, Tuple

import numpy as np
Expand All @@ -9,7 +10,6 @@
from yt.data_objects.selection_objects.data_selection_objects import (
YTSelectionContainer,
)
from yt.funcs import is_sequence
from yt.geometry.selection_routines import convert_mask_to_indices
from yt.units.yt_array import YTArray
from yt.utilities.exceptions import (
Expand Down Expand Up @@ -171,7 +171,7 @@ def _prepare_grid(self):
# This can be expensive so we allow people to disable this behavior
# via a config option
if RECONSTRUCT_INDEX:
if is_sequence(self.Parent) and len(self.Parent) > 0:
if isinstance(self.Parent, Sized) and len(self.Parent) > 0:
p = self.Parent[0]
else:
p = self.Parent
Expand Down
12 changes: 7 additions & 5 deletions yt/data_objects/profiles.py
@@ -1,10 +1,12 @@
from collections.abc import Sized

import numpy as np
from more_itertools import collapse

from yt.data_objects.field_data import YTFieldData
from yt.fields.derived_field import DerivedField
from yt.frontends.ytdata.utilities import save_as_dataset
from yt.funcs import get_output_filename, is_sequence, iter_fields, mylog
from yt.funcs import get_output_filename, iter_fields, mylog
from yt.units.unit_object import Unit
from yt.units.yt_array import YTQuantity, array_like_field
from yt.utilities.exceptions import (
Expand Down Expand Up @@ -1335,9 +1337,9 @@ def create_profile(
wf = data_source.ds._get_field_info(weight_field)
if not wf.sampling_type == "particle":
weight_field = None
if not is_sequence(n_bins):
if not isinstance(n_bins, Sized):
n_bins = [n_bins] * len(bin_fields)
if not is_sequence(accumulation):
if not isinstance(accumulation, Sized):
accumulation = [accumulation] * len(bin_fields)
if logs is None:
logs = {}
Expand Down Expand Up @@ -1405,10 +1407,10 @@ def create_profile(
fe = data_source.ds.arr(field_ex, bf_units)
fe.convert_to_units(bf_units)
field_ex = [fe[0].v, fe[1].v]
if is_sequence(field_ex[0]):
if isinstance(field_ex[0], Sized):
field_ex[0] = data_source.ds.quan(field_ex[0][0], field_ex[0][1])
field_ex[0] = field_ex[0].in_units(bf_units)
if is_sequence(field_ex[1]):
if isinstance(field_ex[1], Sized):
field_ex[1] = data_source.ds.quan(field_ex[1][0], field_ex[1][1])
field_ex[1] = field_ex[1].in_units(bf_units)
ex.append(field_ex)
Expand Down
13 changes: 7 additions & 6 deletions yt/data_objects/selection_objects/data_selection_objects.py
@@ -1,6 +1,7 @@
import itertools
import uuid
from collections import defaultdict
from collections.abc import Iterable, Sized
from contextlib import contextmanager

import numpy as np
Expand All @@ -12,7 +13,7 @@
from yt.data_objects.derived_quantities import DerivedQuantityCollection
from yt.data_objects.field_data import YTFieldData
from yt.fields.field_exceptions import NeedsGridType
from yt.funcs import fix_axis, is_sequence, iter_fields, validate_width_tuple
from yt.funcs import fix_axis, iter_fields, validate_width_tuple
from yt.geometry.selection_routines import compose_selector
from yt.units import YTArray, dimensions as ytdims
from yt.utilities.exceptions import (
Expand Down Expand Up @@ -594,7 +595,7 @@ def to_frb(self, width, resolution, center=None, height=None, periodic=False):
)

validate_width_tuple(width)
if is_sequence(resolution):
if isinstance(resolution, Iterable):
resolution = max(resolution)
frb = CylindricalFixedResolutionBuffer(self, width, resolution)
return frb
Expand All @@ -603,9 +604,9 @@ def to_frb(self, width, resolution, center=None, height=None, periodic=False):
center = self.center
if center is None:
center = (self.ds.domain_right_edge + self.ds.domain_left_edge) / 2.0
elif is_sequence(center) and not isinstance(center, YTArray):
elif isinstance(center, Sized) and not isinstance(center, YTArray):
center = self.ds.arr(center, "code_length")
if is_sequence(width):
if isinstance(width, Sized):
w, u = width
if isinstance(w, tuple) and isinstance(u, tuple):
height = u
Expand All @@ -615,12 +616,12 @@ def to_frb(self, width, resolution, center=None, height=None, periodic=False):
width = self.ds.quan(width, "code_length")
if height is None:
height = width
elif is_sequence(height):
elif isinstance(height, Sized):
h, u = height
height = self.ds.quan(h, units=u)
elif not isinstance(height, YTArray):
height = self.ds.quan(height, "code_length")
if not is_sequence(resolution):
if not isinstance(resolution, Sized):
resolution = (resolution, resolution)
from yt.visualization.fixed_resolution import FixedResolutionBuffer

Expand Down
9 changes: 5 additions & 4 deletions yt/data_objects/selection_objects/slices.py
@@ -1,3 +1,5 @@
from collections.abc import Sized

import numpy as np

from yt.data_objects.selection_objects.data_selection_objects import (
Expand All @@ -6,7 +8,6 @@
)
from yt.data_objects.static_output import Dataset
from yt.funcs import (
is_sequence,
iter_fields,
validate_3d_array,
validate_axis,
Expand Down Expand Up @@ -353,15 +354,15 @@ def to_frb(self, width, resolution, height=None, periodic=False):
>>> frb = cutting.to_frb((1.0, "pc"), 1024)
>>> write_image(np.log10(frb[("gas", "density")]), "density_1pc.png")
"""
if is_sequence(width):
if isinstance(width, Sized):
validate_width_tuple(width)
width = self.ds.quan(width[0], width[1])
if height is None:
height = width
elif is_sequence(height):
elif isinstance(height, Sized):
validate_width_tuple(height)
height = self.ds.quan(height[0], height[1])
if not is_sequence(resolution):
if not isinstance(resolution, Sized):
resolution = (resolution, resolution)
from yt.visualization.fixed_resolution import FixedResolutionBuffer

Expand Down
7 changes: 4 additions & 3 deletions yt/data_objects/static_output.py
Expand Up @@ -6,6 +6,7 @@
import time
import weakref
from collections import defaultdict
from collections.abc import Sized
from stat import ST_CTIME

import numpy as np
Expand All @@ -19,7 +20,7 @@
from yt.fields.derived_field import ValidateSpatial
from yt.fields.field_type_container import FieldTypeContainer
from yt.fields.fluid_fields import setup_gradient_fields
from yt.funcs import is_sequence, iter_fields, mylog, set_intersection, setdefaultattr
from yt.funcs import iter_fields, mylog, set_intersection, setdefaultattr
from yt.geometry.coordinates.api import (
CartesianCoordinateHandler,
CoordinateHandler,
Expand Down Expand Up @@ -276,7 +277,7 @@ def periodicity(self, val):
removal="4.1.0",
)
err_msg = f"Expected a 3-element boolean tuple, received `{val}`."
if not is_sequence(val):
if not isinstance(val, Sized):
raise TypeError(err_msg)
if len(val) != 3:
raise ValueError(err_msg)
Expand Down Expand Up @@ -1941,7 +1942,7 @@ def __init__(
def validate_index_order(index_order):
if index_order is None:
index_order = (6, 2)
elif not is_sequence(index_order):
elif not isinstance(index_order, Sized):
index_order = (int(index_order), 1)
else:
if len(index_order) != 2:
Expand Down
5 changes: 3 additions & 2 deletions yt/data_objects/time_series.py
Expand Up @@ -3,6 +3,7 @@
import inspect
import os
import weakref
from collections.abc import Sequence
from functools import wraps

import numpy as np
Expand All @@ -12,7 +13,7 @@
from yt.config import ytcfg
from yt.data_objects.analyzer_objects import AnalysisTask, create_quantity_proxy
from yt.data_objects.particle_trajectories import ParticleTrajectories
from yt.funcs import is_sequence, mylog
from yt.funcs import mylog
from yt.units.yt_array import YTArray, YTQuantity
from yt.utilities.exceptions import YTException
from yt.utilities.object_registries import (
Expand Down Expand Up @@ -169,7 +170,7 @@ def __init__(
):
# This is needed to properly set _pre_outputs for Simulation subclasses.
self._mixed_dataset_types = mixed_dataset_types
if is_sequence(outputs) and not isinstance(outputs, str):
if isinstance(outputs, Sequence) and not isinstance(outputs, str):
self._pre_outputs = outputs[:]
self.tasks = AnalysisTaskProxy(self)
self.params = TimeSeriesParametersContainer(self)
Expand Down
5 changes: 3 additions & 2 deletions yt/fields/local_fields.py
@@ -1,4 +1,5 @@
from yt.funcs import is_sequence
from collections.abc import Sized

from yt.utilities.logger import ytLogger as mylog

from .field_info_container import FieldInfoContainer
Expand All @@ -12,7 +13,7 @@ def add_field(self, name, function, sampling_type, **kwargs):
sampling_type, kwargs.get("particle_type")
)

if isinstance(name, str) or not is_sequence(name):
if isinstance(name, str) or not isinstance(name, Sized):
if sampling_type == "particle":
ftype = "all"
else:
Expand Down
6 changes: 4 additions & 2 deletions yt/fields/vector_operations.py
@@ -1,6 +1,8 @@
from collections.abc import Sized

import numpy as np

from yt.funcs import is_sequence, just_one
from yt.funcs import just_one
from yt.geometry.geometry_handler import is_curvilinear
from yt.utilities.lib.misc_utilities import obtain_relative_velocity_vector
from yt.utilities.math_utils import (
Expand Down Expand Up @@ -105,7 +107,7 @@ def _los_field(field, data):
else:
fns = field_comps
ax = data.get_field_parameter("axis")
if is_sequence(ax):
if isinstance(ax, Sized):
# Make sure this is a unit vector
ax /= np.sqrt(np.dot(ax, ax))
ret = data[fns[0]] * ax[0] + data[fns[1]] * ax[1] + data[fns[2]] * ax[2]
Expand Down
4 changes: 2 additions & 2 deletions yt/frontends/stream/definitions.py
@@ -1,8 +1,8 @@
from collections import defaultdict
from collections.abc import Sized

import numpy as np

from yt.funcs import is_sequence
from yt.geometry.grid_container import GridTree, MatchPointsToGrids
from yt.utilities.exceptions import (
YTInconsistentGridFieldShape,
Expand Down Expand Up @@ -161,7 +161,7 @@ def process_data(data, grid_dims=None):
raise RuntimeError("The data dict appears to be invalid.\n" + str(e))

# val is a list of data to be turned into an array
elif is_sequence(val):
elif isinstance(val, Sized):
field_units[field] = ""
new_data[field] = np.asarray(val)

Expand Down

0 comments on commit 7ab33c1

Please sign in to comment.