Function Classes#
See also
- class rocketpy.Function[source]#
Class converts a python function or a data sequence into an object which can be handled more naturally, enabling easy interpolation, extrapolation, plotting and algebra.
- __init__(source, inputs=None, outputs=None, interpolation=None, extrapolation=None, title=None, **kwargs)[source]#
Convert source into a Function, to be used more naturally. Set inputs, outputs, domain dimension, interpolation and extrapolation method, and process the source.
- Parameters:
source (
callable,scalar,ndarray,string, orFunction) –The data source to be used for the function:
Callable: Called for evaluation with input values. Must have the desired inputs as arguments and return a single output value. Input order is important. Complex-valued coordinates are supported only when the supplied callable accepts and correctly handles complex values. Example: Python functions.int,floatorcomplex: Treated as a constant value function.np.ndarray: Used for interpolation. Format as [(x0, y0, z0), (x1, y1, z1), …, (xn, yn, zn)], where ‘x’ and ‘y’ are inputs, and ‘z’ is the output. Sampled coordinates and values are real. One-dimensional sampled Functions propagate an imaginary perturbation only to support complex-step differentiation; this is not general complex-plane interpolation. Sampled N-D Functions do not support complex coordinates.str: Path to a CSV file. The file is read and converted into an ndarray. The file can optionally contain a single header line.Function: Copies the source of the provided Function object, creating a new Function with adjusted inputs and outputs.
inputs (
string,sequenceofstrings, optional) – The name of the inputs of the function. Will be used for representation and graphing (axis names). ‘Scalar’ is default. If source is a function and has multiple inputs, this parameter must be given for correct operation.outputs (
string,sequenceofstrings, optional) – The name of the outputs of the function. Will be used for representation and graphing (axis names). Scalar is default.interpolation (
string, optional) – Interpolation method to be used if source type is ndarray. For 1-D functions, linear, polynomial, akima, pchip and spline are supported. For N-D functions, linear, shepard, rbf and regular_grid are supported. Default for 1-D functions is spline and for N-D functions is shepard.extrapolation (
string, optional) – Extrapolation method to be used if source type is ndarray. Options are ‘natural’, ‘constant’ and ‘zero’. For 1-D functions, ‘natural’ extends the selected interpolation method outside the data range. For scattered N-D functions, ‘natural’ usually keeps the interpolation method; the documented exception is scattered N-D ‘linear’, which falls back to an RBF extrapolator. For regular-grid functions, ‘natural’ uses SciPy’s regular grid extrapolation behavior. ‘constant’ returns the value of the function at the nearest edge of the domain, and ‘zero’ returns zero for all points outside the source range. Default for 1-D functions is constant and for N-D functions is natural.title (
string, optional) – Title to be displayed in the plots’ figures. If none, the title will be constructed using the inputs and outputs arguments in the form of “{inputs} x {outputs}”.kwargs (
dict, optional) –- vectorized_callablebool, optional
Whether a callable source accepts NumPy array inputs and returns vectorized outputs. Defaults to False.
- validatebool, optional
Whether to validate and normalize the source before construction. Defaults to True. If False, the caller is responsible for passing an already-normalized source: array sources must be numeric 2D arrays and 1-D array sources must already be sorted by domain.
- Return type:
None
Notes
(I) CSV files may include an optional single header line. If this header line is present and contains names for each data column, those names will be used to label the inputs and outputs unless specified otherwise by the inputs and outputs arguments. If the header is specified for only a few columns, it is ignored.
Commas in a header will be interpreted as a delimiter, which may cause undesired input or output labeling. To avoid this, specify each input and output name using the inputs and outputs arguments.
(II) Fields in CSV files may be enclosed in double quotes. If fields are not quoted, double quotes should not appear inside them.
- classmethod from_regular_grid_csv(csv_source, variable_names, coeff_name, extrapolation)[source]#
Create a regular-grid Function from CSV samples when possible.
- Parameters:
csv_source (
str) – Path to the CSV file.variable_names (
list[str]) – Ordered independent variable names present in the CSV.coeff_name (
str) – Name of the output coefficient.extrapolation (
str) – Extrapolation method passed to the Function constructor.
- Returns:
A
Functionconfigured withregular_gridinterpolation when the CSV forms a strict Cartesian grid, otherwiseNone.- Return type:
FunctionorNone
- set_inputs(inputs)[source]#
Set the name and number of the incoming arguments of the Function.
- Parameters:
inputs (
string,sequenceofstrings) – The name of the parameters (inputs) of the Function.- Returns:
self
- Return type:
- set_outputs(outputs)[source]#
Set the name and number of the output of the Function.
- Parameters:
outputs (
string,sequenceofstrings) – The name of the output of the function. Example: Distance (m).- Returns:
self
- Return type:
- set_source(source, validate=True)[source]#
Sets the data source for the function, defining how the function produces output from a given input.
- Parameters:
source (
callable,scalar,ndarray,string, orFunction) –The data source to be used for the function:
Callable: Called for evaluation with input values. Must have the desired inputs as arguments and return a single output value. Input order is important. Example: Python functions.intorfloat: Treated as a constant value function.np.ndarray: Used for interpolation. Format as [(x0, y0, z0), (x1, y1, z1), …, (xn, yn, zn)], where ‘x’ and ‘y’ are inputs, and ‘z’ is the output.str: Path to a CSV file. The file is read and converted into an ndarray. The file can optionally contain a single header line.Function: Copies the source of the provided Function object, creating a new Function with adjusted inputs and outputs.
validate (
bool, optional) – If True, validate, coerce and sort the source. If False, skip source validation for faster internal construction. In this mode, array sources must already be numeric 2D arrays and sorted for 1-D domains.
Notes
CSV files may include an optional single header line: If this header line is present and contains names for each data column, those names will be used to label the inputs and outputs unless specified otherwise. If the header is specified for only a few columns, it is ignored.
Commas in a header will be interpreted as a delimiter: this may cause undesired input or output labeling. To avoid this, specify each input and output name using the inputs and outputs arguments.
Fields in CSV files may be enclosed in double quotes: If fields are not quoted, double quotes should not appear inside them.
- Returns:
self – Returns the Function instance with the new source set.
- Return type:
- classmethod _from_sorted_arrays(domain, image, inputs=None, outputs=None, interpolation=None, extrapolation=None, title=None)[source]#
Build an array-based Function from already-normalized arrays.
This private constructor is for internal results whose domain is already sorted and whose source data has already been validated by construction.
- property min#
Get the minimum value of the Function y_array. Raises an error if the Function is lambda based.
- Returns:
minimum
- Return type:
float
- property max#
Get the maximum value of the Function y_array. Raises an error if the Function is lambda based.
- Returns:
maximum
- Return type:
float
- set_interpolation(method='spline')[source]#
Set interpolation method and process data is method requires.
- Parameters:
method (
string, optional) – Interpolation method to be used if source type is ndarray. For 1-D functions, linear, polynomial, akima and spline is supported. For N-D functions, linear, shepard, rbf and regular_grid are supported. Default for 1-D functions is spline and for N-D functions is shepard.- Returns:
self
- Return type:
- set_extrapolation(method='constant')[source]#
Set extrapolation behavior of data set.
- Parameters:
extrapolation (
string, optional) – Extrapolation method to be used if source type is ndarray. Options are ‘natural’, ‘constant’ and ‘zero’. For 1-D functions, ‘natural’ extends the selected interpolation method outside the data range. For scattered N-D functions, ‘natural’ usually keeps the interpolation method; the documented exception is scattered N-D ‘linear’, which falls back to an RBF extrapolator. For regular -grid functions, ‘natural’ uses SciPy’s regular grid extrapolation behavior. ‘constant’ returns the value of the function at the nearest edge of the domain, and ‘zero’ returns zero for all points outside the source range. Default for 1-D functions is constant and for N-D functions is natural.- Returns:
self – The Function object.
- Return type:
- _build_interp_extrap()[source]#
Build interpolation and extrapolation callables from the
interpolationsubmodule and store them directly as attributes.This replaces the old
__set_interpolation_func,__update_interpolation_coefficients, and__set_extrapolation_funcmethods with a single setup call that delegates all algorithmic work to factory functions.
- _build_regular_grid_polation(extrap)[source]#
Set up interpolation/extrapolation for regular_grid data.
Expects
_grid_axesand_grid_datato already be set on the instance (done byset_sourcewhen it receives a tuple). Falls back to shepard interpolation if grid data is not available.
- set_get_value_opt()[source]#
Defines a method that evaluates interpolations.
- Returns:
self
- Return type:
- set_discrete(lower=None, upper=None, samples=200, interpolation='spline', extrapolation='constant', one_by_one=True, mutate_self=True)[source]#
This method discretizes a 1-D or 2-D Function by evaluating it at certain points (sampling range) and storing the results in a list, which is converted into a Function and then returned. By default, the original Function object is replaced by the new one, which can be changed by the attribute mutate_self.
This method is specially useful to change a dataset sampling or to convert a Function defined by a callable into a list based Function.
- Parameters:
lower (
scalar, optional) – Value where sampling range will start. Default is None.upper (
scalar, optional) – Value where sampling range will end. Default is None.samples (
int, optional) – Number of samples to be taken from inside range. Default is 200.interpolation (
string) – Interpolation method to be used if source type is ndarray. For 1-D functions, linear, polynomial, akima and spline are supported. For N-D functions, linear, shepard, rbf and regular_grid are supported. Default for 1-D functions is spline and for N-D functions is shepard.extrapolation (
string, optional) – Extrapolation method to be used if source type is ndarray. Options are ‘natural’, which keeps interpolation, ‘constant’, which returns the value of the function at the nearest edge of the domain, and ‘zero’, which returns zero for all points outside of source range. Default for 1-D functions is constant and for N-D functions is natural.one_by_one (
boolean, optional) – If True, evaluate Function in each sample point separately. If False, evaluates Function in vectorized form. Default is True.mutate_self (
boolean, optional) – If True, the original Function object source will be replaced by the new one. If False, the original Function object source will remain unchanged, and the new one is simply returned. Default is True.
- Returns:
self
- Return type:
Notes
1. This method performs by default in place replacement of the original Function object source. This can be changed by the attribute mutate_self.
2. For N-D functions (dim > 1) the interpolation is forced to
shepardand extrapolation tonatural, regardless of the arguments passed.
- set_discrete_based_on_model(model_function, one_by_one=True, keep_self=True, mutate_self=True)[source]#
This method transforms the domain of an N-D Function instance into a list of discrete points based on the domain of a model Function instance. It does so by retrieving the domain, domain name, interpolation method and extrapolation method of the model Function instance. It then evaluates the original Function instance in all points of the retrieved domain to generate the list of discrete points that will be used for interpolation when this Function is called.
By default, the original Function object is replaced by the new one, which can be changed by the attribute mutate_self.
- Parameters:
model_function (
Function) – Function object that will be used to define the sampling points, interpolation method and extrapolation method. Must be a Function whose source attribute is a list (i.e. a list based Function instance). Must have the same domain dimension as the Function to be discretized.one_by_one (
boolean, optional) – If True, evaluate Function in each sample point separately. If False, evaluates Function in vectorized form. Default is True.keep_self (
boolean, optional) – If True, the original Function interpolation and extrapolation methods will be kept. If False, those are substituted by the ones from the model Function. Default is True.mutate_self (
boolean, optional) – If True, the original Function object source will be replaced by the new one. If False, the original Function object source will remain unchanged, and the new one is simply returned.
- Returns:
self
- Return type:
See also
Examples
This method is particularly useful when algebraic operations are carried out using Function instances defined by different discretized domains (same range, but different mesh size). Once an algebraic operation is done, it will not directly be applied between the list of discrete points of the two Function instances. Instead, the result will be a Function instance defined by a callable that calls both Function instances and performs the operation. This makes the evaluation of the resulting Function inefficient, due to extra function calling overhead and multiple interpolations being carried out.
>>> from rocketpy import Function >>> f = Function([(0, 0), (1, 1), (2, 4), (3, 9), (4, 16)]) >>> g = Function([(0, 0), (2, 2), (4, 4)]) >>> h = f * g >>> type(h.source) <class 'function'>
Therefore, it is good practice to make sure both Function instances are defined by the same domain, i.e. by the same list of mesh points. This way, the algebraic operation will be carried out directly between the lists of discrete points, generating a new Function instance defined by this result. When it is evaluated, there are no extra function calling overheads neither multiple interpolations.
>>> g.set_discrete_based_on_model(f) 'Function from R1 to R1 : (Scalar) → (Scalar)' >>> h = f * g >>> h.source array([[ 0., 0.], [ 1., 1.], [ 2., 8.], [ 3., 27.], [ 4., 64.]])
Notes
1. This method performs by default in place replacement of the original Function object source. This can be changed by the attribute mutate_self.
2. This method is similar to set_discrete, but it uses the domain of a model Function to define the domain of the new Function instance.
This method supports functions of any domain dimension.
- reset(inputs=None, outputs=None, interpolation=None, extrapolation=None, title=None)[source]#
This method allows the user to reset the inputs, outputs, interpolation and extrapolation settings of a Function object, all at once, without having to call each of the corresponding methods.
- Parameters:
inputs (
string,sequenceofstrings, optional) – List of input variable names. If None, the original inputs are kept. See Function.set_inputs for more information.outputs (
string,sequenceofstrings, optional) – List of output variable names. If None, the original outputs are kept. See Function.set_outputs for more information.interpolation (
string, optional) – Interpolation method to be used if source type is ndarray. See Function.set_interpolation for more information.extrapolation (
string, optional) – Extrapolation method to be used if source type is ndarray. See Function.set_extrapolation for more information.
Examples
A simple use case is to reset the inputs and outputs of a Function object that has been defined by algebraic manipulation of other Function objects.
>>> from rocketpy import Function >>> v = Function(lambda t: (9.8*t**2)/2, inputs='t', outputs='v') >>> mass = 10 # Mass >>> kinetic_energy = mass * v**2 / 2 >>> v.get_inputs(), v.get_outputs() (['t'], ['v']) >>> kinetic_energy 'Function from R1 to R1 : (t) → (Scalar)' >>> kinetic_energy.reset(inputs='t', outputs='Kinetic Energy'); 'Function from R1 to R1 : (t) → (Kinetic Energy)'
- Returns:
self
- Return type:
- crop(x_lim)[source]#
Restrict the input domain of the Function to specified ranges.
This method limits the input values of the Function to the intervals defined in x_lim, effectively trimming the data so that only values within the specified ranges are retained. For multi-dimensional functions, each dimension can be cropped independently by providing a tuple with lower and upper bounds for each input variable. If a dimension is set to None, it will not be cropped.
- Parameters:
x_lim (
list[tuple]) – Range of values with lower and upper limits for input values to be cropped within.- Returns:
A new Function instance with the cropped domain.
- Return type:
See also
Examples
>>> from rocketpy import Function >>> import numpy as np
Create two 2D functions: >>> f1 = Function( … lambda x1, x2: np.sin(x1)*np.cos(x2), … inputs=[‘x1’, ‘x2’], … outputs=’y’ … ) >>> f2 = Function( … lambda x1, x2: np.cos(x1)*np.sin(x2), … inputs=[‘x1’, ‘x2’], … outputs=’y’ … )
Crop their domains: >>> f1_cropped = f1.crop([(-1, 1), (-2, 2)]) >>> f2_cropped = f2.crop([None, (-2, 2)])
Compare the cropped functions using Function.compare_plots: >>> # Function.compare_plots([ >>> # (f1_cropped, ‘sin(x1)*cos(x2), cropped’), >>> # (f2_cropped, ‘cos(x1)*sin(x2), cropped’) >>> # ])
- clip(y_lim)[source]#
Restrict the output values of the Function to specified ranges.
This method limits the output values of the Function to the intervals defined in y_lim, effectively removing all input-output pairs where the output values fall outside the specified ranges. This operation filters the data based on output constraints rather than input domain restrictions.
- Parameters:
y_lim (
list[tuple]) – Range of values with lower and upper limits for output values to be clipped within.- Returns:
A new Function instance with the clipped output values.
- Return type:
See also
Examples
>>> from rocketpy import Function >>> f = Function(lambda x: x**2, inputs='x', outputs='y') >>> f_clip = f.clip([(-5.0, 5.0)]) >>> f.get_value(-3.0), f.get_value(0.0), f.get_value(3.0) (9.0, 0.0, 9.0) >>> f_clip.get_value(-3.0), f_clip.get_value(0.0), f_clip.get_value(3.0) (5.0, 0.0, 5.0)
- get_source_type()[source]#
Return the Function source type.
- Returns:
Enum describing whether the source is callable, array, or scalar.
- Return type:
SourceType
- get_scalar_value()[source]#
Return the scalar value for a constant Function.
- Raises:
ValueError – If the Function is not scalar-based.
- get_value(*args)[source]#
This method returns the value of the Function at the specified point. See Function.get_value_opt for a faster, but limited, implementation.
- Parameters:
args (
scalarorarray-like) –Coordinates where the Function is evaluated. A 1-D Function takes one argument. An N-D Function takes N arguments; array-like arguments are broadcast together and evaluated pointwise.
Callable sources support complex coordinates only when the supplied callable accepts and correctly handles complex values. For sampled sources, complex coordinates are not a general interpolation domain: the 1-D implementation propagates an infinitesimal imaginary perturbation only for complex-step differentiation, with interval selection based on the real component. Sampled N-D sources do not support complex coordinates.
- Returns:
Value of the Function at the specified point, or an array of values for array-like coordinates. The result may be complex when a compatible callable source produces complex values or while the 1-D implementation is being used for complex-step differentiation.
- Return type:
scalarornp.ndarray
Examples
>>> from rocketpy import Function
Testing with callable source (1 dimension):
>>> f = Function(lambda x: x**2) >>> f.get_value(2) 4 >>> f.get_value(2.5) 6.25 >>> f.get_value([1, 2, 3]) array([1., 4., 9.]) >>> f.get_value([1, 2.5, 4.0]) array([ 1. , 6.25, 16. ]) >>> f.get_value(1 + 2j) (-3+4j)
Testing with callable source (2 dimensions):
>>> f2 = Function(lambda x, y: x**2 + y**2) >>> f2.get_value(1, 2) 5 >>> f2.get_value([1, 2, 3], [1, 2, 3]) array([ 2., 8., 18.]) >>> f2.get_value([5], [5]) array([50.])
Testing with ndarray source (1 dimension):
>>> f3 = Function( ... [(0, 0), (1, 1), (1.5, 2.25), (2, 4), (2.5, 6.25), (3, 9), (4, 16)] ... ) >>> f3.get_value(2) np.float64(4.0) >>> f3.get_value(2.5) np.float64(6.25) >>> f3.get_value([1, 2, 3]) array([1., 4., 9.]) >>> f3.get_value([1, 2.5, 4.0]) array([ 1. , 6.25, 16. ])
Testing with ndarray source (2 dimensions):
>>> f4 = Function( ... [(0, 0, 0), (1, 1, 1), (1, 2, 2), (2, 4, 8), (3, 9, 27)] ... ) >>> f4.get_value(1, 1) 1.0 >>> f4.get_value(2, 4) 8.0 >>> abs(f4.get_value(1, 1.5) - 1.5) < 1e-2 # the interpolation is not perfect True >>> f4.get_value(3, 9) 27.0
- __getitem__(args)[source]#
Returns item of the Function source. If the source is not an array, an error will result.
- Parameters:
args (
int,float) – Index of the item to be retrieved.- Returns:
self.source[args] – Item specified from Function.source.
- Return type:
float,array
- __len__()[source]#
Returns length of the Function source. If the source is not an array, an error will result.
- Returns:
len(self.source) – Length of Function.source.
- Return type:
int
- __bool__()[source]#
Returns true if self exists. This is to avoid getting into __len__ method in boolean statements.
- Returns:
bool – Always True.
- Return type:
bool
- to_frequency_domain(lower, upper, sampling_frequency, remove_dc=True)[source]#
Performs the conversion of the Function to the Frequency Domain and returns the result. This is done by taking the Fourier transform of the Function. The resulting frequency domain is symmetric, i.e., the negative frequencies are included as well.
- Parameters:
lower (
float) – Lower bound of the time range.upper (
float) – Upper bound of the time range.sampling_frequency (
float) – Sampling frequency at which to perform the Fourier transform.remove_dc (
bool, optional) – If True, the DC component is removed from the Fourier transform.
- Returns:
The Function in the frequency domain.
- Return type:
Examples
>>> from rocketpy import Function >>> import numpy as np >>> main_frequency = 10 # Hz >>> time = np.linspace(0, 10, 1000) >>> signal = np.sin(2 * np.pi * main_frequency * time) >>> time_domain = Function(np.array([time, signal]).T) >>> frequency_domain = time_domain.to_frequency_domain( ... lower=0, upper=10, sampling_frequency=100 ... ) >>> peak_frequencies_index = np.where(frequency_domain[:, 1] > 0.001) >>> peak_frequencies = frequency_domain[peak_frequencies_index, 0] >>> print(peak_frequencies) [[-10. 10.]]
- short_time_fft(lower, upper, sampling_frequency, window_size, step_size, remove_dc=True, only_positive=True)[source]#
Performs the Short-Time Fourier Transform (STFT) of the Function and returns the result. The STFT is computed by applying the Fourier transform to overlapping windows of the Function.
- Parameters:
lower (
float) – Lower bound of the time range.upper (
float) – Upper bound of the time range.sampling_frequency (
float) – Sampling frequency at which to perform the Fourier transform.window_size (
float) – Size of the window for the STFT, in seconds.step_size (
float) – Step size for the window, in seconds.remove_dc (
bool, optional) – If True, the DC component is removed from each window before computing the Fourier transform.only_positive (
bool, optional) – If True, only the positive frequencies are returned.
- Returns:
A list of Functions, each representing the STFT of a window.
- Return type:
list[Function]
Examples
>>> import numpy as np >>> import matplotlib.pyplot as plt >>> from rocketpy import Function
Generate a signal with varying frequency:
>>> T_x, N = 1 / 20 , 1000 # 20 Hz sampling rate for 50 s signal >>> t_x = np.arange(N) * T_x # time indexes for signal >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency >>> signal = np.sin(2 * np.pi * np.cumsum(f_i) * T_x) # the signal
Create the Function object and perform the STFT:
>>> time_domain = Function(np.array([t_x, signal]).T) >>> stft_result = time_domain.short_time_fft( ... lower=0, ... upper=50, ... sampling_frequency=95, ... window_size=2, ... step_size=0.5, ... )
Plot the spectrogram:
>>> Sx = np.abs([window[:, 1] for window in stft_result]) >>> t_lo, t_hi = t_x[0], t_x[-1] >>> fig1, ax1 = plt.subplots(figsize=(10, 6)) >>> im1 = ax1.imshow( ... Sx.T, ... origin='lower', ... aspect='auto', ... extent=[t_lo, t_hi, 0, 50], ... cmap='viridis' ... ) >>> _ = ax1.set_title(rf"STFT (2$\,s$ Gaussian window, $\sigma_t=0.4\,$s)") >>> _ = ax1.set( ... xlabel=f"Time $t$ in seconds", ... ylabel=f"Freq. $f$ in Hz)", ... xlim=(t_lo, t_hi) ... ) >>> _ = ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$') >>> _ = fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$") >>> # Shade areas where window slices stick out to the side >>> for t0_, t1_ in [(t_lo, 1), (49, t_hi)]: ... _ = ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2) >>> # Mark signal borders with vertical line >>> for t_ in [t_lo, t_hi]: ... _ = ax1.axvline(t_, color='y', linestyle='--', alpha=0.5) >>> # Add legend and finalize plot >>> _ = ax1.legend() >>> fig1.tight_layout() >>> # plt.show() # uncomment to show the plot
References
Example adapted from the SciPy documentation: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.ShortTimeFFT.html
- low_pass_filter(alpha, file_path=None)[source]#
Implements a low pass filter with a moving average filter. This does not mutate the original Function object, but returns a new one with the filtered source. The filtered source is also saved to a CSV file if a file path is given.
- Parameters:
alpha (
float) – Attenuation coefficient, 0 <= alpha <= 1 For a given dataset, the larger alpha is, the more closely the filtered function returned will match the function the smaller alpha is, the smoother the filtered function returned will be (but with a phase shift)file_path (
string, optional) – File path or file name of the CSV to save. Don’t save any CSV if if no argument is passed. Initiated to None.
- Returns:
The function with the incoming source filtered
- Return type:
- remove_outliers_iqr(threshold=1.5)[source]#
Remove outliers from the Function source using the interquartile range method. The Function should have an array-like source.
- Parameters:
threshold (
float, optional) – Threshold for the interquartile range method. Default is 1.5.- Returns:
The Function with the outliers removed.
- Return type:
References
- __call__(*args, filename=None)[source]#
Plot the Function if no argument is given. If an argument is given, return the value of the function at the desired point.
- Parameters:
args (
scalar,list, optional) – Value where the Function is to be evaluated. If the Function is 1-D, only one argument is expected, which may be an int, a float or a list of ints or floats, in which case the Function will be evaluated at all points in the list and a list of floats will be returned. If the function is N-D, N arguments must be given, each one being an scalar or list.filename (
str | None, optional) – The path the plot should be saved to. By default None, in which case the plot will be shown instead of saved. Supported file endings are: eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff and webp (these are the formats supported by matplotlib).
- Returns:
ans
- Return type:
None,scalar,list
- set_title(title)[source]#
Used to define the title of the Function object.
- Parameters:
title (
str) – Title to be assigned to the Function.
- plot(*args, **kwargs)[source]#
Call Function.plot_1d if Function is 1-Dimensional or call Function.plot_2d if Function is 2-Dimensional and forward arguments and key-word arguments.
- plot_1d(lower=None, upper=None, samples=1000, force_data=False, force_points=False, return_object=False, equal_axis=False, *, filename=None)[source]#
Plot 1-Dimensional Function, from a lower limit to an upper limit, by sampling the Function several times in the interval. The title of the graph is given by the name of the axes, which are taken from the Function`s input and output names.
- Parameters:
lower (
scalar, optional) – The lower limit of the interval in which the function is to be plotted. The default value for function type Functions is 0. By contrast, if the Function is given by a dataset, the default value is the start of the dataset.upper (
scalar, optional) – The upper limit of the interval in which the function is to be plotted. The default value for function type Functions is 10. By contrast, if the Function is given by a dataset, the default value is the end of the dataset.samples (
int, optional) – The number of samples in which the function will be evaluated for plotting it, which draws lines between each evaluated point. The default value is 1000.force_data (
Boolean, optional) – If Function is given by an interpolated dataset, setting force_data to True will plot all points, as a scatter, in the dataset. Default value is False.force_points (
Boolean, optional) – Setting force_points to True will plot all points, as a scatter, in which the Function was evaluated in the dataset. Default value is False.filename (
str | None, optional) – The path the plot should be saved to. By default None, in which case the plot will be shown instead of saved. Supported file endings are: eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff and webp (these are the formats supported by matplotlib).
- Return type:
None
- plot_2d(lower=None, upper=None, samples=None, force_data=True, disp_type='surface', alpha=0.6, cmap='viridis', *, filename=None)[source]#
Plot 2-Dimensional Function, from a lower limit to an upper limit, by sampling the Function several times in the interval. The title of the graph is given by the name of the axis, which are taken from the Function`s inputs and output names.
- Parameters:
lower (
scalar,arrayofintorfloat, optional) – The lower limits of the interval in which the function is to be plotted, which can be an int or float, which is repeated for both axis, or an array specifying the limit for each axis. The default value for function type Functions is 0. By contrast, if the Function is given by a dataset, the default value is the start of the dataset for each axis.upper (
scalar,arrayofintorfloat, optional) – The upper limits of the interval in which the function is to be plotted, which can be an int or float, which is repeated for both axis, or an array specifying the limit for each axis. The default value for function type Functions is 0. By contrast, if the Function is given by a dataset, the default value is the end of the dataset for each axis.samples (
int,arrayofint, optional) – The number of samples in which the function will be evaluated for plotting it, which draws lines between each evaluated point. The default value is 30 for each axis.force_data (
Boolean, optional) – If Function is given by an interpolated dataset, setting force_data to True will plot all points, as a scatter, in the dataset. Default value is False.disp_type (
string, optional) – Display type of plotted graph, which can be surface, wireframe, contour, or contourf. Default value is surface.alpha (
float, optional) – Transparency of plotted graph, which can be a value between 0 and 1. Default value is 0.6.cmap (
string, optional) – Colormap of plotted graph, which can be any of the color maps available in matplotlib. Default value is viridis.filename (
str | None, optional) – The path the plot should be saved to. By default None, in which case the plot will be shown instead of saved. Supported file endings are: eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff and webp (these are the formats supported by matplotlib).
- Return type:
None
- static compare_plots(plot_list, lower=None, upper=None, samples=1000, title='', xlabel='', ylabel='', force_data=False, force_points=False, return_object=False, show=True, *, filename=None)[source]#
Plots N 1-Dimensional Functions in the same plot, from a lower limit to an upper limit, by sampling the Functions several times in the interval.
- Parameters:
plot_list (
list[Tuple[Function,str]]) – List of Functions or list of tuples in the format (Function, label), where label is a string which will be displayed in the legend.lower (
float, optional) – This represents the lower limit of the interval for plotting the Functions. If the Functions are defined by a dataset, the smallest value from the dataset is used. If no value is provided (None), and the Functions are of Function type, 0 is used as the default.upper (
float, optional) – This represents the upper limit of the interval for plotting the Functions. If the Functions are defined by a dataset, the largest value from the dataset is used. If no value is provided (None), and the Functions are of Function type, 10 is used as the default.samples (
int, optional) – The number of samples in which the functions will be evaluated for plotting it, which draws lines between each evaluated point. The default value is 1000.title (
str, optional) – Title of the plot. Default value is an empty string.xlabel (
str, optional) – X-axis label. Default value is an empty string.ylabel (
str, optional) – Y-axis label. Default value is an empty string.force_data (
bool, optional) – If Function is given by an interpolated dataset, setting force_data to True will plot all points, as a scatter, in the dataset. Default value is False.force_points (
bool, optional) – Setting force_points to True will plot all points, as a scatter, in which the Function was evaluated to plot it. Default value is False.return_object (
bool, optional) – If True, returns the figure and axis objects. Default value is False.show (
bool, optional) – If True, shows the plot. Default value is True.filename (
str | None, optional) – The path the plot should be saved to. By default None, in which case the plot will be shown instead of saved. Supported file endings are: eps, jpg, jpeg, pdf, pgf, png, ps, raw, rgba, svg, svgz, tif, tiff and webp (these are the formats supported by matplotlib).
- Return type:
None
- __neg__()[source]#
Negates the Function object. The result has the same effect as multiplying the Function by -1.
- Returns:
The negated Function object.
- Return type:
- __ge__(other)[source]#
Greater than or equal to comparison operator. It can be used to compare a Function object with a scalar or another Function object. This has the same effect as comparing numpy arrays.
Note that it only works for Functions if at least one of them is defined by a set of points so that the bounds of the domain can be set. If both are defined by a set of points, they must have the same discretization.
- Parameters:
other (
scalarorFunction)- Returns:
The result of the comparison one by one.
- Return type:
numpy.ndarrayofbool
- __le__(other)[source]#
Less than or equal to comparison operator. It can be used to compare a Function object with a scalar or another Function object. This has the same effect as comparing numpy arrays.
Note that it only works for Functions if at least one of them is defined by a set of points so that the bounds of the domain can be set. If both are defined by a set of points, they must have the same discretization.
- Parameters:
other (
scalarorFunction)- Returns:
The result of the comparison one by one.
- Return type:
numpy.ndarrayofbool
- __gt__(other)[source]#
Greater than comparison operator. It can be used to compare a Function object with a scalar or another Function object. This has the same effect as comparing numpy arrays.
Note that it only works for Functions if at least one of them is defined by a set of points so that the bounds of the domain can be set. If both are defined by a set of points, they must have the same discretization.
- Parameters:
other (
scalarorFunction)- Returns:
The result of the comparison one by one.
- Return type:
numpy.ndarrayofbool
- __lt__(other)[source]#
Less than comparison operator. It can be used to compare a Function object with a scalar or another Function object. This has the same effect as comparing numpy arrays.
Note that it only works for Functions if at least one of them is defined by a set of points so that the bounds of the domain can be set. If both are defined by a set of points, they must have the same discretization.
- Parameters:
other (
scalarorFunction)- Returns:
The result of the comparison one by one.
- Return type:
numpy.ndarrayofbool
- __add__(other)[source]#
Sums a Function object and ‘other’, returns a new Function object which gives the result of the sum.
- Parameters:
other (
Function,int,float,callable) – What self will be added to. If other and self are Function objects which are based on a list of points, have the exact same domain (are defined in the same grid points) and have the same dimension, then a special implementation is used. This implementation is faster, however behavior between grid points is only interpolated, not calculated as it would be; the resultant Function has the same interpolation as self.- Returns:
result – A Function object which gives the result of self(x)+other(x).
- Return type:
- __radd__(other)[source]#
Sums ‘other’ and a Function object and returns a new Function object which gives the result of the sum.
- Parameters:
other (
int,float,callable) – What self will be added to.- Returns:
result – A Function object which gives the result of other(x)+self(x).
- Return type:
- __sub__(other)[source]#
Subtracts from a Function object and returns a new Function object which gives the result of the subtraction.
- Parameters:
other (
Function,int,float,callable) – What self will be subtracted by. If other and self are Function objects which are based on a list of points, have the exact same domain (are defined in the same grid points) and have the same dimension, then a special implementation is used. This implementation is faster, however behavior between grid points is only interpolated, not calculated as it would be; the resultant Function has the same interpolation as self.- Returns:
result – A Function object which gives the result of self(x)-other(x).
- Return type:
- __rsub__(other)[source]#
Subtracts a Function object from ‘other’ and returns a new Function object which gives the result of the subtraction. Only implemented for 1D domains.
- Parameters:
other (
int,float,callable) – What self will subtract from.- Returns:
result – A Function object which gives the result of other(x)-self(x).
- Return type:
- __mul__(other)[source]#
Multiplies a Function object and returns a new Function object which gives the result of the multiplication.
- Parameters:
other (
Function,int,float,callable) – What self will be multiplied by. If other and self are Function objects which are based on a list of points, have the exact same domain (are defined in the same grid points) and have the same dimension, then a special implementation is used. This implementation is faster, however behavior between grid points is only interpolated, not calculated as it would be; the resultant Function has the same interpolation as self.- Returns:
result – A Function object which gives the result of self(x)*other(x).
- Return type:
- __rmul__(other)[source]#
Multiplies ‘other’ by a Function object and returns a new Function object which gives the result of the multiplication.
- Parameters:
other (
int,float,callable) – What self will be multiplied by.- Returns:
result – A Function object which gives the result of other(x)*self(x).
- Return type:
- __truediv__(other)[source]#
Divides a Function object and returns a new Function object which gives the result of the division.
- Parameters:
other (
Function,int,float,callable) – What self will be divided by. If other and self are Function objects which are based on a list of points, have the exact same domain (are defined in the same grid points) and have the same dimension, then a special implementation is used. This implementation is faster, however behavior between grid points is only interpolated, not calculated as it would be; the resultant Function has the same interpolation as self.- Returns:
result – A Function object which gives the result of self(x)/other(x).
- Return type:
- __rtruediv__(other)[source]#
Divides ‘other’ by a Function object and returns a new Function object which gives the result of the division.
- Parameters:
other (
int,float,callable) – What self will divide.- Returns:
result – A Function object which gives the result of other(x)/self(x).
- Return type:
- __pow__(other)[source]#
Raises a Function object to the power of ‘other’ and returns a new Function object which gives the result.
- Parameters:
other (
Function,int,float,callable) – What self will be raised to. If other and self are Function objects which are based on a list of points, have the exact same domain (are defined in the same grid points) and have the same dimension, then a special implementation is used. This implementation is faster, however behavior between grid points is only interpolated, not calculated as it would be; the resultant Function has the same interpolation as self.- Returns:
result – A Function object which gives the result of self(x)**other(x).
- Return type:
- __rpow__(other)[source]#
Raises ‘other’ to the power of a Function object and returns a new Function object which gives the result.
- Parameters:
other (
int,float,callable) – The object that will be exponentiated by the function.- Returns:
result – A Function object which gives the result of other(x)**self(x).
- Return type:
- __matmul__(other)[source]#
Operator @ as an alias for composition. Therefore, this method is a shorthand for Function.compose(other).
- Parameters:
other (
Function) – Function object to be composed with self.- Returns:
result – A Function object which gives the result of self(other(x)).
- Return type:
See also
- integral(a, b, numerical=False)[source]#
Evaluate a definite integral of a 1-D Function in the interval from a to b.
- Parameters:
a (
float) – Lower limit of integration.b (
float) – Upper limit of integration.numerical (
bool) – If True, forces the definite integral to be evaluated numerically. The current numerical method used is scipy.integrate.quad. If False, try to calculate using the precomputed analytical antiderivative when available (all 1-D array-based methods). Falls back to numerical integration otherwise.
- Returns:
ans – Evaluated integral.
- Return type:
float
- differentiate(x, dx=1e-06, order=1)[source]#
Differentiate a Function object at a given point.
- Parameters:
x (
float) – Point at which to differentiate.dx (
float) – Step size to use for numerical differentiation (fallback).order (
int) – Order of differentiation.
- Returns:
ans – Evaluated derivative.
- Return type:
float
- differentiate_complex_step(x, dx=1e-200, order=1)[source]#
Differentiate a Function object at a given point using the complex step method. This method can be faster than
Function.differentiatesince it requires only one evaluation of the function.Callable sources support this method only when they accept complex inputs, preserve the imaginary perturbation, and are analytic near the evaluation point. For sampled 1-D sources, complex propagation exists specifically for this method and is not a general complex-plane interpolation contract. The real component selects the interpolation or extrapolation segment, while the full complex value is evaluated by that segment’s polynomial. Sampled N-D sources do not support complex coordinates. Avoid evaluating at points where the selected interpolation or extrapolation is not differentiable, such as a slope-changing linear interpolation knot.
- Parameters:
x (
float) – Real scalar point at which to differentiate. This method supports 1-D Functions only.dx (
float, optional) – Step size to use for numerical differentiation, by default 1e-200.order (
int, optional) – Order of differentiation, by default 1. Right now, only first order derivative is supported.
- Returns:
First derivative of the function at the given point.
- Return type:
float
- identity_function()[source]#
Returns a Function object that correspond to the identity mapping, i.e. f(x) = x. If the Function object is defined on an array, the identity Function follows the same discretization, and has linear interpolation and extrapolation. If the Function is defined by a lambda, the identity Function is the identity map ‘lambda x: x’.
- Returns:
result – A Function object that corresponds to the identity mapping.
- Return type:
- derivative_function(order=1)[source]#
Returns a Function object which gives the derivative of the Function object.
- Returns:
result – A Function object which gives the derivative of self.
- Return type:
- integral_function(lower=None, upper=None, datapoints=100)[source]#
Returns a Function object representing the integral of the Function object.
- Parameters:
lower (
scalar, optional) – The lower limit of the interval in which the function is to be evaluated at. If the Function is given by a dataset, the default value is the start of the dataset.upper (
scalar, optional) – The upper limit of the interval in which the function is to be evaluated at. If the Function is given by a dataset, the default value is the end of the dataset.datapoints (
int, optional) – The number of points in which the integral will be evaluated for plotting it, which draws lines between each evaluated point. The default value is 100.
- Returns:
result – The integral of the Function object.
- Return type:
- isbijective()[source]#
Checks whether the Function is bijective. Only applicable to Functions whose source is a list of points, raises an error otherwise.
- Returns:
result – True if the Function is bijective, False otherwise.
- Return type:
bool
- is_strictly_bijective()[source]#
Checks whether the Function is “strictly” bijective. Only applicable to Functions whose source is a list of points, raises an error otherwise.
Notes
By “strictly” bijective, this implementation considers the list-of-points-defined Function bijective between each consecutive pair of points. Therefore, the Function may be flagged as not bijective even if the mapping between the set of points which define the Function is bijective.
- Returns:
result – True if the Function is “strictly” bijective, False otherwise.
- Return type:
bool
Examples
>>> f = Function([[0, 0], [1, 1], [2, 4]]) >>> f.isbijective() == True True >>> f.is_strictly_bijective() == True np.True_
>>> f = Function([[-1, 1], [0, 0], [1, 1], [2, 4]]) >>> f.isbijective() False >>> f.is_strictly_bijective() np.False_
A Function which is not “strictly” bijective, but is bijective, can be constructed as x^2 defined at -1, 0 and 2.
>>> f = Function([[-1, 1], [0, 0], [2, 4]]) >>> f.isbijective() True >>> f.is_strictly_bijective() np.False_
- inverse_function(approx_func=None, tol=0.0001)[source]#
Returns the inverse of the Function. The inverse function of F is a function that undoes the operation of F. The inverse of F exists if and only if F is bijective. Makes the domain the range and the range the domain.
If the Function is given by a list of points, the method is_strictly_bijective() is called and an error is raised if the Function is not bijective. If the Function is given by a function, its bijection is not checked and may lead to inaccuracies outside of its bijective region.
- Parameters:
approx_func (
callable, optional) – A function that approximates the inverse of the Function. This function is used to find the starting guesses for the inverse root finding algorithm. This is better used when the inverse in complex but has a simple approximation or when the root finding algorithm performs poorly due to default start point. The default is None in which case the starting point is zero.tol (
float, optional) – The tolerance for the inverse root finding algorithm. The default is 1e-4.
- Returns:
result – A Function whose domain and range have been inverted.
- Return type:
- find_input(val, start, tol=0.0001)[source]#
Finds the optimal input for a given output.
- Parameters:
val (
int,float) – The value of the output.start (
int,float) – Initial guess of the output.tol (
int,float) – Tolerance for termination.
- Returns:
result – The value of the input which gives the output closest to val.
- Return type:
ndarray
- average(lower, upper)[source]#
Returns the average of the function.
- Parameters:
lower (
float) – Lower point of the region that the average will be calculated at.upper (
float) – Upper point of the region that the average will be calculated at.
- Returns:
result – The average of the function.
- Return type:
float
- average_function(lower=None)[source]#
Returns a Function object representing the average of the Function object.
- Parameters:
lower (
float) – Lower limit of the new domain. Only required if the Function’s source is a callable instead of a list of points.- Returns:
result – The average of the Function object.
- Return type:
- compose(func, extrapolate=False)[source]#
Returns a Function object which is the result of inputting a function into a function (i.e. f(g(x))). The domain will become the domain of the input function and the range will become the range of the original function.
- Parameters:
func (
Function) – The function to be inputted into the function.extrapolate (
bool, optional) – Whether or not to extrapolate the function if the input function’s range is outside of the original function’s domain. The default is False.
- Returns:
result – The result of inputting the function into the function.
- Return type:
- savetxt(filename, lower=None, upper=None, samples=None, fmt='%.6f', delimiter=',', newline='\n', encoding=None)[source]#
Save a Function object to a text file. The first line is the header with inputs and outputs. The following lines are the data. The text file can have any extension, but it is recommended to use .csv or .txt.
- Parameters:
filename (
str) – The name of the file to be saved, with the extension.lower (
floatorint, optional) – The lower bound of the range for which data is to be generated. This is required if the source is a callable function.upper (
floatorint, optional) – The upper bound of the range for which data is to be generated. This is required if the source is a callable function.samples (
int, optional) – The number of sample points to generate within the specified range. This is required if the source is a callable function.fmt (
str, optional) – The format string for each line of the file, by default “%.6f”.delimiter (
str, optional) – The string used to separate values, by default “,”.newline (
str, optional) – The string used to separate lines in the file, by default “n”.encoding (
str, optional) – The encoding to be used for the file, by default None (which means using the system default encoding).
- Raises:
ValueError – Raised if lower, upper, and samples are not provided when the source is a callable function. These parameters are necessary to generate the data points for saving.
- to_dict(**kwargs)[source]#
Serializes the Function instance to a dictionary.
- Returns:
A dictionary containing the Function’s attributes.
- Return type:
dict
- classmethod from_grid(grid_data, axes, inputs=None, outputs=None, interpolation='regular_grid', extrapolation='constant', flatten_for_compatibility=True, **kwargs)[source]#
Creates a Function from N-dimensional grid data.
This method is designed for structured grid data, such as CFD simulation results where values are computed on a regular grid. It uses scipy.interpolate.RegularGridInterpolator for efficient interpolation.
- Parameters:
grid_data (
ndarray) – N-dimensional array containing the function values on the grid. For example, for a 3D function Cd(M, Re, α), this would be a 3D array where grid_data[i, j, k] = Cd(M[i], Re[j], α[k]).axes (
listofndarray) – List of 1D arrays defining the grid points along each axis. Each array should be sorted in ascending order. For example: [M_axis, Re_axis, alpha_axis].inputs (
listofstr, optional) – Names of the input variables. If None, generic names will be used. For example: [‘Mach’, ‘Reynolds’, ‘Alpha’].outputs (
str, optional) – Name of the output variable. For example: ‘Cd’.interpolation (
str, optional) – Interpolation method. Default is ‘regular_grid’. Currently only ‘regular_grid’ is supported for grid data.extrapolation (
str, optional) –Extrapolation behavior. Default is
'constant'which clamps to edge values. Supported options are:'constant' Use nearest edge value for out-of-bounds points (clamp). 'zero' Return zero for out-of-bounds points. 'natural' Use the interpolator's natural behavior: when the underlying ``RegularGridInterpolator`` is created with ``fill_value=None`` and ``method='linear'``, this results in linear extrapolation based on the edge gradients.If an unsupported extrapolation value is supplied a
ValueErroris raised.flatten_for_compatibility (
bool, optional) – If True (default), creates flattened_domain,_image, andsourcearrays for backward compatibility with existing Function methods and serialization. For large N-dimensional grids (e.g., 100x100x100 points), this requires O(n^d) additional memory where n is the typical axis length and d is the number of dimensions. Set to False to skip this flattening and reduce memory usage if compatibility with legacy code paths is not required.**kwargs (
dict, optional) – Additional arguments passed to the Function constructor.
- Returns:
A Function object using RegularGridInterpolator for evaluation.
- Return type:
Notes
Grid data must be on a regular (structured) grid.
For unstructured data, use the regular Function constructor with scattered points.
Extrapolation with ‘constant’ mode uses the nearest edge values, which is appropriate for aerodynamic coefficients where extrapolation beyond the data range should be avoided.
Examples
>>> import numpy as np >>> # Create 3D drag coefficient data >>> mach = np.array([0.0, 0.5, 1.0, 1.5, 2.0]) >>> reynolds = np.array([1e5, 5e5, 1e6]) >>> alpha = np.array([0.0, 2.0, 4.0, 6.0]) >>> # Create a simple drag coefficient function >>> M, Re, A = np.meshgrid(mach, reynolds, alpha, indexing='ij') >>> cd_data = 0.3 + 0.1 * M + 1e-7 * Re + 0.01 * A >>> # Create Function object >>> cd_func = Function.from_grid( ... cd_data, ... [mach, reynolds, alpha], ... inputs=['Mach', 'Reynolds', 'Alpha'], ... outputs='Cd' ... ) >>> # Evaluate at a point >>> cd_func(1.2, 3e5, 3.0) 0.48000000000000004