0
# Mathematical Functionals
1
2
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.
3
4
## Core Imports
5
6
```python
7
from casacore.functionals import functional, gaussian1d, gaussian2d, poly
8
from casacore.functionals import compound, combi, compiled
9
```
10
11
## Capabilities
12
13
### Base Functional Class
14
15
Foundation class for all mathematical functionals with parameter management and evaluation.
16
17
```python { .api }
18
class functional:
19
def __init__(self, name, **kwargs):
20
"""
21
Create functional by name.
22
23
Parameters:
24
- name: str, functional name ('gaussian1d', 'poly', etc.)
25
- order: int, order for applicable functionals
26
- params: list, initial parameter values
27
- mask: list, parameter masks (True = fit, False = fixed)
28
29
Returns:
30
functional object
31
"""
32
33
def f(self, x):
34
"""
35
Evaluate functional at given points.
36
37
Parameters:
38
- x: float, list, or numpy array, evaluation points
39
40
Returns:
41
numpy array, function values
42
"""
43
44
def fdf(self, x):
45
"""
46
Evaluate functional and derivatives.
47
48
Parameters:
49
- x: float, list, or numpy array, evaluation points
50
51
Returns:
52
dict with 'f' (function values) and 'df' (derivatives)
53
"""
54
55
def __call__(self, x, derivatives=False):
56
"""
57
Call interface for functional evaluation.
58
59
Parameters:
60
- x: evaluation points
61
- derivatives: bool, include derivatives (default False)
62
63
Returns:
64
Function values or dict with values and derivatives
65
"""
66
67
def set_parameters(self, params):
68
"""
69
Set functional parameters.
70
71
Parameters:
72
- params: list, parameter values
73
"""
74
75
def get_parameters(self):
76
"""
77
Get functional parameters.
78
79
Returns:
80
numpy array, current parameter values
81
"""
82
83
def set_masks(self, masks):
84
"""
85
Set parameter masks for fitting.
86
87
Parameters:
88
- masks: list of bool, True = fit parameter, False = fixed
89
"""
90
91
def get_masks(self):
92
"""
93
Get parameter masks.
94
95
Returns:
96
numpy array of bool, parameter masks
97
"""
98
99
def nparameters(self):
100
"""
101
Get number of parameters.
102
103
Returns:
104
int, number of parameters
105
"""
106
107
def ndim(self):
108
"""
109
Get functional dimensionality.
110
111
Returns:
112
int, number of independent variables
113
"""
114
115
def clone(self):
116
"""
117
Create copy of functional.
118
119
Returns:
120
functional, deep copy
121
"""
122
```
123
124
### Gaussian Functionals
125
126
One and two-dimensional Gaussian functions with peak, center, and width parameters.
127
128
```python { .api }
129
class gaussian1d:
130
def __init__(self, peak=1.0, center=0.0, width=1.0):
131
"""
132
Create 1D Gaussian functional.
133
f(x) = peak * exp(-0.5 * ((x - center) / width)^2)
134
135
Parameters:
136
- peak: float, peak amplitude (default 1.0)
137
- center: float, center position (default 0.0)
138
- width: float, Gaussian width (default 1.0)
139
140
Parameter order: [peak, center, width]
141
"""
142
143
class gaussian2d:
144
def __init__(self, peak=1.0, x_center=0.0, y_center=0.0,
145
x_width=1.0, y_width=1.0, theta=0.0):
146
"""
147
Create 2D Gaussian functional.
148
f(x,y) = peak * exp(-0.5 * ((x-x0)/sx)^2 - 0.5 * ((y-y0)/sy)^2)
149
with optional rotation by angle theta
150
151
Parameters:
152
- peak: float, peak amplitude
153
- x_center: float, x center position
154
- y_center: float, y center position
155
- x_width: float, x-direction width
156
- y_width: float, y-direction width
157
- theta: float, rotation angle (radians)
158
159
Parameter order: [peak, x_center, y_center, x_width, y_width, theta]
160
"""
161
```
162
163
### Polynomial Functionals
164
165
Various polynomial types including standard, odd, even, and Chebyshev polynomials.
166
167
```python { .api }
168
class poly:
169
def __init__(self, order, params=None):
170
"""
171
Create polynomial functional.
172
f(x) = p0 + p1*x + p2*x^2 + ... + pN*x^N
173
174
Parameters:
175
- order: int, polynomial order (degree)
176
- params: list, polynomial coefficients (default: all 1.0)
177
178
Parameter order: [p0, p1, p2, ..., pN] (constant to highest order)
179
"""
180
181
class oddpoly:
182
def __init__(self, order=1, params=None):
183
"""
184
Create odd polynomial functional.
185
f(x) = p0*x + p1*x^3 + p2*x^5 + ...
186
Contains only odd powers of x.
187
188
Parameters:
189
- order: int, number of odd terms
190
- params: list, coefficients for odd powers
191
"""
192
193
class evenpoly:
194
def __init__(self, order=1, params=None):
195
"""
196
Create even polynomial functional.
197
f(x) = p0 + p1*x^2 + p2*x^4 + ...
198
Contains only even powers of x.
199
200
Parameters:
201
- order: int, number of even terms
202
- params: list, coefficients for even powers
203
"""
204
205
class chebyshev:
206
def __init__(self, order, params=None):
207
"""
208
Create Chebyshev polynomial functional.
209
f(x) = p0*T0(x) + p1*T1(x) + ... + pN*TN(x)
210
where Tn(x) are Chebyshev polynomials of the first kind.
211
212
Parameters:
213
- order: int, highest Chebyshev order
214
- params: list, Chebyshev coefficients
215
"""
216
```
217
218
### Compound Functionals
219
220
Combine multiple functionals through addition or linear combination.
221
222
```python { .api }
223
class compound:
224
def __init__(self):
225
"""
226
Create compound functional (sum of functionals).
227
f(x) = f1(x) + f2(x) + ... + fN(x)
228
"""
229
230
def add(self, func):
231
"""
232
Add functional to compound.
233
234
Parameters:
235
- func: functional object to add
236
"""
237
238
def nfunctions(self):
239
"""
240
Get number of component functions.
241
242
Returns:
243
int, number of functions in compound
244
"""
245
246
class combi:
247
def __init__(self):
248
"""
249
Create linear combination functional.
250
f(x) = c1*f1(x) + c2*f2(x) + ... + cN*fN(x)
251
where ci are linear coefficients (fitted parameters).
252
"""
253
254
def add(self, func):
255
"""
256
Add functional to linear combination.
257
258
Parameters:
259
- func: functional object to add
260
"""
261
```
262
263
### Compiled Functionals
264
265
User-defined functionals from mathematical expressions with automatic differentiation.
266
267
```python { .api }
268
class compiled:
269
def __init__(self, expression, params=None):
270
"""
271
Create functional from mathematical expression.
272
273
Parameters:
274
- expression: str, mathematical expression
275
- params: list, initial parameter values (default: zeros)
276
277
Expression syntax:
278
- Parameters: p0, p1, p2, ... or p, p1, p2, ...
279
- Variables: x (1D) or x, x1, x2, ... (multi-D)
280
- Operations: +, -, *, /, ^, **
281
- Functions: sin, cos, tan, exp, log, sqrt, abs
282
- Constants: pi, e
283
284
Examples:
285
"p0 + p1*x + p2*x*x" # Polynomial
286
"p*exp(-0.5*((x-p1)/p2)^2)" # Gaussian
287
"p0*sin(p1*x + p2)" # Sinusoid
288
"p*x + p1*sin(x1)" # 2D function
289
"""
290
291
def set_expression(self, expression):
292
"""
293
Change functional expression.
294
295
Parameters:
296
- expression: str, new mathematical expression
297
"""
298
299
def get_expression(self):
300
"""
301
Get current expression.
302
303
Returns:
304
str, mathematical expression
305
"""
306
```
307
308
### Additional Functional Types
309
310
Pre-defined functionals for common mathematical forms.
311
312
```python { .api }
313
# Exponential functions
314
class exponential:
315
def __init__(self, height=1.0, scale=1.0, x0=0.0):
316
"""
317
Exponential functional.
318
f(x) = height * exp((x - x0) / scale)
319
"""
320
321
# Logarithmic functions
322
class logarithmic:
323
def __init__(self, height=1.0, scale=1.0, x0=0.0):
324
"""
325
Logarithmic functional.
326
f(x) = height * log((x - x0) / scale)
327
"""
328
329
# Power law functions
330
class powerlaw:
331
def __init__(self, amplitude=1.0, index=-1.0):
332
"""
333
Power law functional.
334
f(x) = amplitude * x^index
335
"""
336
337
# Sinusoidal functions
338
class sinusoid:
339
def __init__(self, amplitude=1.0, period=1.0, x0=0.0):
340
"""
341
Sinusoidal functional.
342
f(x) = amplitude * sin(2*pi*(x - x0) / period)
343
"""
344
```
345
346
### Functional Utilities
347
348
Helper functions for working with functionals and parameter management.
349
350
```python { .api }
351
def copydoc(func):
352
"""
353
Copy docstring from another function.
354
355
Parameters:
356
- func: function, source for docstring
357
358
Returns:
359
Decorator function
360
"""
361
362
# Parameter management helpers
363
def set_all_parameters(functionals, params):
364
"""
365
Set parameters for list of functionals.
366
367
Parameters:
368
- functionals: list of functional objects
369
- params: list of parameter arrays
370
"""
371
372
def get_all_parameters(functionals):
373
"""
374
Get parameters from list of functionals.
375
376
Parameters:
377
- functionals: list of functional objects
378
379
Returns:
380
list of parameter arrays
381
"""
382
```
383
384
## Usage Examples
385
386
### Basic Functional Usage
387
388
```python
389
from casacore.functionals import gaussian1d, poly, compiled
390
import numpy as np
391
392
# Create 1D Gaussian
393
gauss = gaussian1d(peak=10.0, center=5.0, width=2.0)
394
395
# Evaluate at points
396
x = np.linspace(0, 10, 100)
397
y = gauss(x)
398
399
# Get parameters
400
params = gauss.get_parameters()
401
print(f"Gaussian parameters: {params}") # [peak, center, width]
402
403
# Change parameters
404
gauss.set_parameters([15.0, 3.0, 1.5]) # New peak, center, width
405
y_new = gauss(x)
406
407
# Evaluate with derivatives (for fitting)
408
result = gauss(x, derivatives=True)
409
print(f"Function values: {result[:5]}")
410
derivatives = gauss.fdf(x)
411
print(f"Derivatives shape: {derivatives['df'].shape}")
412
```
413
414
### Polynomial Functionals
415
416
```python
417
# Create 3rd order polynomial: f(x) = 1 + 2x + 3x² + 4x³
418
p = poly(3, [1.0, 2.0, 3.0, 4.0])
419
420
x = np.array([0, 1, 2, 3])
421
y = p(x)
422
print(f"Polynomial values: {y}") # [1, 10, 49, 142]
423
424
# Create even polynomial: f(x) = 1 + 2x² + 3x⁴
425
even_p = evenpoly(2, [1.0, 2.0, 3.0])
426
y_even = even_p(x)
427
print(f"Even polynomial values: {y_even}")
428
```
429
430
### Compiled Functionals
431
432
```python
433
# Create custom functional from expression
434
func = compiled('p0*exp(-0.5*((x-p1)/p2)^2) + p3', [1.0, 0.0, 1.0, 0.1])
435
436
# This creates: f(x) = p0*exp(-0.5*((x-p1)/p2)²) + p3
437
# Which is a Gaussian with offset
438
439
x = np.linspace(-5, 5, 100)
440
y = func(x)
441
442
# Multi-dimensional function
443
func2d = compiled('p*sin(x) + p1*cos(x1)', [1.0, 0.5])
444
# f(x,y) = p*sin(x) + p1*cos(y)
445
446
# Evaluate on 2D grid
447
x_vals = np.linspace(0, 2*np.pi, 50)
448
y_vals = np.linspace(0, 2*np.pi, 50)
449
xx, yy = np.meshgrid(x_vals, y_vals)
450
xy_points = np.column_stack([xx.ravel(), yy.ravel()])
451
z = func2d(xy_points.T) # Note: transpose for correct input format
452
```
453
454
### Compound Functionals
455
456
```python
457
# Create compound functional (sum of functions)
458
comp = compound()
459
460
# Add multiple Gaussians
461
gauss1 = gaussian1d(peak=10.0, center=2.0, width=1.0)
462
gauss2 = gaussian1d(peak=5.0, center=8.0, width=1.5)
463
polynomial = poly(1, [1.0, 0.5]) # Linear baseline
464
465
comp.add(gauss1)
466
comp.add(gauss2)
467
comp.add(polynomial)
468
469
# Compound function is sum: f(x) = gauss1(x) + gauss2(x) + poly(x)
470
x = np.linspace(0, 10, 200)
471
y_compound = comp(x)
472
473
print(f"Total parameters: {comp.nparameters()}") # 3 + 3 + 2 = 8
474
print(f"Number of functions: {comp.nfunctions()}") # 3
475
```
476
477
### Linear Combination
478
479
```python
480
# Create linear combination (weighted sum)
481
lc = combi()
482
483
# Add functionals (coefficients become fitting parameters)
484
sine = compiled('sin(p*x)', [1.0]) # sin(x) with frequency parameter
485
cosine = compiled('cos(p*x)', [1.0]) # cos(x) with frequency parameter
486
487
lc.add(sine)
488
lc.add(cosine)
489
490
# Linear combination: f(x) = c1*sin(p1*x) + c2*cos(p2*x)
491
# Parameters are: [c1, p1, c2, p2] where c1,c2 are linear coefficients
492
493
x = np.linspace(0, 4*np.pi, 100)
494
y_lc = lc(x)
495
```
496
497
### Parameter Masks for Fitting
498
499
```python
500
# Create functional with some fixed parameters
501
gauss = gaussian1d(peak=10.0, center=5.0, width=2.0)
502
503
# Set masks: fit peak and center, fix width
504
masks = [True, True, False] # [fit_peak, fit_center, fix_width]
505
gauss.set_masks(masks)
506
507
print(f"Parameter masks: {gauss.get_masks()}")
508
print(f"Fitted parameters: {np.sum(gauss.get_masks())}") # Number of free parameters
509
510
# Only peak and center will be adjusted during fitting
511
# Width remains fixed at 2.0
512
```
513
514
### Advanced Expression Examples
515
516
```python
517
# Complex mathematical expressions
518
expressions = [
519
# Damped oscillation
520
"p0*exp(-p1*x)*sin(p2*x + p3)",
521
522
# Lorentzian profile
523
"p0 / (1 + ((x - p1) / p2)^2)",
524
525
# Double exponential
526
"p0*exp(-x/p1) + p2*exp(-x/p3)",
527
528
# Rational function
529
"(p0 + p1*x) / (1 + p2*x + p3*x*x)",
530
531
# Multi-dimensional Gaussian
532
"p0*exp(-0.5*((x-p1)/p2)^2 - 0.5*((x1-p3)/p4)^2)"
533
]
534
535
for expr in expressions:
536
func = compiled(expr)
537
print(f"Expression: {expr}")
538
print(f"Parameters: {func.nparameters()}")
539
print(f"Dimensions: {func.ndim()}")
540
print()
541
```