Function Classes#

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)[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, or Function) –

    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, classes, and methods.

    • int or float: Treated as a constant value function.

    • 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.

    • string: Path to a CSV file. The file is read and converted into an

    ndarray. The file can optionally contain a single header line, see notes below for more information.

    • Function: Copies the source of the provided Function object,

    creating a new Function with adjusted inputs and outputs.

  • inputs (string, sequence of strings, optional) – The name of the inputs of the function. Will be used for representation and graphing (axis names). ‘Scalar’ is default. If source is function, int or float and has multiple inputs, this parameter must be given for correct operation.

  • outputs (string, sequence of strings, 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 and spline are supported. For N-D functions, only shepard is supported. Default for 1-D functions is spline.

  • 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 edge of the interval, and ‘zero’, which returns zero for all points outside of source range. Default for 1-D functions is constant.

  • 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}”.

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.

set_inputs(inputs)[source]#

Set the name and number of the incoming arguments of the Function.

Parameters:

inputs (string, sequence of strings) – The name of the parameters (inputs) of the Function.

Returns:

self

Return type:

Function

set_outputs(outputs)[source]#

Set the name and number of the output of the Function.

Parameters:

outputs (string, sequence of strings) – The name of the output of the function. Example: Distance (m).

Returns:

self

Return type:

Function

set_source(source)[source]#

Sets the data source for the function, defining how the function produces output from a given input.

Parameters:

source (callable, scalar, ndarray, string, or Function) –

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, classes, and methods.

  • int or float: Treated as a constant value function.

  • 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.

  • string: 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.

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. 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.

Returns:

self – Returns the Function instance.

Return type:

Function

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, only shepard is supported. Default is ‘spline’.

Returns:

self

Return type:

Function

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’, which keeps interpolation, ‘constant’, which returns the value of the function at the edge of the interval, and ‘zero’, which returns zero for all points outside of source range. Default is ‘constant’.

Returns:

self – The Function object.

Return type:

Function

set_get_value_opt()[source]#

Crates a method that evaluates interpolations rather quickly when compared to other options available, such as just calling the object instance or calling Function.get_value directly. See Function.get_value_opt for documentation.

Returns:

self

Return type:

Function

set_discrete(lower=0, upper=10, 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 0.

  • upper (scalar, optional) – Value where sampling range will end. Default is 10.

  • 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 is supported. For N-D functions, only shepard is supported. Default is ‘spline’.

  • 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 edge of the interval, and ‘zero’, which returns zero for all points outside of source range. Default is ‘constant’.

  • 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:

Function

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.

  1. Currently, this method only supports 1-D and 2-D Functions.

set_discrete_based_on_model(model_function, one_by_one=True, keep_self=True, mutate_self=True)[source]#

This method transforms the domain of a 1-D or 2-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:

Function

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.

  1. Currently, this method only supports 1-D and 2-D Functions.

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, sequence of strings, optional) – List of input variable names. If None, the original inputs are kept. See Function.set_inputs for more information.

  • outputs (string, sequence of strings, 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 : (x) → (Scalar)'
>>> kinetic_energy.reset(inputs='t', outputs='Kinetic Energy');
'Function from R1 to R1 : (t) → (Kinetic Energy)'
Returns:

self

Return type:

Function

get_inputs()[source]#

Return tuple of inputs of the function.

get_outputs()[source]#

Return tuple of outputs of the function.

get_source()[source]#

Return source list or function of the Function.

get_image_dim()[source]#

Return int describing dimension of the image space of the function.

get_domain_dim()[source]#

Return int describing dimension of the domain space of the function.

get_interpolation_method()[source]#

Return string describing interpolation method used.

get_extrapolation_method()[source]#

Return string describing extrapolation method used.

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 (scalar, list) – 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.

Returns:

ans – Value of the Function at the specified point(s).

Return type:

scalar, list

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]) [1, 4, 9] >>> f.get_value([1, 2.5, 4.0]) [1, 6.25, 16.0]

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]) [2, 8, 18] >>> f2.get_value([5], [5]) [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) 4.0 >>> f3.get_value(2.5) 6.25 >>> f3.get_value([1, 2, 3]) [1.0, 4.0, 9.0] >>> f3.get_value([1, 2.5, 4.0]) [1.0, 6.25, 16.0]

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:

Function

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.]]
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:

Function

__call__(*args)[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.

Returns:

ans

Return type:

None, scalar, list

__str__()[source]#

Return a string representation of the Function

__repr__()[source]#

Return a string representation of the Function

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.

plot1D(*args, **kwargs)[source]#

Deprecated method, use Function.plot_1d instead.

plot_1d(lower=None, upper=None, samples=1000, force_data=False, force_points=False, return_object=False, equal_axis=False)[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.

Return type:

None

plot2D(*args, **kwargs)[source]#

Deprecated method, use Function.plot_2d instead.

plot_2d(lower=None, upper=None, samples=None, force_data=True, disp_type='surface', alpha=0.6, cmap='viridis')[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, array of int or float, 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, array of int or float, 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, array of 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 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.

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)[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) – 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 (scalar, optional) – The lower limit of the interval in which the Functions are to be plotted. The default value for function type Functions is 0. By contrast, if the Functions given are defined by a dataset, the default value is the lowest value of the datasets.

  • upper (scalar, optional) – The upper limit of the interval in which the Functions are to be plotted. The default value for function type Functions is 10. By contrast, if the Functions given are defined by a dataset, the default value is the highest value of the datasets.

  • 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 (string, optional) – Title of the plot. Default value is an empty string.

  • xlabel (string, optional) – X-axis label. Default value is an empty string.

  • ylabel (string, optional) – Y-axis label. Default value is an empty string.

  • 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 to plot it. Default value is False.

Return type:

None

__interpolate_polynomial__()[source]#

Calculate polynomial coefficients that fit the data exactly.

__interpolate_spline__()[source]#

Calculate natural spline coefficients that fit the data exactly.

__interpolate_akima__()[source]#

Calculate akima spline coefficients that fit the data exactly

__interpolate_shepard__(args)[source]#

Calculates the shepard interpolation from the given arguments. The shepard interpolation is computed by a inverse distance weighting in a vectorized manner.

Parameters:

args (scalar, list) – Values where the Function is to be evaluated.

Returns:

result – The result of the interpolation.

Return type:

scalar, list

__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:

Function

__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 (scalar or Function) –

Returns:

The result of the comparison one by one.

Return type:

numpy.ndarray of bool

__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 (scalar or Function) –

Returns:

The result of the comparison one by one.

Return type:

numpy.ndarray of bool

__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 (scalar or Function) –

Returns:

The result of the comparison one by one.

Return type:

numpy.ndarray of bool

__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 (scalar or Function) –

Returns:

The result of the comparison one by one.

Return type:

numpy.ndarray of bool

__add__(other)[source]#

Sums a Function object and ‘other’, returns a new Function object which gives the result of the sum. Only implemented for 1D domains.

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:

Function

__radd__(other)[source]#

Sums ‘other’ and a Function object and returns a new Function object which gives the result of the sum. Only implemented for 1D domains.

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:

Function

__sub__(other)[source]#

Subtracts from a Function object and returns a new Function object which gives the result of the subtraction. Only implemented for 1D domains.

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:

Function

__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:

Function

__mul__(other)[source]#

Multiplies a Function object and returns a new Function object which gives the result of the multiplication. Only implemented for 1D domains.

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:

Function

__rmul__(other)[source]#

Multiplies ‘other’ by a Function object and returns a new Function object which gives the result of the multiplication. Only implemented for 1D domains.

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:

Function

__truediv__(other)[source]#

Divides a Function object and returns a new Function object which gives the result of the division. Only implemented for 1D domains.

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:

Function

__rtruediv__(other)[source]#

Divides ‘other’ by a Function object and returns a new Function object which gives the result of the division. Only implemented for 1D domains.

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:

Function

__pow__(other)[source]#

Raises a Function object to the power of ‘other’ and returns a new Function object which gives the result. Only implemented for 1D domains.

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:

Function

__rpow__(other)[source]#

Raises ‘other’ to the power of a Function object and returns a new Function object which gives the result. Only implemented for 1D domains.

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:

Function

__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:

Function

See also

Function.compose

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 interpolation information. Currently, only available for spline and linear interpolation. If unavailable, calculate numerically anyways.

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.

  • order (int) – Order of differentiation.

Returns:

ans – Evaluated derivative.

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:

Function

derivative_function()[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:

Function

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:

Function

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
>>> f.is_strictly_bijective()
True
>>> f = Function([[-1, 1], [0, 0], [1, 1], [2, 4]])
>>> f.isbijective()
False
>>> f.is_strictly_bijective()
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()
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, its bijectivity is checked and an error is raised if it 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:

Function

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:

Function

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:

Function

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.

filenamestr

The name of the file to be saved, with the extension.

lowerfloat or int, optional

The lower bound of the range for which data is to be generated. This is required if the source is a callable function.

upperfloat or int, optional

The upper bound of the range for which data is to be generated. This is required if the source is a callable function.

samplesint, optional

The number of sample points to generate within the specified range. This is required if the source is a callable function.

fmtstr, optional

The format string for each line of the file, by default “%.6f”.

delimiterstr, optional

The string used to separate values, by default “,”.

newlinestr, optional

The string used to separate lines in the file, by default “

“.
encodingstr, optional

The encoding to be used for the file, by default None (which means using the system default encoding).

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.

static _check_user_input(source, inputs=None, outputs=None, interpolation=None, extrapolation=None)[source]#

Validates and processes the user input parameters for creating or modifying a Function object. This function ensures the inputs, outputs, interpolation, and extrapolation parameters are compatible with the given source. It converts the source to a numpy array if necessary, sets default values and raises warnings or errors for incompatible or ill-defined parameters.

Parameters:
  • source (list, np.ndarray, or callable) – The source data or Function object. If a list or ndarray, it should contain numeric data. If a Function, its inputs and outputs are checked against the provided inputs and outputs.

  • inputs (list of str or None) – The names of the input variables. If None, defaults are generated based on the dimensionality of the source.

  • outputs (str or list of str) – The name(s) of the output variable(s). If a list is provided, it must have a single element.

  • interpolation (str or None) – The method of interpolation to be used. For multidimensional sources it defaults to ‘shepard’ if not provided.

  • extrapolation (str or None) – The method of extrapolation to be used. For multidimensional sources it defaults to ‘natural’ if not provided.

Returns:

A tuple containing the processed inputs, outputs, interpolation, and extrapolation parameters.

Return type:

tuple

Raises:
  • ValueError – If the dimensionality of the source does not match the combined dimensions of inputs and outputs. If the outputs list has more than one element.

  • TypeError – If the source is not a list, np.ndarray, Function object, str or Path.

  • Warning – If inputs or outputs do not match for a Function source, or if defaults are used for inputs, interpolation,and extrapolation for a multidimensional source.

Examples

>>> from rocketpy import Function
>>> source = np.array([(1, 1), (2, 4), (3, 9)])
>>> inputs = "x"
>>> outputs = ["y"]
>>> interpolation = 'linear'
>>> extrapolation = 'zero'
>>> inputs, outputs, interpolation, extrapolation = Function._check_user_input(
...     source, inputs, outputs, interpolation, extrapolation
... )
>>> inputs
['x']
>>> outputs
['y']
>>> interpolation
'linear'
>>> extrapolation
'zero'