🔍 Code Extractor

function max_range

Maturity: 50

Computes the maximal lower and upper bounds from a list of range tuples, handling various data types including numeric, datetime, and string values.

File:
/tf/active/vicechatdev/patches/util.py
Lines:
944 - 992
Complexity:
moderate

Purpose

This function aggregates multiple range tuples to find the overall minimum and maximum values. It supports two modes: combined mode (finds global min/max across all values) and independent mode (finds min of lower bounds and max of upper bounds separately). It handles special cases like datetime types (including pandas Period and Timestamp), NaN values, and different numpy array data types. The function is designed to be robust with error handling that returns (NaN, NaN) on failure.

Source Code

def max_range(ranges, combined=True):
    """
    Computes the maximal lower and upper bounds from a list bounds.

    Args:
       ranges (list of tuples): A list of range tuples
       combined (boolean, optional): Whether to combine bounds
          Whether range should be computed on lower and upper bound
          independently or both at once

    Returns:
       The maximum range as a single tuple
    """
    try:
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', r'All-NaN (slice|axis) encountered')
            values = [tuple(np.NaN if v is None else v for v in r) for r in ranges]
            if pd and any(isinstance(v, datetime_types) and not isinstance(v, cftime_types+(dt.time,))
                          for r in values for v in r):
                converted = []
                for l, h in values:
                    if isinstance(l, pd.Period) and isinstance(h, pd.Period):
                        l = l.to_timestamp().to_datetime64()
                        h = h.to_timestamp().to_datetime64()
                    elif isinstance(l, datetime_types) and isinstance(h, datetime_types):
                        l, h = (pd.Timestamp(l).to_datetime64(),
                                pd.Timestamp(h).to_datetime64())
                    converted.append((l, h))
                values = converted

            arr = np.array(values)
            if not len(arr):
                return np.NaN, np.NaN
            elif arr.dtype.kind in 'OSU':
                arr = list(python2sort([
                    v for r in values for v in r
                    if not is_nan(v) and v is not None]))
                return arr[0], arr[-1]
            elif arr.dtype.kind in 'M':
                drange = ((arr.min(), arr.max()) if combined else
                          (arr[:, 0].min(), arr[:, 1].max()))
                return drange

            if combined:
                return (np.nanmin(arr), np.nanmax(arr))
            else:
                return (np.nanmin(arr[:, 0]), np.nanmax(arr[:, 1]))
    except:
        return (np.NaN, np.NaN)

Parameters

Name Type Default Kind
ranges - - positional_or_keyword
combined - True positional_or_keyword

Parameter Details

ranges: A list of tuples where each tuple represents a range with (lower_bound, upper_bound). Can contain numeric values, datetime objects, pandas Period/Timestamp objects, strings, or None/NaN values. Empty lists are supported.

combined: Boolean flag (default: True). When True, computes the global minimum and maximum across all values in all ranges. When False, computes the minimum of all lower bounds and maximum of all upper bounds independently, preserving the range structure.

Return Value

Returns a tuple of two values (min_value, max_value) representing the computed range. For combined=True, returns (global_min, global_max). For combined=False, returns (min_of_lower_bounds, max_of_upper_bounds). Returns (np.NaN, np.NaN) if the input is empty or an error occurs. The return type matches the input data type (numeric, datetime64, or comparable objects).

Dependencies

  • numpy
  • pandas
  • warnings
  • datetime
  • cftime

Required Imports

import numpy as np
import pandas as pd
import warnings
import datetime as dt

Conditional/Optional Imports

These imports are only needed under specific conditions:

import cftime

Condition: only if working with climate forecast datetime types (cftime_types variable must be defined)

Optional

Usage Example

import numpy as np
import pandas as pd
import warnings
import datetime as dt

# Define required module-level utilities (normally provided by parent module)
datetime_types = (dt.datetime, dt.date, np.datetime64, pd.Timestamp)
cftime_types = tuple()
is_nan = lambda x: x is None or (isinstance(x, float) and np.isnan(x))
python2sort = lambda x: sorted(x)

# Example 1: Numeric ranges with combined=True
ranges = [(1, 5), (3, 8), (2, 6)]
result = max_range(ranges, combined=True)
print(result)  # Output: (1, 8)

# Example 2: Numeric ranges with combined=False
result = max_range(ranges, combined=False)
print(result)  # Output: (1, 8)

# Example 3: Datetime ranges
date_ranges = [
    (dt.datetime(2020, 1, 1), dt.datetime(2020, 6, 30)),
    (dt.datetime(2020, 3, 1), dt.datetime(2020, 12, 31))
]
result = max_range(date_ranges, combined=True)
print(result)  # Output: datetime range covering full span

# Example 4: Ranges with None/NaN values
ranges_with_nan = [(1, 5), (None, 8), (2, np.NaN)]
result = max_range(ranges_with_nan, combined=True)
print(result)  # Output: (1.0, 8.0)

# Example 5: String ranges
string_ranges = [('a', 'f'), ('c', 'z'), ('b', 'm')]
result = max_range(string_ranges, combined=True)
print(result)  # Output: ('a', 'z')

Best Practices

  • Ensure that 'datetime_types', 'cftime_types', 'is_nan', and 'python2sort' are defined in the module scope before using this function
  • The function silently catches all exceptions and returns (np.NaN, np.NaN), so validate inputs beforehand if you need to detect errors
  • When working with datetime ranges, be aware that pandas Period and Timestamp objects are automatically converted to datetime64
  • For mixed-type ranges (strings, numbers), the function will attempt to handle them but may return NaN on type conflicts
  • Use combined=False when you need to preserve the range structure (min of starts, max of ends) rather than finding global extremes
  • Empty range lists will return (np.NaN, np.NaN)
  • The function filters 'All-NaN slice/axis' warnings internally, so NaN handling is intentionally silent

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function find_minmax 64.7% similar

    Computes the minimum of the first elements and maximum of the second elements from two tuples of numeric values, handling NaN values gracefully.

    From: /tf/active/vicechatdev/patches/util.py
  • function find_range 62.3% similar

    Robustly computes the minimum and maximum values from a collection, with fallback mechanisms for edge cases and support for extending the range with soft bounds.

    From: /tf/active/vicechatdev/patches/util.py
  • function max_extents 59.9% similar

    Computes the maximal extent (bounding box) from a list of extent tuples, supporting both 2D (4-tuples) and 3D (6-tuples) coordinate systems with special handling for datetime and string values.

    From: /tf/active/vicechatdev/patches/util.py
  • function bound_range 54.5% similar

    Computes a bounding range and density from evenly spaced samples, extending the range by half the density on each side and detecting if values are inverted.

    From: /tf/active/vicechatdev/patches/util.py
  • function dimension_range 50.4% similar

    Computes the effective range along a dimension by combining data bounds with soft and hard range constraints, optionally applying padding and logarithmic scaling.

    From: /tf/active/vicechatdev/patches/util.py
← Back to Browse