Name | pysics JSON |
Version |
0.1.0
JSON |
| download |
home_page | None |
Summary | Library to make laboratory calculations easy |
upload_time | 2024-09-24 09:59:01 |
maintainer | None |
docs_url | None |
author | None |
requires_python | >=3.12 |
license | None |
keywords |
physics
laboratory
units
least squares
|
VCS |
|
bugtrack_url |
|
requirements |
No requirements were recorded.
|
Travis-CI |
No Travis.
|
coveralls test coverage |
No coveralls.
|
# Pysics
Pysics is a Python module designed to perform calculations typically done in physics laboratories. It is based on the use of the "Measure" class, which allows storing measures with errors and performing standard approximation (first significant digit of the error, two if it is a 1).
## Table of Contents
1. [Installation](#installation)
2. [Basic Operations](#basic-operations)
3. [Units](#units)
4. [Plot](#plot)
5. [Fit](#fit)
6. [Func](#func)
7. [Read](#read)
8. [Tables](#tables)
9. [Acknowledgements](#acknowledgements)
## Installation
The library is available in pip so you can install it with:
```
pip install pysics
```
## Basic Operations
The fundamental part of the module is the Measure class. Initializing an object can be done in several ways.
```python
# If it is a measure without error because it is negligible or for some other reason, it can be done simply by passing the value
m = Measure(9.81)
# If we have an error, it will be passed as the second argument, e.g., (7.831 ± 0.0138).
a = Measure(7.831, 0.0138)
```
If we execute the previous line, we will see that the result of `a` is 7.831 ± 0.014.
This is because by default, Measure performs the approximation when initializing the object.
To avoid this, you can pass the argument `approximate=False`
```python
b = Measure(7.831, 0.0138, approximate=False)
```
If we want to perform the approximation later, it can be done with `.approx()`
```python
b.approx()
# approx also returns a pointer to the object, which allows things like
b = b.approx()
# now a==b
# or
c = (a+b).approx()
# which would be equivalent to
c = a+b
c.approx()
```
Measures can also be a list of several values, e.g., c = 1.1 ± 0.1, 2.2 ± 0.1, 3.3 ± 0.1
```python
# Since all values have the same error, it is enough to write it once
c = Measure([1.1, 2.2, 3.3], 0.1, approximate=False)
```
d = 1.1 ± 0.1, 2.2 ± 0.2, 3.3 ± 0.3
In this case, there are different errors, so two lists are passed: the first contains the values, and the second contains the errors such that the index of each list is a value and its corresponding error. If the lists do not have the same length, an error will be thrown.
```python
d = Measure([1.1, 2.2, 3.3], [0.1, 0.2, 0.3])
```
For this kind of Measures, the class method "from_pairs" is provided, which allows passing a list of values in tuples.
The following code is equivalent to the previous one.
```python
d = Measure.from_pairs([1.1, 0.1], [2.2, 0.2], [3.3, 0.3], approximate=True)
```
Measure objects can be added, subtracted, multiplied, etc., by other Measures and by scalars, always returning other Measures.
Additionally, approximations will not be performed when making a calculation; this is to allow concatenating several operations without losing precision.
When performing these calculations, errors are recalculated. For ALL cases except & and ||, Measures are considered independent, so the error is the sum in quadrature.
Operations between Measures are defined element by element, i.e., the first is added to the first, the second to the second, etc.
Operations with scalars are defined as the operation of the scalar over the entire measure, e.g., c+1 will result in Measure([1.1 + 1, 2.2 + 1, 3.3 + 1], [0.1], approximate=False).
If there is a measure with a single value, e.g., Measure(1, 0.1), it will be considered as a scalar taking into account the error. If two Measures with different numbers of elements are added, and neither has a single element, e.g., Measure([1, 2]) + Measure([1, 2, 3]), an error will be thrown.
``` python
e = (a+b).approx() # 15.662 ± 0.02
f = (c*d).approx() # 1.21 ± 0.16, 4.8 ± 0.5, 10.9 ± 1.0
```
If two Measures are dependent and want to be added or subtracted, the operators & and | should be used.
```python
# To add dependent Measures, use the & operator
h = (a&b).approx() # 15.66 ± 0.03
# To subtract dependent Measures, use the | operator
i = (a|b).approx() # 0.0 ± 0.03 equivalent to (a&(-b))
```
To make copies of a measure, you can use the copy method.
In the following example, a copy with the approximations of c is made without modifying c.
```python
j = c.copy().approx()
# If instead of the above we used the following, we would modify c, and it is possible that certain changes applied to j would affect c
j = c.approx()
```
To retrieve the values of the Measures or errors in a list, you can use the properties `measure` and `error`.
```python
print(d.value) # [1.1, 2.2, 3.3]
print(d.error) # [0.1, 0.2, 0.3]
measure, error = d.unpack()
```
To calculate the mean, standard deviation, and standard error of a measure, you can use the methods of the same name.
```python
mean = d.mean()
standard_deviation = d.standard_deviation()
standard_error = d.standard_error() # Standard deviation of the mean
mean, standard_error = d.estimation()
```
## Units
The `Measure` object also supports operations with units. To create a `Measure` with units, you can simply multiply by the unit:
```python
a = Measure(2, 0.1) * kg
print(a) # 2 ± 0.1 kg
```
This will create `a` as a measure with `kg` as its unit. The most common units are predefined in *units* for your convenience. However, you can also create your own unit using the `Unit` class constructor:
```python
year = Unit(s, scale=365.25*24*3600, symbol="year")
```
To define a custom unit:
1. Provide its equivalent in the [International System of Units (SI)](https://en.wikipedia.org/wiki/International_System_of_Units). This can be a combination of existing units.
2. Specify the `scale` factor to convert your unit to the SI unit.
3. Set a `symbol` for concise representation of the unit.
The `scale` is the factor you multiply your unit by to convert it to the SI unit. The `symbol` is used for formatting when printing the value with its unit.
Once created, you can use your custom unit just like the predefined ones.
## Plot
Pysics also provides a powerful plotting API that integrates seamlessly with the `Measure` class. It offers various types of plots and data fitting capabilities.
### Basic Plotting
The plotting module supports different types of plots, including scatter, line and polar plots. Here's an example using them:
```python
from pysics.plot import scatter, plot, polar_plot, show, legend
from pysics.constants import pi
import numpy as np
x = Measure([1, 2, 3, 4, 5], 0.1)
y = Measure([2, 4, 5, 4, 5], 0.2)
# Create a scatter plot with error bars
scatter(x, y, xerr=True, yerr=True, label='Data with Errors')
# The xerr and yerr parameters set to True tell the function to use the errors from the Measure objects. You can also pass a list of errors to them and it will use that list as errors.
# Create a line plot using the same data
plot(x, y, label='Data Line')
# Create a polar plot
theta = np.linspace(0, 2*pi, 100)
r = np.cos(4*theta)
polar_plot(theta, r, label='Polar Data')
# Displays the labels
legend()
# Display the plots
show()
```
This example demonstrates how to create diferent plots with error bars using Measure objects. The `scatter` function automatically uses the error values from the Measure objects when `xerr` and `yerr` are set to True. There is also a `polar_scatter` function.
### Customizing Plots
Pysics allows for extensive customization of plots, including the use of LaTeX for rendering labels:
```python
from pysics.plot import scatter, xlabel, ylabel, title, use_latex, show
use_latex() # Enable LaTeX rendering
x = [1,2,3,4]
y = [1,2,3,4]
scatter(x, y)
# Set axis labels and title using LaTeX syntax
xlabel(r'$x$ axis')
ylabel(r'$y$ axis')
title(r'Plot with $\LaTeX$ labels')
show()
```
The `use_latex()` function enables LaTeX rendering for all text elements in the plot. The `r` prefix before the strings denotes raw strings, which is useful when writing LaTeX code to avoid issues with backslashes.
Furthermore, since Pysics uses Matplotlib underneath, you can use Matplotlib functions to further customize your plots.
### Saving Plots
Saving plots to various file formats is straightforward:
```python
from pysics.plot import scatter, save
scatter(x, y)
save('my_plot', format='png')
```
This code creates a scatter plot and saves it as 'my_plot.png' in the current directory. The `save` function supports various formats including 'png', 'pdf', 'svg', and more.
## Fit
The Fit module in Pysics provides functions for fitting data to various models using measures. Here's an example of a linear fit:
```python
from pysics.fit import least_squares
from pysics.plot import scatter, line
x = Measure([1, 2, 3, 4, 5], 0.3)
y = Measure([2.1, 3.9, 6.2, 7.8, 9.9], 0.1)
# Perform a linear fit
fit_result = least_squares(x, y)
# Plot the original data
scatter(x, y)
# Plot the fit line
line(x, fit_result)
show()
```
In this example, `least_squares` performs a linear fit on the data. The resulting `fit_result` contains the parameters of the fit (slope and intercept) as Measure objects, including the errors of the fit. The `line` function then uses these parameters to plot the fit line.
Here's another example of fitting data, this time we use a custom function:
```python
from pysics.fit import curve as curve_fit
from pysics.plot import curve as curve_plot, show
def quadratic(x, a, b, c):
return a * x**2 + b * x + c
x = [0, 1, 2, 3, 4, 5]
y = [1, 2.1, 5.2, 10.3, 17.4, 26.5]
fit_params = curve_fit(quadratic, x, y)
# Plot the fit curve
curve_plot(quadratic, x, fit_params)
show()
```
In this example:
1. We define a quadratic function `quadratic(x, a, b, c)` that represents our model.
2. We provide x and y data points.
3. The `curve_fit` function fits the data to the quadratic model.
4. `fit_params` contains the best-fit values for a, b, and c as Measure objects, including their uncertainties.
5. `curve_plot` function plots the obtained curve.
This powerful fitting capability allows you to fit your data to any custom function, making it versatile for various scientific applications.
## Func
The `func` module provides a comprehensive set of mathematical and physics-related functions that work seamlessly with the `Measure` class. The functions available are:
1. Trigonometric functions: sin, cos, tan, and their inverses (asin, acos, atan)
2. Angular conversions: rad (degrees to radians) and grad (radians to degrees)
3. Logarithmic and exponential functions: ln, exp
4. Other mathematical operations: sqrt, atan2 (polar coordinate angle)
5. Utility functions: delta (difference between consecutive values)
All these functions are designed to work with `Measure` objects, handling both scalar and array inputs.
Examples of usage:
1. Trigonometric functions:
```python
from pysics import Measure, units, func
angle = Measure(45, 1, units=units.deg)
sin_value = func.sin(func.rad(angle))
print(f"sin(45°) = {sin_value}")
```
2. Inverse trigonometric functions:
```python
x = Measure(0.5, 0.01)
angle = func.asin(x)
print(f"arcsin(0.5) = {angle}")
```
3. Logarithmic and exponential functions:
```python
value = Measure(10, 0.1)
log_value = func.ln(value)
exp_value = func.exp(Measure(1, 0.01))
print(f"ln(10) = {log_value}")
print(f"e^1 = {exp_value}")
```
4. Square root:
```python
number = Measure(16, 0.5)
root = func.sqrt(number)
print(f"sqrt(16) = {root}")
```
5. Polar coordinate angle:
```python
x = Measure(3, 0.1)
y = Measure(4, 0.1)
angle = func.atan2(y, x)
print(f"atan2(4, 3) = {angle}")
```
6. Delta function (for array inputs):
```python
values = Measure([1, 3, 6, 10], [0.1, 0.1, 0.2, 0.2])
differences = func.delta(values)
print(f"Differences: {differences}")
```
These functions automatically handle error propagation, making it easy to perform complex calculations while keeping track of uncertainties. They also include warnings for potentially incorrect usage, such as passing non-angular values to trigonometric functions.
## Read
The `reader` module in Pysics provides functions for loading data from files and saving data in LaTeX format.
To load data from a file:
```python
from pysics.reader import load
data = load("input.txt", separator=",", headers=1)
```
The `load` function parameters are:
- `file`: Path to the input file.
- `separator`: Character used to separate values (default: '\t').
- `line`: Character used to separate rows (default: '\n').
- `decimal`: Character used as decimal separator (default: ',').
- `headers`: Number of header rows to skip (default: 0).
- `by_columns`: If True, organizes data by columns; if False, by rows (default: True).
To save data in LaTeX format:
```python
from pysics.reader import save_latex
save_latex("output.tex", data, separator="&", style=Measure.Style.scientific)
```
The `save_latex` function parameters are:
- `file`: Path to the output file.
- `data`: List of data to be saved.
- `separator`: Character used to separate values (default: '\t').
- `line`: Character used to separate rows (default: '\n').
- `by_columns`: If True, organizes data by columns; if False, by rows (default: True).
- `style`: Style for formatting Measure objects (default: Measure.Style.latex_table).
This function converts the input data to strings, ensures consistent row lengths, and writes the formatted data to the specified file.
## Tables
The `tables` module in Pysics provides utilities for creating and formatting tables in various output formats.
To create a formatted table as a list of lists:
```python
from pysics.tables import create_table_list
data = [[1, 2, 3], [4, 5, 6]]
header = ['A', 'B', 'C']
formatted_table = create_table_list(data, header=header, style=Measure.Style.table)
```
To create a string representation of a table for terminal display:
```python
from pysics.tables import terminal
data = [[1, 2, 3], [4, 5, 6]]
header = ['A', 'B', 'C']
print(terminal(data, header=header))
```
To create a LaTeX representation of a table:
```python
from pysics.tables import latex
data = [[1, 2, 3], [4, 5, 6]]
header = ['A', 'B', 'C']
latex_table = latex(data, header=header, caption="My Table", label="tab:example")
print(latex_table)
```
To create a Typst representation of a table:
```python
from pysics.tables import typst
data = [[1, 2, 3], [4, 5, 6]]
header = ['A', 'B', 'C']
typst_table = typst(data, header=header)
print(typst_table)
```
These functions provide flexible table formatting options for various output formats, making it easy to present data in the desired style for different applications.
## Acknowledgements
Special thanks to [Jonathan Dönszelmann](https://donsz.nl/) for the pypi project name
Raw data
{
"_id": null,
"home_page": null,
"name": "pysics",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.12",
"maintainer_email": null,
"keywords": "physics, laboratory, units, least squares",
"author": null,
"author_email": "asaltanubes <gustavodragonico@gmail.com>, O2s0k0i3 <elultimopekka@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/87/25/e13317ce4cd815d7079ebd8148d4ec9b89d19f8504294873e1e9d56b60d8/pysics-0.1.0.tar.gz",
"platform": null,
"description": "# Pysics\r\nPysics is a Python module designed to perform calculations typically done in physics laboratories. It is based on the use of the \"Measure\" class, which allows storing measures with errors and performing standard approximation (first significant digit of the error, two if it is a 1).\r\n\r\n## Table of Contents\r\n1. [Installation](#installation)\r\n2. [Basic Operations](#basic-operations)\r\n3. [Units](#units)\r\n4. [Plot](#plot)\r\n5. [Fit](#fit)\r\n6. [Func](#func)\r\n7. [Read](#read)\r\n8. [Tables](#tables)\r\n9. [Acknowledgements](#acknowledgements)\r\n\r\n## Installation\r\n\r\nThe library is available in pip so you can install it with:\r\n\r\n```\r\npip install pysics\r\n```\r\n\r\n## Basic Operations\r\nThe fundamental part of the module is the Measure class. Initializing an object can be done in several ways.\r\n```python\r\n# If it is a measure without error because it is negligible or for some other reason, it can be done simply by passing the value\r\nm = Measure(9.81)\r\n# If we have an error, it will be passed as the second argument, e.g., (7.831 \u00b1 0.0138).\r\na = Measure(7.831, 0.0138)\r\n```\r\n\r\nIf we execute the previous line, we will see that the result of `a` is 7.831 \u00b1 0.014.\r\nThis is because by default, Measure performs the approximation when initializing the object.\r\nTo avoid this, you can pass the argument `approximate=False`\r\n```python\r\nb = Measure(7.831, 0.0138, approximate=False)\r\n```\r\n\r\nIf we want to perform the approximation later, it can be done with `.approx()`\r\n```python\r\nb.approx()\r\n# approx also returns a pointer to the object, which allows things like\r\nb = b.approx()\r\n# now a==b\r\n# or\r\nc = (a+b).approx()\r\n# which would be equivalent to\r\nc = a+b\r\nc.approx()\r\n```\r\nMeasures can also be a list of several values, e.g., c = 1.1 \u00b1 0.1, 2.2 \u00b1 0.1, 3.3 \u00b1 0.1\r\n```python\r\n# Since all values have the same error, it is enough to write it once\r\nc = Measure([1.1, 2.2, 3.3], 0.1, approximate=False)\r\n```\r\nd = 1.1 \u00b1 0.1, 2.2 \u00b1 0.2, 3.3 \u00b1 0.3\r\nIn this case, there are different errors, so two lists are passed: the first contains the values, and the second contains the errors such that the index of each list is a value and its corresponding error. If the lists do not have the same length, an error will be thrown.\r\n```python\r\nd = Measure([1.1, 2.2, 3.3], [0.1, 0.2, 0.3])\r\n```\r\nFor this kind of Measures, the class method \"from_pairs\" is provided, which allows passing a list of values in tuples.\r\nThe following code is equivalent to the previous one.\r\n```python\r\nd = Measure.from_pairs([1.1, 0.1], [2.2, 0.2], [3.3, 0.3], approximate=True)\r\n```\r\n\r\nMeasure objects can be added, subtracted, multiplied, etc., by other Measures and by scalars, always returning other Measures.\r\nAdditionally, approximations will not be performed when making a calculation; this is to allow concatenating several operations without losing precision.\r\nWhen performing these calculations, errors are recalculated. For ALL cases except & and ||, Measures are considered independent, so the error is the sum in quadrature.\r\nOperations between Measures are defined element by element, i.e., the first is added to the first, the second to the second, etc.\r\nOperations with scalars are defined as the operation of the scalar over the entire measure, e.g., c+1 will result in Measure([1.1 + 1, 2.2 + 1, 3.3 + 1], [0.1], approximate=False).\r\nIf there is a measure with a single value, e.g., Measure(1, 0.1), it will be considered as a scalar taking into account the error. If two Measures with different numbers of elements are added, and neither has a single element, e.g., Measure([1, 2]) + Measure([1, 2, 3]), an error will be thrown.\r\n``` python\r\ne = (a+b).approx() # 15.662 \u00b1 0.02\r\nf = (c*d).approx() # 1.21 \u00b1 0.16, 4.8 \u00b1 0.5, 10.9 \u00b1 1.0\r\n```\r\nIf two Measures are dependent and want to be added or subtracted, the operators & and | should be used.\r\n```python\r\n# To add dependent Measures, use the & operator\r\nh = (a&b).approx() # 15.66 \u00b1 0.03\r\n# To subtract dependent Measures, use the | operator\r\ni = (a|b).approx() # 0.0 \u00b1 0.03 equivalent to (a&(-b))\r\n```\r\n\r\nTo make copies of a measure, you can use the copy method.\r\nIn the following example, a copy with the approximations of c is made without modifying c.\r\n```python\r\nj = c.copy().approx()\r\n# If instead of the above we used the following, we would modify c, and it is possible that certain changes applied to j would affect c\r\nj = c.approx()\r\n```\r\n\r\nTo retrieve the values of the Measures or errors in a list, you can use the properties `measure` and `error`.\r\n```python\r\nprint(d.value) # [1.1, 2.2, 3.3]\r\nprint(d.error) # [0.1, 0.2, 0.3]\r\nmeasure, error = d.unpack()\r\n```\r\nTo calculate the mean, standard deviation, and standard error of a measure, you can use the methods of the same name.\r\n```python\r\nmean = d.mean()\r\nstandard_deviation = d.standard_deviation()\r\nstandard_error = d.standard_error() # Standard deviation of the mean\r\nmean, standard_error = d.estimation()\r\n```\r\n\r\n## Units\r\n\r\nThe `Measure` object also supports operations with units. To create a `Measure` with units, you can simply multiply by the unit:\r\n\r\n```python\r\na = Measure(2, 0.1) * kg\r\nprint(a) # 2 \u00b1 0.1 kg\r\n```\r\n\r\nThis will create `a` as a measure with `kg` as its unit. The most common units are predefined in *units* for your convenience. However, you can also create your own unit using the `Unit` class constructor:\r\n\r\n```python\r\nyear = Unit(s, scale=365.25*24*3600, symbol=\"year\")\r\n```\r\n\r\nTo define a custom unit:\r\n1. Provide its equivalent in the [International System of Units (SI)](https://en.wikipedia.org/wiki/International_System_of_Units). This can be a combination of existing units.\r\n2. Specify the `scale` factor to convert your unit to the SI unit.\r\n3. Set a `symbol` for concise representation of the unit.\r\n\r\nThe `scale` is the factor you multiply your unit by to convert it to the SI unit. The `symbol` is used for formatting when printing the value with its unit.\r\n\r\nOnce created, you can use your custom unit just like the predefined ones.\r\n\r\n\r\n## Plot\r\n\r\nPysics also provides a powerful plotting API that integrates seamlessly with the `Measure` class. It offers various types of plots and data fitting capabilities.\r\n\r\n### Basic Plotting\r\n\r\nThe plotting module supports different types of plots, including scatter, line and polar plots. Here's an example using them:\r\n\r\n```python\r\nfrom pysics.plot import scatter, plot, polar_plot, show, legend\r\nfrom pysics.constants import pi\r\nimport numpy as np\r\n\r\nx = Measure([1, 2, 3, 4, 5], 0.1)\r\ny = Measure([2, 4, 5, 4, 5], 0.2)\r\n\r\n# Create a scatter plot with error bars\r\nscatter(x, y, xerr=True, yerr=True, label='Data with Errors')\r\n# The xerr and yerr parameters set to True tell the function to use the errors from the Measure objects. You can also pass a list of errors to them and it will use that list as errors.\r\n\r\n# Create a line plot using the same data\r\nplot(x, y, label='Data Line')\r\n\r\n# Create a polar plot\r\ntheta = np.linspace(0, 2*pi, 100)\r\nr = np.cos(4*theta)\r\n\r\npolar_plot(theta, r, label='Polar Data')\r\n\r\n# Displays the labels\r\nlegend()\r\n# Display the plots\r\nshow()\r\n```\r\n\r\nThis example demonstrates how to create diferent plots with error bars using Measure objects. The `scatter` function automatically uses the error values from the Measure objects when `xerr` and `yerr` are set to True. There is also a `polar_scatter` function.\r\n\r\n### Customizing Plots\r\n\r\nPysics allows for extensive customization of plots, including the use of LaTeX for rendering labels:\r\n\r\n```python\r\nfrom pysics.plot import scatter, xlabel, ylabel, title, use_latex, show\r\n\r\nuse_latex() # Enable LaTeX rendering\r\n\r\nx = [1,2,3,4]\r\ny = [1,2,3,4]\r\n\r\nscatter(x, y)\r\n\r\n# Set axis labels and title using LaTeX syntax\r\nxlabel(r'$x$ axis')\r\nylabel(r'$y$ axis')\r\ntitle(r'Plot with $\\LaTeX$ labels')\r\n\r\nshow()\r\n```\r\n\r\nThe `use_latex()` function enables LaTeX rendering for all text elements in the plot. The `r` prefix before the strings denotes raw strings, which is useful when writing LaTeX code to avoid issues with backslashes.\r\n\r\nFurthermore, since Pysics uses Matplotlib underneath, you can use Matplotlib functions to further customize your plots.\r\n\r\n### Saving Plots\r\n\r\nSaving plots to various file formats is straightforward:\r\n\r\n```python\r\nfrom pysics.plot import scatter, save\r\n\r\nscatter(x, y)\r\nsave('my_plot', format='png')\r\n```\r\n\r\nThis code creates a scatter plot and saves it as 'my_plot.png' in the current directory. The `save` function supports various formats including 'png', 'pdf', 'svg', and more.\r\n\r\n\r\n## Fit\r\n\r\nThe Fit module in Pysics provides functions for fitting data to various models using measures. Here's an example of a linear fit:\r\n\r\n```python\r\nfrom pysics.fit import least_squares\r\nfrom pysics.plot import scatter, line\r\n\r\nx = Measure([1, 2, 3, 4, 5], 0.3)\r\ny = Measure([2.1, 3.9, 6.2, 7.8, 9.9], 0.1)\r\n\r\n# Perform a linear fit\r\nfit_result = least_squares(x, y)\r\n\r\n# Plot the original data\r\nscatter(x, y)\r\n\r\n# Plot the fit line\r\nline(x, fit_result)\r\n\r\nshow()\r\n```\r\n\r\nIn this example, `least_squares` performs a linear fit on the data. The resulting `fit_result` contains the parameters of the fit (slope and intercept) as Measure objects, including the errors of the fit. The `line` function then uses these parameters to plot the fit line.\r\n\r\nHere's another example of fitting data, this time we use a custom function:\r\n\r\n```python\r\nfrom pysics.fit import curve as curve_fit\r\nfrom pysics.plot import curve as curve_plot, show\r\n\r\ndef quadratic(x, a, b, c):\r\n return a * x**2 + b * x + c\r\n\r\nx = [0, 1, 2, 3, 4, 5]\r\ny = [1, 2.1, 5.2, 10.3, 17.4, 26.5]\r\n\r\nfit_params = curve_fit(quadratic, x, y)\r\n\r\n# Plot the fit curve\r\ncurve_plot(quadratic, x, fit_params)\r\nshow()\r\n```\r\n\r\nIn this example:\r\n1. We define a quadratic function `quadratic(x, a, b, c)` that represents our model.\r\n2. We provide x and y data points.\r\n3. The `curve_fit` function fits the data to the quadratic model.\r\n4. `fit_params` contains the best-fit values for a, b, and c as Measure objects, including their uncertainties.\r\n5. `curve_plot` function plots the obtained curve.\r\n\r\nThis powerful fitting capability allows you to fit your data to any custom function, making it versatile for various scientific applications.\r\n\r\n## Func\r\n\r\nThe `func` module provides a comprehensive set of mathematical and physics-related functions that work seamlessly with the `Measure` class. The functions available are:\r\n\r\n1. Trigonometric functions: sin, cos, tan, and their inverses (asin, acos, atan)\r\n2. Angular conversions: rad (degrees to radians) and grad (radians to degrees)\r\n3. Logarithmic and exponential functions: ln, exp\r\n4. Other mathematical operations: sqrt, atan2 (polar coordinate angle)\r\n5. Utility functions: delta (difference between consecutive values)\r\n\r\nAll these functions are designed to work with `Measure` objects, handling both scalar and array inputs.\r\n\r\nExamples of usage:\r\n\r\n1. Trigonometric functions:\r\n```python\r\nfrom pysics import Measure, units, func\r\n\r\nangle = Measure(45, 1, units=units.deg)\r\nsin_value = func.sin(func.rad(angle))\r\nprint(f\"sin(45\u00b0) = {sin_value}\")\r\n```\r\n\r\n2. Inverse trigonometric functions:\r\n```python\r\nx = Measure(0.5, 0.01)\r\nangle = func.asin(x)\r\nprint(f\"arcsin(0.5) = {angle}\")\r\n```\r\n\r\n3. Logarithmic and exponential functions:\r\n```python\r\nvalue = Measure(10, 0.1)\r\nlog_value = func.ln(value)\r\nexp_value = func.exp(Measure(1, 0.01))\r\nprint(f\"ln(10) = {log_value}\")\r\nprint(f\"e^1 = {exp_value}\")\r\n```\r\n\r\n4. Square root:\r\n```python\r\nnumber = Measure(16, 0.5)\r\nroot = func.sqrt(number)\r\nprint(f\"sqrt(16) = {root}\")\r\n```\r\n\r\n5. Polar coordinate angle:\r\n```python\r\nx = Measure(3, 0.1)\r\ny = Measure(4, 0.1)\r\nangle = func.atan2(y, x)\r\nprint(f\"atan2(4, 3) = {angle}\")\r\n```\r\n\r\n6. Delta function (for array inputs):\r\n```python\r\nvalues = Measure([1, 3, 6, 10], [0.1, 0.1, 0.2, 0.2])\r\ndifferences = func.delta(values)\r\nprint(f\"Differences: {differences}\")\r\n```\r\n\r\nThese functions automatically handle error propagation, making it easy to perform complex calculations while keeping track of uncertainties. They also include warnings for potentially incorrect usage, such as passing non-angular values to trigonometric functions.\r\n\r\n## Read\r\n\r\nThe `reader` module in Pysics provides functions for loading data from files and saving data in LaTeX format.\r\n\r\nTo load data from a file:\r\n\r\n```python\r\nfrom pysics.reader import load\r\n\r\ndata = load(\"input.txt\", separator=\",\", headers=1)\r\n```\r\n\r\nThe `load` function parameters are:\r\n- `file`: Path to the input file.\r\n- `separator`: Character used to separate values (default: '\\t').\r\n- `line`: Character used to separate rows (default: '\\n').\r\n- `decimal`: Character used as decimal separator (default: ',').\r\n- `headers`: Number of header rows to skip (default: 0).\r\n- `by_columns`: If True, organizes data by columns; if False, by rows (default: True).\r\n\r\nTo save data in LaTeX format:\r\n\r\n```python\r\nfrom pysics.reader import save_latex\r\n\r\nsave_latex(\"output.tex\", data, separator=\"&\", style=Measure.Style.scientific)\r\n```\r\n\r\nThe `save_latex` function parameters are:\r\n- `file`: Path to the output file.\r\n- `data`: List of data to be saved.\r\n- `separator`: Character used to separate values (default: '\\t').\r\n- `line`: Character used to separate rows (default: '\\n').\r\n- `by_columns`: If True, organizes data by columns; if False, by rows (default: True).\r\n- `style`: Style for formatting Measure objects (default: Measure.Style.latex_table).\r\n\r\nThis function converts the input data to strings, ensures consistent row lengths, and writes the formatted data to the specified file.\r\n\r\n## Tables\r\n\r\nThe `tables` module in Pysics provides utilities for creating and formatting tables in various output formats.\r\n\r\nTo create a formatted table as a list of lists:\r\n\r\n```python\r\nfrom pysics.tables import create_table_list\r\n\r\ndata = [[1, 2, 3], [4, 5, 6]]\r\nheader = ['A', 'B', 'C']\r\nformatted_table = create_table_list(data, header=header, style=Measure.Style.table)\r\n```\r\n\r\nTo create a string representation of a table for terminal display:\r\n\r\n```python\r\nfrom pysics.tables import terminal\r\n\r\ndata = [[1, 2, 3], [4, 5, 6]]\r\nheader = ['A', 'B', 'C']\r\nprint(terminal(data, header=header))\r\n```\r\n\r\nTo create a LaTeX representation of a table:\r\n\r\n```python\r\nfrom pysics.tables import latex\r\n\r\ndata = [[1, 2, 3], [4, 5, 6]]\r\nheader = ['A', 'B', 'C']\r\nlatex_table = latex(data, header=header, caption=\"My Table\", label=\"tab:example\")\r\nprint(latex_table)\r\n```\r\n\r\nTo create a Typst representation of a table:\r\n\r\n```python\r\nfrom pysics.tables import typst\r\n\r\ndata = [[1, 2, 3], [4, 5, 6]]\r\nheader = ['A', 'B', 'C']\r\ntypst_table = typst(data, header=header)\r\nprint(typst_table)\r\n```\r\n\r\nThese functions provide flexible table formatting options for various output formats, making it easy to present data in the desired style for different applications.\r\n\r\n## Acknowledgements\r\nSpecial thanks to [Jonathan D\u00f6nszelmann](https://donsz.nl/) for the pypi project name\r\n",
"bugtrack_url": null,
"license": null,
"summary": "Library to make laboratory calculations easy",
"version": "0.1.0",
"project_urls": {
"Issues": "https://github.com/asaltanubes/pysics/issues",
"Repository": "https://github.com/asaltanubes/pysics"
},
"split_keywords": [
"physics",
" laboratory",
" units",
" least squares"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "9ab5745a0271562d4515b5da2fa0ffa05383fd0a86446cdc333b714c0abec111",
"md5": "9123c4244dc27ca9cbda7a498947ea38",
"sha256": "ae7d12e30ab8ba75882873d1fdd78cbf59b86310fb9a3212c639ec1fe39efe8c"
},
"downloads": -1,
"filename": "pysics-0.1.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "9123c4244dc27ca9cbda7a498947ea38",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.12",
"size": 27944,
"upload_time": "2024-09-24T09:59:00",
"upload_time_iso_8601": "2024-09-24T09:59:00.376292Z",
"url": "https://files.pythonhosted.org/packages/9a/b5/745a0271562d4515b5da2fa0ffa05383fd0a86446cdc333b714c0abec111/pysics-0.1.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "8725e13317ce4cd815d7079ebd8148d4ec9b89d19f8504294873e1e9d56b60d8",
"md5": "f0df10f73f3373c130860b0708b79763",
"sha256": "be8b4a6a39b581eccecaf51b06763e9c32269e9951d39a420647c224936c8bc2"
},
"downloads": -1,
"filename": "pysics-0.1.0.tar.gz",
"has_sig": false,
"md5_digest": "f0df10f73f3373c130860b0708b79763",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.12",
"size": 30651,
"upload_time": "2024-09-24T09:59:01",
"upload_time_iso_8601": "2024-09-24T09:59:01.746573Z",
"url": "https://files.pythonhosted.org/packages/87/25/e13317ce4cd815d7079ebd8148d4ec9b89d19f8504294873e1e9d56b60d8/pysics-0.1.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-09-24 09:59:01",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "asaltanubes",
"github_project": "pysics",
"travis_ci": false,
"coveralls": false,
"github_actions": false,
"lcname": "pysics"
}