Skip to content

ENH: adds new Function.savetxt method #514

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jan 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ straightforward as possible.

### Added

- ENH: adds new Function.savetxt method [#514](https://github.com/RocketPy-Team/RocketPy/pull/514)
- ENH: Argument for Optional Mutation on Function Discretize [#519](https://github.com/RocketPy-Team/RocketPy/pull/519)

### Changed
Expand Down Expand Up @@ -63,8 +64,8 @@ You can install this version by running `pip install rocketpy==1.1.3`

### Fixed

- FIX: Broken Function.get_value_opt for N-Dimensional Functions [#492](https://github.com/RocketPy-Team/RocketPy/pull/492)
- FIX: Never ending Flight simulations when using a GenericMotor [#497](https://github.com/RocketPy-Team/RocketPy/pull/497)
- FIX: Broken Function.get_value_opt for N-Dimensional Functions [#492](https://github.com/RocketPy-Team/RocketPy/pull/492)
- FIX: Never ending Flight simulations when using a GenericMotor [#497](https://github.com/RocketPy-Team/RocketPy/pull/497)

## [v1.1.2] - 2023-11-25

Expand Down
32 changes: 32 additions & 0 deletions docs/user/function.rst
Original file line number Diff line number Diff line change
Expand Up @@ -406,6 +406,38 @@ Here we have shown that we can integrate the gaussian function over a defined in
# Compare the function with the integral
Function.compare_plots([f, f_int], lower=-4, upper=4)

e. Export to a text file (CSV or TXT)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Since rocketpy version 1.2.0, the ``Function`` class supports exporting the
source data to a CSV or TXT file. This is accomplished by the method
:meth:`rocketpy.Function.savetxt` and allows for easy data exportation for
further analysis.

Let's export the gaussian function to a CSV file:

.. jupyter-execute::

# Define the gaussian function
def gaussian(x):
return 1 / np.sqrt(2*np.pi) * np.exp(-x**2/2)

f = Function(gaussian, inputs="x", outputs="f(x)")

# Export to CSV
f.savetxt("gaussian.csv", lower=-4, upper=4, samples=20, fmt="%.2f")

# Read the CSV file
import pandas as pd
pd.read_csv("gaussian.csv")


.. jupyter-execute::

# Delete the CSV file
import os
os.remove("gaussian.csv")

........

This guide shows some of the capabilities of the ``Function`` class, but there are many other functionalities to enhance your analysis. Do not hesitate in tanking a look at the documentation :class:`rocketpy.Function`.
74 changes: 73 additions & 1 deletion rocketpy/mathutils/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@
"""
import warnings
from collections.abc import Iterable
from copy import deepcopy
from inspect import signature
from pathlib import Path

import matplotlib.pyplot as plt
import numpy as np
from copy import deepcopy
from scipy import integrate, linalg, optimize

try:
Expand Down Expand Up @@ -2855,6 +2855,78 @@ def compose(self, func, extrapolate=False):
extrapolation=self.__extrapolation__,
)

def savetxt(
self,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What do you think of having to_txt and to_csv methods instead of just savetxt?
This would make sense if we were ever to add a way to save a function to a .json for example, with to_json

It seems you got savetxt from numpy. The to_ functions come from pandas

This is just a loose suggestion. I don't mind the current name

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, just saw what you commented in the description. I still think it could be more descriptive to use to_ names

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an interesting suggestion.

Between numpy and pandas, I have to say that numpy might be a better inspiration in this case, since pandas is not one of the rocketpy's dependency.

Beyond that, I believe we need to be careful with the to_ methods, let's see:

  • .savetxt: takes a Function instance and save its source to a text file, where each row represents one point from the source.
  • .savecsv: this call the savetxt method above but modify the file extension to .csv
  • .to_json (or other similar name like ``) takes the Function instance and create a json file with different attributes from the object (e.g. interpolation method, inputs and outputs names, repr method, etc.)

If we change the savetxt to to_txt we would be creating an opportunity for confusion since the to_txt and to_json would export totally different contents.
There's a reason for having the save methods to save the source and the to_ methods to convert the entire object to something else.

Let me know in case your disagree with this.

The #522 might be connected to this comment too.

filename,
lower=None,
upper=None,
samples=None,
fmt="%.6f",
delimiter=",",
newline="\n",
encoding=None,
):
"""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 : float 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.
upper : float 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.
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.
"""
# create the header
header_line = delimiter.join(self.__inputs__ + self.__outputs__)

# create the datapoints
if callable(self.source):
if lower is None or upper is None or samples is None:
raise ValueError(
"If the source is a callable, lower, upper and samples"
+ " must be provided."
)
# Generate the data points using the callable
x = np.linspace(lower, upper, samples)
data_points = np.column_stack((x, self.source(x)))
else:
# If the source is already an array, use it as is
data_points = self.source

if lower and upper and samples:
data_points = self.set_discrete(
lower, upper, samples, mutate_self=False
).source

# export to a file
with open(filename, "w", encoding=encoding) as file:
file.write(header_line + newline)
np.savetxt(file, data_points, fmt=fmt, delimiter=delimiter, newline=newline)

@staticmethod
def _check_user_input(
source,
Expand Down
15 changes: 15 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -1166,3 +1166,18 @@ def func_2d_from_csv():
source="tests/fixtures/function/2d.csv",
)
return func


@pytest.fixture
def lambda_quad_func():
"""Create a lambda function based on a string.

Returns
-------
Function
A lambda function based on a string.
"""
func = lambda x: x**2
return Function(
source=func,
)
66 changes: 66 additions & 0 deletions tests/unit/test_function.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
"""Unit tests for the Function class. Each method in tis module tests an
individual method of the Function class. The tests are made on both the
expected behaviour and the return instances."""

import os

import numpy as np
import pytest

Expand Down Expand Up @@ -160,6 +166,66 @@ def test_get_value_opt(x, y, z):
assert np.isclose(func.get_value_opt(x, y), z, atol=1e-6)


@pytest.mark.parametrize(
"func",
[
"linearly_interpolated_func",
"spline_interpolated_func",
"func_2d_from_csv",
"lambda_quad_func",
],
)
def test_savetxt(request, func):
"""Test the savetxt method of various Function objects.

This test function verifies that the `savetxt` method correctly writes the
function's data to a CSV file and that a new function object created from
this file has the same data as the original function object.

Notes
-----
The test performs the following steps:
1. It invokes the `savetxt` method of the given function object.
2. It then reads this file to create a new function object.
3. The test asserts that the data of the new function matches the original.
4. Finally, the test cleans up by removing the created CSV file.

Raises
------
AssertionError
If the `savetxt` method fails to save the file, or if the data of the
newly read function does not match the data of the original function.
"""
func = request.getfixturevalue(func)
assert (
func.savetxt(
filename="test_func.csv",
lower=0,
upper=9,
samples=10,
fmt="%.6f",
delimiter=",",
newline="\n",
encoding=None,
)
is None
), "Couldn't save the file using the Function.savetxt method."

read_func = Function(
"test_func.csv", interpolation="linear", extrapolation="natural"
)
if callable(func.source):
source = np.column_stack(
(np.linspace(0, 9, 10), func.source(np.linspace(0, 9, 10)))
)
assert np.allclose(source, read_func.source)
else:
assert np.allclose(func.source, read_func.source)

# clean up the file
os.remove("test_func.csv")


@pytest.mark.parametrize("samples", [2, 50, 1000])
def test_set_discrete_mutator(samples):
"""Tests the set_discrete method of the Function class."""
Expand Down