Python bindings for the CASACORE radio astronomy library providing comprehensive interfaces for table operations, image processing, coordinate systems, and astronomical measurements.
—
Parameterized mathematical functions including polynomials, Gaussians, and user-defined compiled expressions. These functionals can be used for data modeling, curve fitting, and as input to the least squares fitting system with automatic derivative calculation.
from casacore.functionals import functional, gaussian1d, gaussian2d, poly
from casacore.functionals import compound, combi, compiledFoundation class for all mathematical functionals with parameter management and evaluation.
class functional:
def __init__(self, name, **kwargs):
"""
Create functional by name.
Parameters:
- name: str, functional name ('gaussian1d', 'poly', etc.)
- order: int, order for applicable functionals
- params: list, initial parameter values
- mask: list, parameter masks (True = fit, False = fixed)
Returns:
functional object
"""
def f(self, x):
"""
Evaluate functional at given points.
Parameters:
- x: float, list, or numpy array, evaluation points
Returns:
numpy array, function values
"""
def fdf(self, x):
"""
Evaluate functional and derivatives.
Parameters:
- x: float, list, or numpy array, evaluation points
Returns:
dict with 'f' (function values) and 'df' (derivatives)
"""
def __call__(self, x, derivatives=False):
"""
Call interface for functional evaluation.
Parameters:
- x: evaluation points
- derivatives: bool, include derivatives (default False)
Returns:
Function values or dict with values and derivatives
"""
def set_parameters(self, params):
"""
Set functional parameters.
Parameters:
- params: list, parameter values
"""
def get_parameters(self):
"""
Get functional parameters.
Returns:
numpy array, current parameter values
"""
def set_masks(self, masks):
"""
Set parameter masks for fitting.
Parameters:
- masks: list of bool, True = fit parameter, False = fixed
"""
def get_masks(self):
"""
Get parameter masks.
Returns:
numpy array of bool, parameter masks
"""
def nparameters(self):
"""
Get number of parameters.
Returns:
int, number of parameters
"""
def ndim(self):
"""
Get functional dimensionality.
Returns:
int, number of independent variables
"""
def clone(self):
"""
Create copy of functional.
Returns:
functional, deep copy
"""One and two-dimensional Gaussian functions with peak, center, and width parameters.
class gaussian1d:
def __init__(self, peak=1.0, center=0.0, width=1.0):
"""
Create 1D Gaussian functional.
f(x) = peak * exp(-0.5 * ((x - center) / width)^2)
Parameters:
- peak: float, peak amplitude (default 1.0)
- center: float, center position (default 0.0)
- width: float, Gaussian width (default 1.0)
Parameter order: [peak, center, width]
"""
class gaussian2d:
def __init__(self, peak=1.0, x_center=0.0, y_center=0.0,
x_width=1.0, y_width=1.0, theta=0.0):
"""
Create 2D Gaussian functional.
f(x,y) = peak * exp(-0.5 * ((x-x0)/sx)^2 - 0.5 * ((y-y0)/sy)^2)
with optional rotation by angle theta
Parameters:
- peak: float, peak amplitude
- x_center: float, x center position
- y_center: float, y center position
- x_width: float, x-direction width
- y_width: float, y-direction width
- theta: float, rotation angle (radians)
Parameter order: [peak, x_center, y_center, x_width, y_width, theta]
"""Various polynomial types including standard, odd, even, and Chebyshev polynomials.
class poly:
def __init__(self, order, params=None):
"""
Create polynomial functional.
f(x) = p0 + p1*x + p2*x^2 + ... + pN*x^N
Parameters:
- order: int, polynomial order (degree)
- params: list, polynomial coefficients (default: all 1.0)
Parameter order: [p0, p1, p2, ..., pN] (constant to highest order)
"""
class oddpoly:
def __init__(self, order=1, params=None):
"""
Create odd polynomial functional.
f(x) = p0*x + p1*x^3 + p2*x^5 + ...
Contains only odd powers of x.
Parameters:
- order: int, number of odd terms
- params: list, coefficients for odd powers
"""
class evenpoly:
def __init__(self, order=1, params=None):
"""
Create even polynomial functional.
f(x) = p0 + p1*x^2 + p2*x^4 + ...
Contains only even powers of x.
Parameters:
- order: int, number of even terms
- params: list, coefficients for even powers
"""
class chebyshev:
def __init__(self, order, params=None):
"""
Create Chebyshev polynomial functional.
f(x) = p0*T0(x) + p1*T1(x) + ... + pN*TN(x)
where Tn(x) are Chebyshev polynomials of the first kind.
Parameters:
- order: int, highest Chebyshev order
- params: list, Chebyshev coefficients
"""Combine multiple functionals through addition or linear combination.
class compound:
def __init__(self):
"""
Create compound functional (sum of functionals).
f(x) = f1(x) + f2(x) + ... + fN(x)
"""
def add(self, func):
"""
Add functional to compound.
Parameters:
- func: functional object to add
"""
def nfunctions(self):
"""
Get number of component functions.
Returns:
int, number of functions in compound
"""
class combi:
def __init__(self):
"""
Create linear combination functional.
f(x) = c1*f1(x) + c2*f2(x) + ... + cN*fN(x)
where ci are linear coefficients (fitted parameters).
"""
def add(self, func):
"""
Add functional to linear combination.
Parameters:
- func: functional object to add
"""User-defined functionals from mathematical expressions with automatic differentiation.
class compiled:
def __init__(self, expression, params=None):
"""
Create functional from mathematical expression.
Parameters:
- expression: str, mathematical expression
- params: list, initial parameter values (default: zeros)
Expression syntax:
- Parameters: p0, p1, p2, ... or p, p1, p2, ...
- Variables: x (1D) or x, x1, x2, ... (multi-D)
- Operations: +, -, *, /, ^, **
- Functions: sin, cos, tan, exp, log, sqrt, abs
- Constants: pi, e
Examples:
"p0 + p1*x + p2*x*x" # Polynomial
"p*exp(-0.5*((x-p1)/p2)^2)" # Gaussian
"p0*sin(p1*x + p2)" # Sinusoid
"p*x + p1*sin(x1)" # 2D function
"""
def set_expression(self, expression):
"""
Change functional expression.
Parameters:
- expression: str, new mathematical expression
"""
def get_expression(self):
"""
Get current expression.
Returns:
str, mathematical expression
"""Pre-defined functionals for common mathematical forms.
# Exponential functions
class exponential:
def __init__(self, height=1.0, scale=1.0, x0=0.0):
"""
Exponential functional.
f(x) = height * exp((x - x0) / scale)
"""
# Logarithmic functions
class logarithmic:
def __init__(self, height=1.0, scale=1.0, x0=0.0):
"""
Logarithmic functional.
f(x) = height * log((x - x0) / scale)
"""
# Power law functions
class powerlaw:
def __init__(self, amplitude=1.0, index=-1.0):
"""
Power law functional.
f(x) = amplitude * x^index
"""
# Sinusoidal functions
class sinusoid:
def __init__(self, amplitude=1.0, period=1.0, x0=0.0):
"""
Sinusoidal functional.
f(x) = amplitude * sin(2*pi*(x - x0) / period)
"""Helper functions for working with functionals and parameter management.
def copydoc(func):
"""
Copy docstring from another function.
Parameters:
- func: function, source for docstring
Returns:
Decorator function
"""
# Parameter management helpers
def set_all_parameters(functionals, params):
"""
Set parameters for list of functionals.
Parameters:
- functionals: list of functional objects
- params: list of parameter arrays
"""
def get_all_parameters(functionals):
"""
Get parameters from list of functionals.
Parameters:
- functionals: list of functional objects
Returns:
list of parameter arrays
"""from casacore.functionals import gaussian1d, poly, compiled
import numpy as np
# Create 1D Gaussian
gauss = gaussian1d(peak=10.0, center=5.0, width=2.0)
# Evaluate at points
x = np.linspace(0, 10, 100)
y = gauss(x)
# Get parameters
params = gauss.get_parameters()
print(f"Gaussian parameters: {params}") # [peak, center, width]
# Change parameters
gauss.set_parameters([15.0, 3.0, 1.5]) # New peak, center, width
y_new = gauss(x)
# Evaluate with derivatives (for fitting)
result = gauss(x, derivatives=True)
print(f"Function values: {result[:5]}")
derivatives = gauss.fdf(x)
print(f"Derivatives shape: {derivatives['df'].shape}")# Create 3rd order polynomial: f(x) = 1 + 2x + 3x² + 4x³
p = poly(3, [1.0, 2.0, 3.0, 4.0])
x = np.array([0, 1, 2, 3])
y = p(x)
print(f"Polynomial values: {y}") # [1, 10, 49, 142]
# Create even polynomial: f(x) = 1 + 2x² + 3x⁴
even_p = evenpoly(2, [1.0, 2.0, 3.0])
y_even = even_p(x)
print(f"Even polynomial values: {y_even}")# Create custom functional from expression
func = compiled('p0*exp(-0.5*((x-p1)/p2)^2) + p3', [1.0, 0.0, 1.0, 0.1])
# This creates: f(x) = p0*exp(-0.5*((x-p1)/p2)²) + p3
# Which is a Gaussian with offset
x = np.linspace(-5, 5, 100)
y = func(x)
# Multi-dimensional function
func2d = compiled('p*sin(x) + p1*cos(x1)', [1.0, 0.5])
# f(x,y) = p*sin(x) + p1*cos(y)
# Evaluate on 2D grid
x_vals = np.linspace(0, 2*np.pi, 50)
y_vals = np.linspace(0, 2*np.pi, 50)
xx, yy = np.meshgrid(x_vals, y_vals)
xy_points = np.column_stack([xx.ravel(), yy.ravel()])
z = func2d(xy_points.T) # Note: transpose for correct input format# Create compound functional (sum of functions)
comp = compound()
# Add multiple Gaussians
gauss1 = gaussian1d(peak=10.0, center=2.0, width=1.0)
gauss2 = gaussian1d(peak=5.0, center=8.0, width=1.5)
polynomial = poly(1, [1.0, 0.5]) # Linear baseline
comp.add(gauss1)
comp.add(gauss2)
comp.add(polynomial)
# Compound function is sum: f(x) = gauss1(x) + gauss2(x) + poly(x)
x = np.linspace(0, 10, 200)
y_compound = comp(x)
print(f"Total parameters: {comp.nparameters()}") # 3 + 3 + 2 = 8
print(f"Number of functions: {comp.nfunctions()}") # 3# Create linear combination (weighted sum)
lc = combi()
# Add functionals (coefficients become fitting parameters)
sine = compiled('sin(p*x)', [1.0]) # sin(x) with frequency parameter
cosine = compiled('cos(p*x)', [1.0]) # cos(x) with frequency parameter
lc.add(sine)
lc.add(cosine)
# Linear combination: f(x) = c1*sin(p1*x) + c2*cos(p2*x)
# Parameters are: [c1, p1, c2, p2] where c1,c2 are linear coefficients
x = np.linspace(0, 4*np.pi, 100)
y_lc = lc(x)# Create functional with some fixed parameters
gauss = gaussian1d(peak=10.0, center=5.0, width=2.0)
# Set masks: fit peak and center, fix width
masks = [True, True, False] # [fit_peak, fit_center, fix_width]
gauss.set_masks(masks)
print(f"Parameter masks: {gauss.get_masks()}")
print(f"Fitted parameters: {np.sum(gauss.get_masks())}") # Number of free parameters
# Only peak and center will be adjusted during fitting
# Width remains fixed at 2.0# Complex mathematical expressions
expressions = [
# Damped oscillation
"p0*exp(-p1*x)*sin(p2*x + p3)",
# Lorentzian profile
"p0 / (1 + ((x - p1) / p2)^2)",
# Double exponential
"p0*exp(-x/p1) + p2*exp(-x/p3)",
# Rational function
"(p0 + p1*x) / (1 + p2*x + p3*x*x)",
# Multi-dimensional Gaussian
"p0*exp(-0.5*((x-p1)/p2)^2 - 0.5*((x1-p3)/p4)^2)"
]
for expr in expressions:
func = compiled(expr)
print(f"Expression: {expr}")
print(f"Parameters: {func.nparameters()}")
print(f"Dimensions: {func.ndim()}")
print()Install with Tessl CLI
npx tessl i tessl/pypi-python-casacore