Skip to content
sarasame00 edited this page Sep 16, 2024 · 8 revisions

Data Analysis and Curve Fitting Library

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.

Table of Contents

Imports and Authentication

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.

Variable Class

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)

Table Class

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.

Class Attributes

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

Methods


__init__(self)

Initializes a new 'Table' instance with an empty data table, history stack, and redo stack.


save_state(self)

Saves the current state of the table to allow undo functionality. Clears the redo stack when a new change is made.


undo(self)

Reverts the table to the previous state. If no actions are available to undo, prints an error message.


redo(self)

Restores the last undone state of the table.If no actions are available to undo, prints an error message.


print_data(self)

Prints the current state of the table. If the table is empty, prints an appropriate message.


add_row(self, row_values, index=None)

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.


delete_row(self, index)

Deletes a row at the specified index.

  • Parameters:

  • index: Position of the row to delete.

  • Errors:

  • Index out of bounds.


add_column(self, col_values, index=None)

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.


delete_column(self, index)

Deletes a column at the specified index.

  • Parameters:
  • index: Position of the column to delete.
  • Errors:
  • Table is empty.
  • Index out of bounds.

change_value(self, row, col, new_value)

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.

add_uncertainties(self, uncertainties, axis='column', index=0)

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_from_range(self, fileName, sheetName, cellRange)

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.

transpose(self)

Transposes the table, switching rows and columns.

  • Errors:
  • Table is empty.
  • Row length mismatch, making the transpose operation invalid.

latex_table(self, caption='', label='', hlines='all', vlines='none')

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 hlines or vlines.

Functions

importData

Import data from a specified range in a Google Sheet using Excel-style range notation.

Signature:

importData(fileName, sheetName, cellRange, orientation='columns', data_type='numeric')

Parameters:

  • fileName (str): The name of the Google Sheet file.
  • sheetName (str): The specific worksheet within the Google Sheet.
  • cellRange (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 = importData('MySheet', 'Sheet1', 'A1:B10', orientation='rows', data_type='numeric')
print(data)

safe_eval

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

curveFit

Fit a curve to the provided data using the given function.

Signature:

curveFit(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 = curveFit(linear_func, x, y)
print(fit_results)

regression

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)

propUncertainty

Propagate uncertainties through a symbolic function using partial derivatives.

Signature:

propUncertainty(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:

var1 = Variable('x', 1.0, 0.1)
var2 = Variable('y', 2.0, 0.2)

func = x.sim**2 + y.sim**2

values, uncertainties = propUncertainty(func, [var1, var2])
print(values)
print(uncertainties)

mean

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)

plotData

Plot data with error bars on the specified axis.

Signature:

plotData(ax, x, y, label=None, color='k', marker='o', markersize=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').
  • markersize (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]))

plotData(ax, x, y, label='Data Points', color='b')

plt.show()

plotFit

Plot data with error bars and optionally fit a curve to the data.

Signature:

plotFit(ax, x, y, fit_func, label='Curve Fit', color='k', xrange=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').
  • xrange (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]))

plotFit(ax, x, y, fit_func=linear_func, label='Linear Fit', color='r')

plt.show()

Clone this wiki locally