CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-python-casacore

Python bindings for the CASACORE radio astronomy library providing comprehensive interfaces for table operations, image processing, coordinate systems, and astronomical measurements.

Pending
Overview
Eval results
Files

quantities-units.mddocs/

Quantities and Units

Physical quantities with units, unit conversions, and astronomical constants. Supports scalar and vector quantities with comprehensive unit system including SI, astronomical, and specialized radio astronomy units, enabling precise calculations with automatic unit checking and conversion.

Core Imports

from casacore.quanta import quantity, is_quantity
from casacore.quanta import constants, units, prefixes

Capabilities

Quantity Creation

Create scalar and vector quantities with units from various input formats.

def quantity(*args):
    """
    Create a quantity with units.
    
    Parameters:
    Single argument:
    - str: Parse string like "1.5km/s", "10.3MHz", "45deg"
    - dict: Quantity dictionary with 'value' and 'unit' keys
    - Quantity/QuantVec: Copy existing quantity
    
    Two arguments:
    - value, unit: Numeric value(s) and unit string
    
    Returns:
    Quantity (scalar) or QuantVec (vector) object
    
    Examples:
    quantity(1.0, "km/s")           # Scalar quantity
    quantity("1.5km/s")             # From string  
    quantity([1.0, 2.0], "km/s")    # Vector quantity
    quantity({'value': 1.5, 'unit': 'km/s'})  # From dictionary
    """

def is_quantity(q):
    """
    Check if object is a valid quantity.
    
    Parameters:
    - q: object to check
    
    Returns:
    bool, True if q is Quantity or QuantVec
    """

Scalar Quantities

Handle single-valued quantities with units and mathematical operations.

class Quantity:
    def __init__(self, value, unit):
        """
        Create scalar quantity.
        
        Parameters:
        - value: float, numeric value
        - unit: str, unit specification
        """
    
    def get_value(self):
        """
        Get numeric value.
        
        Returns:
        float, numeric value without units
        """
    
    def get_unit(self):
        """
        Get unit string.
        
        Returns:
        str, unit specification
        """
    
    def to_string(self, fmt="%0.5g"):
        """
        Format quantity as string.
        
        Parameters:
        - fmt: str, format specification
        
        Returns:
        str, formatted quantity with units
        """
    
    def convert(self, unit):
        """
        Convert to different unit.
        
        Parameters:
        - unit: str, target unit
        
        Returns:
        Quantity, converted quantity
        
        Raises:
        RuntimeError if units are incompatible
        """
    
    def conforms(self, other):
        """
        Check unit compatibility.
        
        Parameters:
        - other: Quantity or str, quantity or unit to check
        
        Returns:
        bool, True if units are compatible
        """
    
    def canonical(self):
        """
        Convert to canonical (SI base) units.
        
        Returns:
        Quantity, quantity in canonical units
        """
    
    def to_dict(self):
        """
        Convert to dictionary representation.
        
        Returns:
        dict with 'value' and 'unit' keys
        """
    
    def norm(self, phase=0.0):
        """
        Normalize angle to [0, 2π) range.
        
        Parameters:
        - phase: float, phase offset (default 0.0)
        
        Returns:
        Quantity, normalized angle
        """
    
    def sin(self):
        """Calculate sine of angle quantity."""
    
    def cos(self):
        """Calculate cosine of angle quantity."""
    
    def tan(self):
        """Calculate tangent of angle quantity."""
    
    def asin(self):
        """Calculate arcsine, returns angle quantity."""
    
    def acos(self):
        """Calculate arccosine, returns angle quantity."""
    
    def atan(self):
        """Calculate arctangent, returns angle quantity."""
    
    def atan2(self, x):
        """
        Calculate two-argument arctangent.
        
        Parameters:
        - x: Quantity, x-coordinate
        
        Returns:
        Quantity, angle from +x axis to (x,y) point
        """
    
    def sqrt(self):
        """Calculate square root."""
    
    def log(self):
        """Calculate natural logarithm."""
    
    def log10(self):
        """Calculate base-10 logarithm."""
    
    def exp(self):
        """Calculate exponential."""
    
    def pow(self, exponent):
        """
        Raise to power.
        
        Parameters:
        - exponent: float, exponent value
        
        Returns:
        Quantity, result with appropriate units
        """

Vector Quantities

Handle array-valued quantities with units and vectorized operations.

class QuantVec:
    def __init__(self, value, unit):
        """
        Create vector quantity.
        
        Parameters:
        - value: list or numpy array, numeric values
        - unit: str, unit specification
        """
    
    def get_value(self):
        """
        Get numeric array.
        
        Returns:
        numpy array, numeric values without units
        """
    
    def get_unit(self):
        """
        Get unit string.
        
        Returns:
        str, unit specification
        """
    
    def to_string(self, fmt="%0.5g"):
        """
        Format vector quantity as string.
        
        Parameters:
        - fmt: str, format specification for each element
        
        Returns:
        str, formatted vector with units
        """
    
    def convert(self, unit):
        """
        Convert to different unit.
        
        Parameters:
        - unit: str, target unit
        
        Returns:
        QuantVec, converted vector quantity
        """
    
    def conforms(self, other):
        """
        Check unit compatibility.
        
        Parameters:
        - other: QuantVec, Quantity, or str
        
        Returns:
        bool, True if units are compatible
        """
    
    def canonical(self):
        """
        Convert to canonical (SI base) units.
        
        Returns:
        QuantVec, vector in canonical units
        """
    
    def to_dict(self):
        """
        Convert to dictionary representation.
        
        Returns:
        dict with 'value' (list) and 'unit' keys
        """
    
    def __len__(self):
        """Get number of elements."""
    
    def __getitem__(self, index):
        """
        Get element at index.
        
        Parameters:
        - index: int or slice, element index
        
        Returns:
        Quantity (single element) or QuantVec (slice)
        """
    
    def __setitem__(self, index, value):
        """
        Set element at index.
        
        Parameters:
        - index: int or slice, element index
        - value: Quantity or numeric value
        """

Mathematical Operations

Quantities support standard mathematical operations with automatic unit handling.

# Arithmetic operations (available for both Quantity and QuantVec)
def __add__(self, other):
    """Add quantities (requires compatible units)."""

def __sub__(self, other):
    """Subtract quantities (requires compatible units)."""

def __mul__(self, other):
    """Multiply quantities (units multiply)."""

def __truediv__(self, other):
    """Divide quantities (units divide)."""

def __pow__(self, exponent):
    """Raise to power (units raised to same power)."""

def __neg__(self):
    """Negate quantity."""

def __abs__(self):
    """Absolute value of quantity."""

# Comparison operations
def __eq__(self, other):
    """Test equality (requires compatible units)."""

def __ne__(self, other):
    """Test inequality."""

def __lt__(self, other):
    """Less than comparison."""

def __le__(self, other):
    """Less than or equal comparison."""

def __gt__(self, other):
    """Greater than comparison."""

def __ge__(self, other):
    """Greater than or equal comparison."""

Physical Constants

Access fundamental physical constants with proper units.

# Constants object provides physical constants
constants = {
    # Fundamental constants
    'c': quantity,      # Speed of light in vacuum
    'h': quantity,      # Planck constant  
    'k': quantity,      # Boltzmann constant
    'G': quantity,      # Gravitational constant
    'e': quantity,      # Elementary charge
    'me': quantity,     # Electron mass
    'mp': quantity,     # Proton mass
    'mn': quantity,     # Neutron mass
    'mu0': quantity,    # Permeability of free space
    'eps0': quantity,   # Permittivity of free space
    'R': quantity,      # Gas constant
    'NA': quantity,     # Avogadro number
    'alpha': quantity,  # Fine structure constant
    
    # Astronomical constants
    'pc': quantity,     # Parsec
    'ly': quantity,     # Light year
    'AU': quantity,     # Astronomical unit
    'R_earth': quantity, # Earth radius
    'M_earth': quantity, # Earth mass
    'R_sun': quantity,   # Solar radius
    'M_sun': quantity,   # Solar mass
    'L_sun': quantity,   # Solar luminosity
    
    # Spectroscopic constants
    'HI': quantity,     # 21cm hydrogen line frequency
    'OH1612': quantity, # OH maser line
    'OH1665': quantity, # OH maser line
    'OH1667': quantity, # OH maser line
    'OH1720': quantity, # OH maser line
}

def constants():
    """
    Get constants object.
    
    Returns:
    dict-like object with physical constants
    
    Usage:
    c_light = constants['c']
    hi_freq = constants['HI']
    """

Unit System

Comprehensive unit definitions and conversion factors.

# Units object provides unit definitions
def units():
    """
    Get units object with conversion factors.
    
    Returns:
    dict-like object with unit definitions
    
    Unit categories:
    - Length: m, km, cm, mm, nm, pm, in, ft, mi, AU, pc, ly
    - Time: s, min, h, d, yr, century
    - Mass: kg, g, lb, oz, M_sun, M_earth
    - Angle: rad, deg, arcmin, arcsec, mas, microas
    - Frequency: Hz, kHz, MHz, GHz, THz
    - Energy: J, eV, keV, MeV, GeV, erg, cal
    - Power: W, kW, MW, GW, erg/s, L_sun
    - Temperature: K, Celsius, Fahrenheit
    - Pressure: Pa, bar, atm, Torr, psi
    - Velocity: m/s, km/s, km/h, mph, c
    - Acceleration: m/s2, g_earth
    - Force: N, dyne, lbf
    - Electric: A, V, Ohm, C, F, H
    - Magnetic: T, G, Wb, Mx
    """

# Prefixes object provides SI prefixes
def prefixes():
    """
    Get prefixes object.
    
    Returns:
    dict-like object with SI prefixes
    
    Prefixes: y, z, a, f, p, n, u, m, c, d, da, h, k, M, G, T, P, E, Z, Y
    """

Unit Parsing and Formatting

Advanced unit string parsing and formatting capabilities.

# String parsing functions (used internally by quantity())
def from_string(s):
    """
    Parse quantity from string.
    
    Parameters:
    - s: str, quantity string like "1.5km/s", "45deg", "1.42GHz"
    
    Returns:
    dict with parsed value and unit
    
    Supported formats:
    - "value unit" (e.g., "1.5 km/s")
    - "valueunit" (e.g., "1.5km/s") 
    - Scientific notation (e.g., "1.5e-3m")
    - Fractions (e.g., "1/2 deg")
    - Compound units (e.g., "m/s2", "kg.m/s2")
    - Time formats (e.g., "12h30m15s", "2023-01-01/12:00:00")
    - Angle formats (e.g., "12h30m15s", "45d30m15s", "45:30:15")
    """

def from_dict(d):
    """
    Create quantity from dictionary.
    
    Parameters:
    - d: dict with 'value' and 'unit' keys
    
    Returns:
    Quantity object
    """

def from_dict_v(d):
    """
    Create vector quantity from dictionary.
    
    Parameters:
    - d: dict with 'value' (list) and 'unit' keys
    
    Returns:
    QuantVec object
    """

Usage Examples

Basic Quantity Operations

from casacore.quanta import quantity, is_quantity, constants

# Create quantities different ways
freq1 = quantity(1.42, 'GHz')
freq2 = quantity('1420.405MHz')  # HI line frequency
distance = quantity([1.0, 2.5, 10.0], 'kpc')

print(f"Frequency 1: {freq1}")
print(f"Frequency 2: {freq2}")
print(f"Distances: {distance}")

# Check if object is quantity
print(f"freq1 is quantity: {is_quantity(freq1)}")

# Unit conversions
freq1_mhz = freq1.convert('MHz')
print(f"Frequency in MHz: {freq1_mhz}")

# Check unit compatibility  
print(f"freq1 compatible with MHz: {freq1.conforms('MHz')}")
print(f"freq1 compatible with km/s: {freq1.conforms('km/s')}")

Mathematical Operations

# Arithmetic with automatic unit handling
velocity = quantity(100, 'km/s')
time = quantity(1, 'yr')

# Distance = velocity × time
distance = velocity * time
print(f"Distance traveled: {distance}")
print(f"Distance in parsecs: {distance.convert('pc')}")

# Wavelength from frequency
c = constants['c']  # Speed of light
freq = quantity('1.42GHz')
wavelength = c / freq
print(f"Wavelength: {wavelength}")
print(f"Wavelength in cm: {wavelength.convert('cm')}")

# Angular calculations
angle1 = quantity('45deg')
angle2 = quantity('30deg')
total_angle = angle1 + angle2
print(f"Total angle: {total_angle}")
print(f"Sine of angle: {angle1.sin()}")

Astronomical Calculations

# Distance modulus calculation
distance = quantity(100, 'pc')  # Distance to object
distance_modulus = 5 * distance.convert('pc').log10() - 5
print(f"Distance modulus: {distance_modulus}")

# Doppler shift calculation
rest_freq = constants['HI']  # 21cm line
velocity = quantity('100km/s')  # Recession velocity
c = constants['c']

# Non-relativistic Doppler formula: Δf/f = v/c
doppler_shift = velocity / c
observed_freq = rest_freq * (1 - doppler_shift)
print(f"Rest frequency: {rest_freq}")
print(f"Observed frequency: {observed_freq}")
print(f"Frequency shift: {rest_freq - observed_freq}")

Time and Angle Parsing

# Parse time strings
time1 = quantity('12h30m15s')  # Hours, minutes, seconds
time2 = quantity('2023-01-01/18:30:00')  # Date/time format
time3 = quantity('58000d')  # Modified Julian Day

print(f"Time 1: {time1}")
print(f"Time 2: {time2}")
print(f"Time 3: {time3}")

# Parse angle strings  
ra = quantity('12h30m15.5s')  # Right ascension
dec = quantity('-30d15m30s')  # Declination
angle = quantity('45:30:15')   # Degrees:arcmin:arcsec

print(f"RA: {ra}")
print(f"RA in degrees: {ra.convert('deg')}")
print(f"Dec: {dec}")
print(f"Angle: {angle}")

Vector Quantities

# Work with vector quantities
frequencies = quantity([1.4, 1.42, 1.66, 1.67], 'GHz')
print(f"Frequencies: {frequencies}")

# Convert all elements
freq_mhz = frequencies.convert('MHz')
print(f"Frequencies in MHz: {freq_mhz}")

# Access individual elements
first_freq = frequencies[0]
print(f"First frequency: {first_freq}")

# Slice vector
mid_freqs = frequencies[1:3]
print(f"Middle frequencies: {mid_freqs}")

# Mathematical operations on vectors
wavelengths = constants['c'] / frequencies
print(f"Wavelengths: {wavelengths}")
print(f"Wavelengths in cm: {wavelengths.convert('cm')}")

Physical Constants

# Access physical constants
c = constants['c']        # Speed of light
h = constants['h']        # Planck constant
k = constants['k']        # Boltzmann constant
pc = constants['pc']      # Parsec
hi = constants['HI']      # 21cm line

print(f"Speed of light: {c}")
print(f"Planck constant: {h}")
print(f"21cm rest frequency: {hi}")

# Calculate brightness temperature
frequency = quantity('1.42GHz')
flux_density = quantity('1Jy')  # Jansky
beam_area = quantity('1arcsec2')

# T_b = λ²S / (2k × Ω)
wavelength = c / frequency
brightness_temp = (wavelength**2 * flux_density) / (2 * k * beam_area)
print(f"Brightness temperature: {brightness_temp.convert('K')}")

Install with Tessl CLI

npx tessl i tessl/pypi-python-casacore

docs

coordinate-systems.md

fitting-operations.md

functionals.md

image-processing.md

index.md

quantities-units.md

table-operations.md

tile.json