Skip to main content
Solved

Error using ZOS-API in Python


PhWest

My codes (that were working with the 2024 version) do not work anymore with the 2025 release.
This is the error I get:

Unhandled Exception: System.IO.FileLoadException: Could not load file or assembly 'ZemaxEngine.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A).

Best answer by jwbeenakker

Hi PhWest,

Have you considered using ZOSPy? We recently released a new version, which works very well with the 2025 release (see https://zospy.readthedocs.io/en/latest/compatibility.html )

View original
Did this topic help you find an answer to your question?

jwbeenakker

Hi PhWest,

Have you considered using ZOSPy? We recently released a new version, which works very well with the 2025 release (see https://zospy.readthedocs.io/en/latest/compatibility.html )


MichaelH
Ansys Staff
Forum|alt.badge.img+2
  • Ansys Staff
  • April 2, 2025

Hi Philip,

You can also have multiple versions of OpticStudio installed on your computer so you can install OpticStudio 2024R2 to use your code and OpticStudio 2025R1 with the latest features for your other work.


joachim
  • Monochrome
  • April 8, 2025

I am using the latest version of zospy, but when I want to obtain the Zernike coefficients:

PATH_ZEMAX = r'C:\Program Files\Ansys Zemax OpticStudio 2025 R1.00'

# this is the pythonnet connector to zemax
zos = zp.ZOS(opticstudio_directory=PATH_ZEMAX)

oss = zos.connect("extension")
zern = zp.analyses.wavefront.ZernikeStandardCoefficients(
    sampling="64x64",
    maximum_term=37,
    wavelength=1,
    field=1,
    reference_opd_to_vertex=False,
    surface=5,
).run(oss)

I get the same exception from HRESULT: 0x8007045A:

 Unhandled Exception: Python.Runtime.InternalPythonnetException: Failed to create Python type for ZemaxUI.ZOSAPI.Analysis.Aberrations.AS_ZernikeStandardCoefficients ---> Python.Runtime.InternalPythonnetException: Failed to create Python type for ZemaxUI.ZOSAPI.Analysis.AS_Base ---> System.IO.FileLoadException: Could not load file or assembly 'ZemaxEngine.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)
   at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Signature..ctor(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
   at System.Reflection.RtFieldInfo.get_FieldType()
   at System.Reflection.RuntimeFieldInfo.ToString()
   at Python.Runtime.MaybeMemberInfo`1..ctor(T fi)
   at Python.Runtime.ClassManager.GetClassInfo(Type type, ClassBase impl)
   at Python.Runtime.ClassManager.InitClassBase(Type type, ClassBase impl, ReflectedClrType pyType)
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   --- End of inner exception stack trace ---
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   at Python.Runtime.DefaultBaseTypeProvider.GetBaseType(Type type)
   at Python.Runtime.DefaultBaseTypeProvider.GetBaseTypes(Type type, IList`1 existingBases)
   at Python.Runtime.PythonBaseTypeProviderGroup.GetBaseTypes(Type type, IList`1 existingBases)
   at Python.Runtime.TypeManager.GetBaseTypeTuple(Type clrType)
   at Python.Runtime.TypeManager.InitializeClassCore(Type clrType, PyType pyType, ClassBase impl)
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   --- End of inner exception stack trace ---
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   at Python.Runtime.CLRObject.GetReference(Object ob)
   at Python.Runtime.PyObject.FromManagedObject(Object ob)
   at Python.Runtime.PyObjectConversions.TryEncode(Object obj, Type type)
   at Python.Runtime.Converter.ToPython(Object value, Type type)
   at Python.Runtime.MethodBinder.Invoke(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase info, MethodBase[] methodinfo)
   at Python.Runtime.MethodObject.Invoke(BorrowedReference target, BorrowedReference args, BorrowedReference kw, MethodBase info)
   at Python.Runtime.MethodBinding.tp_call(BorrowedReference ob, BorrowedReference args, BorrowedReference kw)

 

The python kernel dies and is restarted. In Zemax, the Zernike window is open, the connection to python is lost, and I can just click on update and I get the coefficients.

python version 3.13.2,

Zemax: 2025 R1.00

Doing different things works, so it’s not overall broken.


MichaelH
Ansys Staff
Forum|alt.badge.img+2
  • Ansys Staff
  • April 8, 2025

Simple question but is the GUI instance you’re running also 25R1.00?  If you’re trying to connect as an extension (say 25R1.00) but you’re connecting with a different version of OpticStudio (say 24R2), you can get a runtime error.  Does the script work if you simply connect as a Standalone Application and not an Interactive Extension?

Also, it looks like the error is happening with setting the Field.  I don’t know how ZOSPy is setup if no field is passed (does it try to set it to 1 or does it not set it at all), so can you try to remove the field=1 and see if it works?


joachim
  • Monochrome
  • April 8, 2025

I have just one version installed (I uninstalled the old one before I installed the current). I even let Zemax recreate the Documents/ZEMAX folder, to avoid having files from previous versions (however, I copied back my projects).

In standalone mode, the kernel is also dying but it does not give an error message.

I went through the code, and it defaults the field to 1.

Tomorrow, I’ll try to use the ZOS-API directly without the zospy implementation and see if I can reproduce the same error.


joachim
  • Monochrome
  • April 10, 2025

I tried to use the ZOS-API directly, but after I give up at this point:

    zemax_application = ZOSAPI.ZOSAPI_Connection()
    prim_api = zemax_application.ConnectAsExtension(0)
#    prim_api = zemax_application.CreateNewApplication()

    if prim_api is None:
        print("Unable to connect to OpticStudio")
        return

    system = prim_api.PrimarySystem
 #   system.LoadFile(sample_file, False)

    analysis_manager = system.Analyses
    #zernike_analysis = analysis_manager.New_Analysis(ZOSAPI.Analysis.AnalysisIDM.ZernikeStandardCoefficients)
    zernike_analysis = analysis_manager.New_ZernikeStandardCoefficients()

    zern_settings = zernike_analysis.GetSettings()
    filename = 'C:/temp/zemax.config'
    zern_settings.SaveTo(filename)
    zern_settings.ModifySettings(filename, 'Surface', '4')
    zern_settings.LoadFrom(filename)

It is not possible to change the settings with that (“Surface” I tried to guess). zernike_analysis unfortunately has no properties I can modify directly. And having to create a file to write, change and reload feels a bit wrong, but I certainly misunderstood something.

In the documentation, I found this comment (in example 15):

# MODIFYSETTINGS are defined in ZPL help files: The Programming Tab > About the ZPL > Keywords

In the programming tab, I cannot find the ZPL keywords:

 

 


MichaelH
Ansys Staff
Forum|alt.badge.img+2
  • Ansys Staff
  • April 10, 2025

Hey Joachim,

The IAS_ZernikeStandardCoefficient (as well as Annular & Fringe) is hooked up to the ZOS-API:

The following code works for me to get the Zernike Standard Coefficients:

import os
import tempfile
import zospy as zp

zos = zp.ZOS()
TheSystem = zos.connect()

TheSystem.load(os.path.join(os.path.sep, TheSystem.TheApplication.SamplesDir, r'Sequential\Objectives\Double Gauss 28 degree field.zmx'))

win = TheSystem.Analyses.New_Analysis_SettingsFirst(zos.ZOSAPI.Analysis.AnalysisIDM.ZernikeStandardCoefficients)

win_settings = win.GetSettings()
win_settings.Field.SetFieldNumber(2)
win_settings.Surface.UseImageSurface()
win_settings.Wavelength.SetWavelengthNumber(2)
win_settings.SampleSize = zos.ZOSAPI.Analysis.SampleSizes.S_128x128
win_settings.ReferenceOBDToVertex = True
win_settings.Sx = 0.0
win_settings.Sy = 0.0
win_settings.Sr = 0.0
win_settings.Epsilon = 0.0
win_settings.MaximumNumberOfTerms = 36

win.ApplyAndWaitForCompletion()

res = win.GetResults()

temp = tempfile.TemporaryFile()
res.GetTextFile(temp.name + '.txt')

with open(temp.name + '.txt', encoding='utf-16') as f:
    print(f.read())

The ZPL Keyword is in the Help Files under The Programming Tab > About the ZPL > KEYWORDS (about the zpl).


joachim
  • Monochrome
  • April 10, 2025

I found that I can get the right settings-class:

zs = ZOSAPI.Analysis.Settings.Aberrations.IAS_ZernikeStandardCoefficients(zern_settings)

I can now access the Sx, ... values, however the Surface is just read only. Why is there no property for the surface number? Is that the reason why the zospy code crashes?


joachim
  • Monochrome
  • April 11, 2025

Hey Michael,

your example helped me a lot to narrow down the problem:

In pycharm (also IDLE), your script works, it also works with my file, it works in extension and interactive mode. Perfect.

To analyze problems, in pycharm I was using the debugging mode, and there it fails:

Unhandled Exception: Python.Runtime.InternalPythonnetException: Failed to create Python type for ZemaxUI.ZOSAPI.Analysis.Aberrations.AS_ZernikeStandardCoefficients ---> Python.Runtime.InternalPythonnetException: Failed to create Python type for ZemaxUI.ZOSAPI.Analysis.AS_Base ---> System.IO.FileLoadException: Could not load file or assembly 'ZemaxEngine.dll' or one of its dependencies. A dynamic link library (DLL) initialization routine failed. (Exception from HRESULT: 0x8007045A)
   at System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType)
   at System.Signature..ctor(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType)
   at System.Reflection.RtFieldInfo.get_FieldType()
   at System.Reflection.RuntimeFieldInfo.ToString()
   at Python.Runtime.MaybeMemberInfo`1..ctor(T fi)
   at Python.Runtime.ClassManager.GetClassInfo(Type type, ClassBase impl)
   at Python.Runtime.ClassManager.InitClassBase(Type type, ClassBase impl, ReflectedClrType pyType)
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   --- End of inner exception stack trace ---
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   at Python.Runtime.DefaultBaseTypeProvider.GetBaseType(Type type)
   at Python.Runtime.DefaultBaseTypeProvider.GetBaseTypes(Type type, IList`1 existingBases)
   at Python.Runtime.PythonBaseTypeProviderGroup.GetBaseTypes(Type type, IList`1 existingBases)
   at Python.Runtime.TypeManager.GetBaseTypeTuple(Type clrType)
   at Python.Runtime.TypeManager.InitializeClassCore(Type clrType, PyType pyType, ClassBase impl)
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   --- End of inner exception stack trace ---
   at Python.Runtime.ReflectedClrType.GetOrCreate(Type type)
   at Python.Runtime.CLRObject.GetReference(Object ob)
   at Python.Runtime.PyObject.FromManagedObject(Object ob)
   at Python.Runtime.PyObjectConversions.TryEncode(Object obj, Type type)
   at Python.Runtime.Converter.ToPython(Object value, Type type)
   at Python.Runtime.MethodBinder.Invoke(BorrowedReference inst, BorrowedReference args, BorrowedReference kw, MethodBase info, MethodBase[] methodinfo)
   at Python.Runtime.MethodObject.Invoke(BorrowedReference target, BorrowedReference args, BorrowedReference kw, MethodBase info)
   at Python.Runtime.MethodBinding.tp_call(BorrowedReference ob, BorrowedReference args, BorrowedReference kw)

and it is the line with GetSettings() that triggers the problem.

When I run the script in Spyder (6.0.5), the kernel just dies without further information. In debug mode, it fails with the message I had in the first place (Exception from HRESULT: 0x8007045A).


MichaelH
Ansys Staff
Forum|alt.badge.img+2
  • Ansys Staff
  • April 11, 2025

Hmm, interesting.  Obviously not an ideal situation, but there appears to be a known issue with cpython speedup in debug mode for PyCharm (and I assume other IDE’s in debug mode):

Exception only happens in PyCharm's debug mode : PY-59698

The simple solution is to add the PYDEVD_USE_CYTHON=NO environment variable to the debug configuration.

However, most users won’t know this is an issue with the IDE and won’t know how to fix it 😔.


joachim
  • Monochrome
  • April 11, 2025

Yes, I found that issue with pycharm as well, but disabling did not help in this case. I was thinking it might be that the debug mode analysis the variable types and structures, also something that the Spyder-IDE might be doing that in this case does not work great. Unfortunately, I don't see through this code at all.

I finally use jupyter notebooks, there I use an established connection to Zemax. I can see and analyse data, modify my routines. So I have similar flexibility like with Spyder. In the jupyter notebook I can use your code but also the initial code directly from the zospy library.


Reply


Cookie policy

We use cookies to enhance and personalize your experience. If you accept you agree to our full cookie policy. Learn more about our cookies.

 
Cookie settings