sterncat / opticspy Goto Github PK
View Code? Open in Web Editor NEWpython optics module
License: MIT License
python optics module
License: MIT License
Hi there, just found your awesome library. Thanks a lot for sharing the code!
From the fact that opticspy is present on pypi, i conclude that you have a setup.py lying around somewhere already. Would be awesome if you could add it to the repo, so package installation (i.e. "python3 setup.py build, python3 setup.py install") would be much easier. Thx a lot!
I need to model a system with finite conjugates, and I see that you have set infinite conjugates as the default, specifically in the function 'refresh paraxial' where you have set 'object_position' to -10000000. Changing this number only affects the calculated image position, but not the analysis of the spot diagram at the new image position (or the drawing of the lens system).
Can you tell me how to modify the functions to allow finite conjugates? I'm sure it's in the code somewhere, but so far I have not found a solution..
Thanks!
There is an errata for 2007 Mahajan paper. The orthonormal rectangular polynomials functions need to be reviewed and edit!
git clone reads
https://github.com/Diti24/opticspy.git
which is partly corrupted.
Should read https://github.com/Sterncat/opticspy.git
Hi Sterncat
I have installed opticspy using pip command after referring to issue #33
pip install git+git://github.com/Sterncat/opticspy.git@master
The installation had no issues but when I import the module I get the following error:
Python 3.9.4 (default, Apr 9 2021, 16:34:09)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import opticspy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/ashok/anaconda3/envs/opticspy/lib/python3.9/site-packages/opticspy/__init__.py", line 14, in <module>
from . import phaseunwrap, lens, asphere, mplot3d, zernike_rec
File "/home/ashok/anaconda3/envs/opticspy/lib/python3.9/site-packages/opticspy/mplot3d/__init__.py", line 6, in <module>
from .axes3d import Axes3D
File "/home/ashok/anaconda3/envs/opticspy/lib/python3.9/site-packages/opticspy/mplot3d/axes3d.py", line 34, in <module>
from . import art3d
File "/home/ashok/anaconda3/envs/opticspy/lib/python3.9/site-packages/opticspy/mplot3d/art3d.py", line 23, in <module>
from matplotlib.cbook import iterable
ImportError: cannot import name 'iterable' from 'matplotlib.cbook' (/home/ashok/anaconda3/envs/opticspy/lib/python3.9/site-packages/matplotlib/cbook/__init__.py)
How should I proceed? Thanks
Hello, I want to calculate the PSF of a single aspheric lens optical system. Is it possible to build an aspheric lens?
Hi, I don't know Python a lot but i think that adding something like this to the zernike.py module could be useful:
import opticspy
import numpy as np
from PIL import Image
from scipy import signal
import matplotlib.pyplot as plt
Z = opticspy.zernike.Coefficient(Z1=0.2)
Z.zernikesurface()
psfmatrix = Z.psf(matrix=True)
Z.mtf()
abspsf=abs(psfmatrix/psfmatrix.max())
im = Image.open("img.bmp")
pic = np.array(im)
imgplot=plt.imshow(pic)
imgplot.set_cmap("gray")
plt.colorbar()
plt.show()
abspic=(pic/pic.max())
outpic=signal.fftconvolve(abspsf,abspic,mode="same")
outpic=np.trunc(255*abs(outpic/outpic.max()))
imgplot=plt.imshow(outpic)
imgplot.set_cmap("gray")
plt.colorbar()
plt.show()
Can you provide more information on how you calculate the PSF?
I see that the function takes arguments for wavelength and distance from the exit pupil to the image plane, but in the function zernike.psfcalculator, these values are not used. It would be good to have these features included..
I also noticed that changing the size of the aperture gives odd results: if the aperture is smaller than about 0.05 (assuming units of mm) then the PSF is too small to see clearly, and if I set the aperture to 2, then I get a PSF that looks nothing like an aperture radius of 1. It almost behaves like the focal plane has been shifted. Are the values reversed somewhere?
Thanks!
I am trying to model lens design from patents. With regards to the glass type, I only have the refractive index and abbe number for d-line. For example, 1.79668 and 45.5. As this is a Nikon patent I tried to see if there was any glass in the Hikari catalog matching this, but there isn't.
Is there a way to add my own glass type just using these two attributes?
Hi,
I am also trying to learning how ray-tracing works, and reading your code helps thank you !
Could you please explain the calculations you do in the traceray()
function, in ray_tracing/trace.py
? In particular what are the calculations leading to Pos_new
and KLM_new
?
Thanks again
How can we use the fitting function if we are given a 3D point cloud of (x,y,z) values where z is the elevation at point (x,y)?
It is not very apparent from the code.
Your help would be appreciated.
Thank you.
Hello,
after that command: ~/Téléchargements/opticspy-master$ pip install opticspy
I get this message at the end:
Successfully installed backports.functools-lru-cache-1.6.1 cffi-1.14.0 cycler-0.10.0 kiwisolver-1.1.0 matplotlib-2.2.5 numpy-1.16.6 opticspy-0.2.1 pycparser-2.20 pyparsing-2.4.7 python-dateutil-2.8.1 pytz-2020.1 setuptools-44.1.1 six-1.15.0 subprocess32-3.5.4 unwrap-0.1.1
Erreur de segmentation (core dumped)
An idea please ? Thanks
Hi, I might be interested in contributing to this project.
I just had a look at some of the files and have a few questions about your conventions.
I'm wondering why you are importing the modules with double under scores, e.g.
import numpy as __np__
I think this might be causing problems, since double underscores are kind of reserved for python's magic methods.
As far as I know, the normal way to do it would be just importing numpy as np.
I have a similar issue with the double-underscores around the class variables.
In particular I was looking at the Aperture class, using self.__scale__
, self.__aper__
etc.
I would consider renaming the class variables so they have a single leading underscore.
That way they are marked as private, but not treated specially by the interpreter.
Also I think the project could profit from using a linter, e.g. pylint to keep the code following the python conventions described in PEP8 at least to some level.
Hi Marvin,
I try to get the foloowing minimal working example from the docs running without success:
import opticspy
New_Lens = lens.Lens(lens_name='Doublegauss',creator='XF')
New_Lens.FNO = 5
New_Lens.lens_info()
I get a NameError: name 'lens' is not defined.
Have you seen this error before? Is it because of Python 3.x?
Thank you a lot in advance!
Nico
Hi, I wonder it is possible to insert an AXICON optical element?
On Ubuntu 16.04
After installation during import it complains about not having write permission to /Library/Python/2.7/site-packages/unwrap/pycache
temporary solved it by reinstallation of unwrap to user space:
pip3 install --user unwrap
It is probably unwrap problem ...
Hi @Sterncat, I would like to open a pull-request to update the readme but I don't have the permission to publish a branch, could you please give me the rights ?
Cheers
Hi,
I played with the examples and worked with the Double Gauss (example 2). I compared the outputs of opticspy and CodeV, with the same input values, here is the comparison :
The layouts are pretty much identical, but the RMS spot-diagram values are quite different, would you happen to know why ?
Kind regards,
DrPaprikaa
There are files using modules from PyTMM and also copies of PyTMM files within opticspy.
This is a bit chaotic, because PyTMM methods are being used by importing them from PyTMM instead of from the local files re-defining them.
Hello,
I think there are some minor changes to do that hopefully may help others in the future and a problem for which I haven't found the solution. All I did for these errors to occur was to test the "Example 1: Basic functions introduction" from the website of opticspy.
• If you have the message No module named 'aperture'
, the problem comes from the version installed, you installed the python 2 version and are using it as a python 3.
-- "pip install" installed the Python 2 version. I don't know how it works but it may need to be updated.
-- on http://opticspy.org/, the link to download it is also for Python2 (even though in this case it's more obvious that it's 2)
Solution → clone the repo on git and run python setup.py install
(or replace python by python3 if you have python 2 as default).
• No module named 'lens'
Solution → go into opticspy/ray_tracing/codev.py and replace import lens
by from . import lens
.
• No module named glass
Solution → go into the file from which you installed if you cloned and in ray_tracing/ you should find a folder glass_database. Copy it and paste it where opticspy has been installed (it should be written on the error message)
• Now this is the error for which I didn't find the solution. When trying to trace the rays with draw.draw_system(New_Lens)
, the error local variable 'verts' referenced before assignment
is returned. The source of the problem is the following. It's in /opticspy/ray_tracing/draw.py in draw_surface(r, x0, d1, d2).
27 verts = [[verts_1[-1][0],d2/2]] + verts_1[::-1] + verts_2[1:] + [[verts_2[-1][0],-d2/2]]
28 codes.append(Path.MOVETO)
---> 29 for j in range(len(verts)-1):
30 codes.append(Path.LINETO)
I tried to rename it and reassign a value before in case there was a problem with a global variable which had the same name but it doesn't seems to be it.
I hope this message belongs here, isn't too long and will be helpful for some !
If so is there an example I can look at?
Installing in py2.7 from pip in Azure notebooks environment gives an error at first base:
!pip2 install opticspy
from opticspy.ray_tracing import *
returns:
ImportErrorTraceback (most recent call last)
<ipython-input-1-518116206b61> in <module>()
1 get_ipython().magic(u'matplotlib inline')
----> 2 from opticspy.ray_tracing import *
/home/nbuser/anaconda2_501/lib/python2.7/site-packages/opticspy/ray_tracing/__init__.py in <module>()
----> 1 import lens, trace, glass, draw, analysis, field, codev
ImportError: No module named glass
Hi
I am getting following error. I am on Redhat 7.7 and using Python 3.6.
Python 3.6.3 (default, Apr 10 2019, 14:37:36)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-16)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from opticspy.ray_tracing import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/dylan/pydev/lib64/python3.6/site-packages/opticspy/__init__.py", line 12, in <module>
import aperture, interferometer_seidel,interferometer_zenike
ModuleNotFoundError: No module named 'aperture'
Any idea what might be wrong?
Thank you
The current circular zernike cartesian polynomials in zernikecartesian(coefficient,x,y) for Z29 and Z30 are inconsistent with their polar form. I think the cartesian forms should be:
Z29 = Z[29] * 4_y_(35_r__6-60_r4+30*r2-4)
Z30 = Z[30] * 4_x_(35_r__6-60_r4+30*r2-4)
Could you provide an example of using apertures, aspherics, and mirrors.
Also useful would be to mount optics at angles and potentially off center.
Thanks
Hi there,
I'm trying to use your software under python 3.6, but it is really not refactored to work. The print statements I've come across so far do not have ()'s, so it doesn't run.
Also, the issue previous issue with the import errors stem from this, I think.
I'm running it from a mac, if it matters, but I don't think it makes a difference.
I'm really hoping to use it, however!
Hi,
I was trying to install opticspy. I have Anaconda system on windows with Spyder 3. 1.4 and Python 3.6 installed.
I got the following error: Please suggest a remedy
!pip install opticspy
Collecting opticspy
Downloading opticspy-0.2.1.tar.gz (1.3MB)
Requirement already satisfied: numpy>=1.9.3 in c:\programdata\anaconda3\lib\site-packages (from opticspy)
Requirement already satisfied: matplotlib>=1.4.3 in c:\programdata\anaconda3\lib\site-packages (from opticspy)
Collecting unwrap (from opticspy)
Downloading unwrap-0.1.1.tar.gz
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\msvc.py", line 474, in init
IndexError: list index out of range
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "C:\Users\abekal\AppData\Local\Temp\pip-build-ywxkot1x\unwrap\setup.py", line 14, in <module>
import unwrap.unwrap2D as unwrap2D
File "C:\Users\abekal\AppData\Local\Temp\pip-build-ywxkot1x\unwrap\unwrap\__init__.py", line 3, in <module>
from unwrap.unwrap import unwrap
File "C:\Users\abekal\AppData\Local\Temp\pip-build-ywxkot1x\unwrap\unwrap\unwrap.py", line 4, in <module>
from unwrap.unwrap2D import unwrap2D
File "C:\Users\abekal\AppData\Local\Temp\pip-build-ywxkot1x\unwrap\unwrap\unwrap2D.py", line 20, in <module>
include_dirs=[_current_directory])
File "C:\ProgramData\Anaconda3\lib\site-packages\cffi\api.py", line 438, in verify
lib = self.verifier.load_library()
File "C:\ProgramData\Anaconda3\lib\site-packages\cffi\verifier.py", line 114, in load_library
self._compile_module()
File "C:\ProgramData\Anaconda3\lib\site-packages\cffi\verifier.py", line 211, in _compile_module
outputfilename = ffiplatform.compile(tmpdir, self.get_extension())
File "C:\ProgramData\Anaconda3\lib\site-packages\cffi\ffiplatform.py", line 20, in compile
outputfilename = _build(tmpdir, ext, compiler_verbose, debug)
File "C:\ProgramData\Anaconda3\lib\site-packages\cffi\ffiplatform.py", line 49, in _build
dist.run_command('build_ext')
File "C:\ProgramData\Anaconda3\lib\distutils\dist.py", line 974, in run_command
cmd_obj.run()
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\command\build_ext.py", line 77, in run
File "C:\ProgramData\Anaconda3\lib\site-packages\Cython\Distutils\old_build_ext.py", line 185, in run
_build_ext.build_ext.run(self)
File "C:\ProgramData\Anaconda3\lib\distutils\command\build_ext.py", line 339, in run
self.build_extensions()
File "C:\ProgramData\Anaconda3\lib\site-packages\Cython\Distutils\old_build_ext.py", line 193, in build_extensions
self.build_extension(ext)
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\command\build_ext.py", line 198, in build_extension
File "C:\ProgramData\Anaconda3\lib\distutils\command\build_ext.py", line 533, in build_extension
depends=ext.depends)
File "C:\ProgramData\Anaconda3\lib\distutils\_msvccompiler.py", line 304, in compile
self.initialize()
File "C:\ProgramData\Anaconda3\lib\distutils\_msvccompiler.py", line 197, in initialize
vc_env = _get_vc_env(plat_spec)
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\msvc.py", line 170, in msvc14_get_vc_env
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\msvc.py", line 767, in __init__
File "C:\ProgramData\Anaconda3\lib\site-packages\setuptools-27.2.0-py3.6.egg\setuptools\msvc.py", line 477, in __init__
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in C:\Users\abekal\AppData\Local\Temp\pip-build-ywxkot1x\unwrap\
Thank you
Anish bekal
I meant this Issue to be used more for some discussion. I think this project was really well done btw
I am trying to recreate the human eye as a series of lenses so I can do some ray tracing calculations on the transformation of a projection onto the retina. I am also trying to fit the projection through the iris, so I need something sort of like this http://i.imgur.com/eej7PIk.png. The image describes having a biconvex lens in front of the eye such that the focal distance allows the image flip somewhere near the iris in order to "fit" the original larger projection.
Is there a way I could just model the cornea->retina as a single lens? Or would I have to model each intermediate lens. I dont need something extremely precise (i.e. accounting for the spherical shape of the retina, as its really the fovea that's my concern). If this isn't something that can be easily solved, then which parts of the problem can I replace with an assumption?
References:
Generalized eye element refractive indices and their thicknesses. http://hyperphysics.phy-astr.gsu.edu/hbase/vision/imgvis/eyesca.gif
media reference:
http://hyperphysics.phy-astr.gsu.edu/hbase/vision/eyescal.html
Hello,
Is it possible to make opticspy Python 3 compatible ?
After a fast looking on your code, incompatibilities come mainly from imports
and prints
.
The use of the following future may help you to have a Python 2/3 compatible code.
from __future__ import print_function
from __future__ import absolute_import
And: Nice to see an optics library on Python, this was missing.
Hi!
Is there any reason this repo doesn't include setup.py
?
I installed opticspy via pip in a clean environment, and it seems like some dependencies are missing.
I had to pip install
or conda install
:
i want to insert a aspheric surface
For zernike.py:
def __psfcaculator__(self,r=1,lambda_1=632*10**(-9),z=0.1):
"""
pupil: Exit pupil diameter
z: Distance from exit pupil to image plane
r: pupil radius, in unit of lambda
"""
pupil = l1 = 200 # exit pupil sample points
x = __np__.linspace(-r, r, l1)
[X,Y] = __np__.meshgrid(x,x)
Z = __interferometer__.__zernikecartesian__(self.__coefficients__,X,Y)
for i in range(len(Z)):
for j in range(len(Z)):
if x[i]**2+x[j]**2>r**2:
Z[i][j] = 0
d = 400 # background
A = __np__.zeros([d,d])
A[d//2-l1//2+1:d//2+l1//2+1,d//2-l1//2+1:d//2+l1//2+1] = Z
axis_1 = d//pupil*r
fig = __plt__.figure()
# ax = fig.gca()
# __plt__.imshow(A,extent=[-axis_1,axis_1,-axis_1,axis_1],cmap=__cm__.RdYlGn)
# ax.set_xlabel('mm',fontsize=14)
# __plt__.colorbar()
# __plt__.show()
I don't see any code effected by z=0.1
from opticspy.ray_tracing import *
gives the following error:
opticspy/ray_tracing/__init__.py in <module>()
----> 1 import lens, trace, glass, draw, analysis, field, codev
ImportError: No module named glass
I copied out your example from:
http://sterncat.github.io/files/Real_Ray_Tracing.html
import matplotlib.pyplot as plt
from opticspy.ray_tracing import *
New_Lens = lens.Lens(lens_name='Triplet',creator='XF')
New_Lens.FNO = 5
New_Lens.lens_info()
New_Lens.add_wavelength(wl = 656.30)
New_Lens.add_wavelength(wl = 587.60)
New_Lens.add_wavelength(wl = 486.10)
New_Lens.list_wavelengths()
New_Lens.add_field_YAN(angle=0)
New_Lens.add_field_YAN(angle=14)
New_Lens.add_field_YAN(angle=20)
New_Lens.list_fields()
New_Lens.add_surface(number=1,radius=10000000,thickness=1000000,glass='air',output=True)
New_Lens.add_surface(number=2,radius=41.15909,thickness=6.097555 ,glass='S-BSM18_ohara',output=True)
New_Lens.add_surface(number=3,radius=-957.83146,thickness=9.349584,glass='air',output=True)
New_Lens.add_surface(number=4,radius=-51.32104,thickness=2.032518,glass='N-SF2_schott',output=True)
New_Lens.add_surface(number=5,radius=42.37768 ,thickness=5.995929 ,glass='air',output=True)
New_Lens.add_surface(number=6,radius=10000000,thickness=4.065037,glass='air',STO=True,output=True)
New_Lens.add_surface(number=7,radius=247.44562,thickness=6.097555,glass='S-BSM18_ohara',output=True)
New_Lens.add_surface(number=8,radius=-40.04016,thickness=85.593426,glass='air',output=True)
New_Lens.add_surface(number=9,radius=10000000,thickness=0,glass='air',output=True)
New_Lens.refresh_paraxial()
dict_list = trace.trace_draw_ray(New_Lens)
draw.draw_system(New_Lens)
Unfortunately I was getting a few different errors, initially realised I had an older version, fixed that and downloaded the new files, but now i get the following:
RESTART: E:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\Lib\site-packages\opticspy\Opticspy Project\Triplet.py
Traceback (most recent call last):
File "E:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\Lib\site-packages\opticspy\Opticspy Project\Triplet.py", line 2, in <module>
from opticspy.ray_tracing import *
File "E:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\opticspy\ray_tracing\__init__.py", line 1, in <module>
from . import lens, trace, glass_function, draw, analysis, field, codev
File "E:\WinPython-64bit-3.5.3.0Qt5\python-3.5.3.amd64\lib\site-packages\opticspy\ray_tracing\codev.py", line 1, in <module>
import lens
ImportError: No module named 'lens'
>>>
I made sure to put my project folder into the opticspy folder, and i certainly have the lens.py file as well as the others in the ray_tracing folder. I took a screenshot and uploaded it here: http://imgur.com/a/0bM5Z
Thanks very much for the help and the wonderful module, I am excited to try it further!
ModuleNotFoundError Traceback (most recent call last)
/var/folders/5c/d7dj1h4j7znbnw5542h0plrh0000gp/T/ipykernel_74846/1698587845.py in
----> 1 import opticspy
~/SynologyDrive/venv/opticspy/init.py in
10 """
11 from future import division as division
---> 12 import aperture, interferometer_seidel,interferometer_zenike
13 import seidel, seidel2, zernike, test, tools, diffraction, jones, gauss
14 import phaseunwrap, lens, asphere, mplot3d, zernike_rec
ModuleNotFoundError: No module named 'aperture'
Hi,
Thank you for this amazing library !
I couldn't find a way to add a mirror surface or to decenter surfaces, could you walk me through the steps please ?
Thanks,
DrPaprikaa
Where exactly is the fitting taking place in the zernike fitting fuction? There should be a least square error solver or and SVD operation somewhere right?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.