-
Notifications
You must be signed in to change notification settings - Fork 0
Home
This repository provides a set of functions and classes for data analysis, curve fitting, and symbolic mathematics. It includes utilities for importing data from Google Sheets, performing curve fitting, linear regression, uncertainty propagation, and plotting data with error bars.
The following libraries are used:
-
numpy: For numerical operations. -
gspread: For accessing Google Sheets via API. -
google.auth: For Google authentication. -
matplotlib.pyplot: For plotting. -
sympy: For symbolic mathematics. -
scipy.optimize.curve_fit: For fitting curves to data.
Authentication is handled through Google Colab, which requires user authentication to access Google Sheets.
A class representing a variable with symbolic representation, value, and uncertainty.
Signature:
Variable(sim, val, inc)Constructor:
__init__(self, sim, val, inc)
Parameters:
-
sim(str): Symbolic name of the variable. -
val(float): The value of the variable. -
inc(float): The uncertainty associated with the variable.
Usage Example:
var = Variable('x', 5.0, 0.1)
print(var.sim)
print(var.val)
print(var.inc)The Table class provides functionality to manage tabular data with methods for adding/removing rows and columns, changing values, transposing the table generating LaTex code, and supporting undo/redo operations.
-
data: A list of lists representing the current state of the table. -
history: A list to store previous states of the table (for undo functionality): -
redo_stack: A list to store states that can be restored after undoing changes.
Initializes a new 'Table' instance with an empty data table, history stack, and redo stack.
Saves the current state of the table to allow undo functionality. Clears the redo stack when a new change is made.
Reverts the table to the previous state. If no actions are available to undo, prints an error message.
Restores the last undone state of the table.If no actions are available to undo, prints an error message.
Prints the current state of the table. If the table is empty, prints an appropriate message.
Adds a row to the table.
-
Parameters:
-
row_values: List of values for the row. *index: (Optional) Position to insert the row. If not provided, the row is added at the end. -
Errors:
-
Index out of bounds.
-
Row length mismatch with existing columns.
Deletes a row at the specified index.
-
Parameters:
-
index: Position of the row to delete. -
Errors:
-
Index out of bounds.
Add a column to the table.
-
Parameters: *
col_values: List of values for the new column. -
index: (Optional) Position to insert the column. If not provided, the column is added at the end. -
Errors:
-
Table is empty.
-
Column length mismatch with existing rows.
Deletes a column at the specified index.
- Parameters:
-
index: Position of the column to delete. - Errors:
- Table is empty.
- Index out of bounds.
Changes the value at specific row and column.
- Parameters:
-
row: The row index. -
col: The column index. -
new_value: The new value to be assigned. - Errors:
- Index out of bounds for rows or columns.
Adds uncertainties to either a row or a column.
- Parameters:
-
uncertainties: List of uncertainties to add. -
axis: Specifies whether the uncertainties should be added to a 'column' or a 'row'. -
index: Index of the row/column where uncertainties will be added. - Errors:
- Length mismatch with the number of rows/columns.
- Invalid axis input.
Import data from a specified range in a Google Sheet.
- Parameters:
-
fileName: Name of the Google Sheet. -
sheetName: Sheet within the Google Sheet. -
cellRange: The cell range to import data from. - Errors:
- Issues with accessing the Google Sheets API.
- Error retrieving the specified range.
Transposes the table, switching rows and columns.
- Errors:
- Table is empty.
- Row length mismatch, making the transpose operation invalid.
Generates LaTeX code to represent the current table.
- Parameters:
-
caption: (Optional) Caption of the LaTeX table. -
label: (Optional) Label for referencing the table. -
hlines: Specifies horizontal lines (options: 'all, 'none', or list of '0'/'1'). -
vlines: Specifies vertical lines (options: 'all, 'none', or list of '0'/'1'). - Errors:
- Empty table.
- Invalid length for
hlinesorvlines.
Import data from a specified range in a Google Sheet using Excel-style range notation.
Signature:
import_data(file_name, sheet_name, cell_range, orientation='columns', data_type='numeric')Parameters:
-
file_name(str): The name of the Google Sheet file. -
sheet_name(str): The specific worksheet within the Google Sheet. -
cell_range(str): The range of cells to import (e.g., 'A1:A10', 'B2:F7', 'A1'). -
orientation(str, optional): 'columns' or 'rows' (default: 'columns'). -
data_type(str, optional): 'numeric' (default), 'string', or 'raw'.
Returns:
- A list, list of lists, or single value depending on the range.
Usage Example:
data = import_data('MySheet', 'Sheet1', 'A1:B10', orientation='rows', data_type='numeric')
print(data)Convert a string to a float, handling non-numeric values gracefully.
Signature:
safe_eval(value)Parameters:
-
value(str): The string to be converted.
Returns:
-
float: The converted float value or NaN if conversion fails.
Usage Example:
value = safe_eval('1234.56')
print(value) # Output: 1234.56
value = safe_eval('not a number')
print(value) # Output: nanFit a curve to the provided data using the given function.
Signature:
fit_curve(func, x, y)Parameters:
-
func(callable): The function to use for fitting. -
x(array-like): Data for the independent variable. -
y(array-like): Data for the dependent variable.
Returns:
-
dict: Contains 'parameters', 'parameter_uncertainties', and 'r_squared'.
Usage Example:
def linear_func(x, a, b):
return a * x + b
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.2, 2.8, 3.6, 4.5, 5.1])
fit_results = fit_curve(linear_func, x, y)
print(fit_results)Conduct linear regression on the data and present the results.
Signature:
regression(x, y, table=False)Parameters:
-
x(array-like): Data for the independent variable. -
y(array-like): Data for the dependent variable. -
table(bool, optional): Display results in LaTeX table format if True (default: False).
Returns:
-
dict: Contains 'slope', 'intercept', and 'r_squared'.
Usage Examples:
x = np.array([1, 2, 3, 4, 5])
y = np.array([2.2, 2.8, 3.6, 4.5, 5.1])
results = regression(x, y)
print(results)Propagate uncertainties through a symbolic function using partial derivatives.
Signature:
prop_uncertainty(fun, variables)Parameters:
-
fun(sympy expression): The symbolic function for uncertainty propagation. -
variables(list of Variable or Variable): Variables with uncertainties.
Returns:
-
tuple: Contains lists of evaluated function values and uncertainties.
Usage Example:
x = Variable('x', 1.0, 0.1)
y = Variable('y', 2.0, 0.2)
func = x.sim**2 + y.sim**2
values, uncertainties = propUncertainty(func, [x, y])
print(values)
print(uncertainties)Compute the mean and combined uncertainty of a set of measurements.
Signature:
mean(values, instrumental_error)Parameters:
-
values(list of float): The measured values. -
instrumental_error(float): The uncertainty associated with the measurement process.
Returns:
-
tuple: Mean of the values and combined uncertainty.
Usage Example:
values = [1.0, 1.1, 1.2, 0.9]
instrumental_error = 0.05
mean_value, combined_uncertainty = mean(values, instrumental_error)
print(mean_value)
print(combined_uncertainty)Plot data with error bars on the specified axis.
Signature:
plot_data(ax, x, y, label=None, color='k', marker='o', marker_size=3)Parameters:
-
ax(matplotlib.axes.Axes): The axis object from Matplotlib. -
x(Variable): Data for the independent variable with uncertainties. -
y(Variable): Data for the dependent variable with uncertainties. -
label(str, optional): Label for the data series (default: None). -
color(str, optional): Color for the data points and error bars (default: 'k'). -
marker(str, optional): Marker style (default: 'o'). -
marker_size(int, optional): Size of the markers (default: 3).
Raises:
-
TypeError: If x or y are not instances of the Variable class.
Usage Example:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
x = Variable('x', np.array([1, 2, 3]), np.array([0.1, 0.1, 0.1]))
y = Variable('y', np.array([2, 4, 6]), np.array([0.2, 0.2, 0.2]))
plot_data(ax, x, y, label='Data Points', color='b')
plt.show()Plot data with error bars and optionally fit a curve to the data.
Signature:
plot_fit(ax, x, y, fit_func, label='Curve Fit', color='k', x_range=None)Parameters:
-
ax(matplotlib.axes.Axes): The axis object from Matplotlib. -
x(Variable): Data for the independent variable with uncertainties. -
y(Variable): Data for the dependent variable with uncertainties. -
fit_func(callable, optional): Function to fit to the data (default: None). -
label(str, optional): Label for the fit curve (default: 'Curve Fit'). -
color(str, optional): Color for the fit curve (default: 'k'). -
x_range(tuple, optional): Range for the x-axis (default: None).
Raises:
-
TypeError: If x or y are not instances of the Variable class.
Usage Example:
import matplotlib.pyplot as plt
def linear_func(x, a, b):
return a * x + b
fig, ax = plt.subplots()
x = Variable('x', np.array([1, 2, 3]), np.array([0.1, 0.1, 0.1]))
y = Variable('y', np.array([2, 4, 6]), np.array([0.2, 0.2, 0.2]))
plot_fit(ax, x, y, fit_func=linear_func, label='Linear Fit', color='r')
plt.show()