Astronomy and astrophysics core library providing comprehensive tools for astronomical computations and data handling
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Tools for creating astronomical plots and visualizations with matplotlib integration and astronomy-specific features.
from astropy.visualization import quantity_support
from astropy.visualization import ImageNormalize, MinMaxInterval, ZScaleInterval
from astropy.visualization import LogStretch, SqrtStretch, AsinhStretch, LinearStretch
from astropy.visualization import make_lupton_rgbFunctions to enable matplotlib to work seamlessly with astropy objects and quantities.
def quantity_support(format='latex'):
"""
Enable matplotlib to work with astropy Quantity objects.
Parameters:
- format: format for unit display ('latex', 'unicode', 'console')
This function allows matplotlib to automatically handle Quantity objects
for axis labels and formatting.
"""Classes for normalizing astronomical image data with appropriate scaling and clipping.
class ImageNormalize:
"""
Normalization class for astronomical images.
Parameters:
- data: image data for determining normalization (optional)
- interval: interval method for data clipping
- vmin: minimum value for normalization
- vmax: maximum value for normalization
- stretch: stretch function to apply
- clip: whether to clip values outside [0,1]
"""
def __init__(self, data=None, interval=None, vmin=None, vmax=None, stretch=LinearStretch(), clip=True): ...
def __call__(self, values, clip=None):
"""Apply normalization to values."""
def inverse(self, values):
"""Apply inverse normalization."""
class ManualInterval:
"""
Manually specified interval for normalization.
Parameters:
- vmin: minimum value
- vmax: maximum value
"""
def __init__(self, vmin, vmax): ...
class MinMaxInterval:
"""Interval from minimum to maximum values in data."""
def __init__(self): ...
class PercentileInterval:
"""
Interval based on percentiles of the data.
Parameters:
- percentile: percentile value (e.g., 95 for 2.5% to 97.5%)
- n_samples: number of samples for percentile calculation
"""
def __init__(self, percentile, n_samples=None): ...
class AsymmetricPercentileInterval:
"""
Interval with different lower and upper percentiles.
Parameters:
- lower_percentile: lower percentile
- upper_percentile: upper percentile
- n_samples: number of samples
"""
def __init__(self, lower_percentile, upper_percentile, n_samples=None): ...
class ZScaleInterval:
"""
Interval using IRAF's zscale algorithm.
Parameters:
- nsamples: number of sample points
- contrast: contrast parameter
- max_reject: maximum fraction of pixels to reject
- min_npixels: minimum number of pixels for fitting
- krej: k-sigma rejection threshold
- max_iterations: maximum iterations for rejection
"""
def __init__(self, nsamples=1000, contrast=0.25, max_reject=0.5, min_npixels=5, krej=2.5, max_iterations=5): ...Functions for applying different stretch algorithms to image data.
class LinearStretch:
"""Linear stretch (no transformation)."""
def __init__(self): ...
class LogStretch:
"""
Logarithmic stretch.
Parameters:
- a: stretch parameter (default 1000)
"""
def __init__(self, a=1000): ...
class SqrtStretch:
"""Square root stretch."""
def __init__(self): ...
class SquaredStretch:
"""Squared stretch."""
def __init__(self): ...
class AsinhStretch:
"""
Inverse hyperbolic sine stretch.
Parameters:
- a: stretch parameter
"""
def __init__(self, a=0.1): ...
class SinhStretch:
"""
Hyperbolic sine stretch.
Parameters:
- a: stretch parameter
"""
def __init__(self, a=0.33): ...
class PowerStretch:
"""
Power law stretch.
Parameters:
- a: power law index
"""
def __init__(self, a=1.0): ...
class PowerDistStretch:
"""
Power distribution stretch.
Parameters:
- a: power parameter
"""
def __init__(self, a=1000): ...
class ContrastBiasStretch:
"""
Contrast-bias stretch.
Parameters:
- contrast: contrast parameter
- bias: bias parameter
"""
def __init__(self, contrast, bias): ...
class HistEqStretch:
"""
Histogram equalization stretch.
Parameters:
- data: data for computing histogram
- values: values to stretch
"""
def __init__(self, data, values=None): ...Functions for creating color composite images from multiple bands.
def make_lupton_rgb(image_r, image_g, image_b, minimum=0, stretch=5, Q=8, filename=None):
"""
Create RGB color image using Lupton et al. algorithm.
Parameters:
- image_r: red channel image data
- image_g: green channel image data
- image_b: blue channel image data
- minimum: minimum value for scaling
- stretch: stretch parameter
- Q: asinh scaling parameter
- filename: output filename (optional)
Returns:
array: RGB image array
"""
def lupton_rgb(image_r, image_g, image_b, minimum=0, stretch=5, Q=8):
"""
Apply Lupton RGB scaling to images.
Parameters: (same as make_lupton_rgb)
Returns:
tuple: (scaled_r, scaled_g, scaled_b) arrays
"""Utility functions for astronomical plotting and data visualization.
def simple_norm(data, stretch='linear', power=1.0, asinh_a=0.1, min_cut=None, max_cut=None, min_percent=None, max_percent=None, percent=None, clip=True):
"""
Simple image normalization function.
Parameters:
- data: image data
- stretch: stretch type ('linear', 'sqrt', 'log', 'asinh', 'power')
- power: power for power stretch
- asinh_a: parameter for asinh stretch
- min_cut: minimum cut value
- max_cut: maximum cut value
- min_percent: minimum percentile cut
- max_percent: maximum percentile cut
- percent: symmetric percentile cut
- clip: whether to clip values
Returns:
ImageNormalize: normalization object
"""
def hist(x, bins=10, ax=None, max_bins=1e6, **kwargs):
"""
Enhanced histogram function with automatic binning.
Parameters:
- x: data to histogram
- bins: number of bins or bin edges
- ax: matplotlib axes object
- max_bins: maximum number of bins
- **kwargs: additional arguments for matplotlib.hist
Returns:
tuple: (n, bins, patches) from matplotlib.hist
"""import numpy as np
import matplotlib.pyplot as plt
from astropy.visualization import ImageNormalize, ZScaleInterval, LogStretch
# Create sample image data
data = np.random.random((100, 100)) * 1000 + np.random.exponential(100, (100, 100))
# Apply zscale normalization with log stretch
norm = ImageNormalize(data, interval=ZScaleInterval(), stretch=LogStretch())
# Display image
plt.figure(figsize=(8, 6))
plt.imshow(data, norm=norm, cmap='viridis', origin='lower')
plt.colorbar()
plt.title('Astronomical Image with ZScale + Log Stretch')
plt.show()from astropy.visualization import quantity_support
import astropy.units as u
# Enable quantity support
quantity_support()
# Create data with units
time = np.linspace(0, 10, 100) * u.day
flux = 1000 + 100 * np.sin(2 * np.pi * time / (2 * u.day)) * u.Jy
# Plot with automatic unit formatting
plt.figure(figsize=(8, 5))
plt.plot(time, flux)
plt.xlabel('Time') # Will automatically show "(day)"
plt.ylabel('Flux') # Will automatically show "(Jy)"
plt.title('Light Curve')
plt.show()from astropy.visualization import make_lupton_rgb
# Simulate three-band image data
r_band = np.random.exponential(50, (200, 200))
g_band = np.random.exponential(40, (200, 200))
b_band = np.random.exponential(30, (200, 200))
# Create RGB image
rgb_image = make_lupton_rgb(r_band, g_band, b_band,
minimum=0, stretch=0.5, Q=10)
# Display RGB image
plt.figure(figsize=(8, 8))
plt.imshow(rgb_image, origin='lower')
plt.title('RGB Composite Image')
plt.axis('off')
plt.show()from astropy.visualization import AsinhStretch, PercentileInterval
# Apply asinh stretch with percentile interval
interval = PercentileInterval(99.5)
stretch = AsinhStretch(a=0.1)
norm = ImageNormalize(data, interval=interval, stretch=stretch)
plt.figure(figsize=(12, 4))
# Original data
plt.subplot(1, 3, 1)
plt.imshow(data, origin='lower', cmap='gray')
plt.title('Original')
# Linear stretch
plt.subplot(1, 3, 2)
plt.imshow(data, norm=ImageNormalize(data, interval=interval),
origin='lower', cmap='gray')
plt.title('Linear Stretch')
# Asinh stretch
plt.subplot(1, 3, 3)
plt.imshow(data, norm=norm, origin='lower', cmap='gray')
plt.title('Asinh Stretch')
plt.tight_layout()
plt.show()# Normalization types
ImageNormalize = astropy.visualization.ImageNormalize
# Interval types
ManualInterval = astropy.visualization.ManualInterval
MinMaxInterval = astropy.visualization.MinMaxInterval
PercentileInterval = astropy.visualization.PercentileInterval
ZScaleInterval = astropy.visualization.ZScaleInterval
# Stretch types
LinearStretch = astropy.visualization.LinearStretch
LogStretch = astropy.visualization.LogStretch
SqrtStretch = astropy.visualization.SqrtStretch
AsinhStretch = astropy.visualization.AsinhStretch