Function Class#
- class rocketpy.Function.Function(source, inputs=['Scalar'], outputs=['Scalar'], interpolation=None, extrapolation=None)[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.
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 (function, scalar, ndarray, string) – The actual function. If type is function, it will be called for evaluation. If type is int or float, it will be treated as a constant function. If ndarray, its points will be used for interpolation. An ndarray should be as [(x0, y0, z0), (x1, y1, z1), (x2, y2, z2), …] where x0 and y0 are inputs and z0 is output. If string, imports file named by the string and treats it as csv. The file is converted into ndarray and should not have headers.
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.
- Return type:
None
- setInputs(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:
- setOutputs(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:
- setSource(source)[source]#
Set the source which defines the output of the function giving a certain input.
- Parameters:
source (function, scalar, ndarray, string) – The actual function. If type is function, it will be called for evaluation. If type is int or float, it will be treated as a constant function. If ndarray, its points will be used for interpolation. An ndarray should be as [(x0, y0, z0), (x1, y1, z1), (x2, y2, z2), …] where x0 and y0 are inputs and z0 is output. If string, imports file named by the string and treats it as csv. The file is converted into ndarray and should not have headers.
- Returns:
self
- Return type:
- setInterpolation(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:
- setExtrapolation(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 ‘zero’.
- Returns:
self
- Return type:
- setGetValueOpt()[source]#
Crates a method that evaluates interpolations rather quickly when compared to other options available, such as just calling the object instance or calling self.getValue directly. See Function.getValueOpt for documentation.
- Returns:
self
- Return type:
- setDiscrete(lower=0, upper=10, samples=200, interpolation='spline', extrapolation='constant', oneByOne=True)[source]#
This method transforms function defined Functions into list defined Functions. It evaluates the function at certain points (sampling range) and stores the results in a list, which is converted into a Function and then returned. The original Function object is replaced by the new one.
- 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’.
oneByOne (boolean, optional) – If True, evaluate Function in each sample point separately. If False, evaluates Function in vectorized form. Default is True.
- Returns:
self
- Return type:
- setDiscreteBasedOnModel(modelFunction, oneByOne=True)[source]#
This method transforms the domain of 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.
- Parameters:
modelFunction (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.
oneByOne (boolean, optional) – If True, evaluate Function in each sample point separately. If False, evaluates Function in vectorized form. Default is True.
- 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.setDiscreteBasedOnModel(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 in place replacement of the original Function object source.
2. This method is similar to setDiscrete, but it uses the domain of a model Function to define the domain of the new Function instance.
- reset(inputs=None, outputs=None, interpolation=None, extrapolation=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.setInputs for more information.
outputs (string, sequence of strings, optional) – List of output variable names. If None, the original outputs are kept. See Function.setOutputs for more information.
interpolation (string, optional) – Interpolation method to be used if source type is ndarray. See Function.setInterpolation for more information.
extrapolation (string, optional) – Extrapolation method to be used if source type is ndarray. See Function.setExtrapolation 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.getInputs(), v.getOutputs() (['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:
- getValue(*args)[source]#
This method returns the value of the Function at the specified point. See Function.getValueOpt 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
- Return type:
scalar, list
- getValueOpt_deprecated(*args)[source]#
THE CODE BELOW IS HERE FOR DOCUMENTATION PURPOSES ONLY. IT WAS REPLACED FOR ALL INSTANCES BY THE FUNCTION.SETGETVALUEOPT METHOD.
This method returns the value of the Function at the specified point in a limited but optimized manner. See Function.getValue for an implementation which allows more kinds of inputs. This method optimizes the Function.getValue method by only implementing function evaluations of single inputs, i.e., it is not vectorized. Furthermore, it actually implements a different method for each interpolation type, eliminating some if statements. Currently supports callables and spline, linear, akima, polynomial and shepard interpolated Function objects.
- Parameters:
args (scalar) – Value where the Function is to be evaluated. If the Function is 1-D, only one argument is expected, which may be an int or a float If the function is N-D, N arguments must be given, each one being an int or a float.
- Returns:
x
- Return type:
scalar
- getValueOpt2(*args)[source]#
DEPRECATED!! - See Function.getValueOpt for new version. This method returns the value of the Function at the specified point in a limited but optimized manner. See Function.getValue for an implementation which allows more kinds of inputs. This method optimizes the Function.getValue method by only implementing function evaluations of single inputs, i.e., it is not vectorized. Furthermore, it actually implements a different method for each interpolation type, eliminating some if statements. Finally, it uses Numba to compile the methods, which further optimizes the implementation. The code below is here for documentation purposes only. It is overwritten for all instances by the Function.setGetValuteOpt2 method.
- Parameters:
args (scalar) – Value where the Function is to be evaluated. If the Function is 1-D, only one argument is expected, which may be an int or a float If the function is N-D, N arguments must be given, each one being an int or a float.
- Returns:
x
- Return type:
scalar
- toFrequencyDomain(lower, upper, samplingFrequency, removeDC=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.
samplingFrequency (float) – Sampling frequency at which to perform the Fourier transform.
removeDC (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 >>> mainFrequency = 10 # Hz >>> time = np.linspace(0, 10, 1000) >>> signal = np.sin(2 * np.pi * mainFrequency * time) >>> timeDomain = Function(np.array([time, signal]).T) >>> frequencyDomain = timeDomain.toFrequencyDomain(lower=0, upper=10, samplingFrequency=100) >>> peakFrequenciesIndex = np.where(frequencyDomain[:, 1] > 0.001) >>> peakFrequencies = frequencyDomain[peakFrequenciesIndex, 0] >>> print(peakFrequencies) [[-10. 10.]]
- plot(*args, **kwargs)[source]#
Call Function.plot1D if Function is 1-Dimensional or call Function.plot2D if Function is 2-Dimensional and forward arguments and key-word arguments.
- plot1D(lower=None, upper=None, samples=1000, forceData=False, forcePoints=False, returnObject=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.
forceData (Boolean, optional) – If Function is given by an interpolated dataset, setting forceData to True will plot all points, as a scatter, in the dataset. Default value is False.
forcePoints (Boolean, optional) – Setting forcePoints 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(lower=None, upper=None, samples=[30, 30], forceData=True, dispType='surface')[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.
forceData (Boolean, optional) – If Function is given by an interpolated dataset, setting forceData to True will plot all points, as a scatter, in the dataset. Default value is False.
dispType (string, optional) – Display type of plotted graph, which can be surface, wireframe, contour, or contourf. Default value is surface.
- Return type:
None
- static comparePlots(plot_list, lower=None, upper=None, samples=1000, title='', xlabel='', ylabel='', forceData=False, forcePoints=False, returnObject=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.
forceData (Boolean, optional) – If Function is given by an interpolated dataset, setting forceData to True will plot all points, as a scatter, in the dataset. Default value is False.
forcePoints (Boolean, optional) – Setting forcePoints 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
- 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
- rocketpy.Function.funcify_method(*args, **kwargs)[source]#
Decorator factory to wrap methods as Function objects and save them as cached properties.
- Parameters:
*args (list) – Positional arguments to be passed to rocketpy.Function.
**kwargs (dict) – Keyword arguments to be passed to rocketpy.Function.
- Returns:
decorator – Decorator function to wrap callables as Function objects.
- Return type:
function
Examples
There are 3 types of methods that this decorator supports:
Method which returns a valid rocketpy.Function source argument.
>>> from rocketpy.Function import funcify_method >>> class Example(): ... @funcify_method(inputs=['x'], outputs=['y']) ... def f(self): ... return lambda x: x**2 >>> example = Example() >>> example.f Function from R1 to R1 : (x) → (y)
Normal algebra can be performed afterwards:
>>> g = 2*example.f + 3 >>> g(2) 11
2. Method which returns a rocketpy.Function instance. An interesting use is to reset input and output names after algebraic operations.
>>> class Example(): ... @funcify_method(inputs=['x'], outputs=['x**3']) ... def cube(self): ... f = Function(lambda x: x**2) ... g = Function(lambda x: x**5) ... return g / f >>> example = Example() >>> example.cube Function from R1 to R1 : (x) → (x**3)
Method which is itself a valid rocketpy.Function source argument.
>>> class Example(): ... @funcify_method('x', 'f(x)') ... def f(self, x): ... return x**2 >>> example = Example() >>> example.f Function from R1 to R1 : (x) → (f(x))
In order to reset the cache, just delete de attribute from the instance:
>>> del example.f
Once it is requested again, it will be re-created as a new Function object:
>>> example.f Function from R1 to R1 : (x) → (f(x))