function range_pad
Pads a numeric or datetime range by a specified fraction of the interval, with optional logarithmic scaling for positive numeric values.
/tf/active/vicechatdev/patches/util.py
995 - 1022
moderate
Purpose
This function extends the boundaries of a range (lower and upper bounds) by adding padding proportional to the interval size. It supports linear and logarithmic padding for numeric ranges, and handles datetime types including numpy datetime64 and cftime types. Commonly used in data visualization to add margins around data ranges for better display.
Source Code
def range_pad(lower, upper, padding=None, log=False):
"""
Pads the range by a fraction of the interval
"""
if padding is not None and not isinstance(padding, tuple):
padding = (padding, padding)
if is_number(lower) and is_number(upper) and padding is not None:
if not isinstance(lower, datetime_types) and log and lower > 0 and upper > 0:
log_min = np.log(lower) / np.log(10)
log_max = np.log(upper) / np.log(10)
lspan = (log_max-log_min)*(1+padding[0]*2)
uspan = (log_max-log_min)*(1+padding[1]*2)
center = (log_min+log_max) / 2.0
start, end = np.power(10, center-lspan/2.), np.power(10, center+uspan/2.)
else:
if isinstance(lower, datetime_types) and not isinstance(lower, cftime_types):
# Ensure timedelta can be safely divided
lower, upper = np.datetime64(lower), np.datetime64(upper)
span = (upper-lower).astype('>m8[ns]')
else:
span = (upper-lower)
lpad = span*(padding[0])
upad = span*(padding[1])
start, end = lower-lpad, upper+upad
else:
start, end = lower, upper
return start, end
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
lower |
- | - | positional_or_keyword |
upper |
- | - | positional_or_keyword |
padding |
- | None | positional_or_keyword |
log |
- | False | positional_or_keyword |
Parameter Details
lower: The lower bound of the range. Can be a number (int, float), datetime object, numpy datetime64, or cftime datetime type. This is the starting value that will be padded downward.
upper: The upper bound of the range. Can be a number (int, float), datetime object, numpy datetime64, or cftime datetime type. This is the ending value that will be padded upward.
padding: Optional padding fraction(s) to apply. Can be a single numeric value (applied to both sides) or a tuple of two values (lower_padding, upper_padding). Values represent the fraction of the interval to add as padding. For example, 0.1 adds 10% of the range on each side. Default is None (no padding).
log: Boolean flag indicating whether to apply logarithmic scaling when padding. Only applies to positive numeric values (not datetime types). When True, padding is applied in log10 space. Default is False.
Return Value
Returns a tuple (start, end) representing the padded range. The types of start and end match the input types (numeric, datetime64, etc.). If padding is None or inputs are not numbers, returns the original (lower, upper) values unchanged.
Dependencies
numpydatetimecftime
Required Imports
import numpy as np
import datetime
import cftime
Conditional/Optional Imports
These imports are only needed under specific conditions:
import cftime
Condition: only if working with cftime datetime types (climate/forecast time representations)
OptionalUsage Example
import numpy as np
import datetime
# Numeric range with 10% padding
start, end = range_pad(0, 100, padding=0.1)
# Returns approximately (-10, 110)
# Asymmetric padding
start, end = range_pad(0, 100, padding=(0.05, 0.15))
# Returns approximately (-5, 115)
# Logarithmic padding for positive values
start, end = range_pad(1, 1000, padding=0.1, log=True)
# Pads in log space, useful for log-scale plots
# Datetime padding
lower = datetime.datetime(2020, 1, 1)
upper = datetime.datetime(2020, 12, 31)
start, end = range_pad(lower, upper, padding=0.1)
# Adds ~36.5 days padding on each side
# No padding
start, end = range_pad(10, 20)
# Returns (10, 20) unchanged
Best Practices
- Ensure 'is_number()' helper function is available to check if values are numeric
- Define 'datetime_types' and 'cftime_types' tuples containing relevant datetime type classes before using this function
- When using log=True, ensure both lower and upper are positive numbers, otherwise the function falls back to linear padding
- For datetime padding, the function converts to numpy datetime64 internally for safe timedelta operations
- Padding values should typically be between 0 and 1 for reasonable results (e.g., 0.1 for 10% padding)
- Use tuple padding (lower_pad, upper_pad) when asymmetric margins are needed
- The function returns original values unchanged if padding is None or if inputs are not recognized as numbers
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function dimension_range 62.8% similar
-
function date_range 56.0% similar
-
function bound_range 55.6% similar
-
function find_range 46.5% similar
-
function find_minmax 42.9% similar