zernpy


Namezernpy JSON
Version 0.0.13 PyPI version JSON
download
home_pageNone
SummaryCalculation of Zernike polynomial value, their sums and basic plotting of their values in polar coordinates
upload_time2024-06-14 11:04:55
maintainerNone
docs_urlNone
authorSergei Klykov
requires_python>=3.8
licenseMIT
keywords zernike-polynomials zernike-psf
VCS
bugtrack_url
requirements numpy matplotlib scipy
Travis-CI No Travis.
coveralls test coverage No coveralls.
            ### zernpy - Python package for calculation real-valued Zernike polynomials and associated 2D PSF kernels

#### Project description and references
This project is intended for calculation of Zernike polynomials' parameters / real values / properties using exact (analytical) and recursive equations.   
The recursive and tabular equations, as well as the valuable information, are taken from the articles: [[1]](https://doi.org/10.1364/OL.38.002487), 
[[2]](https://doi.org/10.1080/09500340.2011.554896) and [[3]](https://doi.org/10.1364/OE.26.018878).    
The possibly useful functionality for further usage include: conversion between common indexing schemes (OSA / Noll / Fringe), radial / angular / polynomial 
real values calculation along with their derivatives, plotting the circular 2D or 3D profile of single or sum of polynomials, fitting the arbitrary phase 
profile specified on the circle aperture by the set of polynomials (see the description [below](#fitting-zernike-polynomials-to-a-2D-image-with-phases)). 
For the complete list of implemented methods for Zernike polynomial, please refer to [ZernPol API documentation](https://sklykov.github.io/zernpy/api/zernpy/zernikepol.html).   
For the implemented 2D PSF calculation as the class, please refer to [ZernPol API documentation] (https://sklykov.github.io/zernpy/api/zernpy/zernpsf.html).

#### Notes about implementation
It was supposed at the project start, that the recursive equations would be the faster way to calculate real values of high order polynomials in comparison 
to usage of their exact definition (that used the sum of factorials, see the [Wiki article](https://en.wikipedia.org/wiki/Zernike_polynomials) for details).        
However, it's turned out during the development and tests, that sum of factorials computation (based on Python built-in *math.factorial* method) even for high 
orders (> 10th order) provides sufficiently fast calculation of radial polynomials.   
On other hand, I found that for polynomials with radial orders higher than 46th order the exact equation with factorials starts providing ambiguous results 
due to the big integer coefficients (exceeding the size of Python built-in *int* type) produced by factorials. Thus, it turns out that the stable way to get 
polynomial (radial) values for these orders is to use the recursive equations for retain stability of calculation along with the drawback of fast 
decreasing of the computational performance with the increased radial order.

### Setup instructions

#### Basic installation
For installation of this package, use the command: ***pip install zernpy***    
For updating already installed package:  ***pip install --upgrade zernpy*** or ***pip install -U zernpy***

#### Requirements
For installation, the *numpy* and *matplotlib* libraries are required.  
For running tests, the *pytest* library is required for automatic recognition of tests stored in package folders.  

#### Running tests
Simply run the command ***pytest*** in the command line from the project folder root. It should collect 10 tests and automatically run them.

### A few examples of the library features usage

#### Initialization of base class instance
The useful calculation methods are written as the instance and static methods. The first ones are accessible after initialization of a class instance
by providing characteristic orders (see the Zernike polynomial definition, e.g. in [Wiki](https://en.wikipedia.org/wiki/Zernike_polynomials)):   
```python  # code block for Python code
from zernpy import ZernPol
zp = ZernPol(m=-2, n=2)  
```
Alternative initializations using other indices: ***ZernPol(osa_index=3)***, ***ZernPol(noll_index=5)***, ***ZernPol(fringe_index=6)***   
For details, please, refer to the API Dictionary provided on the GitHub page (see "Documentation" tab on [pypi](https://pypi.org/project/zernpy/)).

#### Some useful class instance methods:
1) For getting all characteristic indices for the initialized polynomial: ***zp.get_indices()***   
This method returns the following tuple: *((azimuthal order, radial order), OSA index, Noll index, Fringe index)*
2) For getting the string name of the initialized polynomial (up to 7th order): ***zp.get_polynomial_name()***
3) For calculating polynomial value for polar coordinates (r, theta): ***zp.polynomial_value(r, theta)***  
Note that *r* and *theta* are accepted as float numbers or numpy.ndarrays with the equal shape, it is also applicable for
functions below 4. - 7.    
4) For calculating radial polynomial value for radius (radii) r: ***zp.radial(r)***  
5) For calculating derivative of radial polynomial value for radius (radii) r: ***zp.radial_dr(r)***
6) For calculating triangular function value for angle theta: ***zp.triangular(theta)*** 
7) For calculating derivative of triangular function value for angle theta: ***zp.triangular_dtheta(theta)***   
8) For calculating normalization factor (N): ***zp.normf()*** 

#### Some useful static methods of the ZernPol class:
1) For getting tuple as (azimuthal order, radial order) for OSA index i: ***ZernPol.index2orders(osa_index=i)***  
Same for Fringe and Noll indices: ***ZernPol.index2orders(noll_index=i)*** or ***ZernPol.index2orders(fringe_index=i)***
2) Conversion between indices: ***ZernPol.osa2noll(osa_index)***,
with similar signature: ***noll2osa(...)***, ***osa2fringe(...)***, ***osa2fringe(...)***, ***fringe2osa(...)***
3) Calculation of Zernike polynomials sum: ***ZernPol.sum_zernikes(coefficients, polynomials, r, theta, get_surface)***   
It calculates the sum of initialized Zernike polynomials (*ZernPol*) using coefficients and (r, theta) polar coordinates.
The variable *get_surface* allows returning for vector polar coordinates with different shapes the values as for mesh of these coordinates.
The details of acceptable values - see the docstring of this method or the API Dictionary.
4) Plotting the initialized Zernike polynomial (ZernPol) with default parameters for coordinates: ***ZernPol.plot_profile(polynomial)***   
It plots the Zernike polynomial on unit circle using polar coordinates - on "2D" projection (blocked non-interactive call of *matplotlib.pyplot.show()*).   
For "3D" projection the polar coordinates are converted to the cartesian ones, as demanded by plotting method.  
**(!):** Note that the plotting method name has been changed from  ***plot_profile(...)*** for ver. <= 0.0.10, the new version of the package will be 
simply sequentially incremented, without minor version changing, since there is no packages dependent on this one.   
5) Plotting Zernike polynomials sum:  ***ZernPol.plot_sum_zernikes_on_fig(...)*** - check the list of parameters in the docstring.
By using only default parameters, this method will plot sum of Zernike polynomials specified in the list with their coefficients
on the provided figure (expected as an instance of the class *matplotlib.pyplot.Figure*).

#### Fitting Zernike polynomials to a 2D image with phases
Random generated set of Zernike polynomials plotted on an image - as the sample for testing the fitting procedure:     
![Random Profile](./src/zernpy/readme_images/Random_Profile.png "Random phases profile, 'jet' matplotlib colormap")        
This image is assumed to contain phases wrapped in a circular aperture, used function for generation:
***generate_random_phases(...)*** from the main *zernikepol* module.    
Below is profile made by calculation of fitted Zernike polynomials:    
![Fitted Profile](./src/zernpy/readme_images/Fitted_Profile.png "Fitted polynomials profile, 'jet' matplotlib colormap")               
The function used for fitting: ***fit_polynomials(...)*** from the main *zernikepol* module.    
This function could be useful for making approximation of any image containing phases recorded by the optical system
to the sum of Zernike polynomials. Check the detailed description of functions in the API dictionary, available on
the separate tab on the GitHub page of this repository.   
The function ***fit_polynomials_vectors(...)*** allows to fit composed in vectors (arrays with single dimension) phases 
recorded in polar coordinates (provided separately also in vectors) to the provided set of Zernike polynomials. This is analogous
to the procedure described above, but this function doesn't perform any cropping or phases pre-selection.   
Import statement for using the scripts the mentioned functions:  
```python
from zernpy import generate_polynomials, fit_polynomials, generate_random_phases, generate_phases_image, fit_polynomials_vectors
```
Or for importing all available functions and base class in one statement:    
```python
from zernpy import *
```
Note that the function ***generate_polynomials(...)*** returns tuple with OSA indexed polynomials as instances of the *ZernPol* class, starting from the 'Piston' polynomial.    

#### 2D PSF kernel calculation
The 2D PSF kernel is calculated from the diffraction integral over the round pupil plane and described as Zernike polynomial phase distribution for the focal point (no Z-axis dependency). The used references are listed in the docstring of the **calculate_psf_kernel()** method.   
The sample of calculated PSF for Vertical Trefoil:    
![Vertical Trefoil Kernel](./src/zernpy/readme_images/(-3,_3)_Vert._3foil_0.85.png "Vertical Trefoil Kernel")    
Initialization and usage of the class instance (basic usage with default calculation parameters, such as the kernel size):    
```python  # code block for Python code
from zernpy import ZernPSF
zpsf = ZernPSF(ZernPol(m=1, n=3))  # horizontal coma
zpsf.set_physical_properties(NA, wavelength, expansion_coeff, pixel_physical_size)  # provide physical properties of the system
kernel = zpsf.calculate_psf_kernel(normalized=True)  # get the kernel as the square normalized matrix
```
Check the API documentation for other available methods.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "zernpy",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": "zernike-polynomials, zernike-psf",
    "author": "Sergei Klykov",
    "author_email": "sergej.klykow@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/33/01/977f16652d5f2715862f1e9354cf9a03d2d1d5e0e8bb6fecc90363115cb4/zernpy-0.0.13.tar.gz",
    "platform": null,
    "description": "### zernpy - Python package for calculation real-valued Zernike polynomials and associated 2D PSF kernels\r\n\r\n#### Project description and references\r\nThis project is intended for calculation of Zernike polynomials' parameters / real values / properties using exact (analytical) and recursive equations.   \r\nThe recursive and tabular equations, as well as the valuable information, are taken from the articles: [[1]](https://doi.org/10.1364/OL.38.002487), \r\n[[2]](https://doi.org/10.1080/09500340.2011.554896) and [[3]](https://doi.org/10.1364/OE.26.018878).    \r\nThe possibly useful functionality for further usage include: conversion between common indexing schemes (OSA / Noll / Fringe), radial / angular / polynomial \r\nreal values calculation along with their derivatives, plotting the circular 2D or 3D profile of single or sum of polynomials, fitting the arbitrary phase \r\nprofile specified on the circle aperture by the set of polynomials (see the description [below](#fitting-zernike-polynomials-to-a-2D-image-with-phases)). \r\nFor the complete list of implemented methods for Zernike polynomial, please refer to [ZernPol API documentation](https://sklykov.github.io/zernpy/api/zernpy/zernikepol.html).   \r\nFor the implemented 2D PSF calculation as the class, please refer to [ZernPol API documentation] (https://sklykov.github.io/zernpy/api/zernpy/zernpsf.html).\r\n\r\n#### Notes about implementation\r\nIt was supposed at the project start, that the recursive equations would be the faster way to calculate real values of high order polynomials in comparison \r\nto usage of their exact definition (that used the sum of factorials, see the [Wiki article](https://en.wikipedia.org/wiki/Zernike_polynomials) for details).        \r\nHowever, it's turned out during the development and tests, that sum of factorials computation (based on Python built-in *math.factorial* method) even for high \r\norders (> 10th order) provides sufficiently fast calculation of radial polynomials.   \r\nOn other hand, I found that for polynomials with radial orders higher than 46th order the exact equation with factorials starts providing ambiguous results \r\ndue to the big integer coefficients (exceeding the size of Python built-in *int* type) produced by factorials. Thus, it turns out that the stable way to get \r\npolynomial (radial) values for these orders is to use the recursive equations for retain stability of calculation along with the drawback of fast \r\ndecreasing of the computational performance with the increased radial order.\r\n\r\n### Setup instructions\r\n\r\n#### Basic installation\r\nFor installation of this package, use the command: ***pip install zernpy***    \r\nFor updating already installed package:  ***pip install --upgrade zernpy*** or ***pip install -U zernpy***\r\n\r\n#### Requirements\r\nFor installation, the *numpy* and *matplotlib* libraries are required.  \r\nFor running tests, the *pytest* library is required for automatic recognition of tests stored in package folders.  \r\n\r\n#### Running tests\r\nSimply run the command ***pytest*** in the command line from the project folder root. It should collect 10 tests and automatically run them.\r\n\r\n### A few examples of the library features usage\r\n\r\n#### Initialization of base class instance\r\nThe useful calculation methods are written as the instance and static methods. The first ones are accessible after initialization of a class instance\r\nby providing characteristic orders (see the Zernike polynomial definition, e.g. in [Wiki](https://en.wikipedia.org/wiki/Zernike_polynomials)):   \r\n```python  # code block for Python code\r\nfrom zernpy import ZernPol\r\nzp = ZernPol(m=-2, n=2)  \r\n```\r\nAlternative initializations using other indices: ***ZernPol(osa_index=3)***, ***ZernPol(noll_index=5)***, ***ZernPol(fringe_index=6)***   \r\nFor details, please, refer to the API Dictionary provided on the GitHub page (see \"Documentation\" tab on [pypi](https://pypi.org/project/zernpy/)).\r\n\r\n#### Some useful class instance methods:\r\n1) For getting all characteristic indices for the initialized polynomial: ***zp.get_indices()***   \r\nThis method returns the following tuple: *((azimuthal order, radial order), OSA index, Noll index, Fringe index)*\r\n2) For getting the string name of the initialized polynomial (up to 7th order): ***zp.get_polynomial_name()***\r\n3) For calculating polynomial value for polar coordinates (r, theta): ***zp.polynomial_value(r, theta)***  \r\nNote that *r* and *theta* are accepted as float numbers or numpy.ndarrays with the equal shape, it is also applicable for\r\nfunctions below 4. - 7.    \r\n4) For calculating radial polynomial value for radius (radii) r: ***zp.radial(r)***  \r\n5) For calculating derivative of radial polynomial value for radius (radii) r: ***zp.radial_dr(r)***\r\n6) For calculating triangular function value for angle theta: ***zp.triangular(theta)*** \r\n7) For calculating derivative of triangular function value for angle theta: ***zp.triangular_dtheta(theta)***   \r\n8) For calculating normalization factor (N): ***zp.normf()*** \r\n\r\n#### Some useful static methods of the ZernPol class:\r\n1) For getting tuple as (azimuthal order, radial order) for OSA index i: ***ZernPol.index2orders(osa_index=i)***  \r\nSame for Fringe and Noll indices: ***ZernPol.index2orders(noll_index=i)*** or ***ZernPol.index2orders(fringe_index=i)***\r\n2) Conversion between indices: ***ZernPol.osa2noll(osa_index)***,\r\nwith similar signature: ***noll2osa(...)***, ***osa2fringe(...)***, ***osa2fringe(...)***, ***fringe2osa(...)***\r\n3) Calculation of Zernike polynomials sum: ***ZernPol.sum_zernikes(coefficients, polynomials, r, theta, get_surface)***   \r\nIt calculates the sum of initialized Zernike polynomials (*ZernPol*) using coefficients and (r, theta) polar coordinates.\r\nThe variable *get_surface* allows returning for vector polar coordinates with different shapes the values as for mesh of these coordinates.\r\nThe details of acceptable values - see the docstring of this method or the API Dictionary.\r\n4) Plotting the initialized Zernike polynomial (ZernPol) with default parameters for coordinates: ***ZernPol.plot_profile(polynomial)***   \r\nIt plots the Zernike polynomial on unit circle using polar coordinates - on \"2D\" projection (blocked non-interactive call of *matplotlib.pyplot.show()*).   \r\nFor \"3D\" projection the polar coordinates are converted to the cartesian ones, as demanded by plotting method.  \r\n**(!):** Note that the plotting method name has been changed from  ***plot_profile(...)*** for ver. <= 0.0.10, the new version of the package will be \r\nsimply sequentially incremented, without minor version changing, since there is no packages dependent on this one.   \r\n5) Plotting Zernike polynomials sum:  ***ZernPol.plot_sum_zernikes_on_fig(...)*** - check the list of parameters in the docstring.\r\nBy using only default parameters, this method will plot sum of Zernike polynomials specified in the list with their coefficients\r\non the provided figure (expected as an instance of the class *matplotlib.pyplot.Figure*).\r\n\r\n#### Fitting Zernike polynomials to a 2D image with phases\r\nRandom generated set of Zernike polynomials plotted on an image - as the sample for testing the fitting procedure:     \r\n![Random Profile](./src/zernpy/readme_images/Random_Profile.png \"Random phases profile, 'jet' matplotlib colormap\")        \r\nThis image is assumed to contain phases wrapped in a circular aperture, used function for generation:\r\n***generate_random_phases(...)*** from the main *zernikepol* module.    \r\nBelow is profile made by calculation of fitted Zernike polynomials:    \r\n![Fitted Profile](./src/zernpy/readme_images/Fitted_Profile.png \"Fitted polynomials profile, 'jet' matplotlib colormap\")               \r\nThe function used for fitting: ***fit_polynomials(...)*** from the main *zernikepol* module.    \r\nThis function could be useful for making approximation of any image containing phases recorded by the optical system\r\nto the sum of Zernike polynomials. Check the detailed description of functions in the API dictionary, available on\r\nthe separate tab on the GitHub page of this repository.   \r\nThe function ***fit_polynomials_vectors(...)*** allows to fit composed in vectors (arrays with single dimension) phases \r\nrecorded in polar coordinates (provided separately also in vectors) to the provided set of Zernike polynomials. This is analogous\r\nto the procedure described above, but this function doesn't perform any cropping or phases pre-selection.   \r\nImport statement for using the scripts the mentioned functions:  \r\n```python\r\nfrom zernpy import generate_polynomials, fit_polynomials, generate_random_phases, generate_phases_image, fit_polynomials_vectors\r\n```\r\nOr for importing all available functions and base class in one statement:    \r\n```python\r\nfrom zernpy import *\r\n```\r\nNote that the function ***generate_polynomials(...)*** returns tuple with OSA indexed polynomials as instances of the *ZernPol* class, starting from the 'Piston' polynomial.    \r\n\r\n#### 2D PSF kernel calculation\r\nThe 2D PSF kernel is calculated from the diffraction integral over the round pupil plane and described as Zernike polynomial phase distribution for the focal point (no Z-axis dependency). The used references are listed in the docstring of the **calculate_psf_kernel()** method.   \r\nThe sample of calculated PSF for Vertical Trefoil:    \r\n![Vertical Trefoil Kernel](./src/zernpy/readme_images/(-3,_3)_Vert._3foil_0.85.png \"Vertical Trefoil Kernel\")    \r\nInitialization and usage of the class instance (basic usage with default calculation parameters, such as the kernel size):    \r\n```python  # code block for Python code\r\nfrom zernpy import ZernPSF\r\nzpsf = ZernPSF(ZernPol(m=1, n=3))  # horizontal coma\r\nzpsf.set_physical_properties(NA, wavelength, expansion_coeff, pixel_physical_size)  # provide physical properties of the system\r\nkernel = zpsf.calculate_psf_kernel(normalized=True)  # get the kernel as the square normalized matrix\r\n```\r\nCheck the API documentation for other available methods.\r\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Calculation of Zernike polynomial value, their sums and basic plotting of their values in polar coordinates",
    "version": "0.0.13",
    "project_urls": {
        "Bug Tracker": "https://github.com/sklykov/zernpy/issues/",
        "Changelog": "https://github.com/sklykov/zernpy/blob/main/CHANGELOG.md",
        "Documentation": "https://sklykov.github.io/zernpy/",
        "Homepage": "https://pypi.org/project/zernpy/",
        "Repository": "https://github.com/sklykov/zernpy/"
    },
    "split_keywords": [
        "zernike-polynomials",
        " zernike-psf"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "2eebb547283e6b47dd9465e73e9142b555f8688b92a788a3b01431118c7a9fe5",
                "md5": "dc0a7a924da035af2c8f37c829c1348f",
                "sha256": "3784eb12abf868f2e853bd8db0ad9d96dd6554d65f5c900d9ac962102af4e1c8"
            },
            "downloads": -1,
            "filename": "zernpy-0.0.13-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "dc0a7a924da035af2c8f37c829c1348f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 213309,
            "upload_time": "2024-06-14T11:04:54",
            "upload_time_iso_8601": "2024-06-14T11:04:54.036940Z",
            "url": "https://files.pythonhosted.org/packages/2e/eb/b547283e6b47dd9465e73e9142b555f8688b92a788a3b01431118c7a9fe5/zernpy-0.0.13-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3301977f16652d5f2715862f1e9354cf9a03d2d1d5e0e8bb6fecc90363115cb4",
                "md5": "638beb4e1f1dda6ea7cfd2478b662e5c",
                "sha256": "5f8c67bc0991d07f0d1f41465f42e7efcd50e3242643e8e933b5620ae84fa9cf"
            },
            "downloads": -1,
            "filename": "zernpy-0.0.13.tar.gz",
            "has_sig": false,
            "md5_digest": "638beb4e1f1dda6ea7cfd2478b662e5c",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 211298,
            "upload_time": "2024-06-14T11:04:55",
            "upload_time_iso_8601": "2024-06-14T11:04:55.915654Z",
            "url": "https://files.pythonhosted.org/packages/33/01/977f16652d5f2715862f1e9354cf9a03d2d1d5e0e8bb6fecc90363115cb4/zernpy-0.0.13.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-06-14 11:04:55",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "sklykov",
    "github_project": "zernpy",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "requirements": [
        {
            "name": "numpy",
            "specs": []
        },
        {
            "name": "matplotlib",
            "specs": []
        },
        {
            "name": "scipy",
            "specs": []
        }
    ],
    "lcname": "zernpy"
}
        
Elapsed time: 0.26760s