def PlotMtfAllConfigs(self, bname, histos): """Loop over all configs in MCE, and plot the MTF for all active fields""" mce = self.TheSystem.MCE mcs = mce.NumberOfConfigurations #Loop over all configs for mc in range(mcs): mce.SetCurrentConfiguration(mc + 1) #Plot MTF gmtf = self.TheSystem.Analyses.New_GeometricMtf() settings = CastTo( gmtf.GetSettings(), 'IAS_GeometricMtf' ) #settings.ShowDiffractionLimit() settings.MaximumFrequency = 20.0 gmtf.ApplyAndWaitForCompletion() #gmtf.ToFile('m:\\gmtf.txt') results = gmtf.GetResults() fig, ax = plt.subplots(1,1, figsize=(8,6)) res5 = [0,0,0] res75 = [0,0,0] res10 = [0,0,0] #Loop over results. for i in range(results.NumberOfDataSeries): ds = results.GetDataSeries(i) plt.plot(ds.XData.Data,ds.YData.Data) resT = self.CheckLimits(ds.XData, ds.YData, 0, histos) #Tangential (or opposite) resS = self.CheckLimits(ds.XData, ds.YData, 1, histos) #Sagittal(or opposite) self.CornerCounter (resT, 0, res5, res75, res10) self.CornerCounter (resS, 1, res5, res75, res10) self.CornerCounter ((resT + resS)/2.0, 2, res5, res75, res10) histos.FillCounterHisto(histos.histos5 , res5) histos.FillCounterHisto(histos.histos75, res75) histos.FillCounterHisto(histos.histos10, res10) plt.grid() fig.savefig('c:\\Users\\haavagj\\plots\\' + bname + str(mc) + '.png') plt.close(fig)
def LocalOptimize(self, target): """ Start local optimization, keep tunning until MF is below target, local optimization converges, or 500 minutes has passed. """ lopt = self.TheSystem.Tools.OpenLocalOptimization() lopt.Algorithm = constants.OptimizationAlgorithm_DampedLeastSquares lopt.Cycles = constants.OptimizationCycles_Infinite lopt.NumberOfCores = 8 print("Starting local optimization") CastTo(lopt, "ISystemTool").Run() mf = lopt.InitialMeritFunction counter = 0 print("Starting loop, mf = " + str(mf)) while mf > target: time.sleep(6) mf = lopt.CurrentMeritFunction print("mf = " + str(mf)) counter = counter + 1 if( counter > 10): break CastTo(lopt, "ISystemTool").Cancel() CastTo(lopt, "ISystemTool").Close() return(mf)
def SpotDiagramAnalysisResults(self): # Spot Diagram Analysis Results spot = self.TheSystem.Analyses.New_Analysis( constants.AnalysisIDM_StandardSpot) spot_setting = spot.GetSettings() baseSetting = CastTo(spot_setting, 'IAS_Spot') baseSetting.Field.SetFieldNumber(0) baseSetting.Wavelength.UseAllWavelengths() baseSetting.Surface.UseImageSurface() # extract RMS & Geo spot size for field points base = CastTo(spot, 'IA_') base.ApplyAndWaitForCompletion() spot_results = base.GetResults() f = open(self.datadir + "rmsgeo.txt", "w+") f.write( str(spot_results.SpotData.GetRMSSpotSizeFor(1, 1)) + "\n" + str(spot_results.SpotData.GetGeoSpotSizeFor(1, 1))) # print('RMS radius: %6.3f' % # (spot_results.SpotData.GetRMSSpotSizeFor(1, 1))) # print('GEO radius: %6.3f' % # (spot_results.SpotData.GetGeoSpotSizeFor(1, 1))) spot.Close()
def OnProcessEvent(self, evt): try: evt = CastTo(evt, 'Event') if not self.handler: debug_event(evt) if evt.EventType == constants.RESPONSE: self.handler.on_event(evt, is_final=True) self.waiting = False elif evt.EventType == constants.PARTIAL_RESPONSE: self.handler.on_event(evt, is_final=False) else: self.handler.on_admin_event(evt) except Exception: import sys self.waiting = False self.exc_info = sys.exc_info()
def LateralColor(self, useAllWavelengths=True, showAiryDisk=True, useRealRays=True): newLateralColor = self.__TheAnalyses.New_LateralColor() newLateralColor_Settings = newLateralColor.GetSettings() newLateralColor_SettingsCast = CastTo(newLateralColor_Settings, 'IAS_LateralColor') newLateralColor_SettingsCast.AllWavelengths = useAllWavelengths newLateralColor_SettingsCast.ShowAiryDisk = showAiryDisk newLateralColor_SettingsCast.UseRealRays = useRealRays newLateralColor.ApplyAndWaitForCompletion() newLateralColor_Results = newLateralColor.GetResults() newLateralColor_ResultsCast = CastTo(newLateralColor_Results, 'IAR_') return newLateralColor_ResultsCast
def AddMTFOPGT(self, field, freq, target,type): """ Add operand of type type (GMTS or GMTT) for field and freq. Then add operant OPGT requiring the previous operand to be larger than target """ mfe = self.TheSystem.MFE mtf = mfe.AddOperand() mtf.ChangeType(type) p1 = mtf.GetOperandCell(constants.MeritColumn_Param1) p1.IntegerValue = 2 p3 = mtf.GetOperandCell(constants.MeritColumn_Param3) p3.IntegerValue = field + 1 p4 = mtf.GetOperandCell(constants.MeritColumn_Param4) p4.DoubleValue = freq p6 = mtf.GetOperandCell(constants.MeritColumn_Param6) p6.IntegerValue = 1 opgt = mfe.AddOperand() opgt.ChangeType(constants.MeritOperandType_OPGT) opgt.Target = target wc = opgt.GetOperandCell(constants.MeritColumn_Weight) wc.DoubleValue = 1.0 p1 = opgt.GetOperandCell(constants.MeritColumn_Param1) p1.IntegerValue = CastTo(mtf,'IEditorRow').RowIndex + 1
def TestGenerated(): # Create an instance of the server. from win32com.client.gencache import EnsureDispatch o = EnsureDispatch("PyCOMTest.PyCOMTest") TestCommon(o, True) counter = EnsureDispatch("PyCOMTest.SimpleCounter") TestCounter(counter, True) # This dance lets us get a CoClass even though it's not explicitly registered. # This is `CoPyComTest` from win32com.client.CLSIDToClass import GetClass coclass_o = GetClass("{8EE0C520-5605-11D0-AE5F-CADD4C000000}")() TestCommon(coclass_o, True) # Test the regression reported in #1753 assert bool(coclass_o) # This is `CoSimpleCounter` and the counter tests should work. coclass = GetClass("{B88DD310-BAE8-11D0-AE86-76F2C1000000}")() TestCounter(coclass, True) # XXX - this is failing in dynamic tests, but should work fine. i1, i2 = o.GetMultipleInterfaces() if not isinstance(i1, DispatchBaseClass) or not isinstance(i2, DispatchBaseClass): # Yay - is now an instance returned! raise error( "GetMultipleInterfaces did not return instances - got '%s', '%s'" % (i1, i2) ) del i1 del i2 # Generated knows to only pass a 32bit int, so should fail. check_get_set_raises(OverflowError, o.GetSetInt, 0x80000000) check_get_set_raises(OverflowError, o.GetSetLong, 0x80000000) # Generated knows this should be an int, so raises ValueError check_get_set_raises(ValueError, o.GetSetInt, "foo") check_get_set_raises(ValueError, o.GetSetLong, "foo") # Pass some non-sequence objects to our array decoder, and watch it fail. try: o.SetVariantSafeArray("foo") raise error("Expected a type error") except TypeError: pass try: o.SetVariantSafeArray(666) raise error("Expected a type error") except TypeError: pass o.GetSimpleSafeArray(None) TestApplyResult(o.GetSimpleSafeArray, (None,), tuple(range(10))) resultCheck = tuple(range(5)), tuple(range(10)), tuple(range(20)) TestApplyResult(o.GetSafeArrays, (None, None, None), resultCheck) l = [] TestApplyResult(o.SetIntSafeArray, (l,), len(l)) l = [1, 2, 3, 4] TestApplyResult(o.SetIntSafeArray, (l,), len(l)) ll = [1, 2, 3, 0x100000000] TestApplyResult(o.SetLongLongSafeArray, (ll,), len(ll)) TestApplyResult(o.SetULongLongSafeArray, (ll,), len(ll)) # Tell the server to do what it does! TestApplyResult(o.Test2, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test3, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test4, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test5, (constants.Attr2,), constants.Attr2) TestApplyResult(o.Test6, (constants.WideAttr1,), constants.WideAttr1) TestApplyResult(o.Test6, (constants.WideAttr2,), constants.WideAttr2) TestApplyResult(o.Test6, (constants.WideAttr3,), constants.WideAttr3) TestApplyResult(o.Test6, (constants.WideAttr4,), constants.WideAttr4) TestApplyResult(o.Test6, (constants.WideAttr5,), constants.WideAttr5) TestApplyResult(o.TestInOut, (2.0, True, 4), (4.0, False, 8)) o.SetParamProp(0, 1) if o.ParamProp(0) != 1: raise RuntimeError(o.paramProp(0)) # Make sure CastTo works - even though it is only casting it to itself! o2 = CastTo(o, "IPyCOMTest") if o != o2: raise error("CastTo should have returned the same object") # Do the connection point thing... # Create a connection object. progress("Testing connection points") o2 = win32com.client.DispatchWithEvents(o, RandomEventHandler) TestEvents(o2, o2) o2 = win32com.client.DispatchWithEvents(o, NewStyleRandomEventHandler) TestEvents(o2, o2) # and a plain "WithEvents". handler = win32com.client.WithEvents(o, RandomEventHandler) TestEvents(o, handler) handler = win32com.client.WithEvents(o, NewStyleRandomEventHandler) TestEvents(o, handler) progress("Finished generated .py test.")
def run(self): self.winh.ApplyAndWaitForCompletion() self.winh_Results = self.winh.GetResults() self.winh_ResultsCast = CastTo(self.winh_Results, 'IAR_')
Operand_1.ChangeType(constants.MeritOperandType_ASTI) Operand_1.Target = 0.0 Operand_1.Weight = 10.0 #! [e03s04_py] Operand_2 = TheMFE.InsertNewOperandAt(2) Operand_2.ChangeType(constants.MeritOperandType_COMA) Operand_2.Target = 0.0 Operand_2.Weight = 1.0 #Air min / max Operand_3 = TheMFE.AddOperand() Operand_3.ChangeType(constants.MeritOperandType_MNCA) Operand_3.Target = 0.5 Operand_3.Weight = 1.0 Operand_3Cast = CastTo(Operand_3, 'IEditorRow') Operand_3Cast.GetCellAt(2).IntegerValue = 1 Operand_3Cast.GetCellAt(3).IntegerValue = 3 Operand_4 = TheMFE.AddOperand() Operand_4.ChangeType(constants.MeritOperandType_MXCA) Operand_4.Target = 1000 Operand_4.Weight = 1.0 Operand_4Cast = CastTo(Operand_4, 'IEditorRow') Operand_4Cast.GetCellAt(2).IntegerValue = 1 Operand_4Cast.GetCellAt(3).IntegerValue = 3 Operand_5 = TheMFE.AddOperand() Operand_5.ChangeType(constants.MeritOperandType_MNEA) Operand_5.Target = 0.5 Operand_5.Weight = 1.0 Operand_5Cast = CastTo(Operand_5, 'IEditorRow') Operand_5Cast.GetCellAt(2).IntegerValue = 1
#im1 = ax1.imshow(data.Values, cmap='hot') #ax1.set_title('%.1f nm rms - %.1f nm ptv' %(RMS,PV)) #ax1.set_xlabel('x (pixels)') #ax1.set_ylabel('y (pixels)') ##plt.pcolormesh(matrix, cmap=plt.cm.get_cmap('plasma')) #plt.colorbar(im1) #plt.show() ############################################################################# # WFE map #Open WFE newWFE = TheAnalyses.New_WavefrontMap() #if settings need to be changed analysisSettings = newWFE.GetSettings() newWFE_SettingsCast = CastTo(analysisSettings, 'IAS_') # Run Analysis newWFE.ApplyAndWaitForCompletion() # Get Analysis Results newWFE_Results = newWFE.GetResults() #newWFE_ResultsCast = CastTo(newWFE_Results,'IAR_') data = newWFE_Results.GetDataGrid(0) print(data.Nx) print(data.Ny) print(data.MinX) print(data.Dx) print(data.Values)
# If the type of operand is THIC, the first parameter here means surface number MCOperand1.Param1 = 0 MCOperand2.Param1 = 11 #! [e18s04_py] #! [e18s05_py] # Set values of operand for each configuration MCOperand1.GetOperandCell(1).DoubleValue = 10000.0 MCOperand1.GetOperandCell(2).DoubleValue = 5000.0 MCOperand1.GetOperandCell(3).DoubleValue = 1000.0 #! [e18s05_py] #! [e18s06_py] # Refocus for each configuration quickfocus = TheSystem.Tools.OpenQuickFocus() QFtool = CastTo(quickfocus, "ISystemTool") # Gain access to ISystemTool methods TheMCE.SetCurrentConfiguration(1) # Set system to config 1 QFtool.RunAndWaitForCompletion() # Quick focus for config 1 TheMCE.SetCurrentConfiguration(2) QFtool.RunAndWaitForCompletion() TheMCE.SetCurrentConfiguration(3) QFtool.RunAndWaitForCompletion() #! [e18s06_py] TheSystem.SaveAs(zosapi.TheApplication.SamplesDir + "\\API\\Python\\e18_Double_Gauss_28_degree_field_MultiConfig.zmx") #! [e18s07_py] # An example of manually "Make Thermal" TheSystem.LoadFile(zosapi.TheApplication.SamplesDir + "\Sequential\Objectives\Doublet.zmx", False) # Add 1 configuration (totally 2) TheMCE.AddConfiguration(False)
# ! [e15s05_py] # Add 3 wavelengths: F,d,C slPreset = SystExplorer.Wavelengths.SelectWavelengthPreset( constants.WavelengthPreset_FdC_Visible) # ! [e15s05_py] # ! [e15s06_py] # Open a shaded model analysis = TheSystem.Analyses.New_Analysis( constants.AnalysisIDM_ShadedModel) analysis.Terminate() analysis.WaitForCompletion() analysisSettings = analysis.GetSettings() cfgFile = os.environ.get('Temp') + '\\sha.cfg' # Save the current settings to the temp file settings = CastTo(analysisSettings, 'IAS_') settings.SaveTo(cfgFile) # make your modifications to it # MODIFYSETTINGS are defined in the ZPL help files: The Programming Tab > About the ZPL > Keywords settings.ModifySettings(cfgFile, 'SHA_ROTX', '90') settings.ModifySettings(cfgFile, 'SHA_ROTY', '0') settings.ModifySettings(cfgFile, 'SHA_ROTZ', '0') # now load in the modified settings settings.LoadFrom(cfgFile) # If you want to overwrite your default CFG, copy it after you are done modifying the settings: # CFG_fullname = os.environ.get('USERPROFILE') + '\\Documents\\Zemax\\Configs\\POP.CFG' # copyfile(cfgFile, CFG_fullname) # We don't need the temp file any more, so delete it if os.path.exists(cfgFile): os.remove(cfgFile) # Run the analysis with the new settings
def run_pop(self, zemax_path, zemax_file, settings): start = time() # check that the file name is correct and the zemax file exists if os.path.exists(os.path.join(zemax_path, zemax_file)) is False: raise FileExistsError("%s does NOT exist" % zemax_file) print("\nOpening Zemax File: ", zemax_file) self.zosapi.OpenFile(os.path.join(zemax_path, zemax_file), False) file_name = zemax_file.split(".")[0] # Remove the ".zmx" suffix pop_sampling = { 32: 1, 64: 2, 128: 3, 256: 4, 512: 5, 1024: 6, 2048: 7, 4096: 8 } beam_types = {'top_hat': 3} # Hard-coded values surf_pupil_mirror = 16 # waist_x = 0.125 # waist_y = 0.125 waist_x = 0.185 waist_y = 0.185 slice_size = 0.47 # Size of a slice at the exit focal plane (slits) # Get some info on the system system = self.zosapi.TheSystem # The Optical System MCE = system.MCE # Multi Configuration Editor LDE = system.LDE # Lens Data Editor N_surfaces = LDE.NumberOfSurfaces # Read the POP Settings config = settings['CONFIG'] # N_slices = settings['N_SLICES'] wave_idx = settings['WAVE_IDX'] if 'WAVE_IDX' in settings else 1 field_idx = settings['FIELD_IDX'] if 'FIELD_IDX' in settings else 1 XWidth = settings['X_WIDTH'] YWidth = settings['Y_WIDTH'] end_surface = settings[ 'END_SURFACE'] if 'END_SURFACE' in settings else LDE.NumberOfSurfaces - 1 N_PIX = pop_sampling[settings['N_PIX']] sampling = pop_sampling[settings['SAMPLING']] beam_type = beam_types[ settings['BEAM_TYPE']] if 'BEAM_TYPE' in settings else 3 # (0) Info print("\nRunning POP analysis to Surface #%d: %s" % (end_surface, LDE.GetSurfaceAt(end_surface).Comment)) # (1) Set the Configuration to the Slice of interest system.MCE.SetCurrentConfiguration(config) print("(1) Setting Configuration to #%d" % config) if 'PM_X_HALFWIDTH' in settings: print("(2) Setting Pupil Mirror Aperture") x_halfwidth = settings['PM_X_HALFWIDTH'] pupil_mirror = system.LDE.GetSurfaceAt(surf_pupil_mirror) # Read Current Aperture Settings apt_type = pupil_mirror.ApertureData.CurrentType if apt_type == 4: # 4 is Rectangular aperture current_apt_sett = pupil_mirror.ApertureData.CurrentTypeSettings print("Current Settings:") print("X_HalfWidth = %.2f" % current_apt_sett._S_RectangularAperture.XHalfWidth) # print("Y_HalfWidth = %.2f" % current_apt_sett._S_RectangularAperture.YHalfWidth) # Change Settings aperture_settings = pupil_mirror.ApertureData.CreateApertureTypeSettings( constants.SurfaceApertureTypes_RectangularAperture) aperture_settings._S_RectangularAperture.XHalfWidth = x_halfwidth # aperture_settings._S_RectangularAperture.YHalfWidth = y_halfwidth pupil_mirror.ApertureData.ChangeApertureTypeSettings( aperture_settings) current_apt_sett = pupil_mirror.ApertureData.CurrentTypeSettings print("New Settings:") print("X_HalfWidth = %.2f" % current_apt_sett._S_RectangularAperture.XHalfWidth) # print("Y_HalfWidth = %.2f" % current_apt_sett._S_RectangularAperture.YHalfWidth) if end_surface == LDE.NumberOfSurfaces - 1: # (2) Set the Sampling at the last surface final_surface = LDE.GetSurfaceAt(end_surface) pop_data = final_surface.PhysicalOpticsData pop_data.ResampleAfterRefraction = True pop_data.AutoResample = False pop_data.XSampling = sampling - 1 # somehow the numbering for the sampling is different pop_data.YSampling = sampling - 1 # for the Resampling... stupid Zemax pop_data.XWidth = XWidth pop_data.YWidth = YWidth # (3) Set the POP Analysis Parameters theAnalyses = system.Analyses nanaly = theAnalyses.NumberOfAnalyses print("Number of Analyses already open: ", nanaly) pop = system.Analyses.New_Analysis_SettingsFirst( constants.AnalysisIDM_PhysicalOpticsPropagation) pop.Terminate() pop_setting = pop.GetSettings() pop_settings = CastTo(pop_setting, 'IAS_') if pop.HasAnalysisSpecificSettings == False: zemax_dir = os.path.abspath('H:\Zemax') # Remember not to mix the POP config with that of HARMONI cfg = zemax_dir + '\\Configs\\SWIFT_POP.CFG' pop_settings.ModifySettings(cfg, 'POP_END', end_surface) pop_settings.ModifySettings(cfg, 'POP_WAVE', wave_idx) pop_settings.ModifySettings(cfg, 'POP_FIELD:', field_idx) pop_settings.ModifySettings(cfg, 'POP_BEAMTYPE', beam_type) # 3 for Top Hap beam pop_settings.ModifySettings(cfg, 'POP_POWER', 1) pop_settings.ModifySettings(cfg, 'POP_SAMPX', N_PIX) pop_settings.ModifySettings(cfg, 'POP_SAMPY', N_PIX) pop_settings.ModifySettings(cfg, 'POP_PARAM1', waist_x) # Waist X pop_settings.ModifySettings(cfg, 'POP_PARAM2', waist_y) # Waist Y pop_settings.ModifySettings(cfg, 'POP_AUTO', 1) # needs to go after POP_PARAM pop_settings.LoadFrom(cfg) # (4) Run POP Analysis pop.ApplyAndWaitForCompletion() pop_results = pop.GetResults() cresults = CastTo(pop_results, 'IAR_') data = np.array(cresults.GetDataGrid(0).Values) # Close the Analysis to avoid piling up theAnalyses.CloseAnalysis(nanaly) self.zosapi.CloseFile(save=False) total_time = time() - start print("Analysis finished in %.2f seconds" % total_time) return data, cresults
#! [e10s01_py] # Open File, Save to New Name file = "\\Non-Sequential\\Ray Splitting\\Beam splitter.zmx" TheSystem.LoadFile(zosapi.TheApplication.SamplesDir + file, False) TheSystem.SaveAs(zosapi.TheApplication.SamplesDir + "\\API\\Python\\e10_NSC_ray_trace.zmx") #! [e10s01_py] #! [e10s02_py] # Run an NSC Ray Trace, Save .zrd file NSCRayTrace = TheSystem.Tools.OpenNSCRayTrace() # Open NSC RayTrace tool NSCRayTrace.ClearDetectors(0) # Clear all detectors # Set up RayTrace tool NSCRayTrace.IgnoreErrors = True NSCRayTrace.SaveRays = True NSCRayTrace.SaveRaysFile = "e10_API_RayTrace.ZRD" # Saves to same directory as lens file TraceTool = CastTo(NSCRayTrace, "ISystemTool") # Cast RayTrace to system tool interface to access Run and Close TraceTool.RunAndWaitForCompletion() TraceTool.Close() #! [e10s02_py] #! [e10s03_py] # Open Detector Viewer, view previously saved .zrd file DetectorView = TheSystem.Analyses.New_DetectorViewer() DetectorView_Settings = DetectorView.GetSettings() DetectorView_Set = CastTo(DetectorView_Settings, "IAS_DetectorViewer") # Gain access to settings properties DetectorView_Set.RayDatabaseFilename = "e10_API_Raytrace.ZRD" DetectorView_Set.ShowAs = constants.DetectorViewerShowAsTypes_FalseColor DetectorView_Set.Filter = "X_HIT(2, 4)" # Detector will only display rays which hit object 2 exactly 4 times DetectorView.ApplyAndWaitForCompletion() # Apply Settings to Detector Viewer #! [e10s03_py]
def run_raytrace(TheSystem, hx_arr, hy_arr, nsur, configurationRange): dfs = [] # Initialize x/y image plane arrays x_ary = np.empty([len(pxpys) * len(hx_arr) ]) # center field +4 extreme fields y_ary = np.empty([len(pxpys) * len(hy_arr)]) error_code = np.empty([len(pxpys) * len(hy_arr)], dtype=np.int32) vignette_code = np.empty([len(pxpys) * len(hy_arr)], dtype=np.int32) l = np.empty([len(pxpys) * len(hy_arr)], dtype=np.float32) m = np.empty([len(pxpys) * len(hy_arr)], dtype=np.float32) n = np.empty([len(pxpys) * len(hy_arr)], dtype=np.float32) px_output = np.empty([len(pxpys) * len(hx_arr)], dtype=np.float32) py_output = np.empty([len(pxpys) * len(hx_arr)], dtype=np.float32) hx_output = np.empty([len(pxpys) * len(hx_arr)], dtype=np.float32) hy_output = np.empty([len(pxpys) * len(hx_arr)], dtype=np.float32) # Adding Rays to Batch, varying normalised object height hy assert len(configurationRange) == 2 for configurationNumber in pb( range(configurationRange[0], configurationRange[1] + 1)): TheSystem.MCE.SetCurrentConfiguration(configurationNumber) TheSystem.SystemData.Fields.SetVignetting() raytrace = TheSystem.Tools.OpenBatchRayTrace() normUnPolData = raytrace.CreateNormUnpol( len(hx_arr) * len(pxpys), constants.RaysType_Real, nsur) normUnPolData.ClearData() waveNumber = 1 ray_counter = 0 for pxpy in pxpys: px, py = pxpy for j in range(len(hx_arr)): px_output[ray_counter], py_output[ray_counter] = px, py hx_output[ray_counter], hy_output[ray_counter] = hx_arr[ j], hy_arr[j] normUnPolData.AddRay(waveNumber, hx_arr[j], hy_arr[j], px, py, constants.OPDMode_None) ray_counter += 1 #! [e22s04_py] print('running raytrace...') baseTool = CastTo(raytrace, 'ISystemTool') baseTool.RunAndWaitForCompletion() normUnPolData.StartReadingResults() output = normUnPolData.ReadNextResult() j = 0 while output[0]: # success error_code[j] = output[2] vignette_code[j] = output[3] x_ary[j] = output[4] # X y_ary[j] = output[5] # Y l[j] = output[7] m[j] = output[8] n[j] = output[9] output = normUnPolData.ReadNextResult() j += 1 hx_deg = max_field * hx_output hy_deg = max_field * hy_output package = { 'hx_deg': hx_deg, 'hy_deg': hy_deg, 'x_pos': x_ary, 'y_pos': y_ary, 'px': px_output, 'py': py_output, 'error_code': error_code, 'vignette_code': vignette_code, 'l': l, 'm': m, 'n': n } df = pd.DataFrame(package) # end extracting rays r = np.sqrt(df['x_pos'].values**2 + df['y_pos'].values**2) sel = r < 85 dfs.append(df.iloc[sel]) baseTool.Close() return dfs
TheSystem.MCE.SetCurrentConfiguration(i+1) ThePrimarySystem = TheApplication.PrimarySystem TheSystemData = ThePrimarySystem.SystemData # use wave 2 (it should be in the cfg of the WFE map too): wave = 2 w = TheSystemData.Wavelengths.GetWavelength(wave).Wavelength # Open WFE newWFE = TheAnalyses.New_WavefrontMap() # if settings need to be changed # if settings are not changed, the cfg setting will be used # so cfg can be re-saved in Zemax if needed and it will be ok!!! newWFE_Settings = newWFE.GetSettings() newWFE_SettingsCast = CastTo(newWFE_Settings,'IAS_WavefrontMap') #newWFE_SettingsCast.Surface.SetSurfaceNumber(surf[i]) newWFE_SettingsCast.Wavelength.SetWavelengthNumber(wave) # Run Analysis newWFE.ApplyAndWaitForCompletion() # Get Analysis Results newWFE_Results = newWFE.GetResults() # get the data, print some data = newWFE_Results.GetDataGrid(0) print(data.Nx) print(data.Ny) #print(data.MinX) #print(data.Dx)
TheSystem = zosapi.TheSystem TheApplication = zosapi.TheApplication sampleDir = TheApplication.SamplesDir # Open file #file = 'Cooke 40 degree field.zmx' #testFile = sampleDir + '\\Sequential\\Objectives\\' + file testFile = sampleDir + '\\Sequential\\Objectives\\Cooke 40 degree field.zmx' TheSystem.LoadFile(testFile, False) # Create analysis TheAnalyses = TheSystem.Analyses newWin = TheAnalyses.New_FftMtf() # Settings newWin_Settings = newWin.GetSettings() newWin_SettingsCast = CastTo(newWin_Settings, 'IAS_FftMtf') newWin_SettingsCast.MaximumFrequency = 80 newWin_SettingsCast.SampleSize = constants.SampleSizes_S_256x256 # Run Analysis newWin.ApplyAndWaitForCompletion() # Get Analysis Results newWin_Results = newWin.GetResults() newWin_ResultsCast = CastTo(newWin_Results, 'IAR_') # Read and plot data series # NOTE: numpy functions are used to unpack and plot the 2D tuple for Sagittal & Tangential MTF # You will need to import the numpy module to get this part of the code to work colors = ('b', 'g', 'r', 'c', 'm', 'y', 'k') for seriesNum in range(0, newWin_ResultsCast.NumberOfDataSeries, 1): data = newWin_ResultsCast.GetDataSeries(seriesNum)
TheNCE.GetObjectAt(2).ZPosition = 9.99 TheNCE.GetObjectAt(2).Material = 'ABSORB' #! [e24s04_py] o3.YPosition = 1.5 o3.ZPosition = 8.99 o3.Material = 'N-BK7' o4.ZPosition = 10 o5.RefObject = 4 o5.ZPosition = 1e-3 #! [e24s05_py] # Sets layout rays based on parameter number TheNCE.GetObjectAt(1).GetObjectCell( constants.ObjectColumn_Par1).IntegerValue = 100 # Sets analysis rays based on object data column o1_data = CastTo(o1.ObjectData, 'IObjectSources') o1_data.NumberOfAnalysisRays = 1E6 #! [e24s05_py] o1.GetObjectCell(constants.ObjectColumn_Par10).DoubleValue = 50 o1.GetObjectCell(constants.ObjectColumn_Par11).DoubleValue = 50 o2.GetObjectCell(constants.ObjectColumn_Par3).DoubleValue = 0.5 o2.GetObjectCell(constants.ObjectColumn_Par4).DoubleValue = 1 o2.GetObjectCell(constants.ObjectColumn_Par9).IntegerValue = 1 o4.GetObjectCell(constants.ObjectColumn_Par1).DoubleValue = 8.223 o4.GetObjectCell(constants.ObjectColumn_Par2).DoubleValue = 2.565 o4.GetObjectCell(constants.ObjectColumn_Par3).IntegerValue = 200 o4.GetObjectCell(constants.ObjectColumn_Par4).IntegerValue = 150
# The connection should now be ready to use. For example: print('Serial #: ', TheApplication.SerialCode) # Insert Code Here TheSystem.New(False) file = '/mnt/c/Users/pwfa-facet2/Desktop/slacecodes/FACET_model_current/wavelength_runs/dtransport.zmx' TheSystem.LoadFile(file, False) TheAnalyses = TheSystem.Analyses TheLDE = TheSystem.LDE POP = TheAnalyses.New_Analysis(constants.AnalysisIDM_PhysicalOpticsPropagation) POP.Terminate() POP_Setting = POP.GetSettings() pop_settings = CastTo(POP_Setting, "IAS_") cfg = POP.GetSettings().LoadFrom( r'C:\Users\pwfa-facet2\Documents\Zemax\Configs\POP.CFG') pop_settings.ModifySettings(cfg, 'POP_BEAMTYPE', 0) pop_settings.ModifySettings(cfg, 'POP_SAMPX', 3) pop_settings.ModifySettings(cfg, 'POP_SAMPY', 3) pop_settings.ModifySettings(cfg, 'POP_PARAM1', 1) pop_settings.ModifySettings(cfg, 'POP_PARAM1', 1) pop_settings.ModifySettings(cfg, 'POP_AUTO', 1) for i in range(2, 5): print(i) pop_settings.ModifySettings(cfg, 'POP_START', 2) pop_settings.ModifySettings(cfg, 'POP_END', i)
o3.ChangeType(o3.GetObjectTypeSettings(constants.ObjectType_NullObject)) o4.ChangeType( o4.GetObjectTypeSettings(constants.ObjectType_DiffractionGrating)) o5.ChangeType(o5.GetObjectTypeSettings(constants.ObjectType_DetectorColor)) #! [e25s02_py] # Sets positions & materials o3.ZPosition = 10 o3.TiltAboutX = 10 o4.RefObject = 3 o4.Material = 'MIRROR' o5.YPosition = 8.45 o5.TiltAboutX = 40 # Sets parameters CastTo(o1.ObjectData, 'IObjectSourceDiode').XMinusDivergence = 5 CastTo(o2.ObjectData, 'IObjectSourceDiode').XMinusDivergence = 5 CastTo(o4.ObjectData, 'IObjectDiffractionGrating').LinesPerMicron = 0.6 CastTo(o4.ObjectData, 'IObjectDiffractionGrating').DiffOrder = 1 #! [e25s03_py] # Changes sourcecolor to Blackbody, sets temperature, min/max wavelength o1.SourcesData.SourceColor = constants.SourceColorMode_BlackBodySpectrum o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.TemperatureK = 6000 o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthFrom = 0.45 o1.SourcesData.SourceColorSettings._S_BlackBodySpectrum.WavelengthTo = 0.65 #! [e25s03_py] o2.SourcesData.SourceColor = constants.SourceColorMode_BlackBodySpectrum o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.TemperatureK = 6000 o2.SourcesData.SourceColorSettings._S_BlackBodySpectrum.SpectrumCount = 100
# Set up primary optical system sys = zosapi.TheSystem sys_data = sys.SystemData app = zosapi.TheApplication # print(dir(sys_data.Fields)) field_1 = sys_data.Fields.GetField(1) # psf = analyses.New_HuygensPsf() TheAnalyses = sys.Analyses asses = TheAnalyses.New_HuygensPsf() settings = asses.GetSettings() IAS_settings = CastTo(settings,'IAS_HuygensPsf') # print(dir(sys_data.__dict__['_oleobj_'].GetIDsOfNames)) asses.ApplyAndWaitForCompletion() asses_results = asses.GetResults() asses_results_cast = CastTo(asses_results, 'IAR_') Xs = [] Ys = [] print(asses_results_cast.NumberOfDataSeries) for seriesNum in range(0,asses_results_cast.NumberOfDataSeries,1): data = asses_results_cast.GetDataSeries(seriesNum) Xs.append(np.array(data.XData.Data))
#! [e17s03_py] # Non-sequential component editor TheNCE = TheSystem.NCE Object_1 = TheNCE.InsertNewObjectAt(1) Object_2 = TheNCE.InsertNewObjectAt(2) Object_3 = TheNCE.GetObjectAt(3) #! [e17s03_py] #! [e17s04_py] # Source point oType_1 = Object_1.GetObjectTypeSettings(constants.ObjectType_SourcePoint) Object_1.ChangeType(oType_1) Source1_data = Object_1.ObjectData Source1_data_cast = CastTo( Source1_data, "IObjectSources" ) # Cast to "IObjectSources" interface to get properties Source1_data_cast.NumberOfLayoutRays = 3 Source1_data_cast.NumberOfAnalysisRays = 1000000 #! [e17s04_py] #! [e17s05_py] # Rectangular Volume # Scattering Properties # Draw:opacity set to 50% oType_2 = Object_2.GetObjectTypeSettings( constants.ObjectType_RectangularVolume) Object_2.ChangeType(oType_2) Object_2.ZPosition = 2 Object_2.Material = "N-BK7" RectVolume2_data = Object_2.ObjectData
def objpath_fill(re_ovr, re_shp=None) -> Dict[Tuple[int, str], Any]: """ Finds paths to objects/properties having data and returns it as dict with values that points to data :param path_dir_out: :param re_ovr: saves only matched overlays' properties :param re_shp: if specified, save also matched shapes' properties :return: obj_path of exported grids: {(shp.Type, shp.Name): {(ovrl.Type, ovr_i): data}} """ doc = Surfer.ActiveDocument shapes = doc.Shapes obj_path = {} if shapes.Count > 0: for i_shp, shp in enumerate(shapes): if re_shp and not re.match(re_shp, shp.Name): continue if shp.Type == constants.srfShapeMapFrame: overlays = shp.Overlays if shp.Name.upper() != "ICON": # Do not touch Icons for ovr_i, ovrl in enumerate(overlays): if not re.match(re_ovr, ovrl.Name): continue if ovrl.Type in (constants.srfShapeContourMap, constants.srfShapeImageMap): ovrl = CastTo(ovrl, obj_interface[ovrl.Type]) data = {'GridFile': str(Path(ovrl.GridFile).name)} elif ovrl.Type == constants.srfShapeVector2Grid: #srfShapeVectorMap ovrl = CastTo(ovrl, obj_interface[ovrl.Type]) data = {'AspectGridFile': str(Path(ovrl.AspectGridFile).name), # East component 'GradientGridFile': str(Path(ovrl.GradientGridFile).name), # North component 'SetScaling': {'Type': constants.srfVSMagnitude, 'Minimum': ovrl.MinMagnitude, 'Maximum': ovrl.MaxMagnitude} # also saves comand to recover vector limits that is needed after grid replacing } # elif: else: data = None if data: if ':' in shp.Name: # Cansel modified Name effect of selected shape shp.Deselect() if (shp.Type, shp.Name) in obj_path: obj_path[(shp.Type, shp.Name)][(ovrl.Type, ovr_i)] = data else: obj_path[(shp.Type, shp.Name)] = {(ovrl.Type, ovr_i): data} if ovrl.Type in (constants.srfShapeContourMap, constants.srfShapeImageMap): # also save color limits that need to recover after grid replacing obj_path[(shp.Type, shp.Name)][(ovrl.Type, ovr_i)].update( {'ColorMap.SetDataLimits': { 'DataMin': ovrl.ColorMap.DataMin, 'DataMax': ovrl.ColorMap.DataMax} }) print(list(data.values())[0]) # if ovrl.Type == srfShapePostmap: # if ovrl.Type == srfShapeBaseMap: # else: # print('What?') # if b_setNames: # ovrl.Name= File + ovrl.Name Else ovrl.Name= Left(ovrl.Name,17) if (shp.Type, shp.Name) in obj_path: # data to replace was found # also save shp limits that need to recover after grid replacing obj_path[(shp.Type, shp.Name)].update({'SetLimits': {key: getattr(shp, key) for key in ( 'xMin', 'xMax', 'yMin', 'yMax')}, 'xMapPerPU': shp.xMapPerPU, 'yMapPerPU': shp.yMapPerPU}) elif re_shp: if shp.Type == constants.srfShapeText: #cast = 'IText' data = {'Text': shp.Text, # East component } if (shp.Type, shp.Name) in obj_path: if isinstance(obj_path[(shp.Type, shp.Name)], list): obj_path[(shp.Type, shp.Name)].append(data) else: obj_path[(shp.Type, shp.Name)] = [obj_path[(shp.Type, shp.Name)], data] else: obj_path[(shp.Type, shp.Name)] = data return obj_path
def FftMtfvsField(self, FieldDensity = 10, ScanType = '+y', SampleSizes = 64, Freq_1 = 0, Freq_2 = 0, Freq_3 = 0, \ Freq_4 = 0, Freq_5 = 0, Freq_6 = 0, RemoveVignetting = False, UsePolarization = False): newMtfvsField = self.__TheAnalyses.New_FftMtfvsField() newMtfvsField_Settings = newMtfvsField.GetSettings() newMtfvsField_SettingsCast = CastTo(newMtfvsField_Settings, 'IAS_FftMtfvsField') newMtfvsField_SettingsCast.FieldDensity = FieldDensity newMtfvsField_SettingsCast.ScanType = eval(dictScanType[ScanType]) newMtfvsField_SettingsCast.SampleSize = eval( dictSampleSize[SampleSizes]) newMtfvsField_SettingsCast.Freq_1 = Freq_1 newMtfvsField_SettingsCast.Freq_2 = Freq_2 newMtfvsField_SettingsCast.Freq_3 = Freq_3 newMtfvsField_SettingsCast.Freq_4 = Freq_4 newMtfvsField_SettingsCast.Freq_5 = Freq_5 newMtfvsField_SettingsCast.Freq_6 = Freq_6 newMtfvsField_SettingsCast.RemoveVignetting = RemoveVignetting newMtfvsField_SettingsCast.UsePolarization = UsePolarization newMtfvsField.ApplyAndWaitForCompletion() newMtfvsField_Results = newMtfvsField.GetResults() newMtfvsField_ResultsCast = CastTo(newMtfvsField_Results, 'IAR_') return newMtfvsField_ResultsCast
def queryInterface(self, obj, klazzName): from win32com.client import CastTo return CastTo(obj, klazzName)
def RemoveAllMtfRows(self): """Remove all the oparands in the merit function editor""" mfe = self.TheSystem.MFE nRows = mfe.NumberOfOperands dmfsrow = -1 CastTo(mfe,'IEditor').DeleteRowsAt(0, nRows)
field_type = 'Height' elif TheSystem.SystemData.Fields.GetFieldType( ) == constants.FieldType_ParaxialImageHeight: field_type = 'Height' elif TheSystem.SystemData.Fields.GetFieldType( ) == constants.FieldType_RealImageHeight: field_type = 'Height' analysis = TheSystem.Analyses.New_RMSFieldMap() analysis.Terminate() analysis.WaitForCompletion() analysisSettings = analysis.GetSettings() newSettings = analysis.GetSettings() rms_settings = CastTo( newSettings, "IAS_RMSFieldMap" ) # Cast to IAS_Spot interface; enables access to Spot Diagram properties rms_settings.Field.SetFieldNumber(1) rms_settings.Surface.SetSurfaceNumber(nsur) rms_settings.Wavelength.SetWavelengthNumber(1) rms_settings.UsePolarization = False rms_settings.RemoveVignettingFactors = False rms_settings.X_FieldSampling = sampling rms_settings.Y_FieldSampling = sampling rms_settings.X_FieldSize = field_semi_width rms_settings.Y_FieldSize = field_semi_width analysis.ApplyAndWaitForCompletion()
# Adding Rays to Batch, varying normalised object height hy normUnPolData.ClearData() waveNumber = wave #for i = 1:((max_rays + 1) * (max_rays + 1)) for i in range(1, (max_rays + 1) * (max_rays + 1) + 1): px = np.random.random() * 2 - 1 py = np.random.random() * 2 - 1 while (px * px + py * py > 1): py = np.random.random() * 2 - 1 normUnPolData.AddRay(waveNumber, hx, hy_ary[field - 1], px, py, constants.OPDMode_None) #! [e22s04_py] baseTool = CastTo(raytrace, 'ISystemTool') baseTool.RunAndWaitForCompletion() #! [e22s05_m] # Read batch raytrace and display results normUnPolData.StartReadingResults() output = normUnPolData.ReadNextResult() while output[0]: # success if ((output[2] == 0) and (output[3] == 0)): # ErrorCode & vignetteCode x_ary[field - 1, wave - 1, output[1] - 1] = output[4] # X y_ary[field - 1, wave - 1, output[1] - 1] = output[5] # Y output = normUnPolData.ReadNextResult() #! [e22s05_m] temp = plt.plot(np.squeeze(x_ary[field - 1, wave - 1, :]),
def runOne(Xdata, Ydata, outputDataFile): # Setup MFE = Merit Function Editor / LDE = lense Data Editor / MCE = Multi-Configuration Editor totalPoints = 0 for x in Xdata: totalPoints += len(x) print("totalPoints", totalPoints) print("chunks", len(Xdata)) TheSystemData.Fields.DeleteAllFields() # clears any residual data in Merit Function Editor (MFE) while TheMFE.NumberOfOperands > 1: TheMFE.RemoveOperandAt(1) if TheMFE.NumberOfOperands == 2: TheMFE.AddOperand() TheMFE.RemoveOperandAt(1) # clears Multi-Configuration Editor (MCE) and fills with n configurations TheMCE.DeleteAllConfigurations() for i in range(len(Xdata) - 1): TheMCE.AddConfiguration(False) for j in range(49): TheSystemData.Fields.AddField(0, 0, 1) # fills MCE with points, must have after fields are filled for j in range(len(Xdata[0])): TheMCE.AddOperand() TheMCE.GetOperandAt(3 * j + 2).ChangeType( constants.MultiConfigOperandType_XFIE) TheMCE.GetOperandAt(3 * j + 2).Param1 = j for k in range(len(Xdata)): if j > len(Xdata[k]) - 1: break TheMCE.GetOperandAt(3 * j + 2).GetOperandCell( 1 + k).DoubleValue = Xdata[k][j] TheMCE.AddOperand() TheMCE.GetOperandAt(3 * j + 3).ChangeType( constants.MultiConfigOperandType_YFIE) TheMCE.GetOperandAt(3 * j + 3).Param1 = j for k in range(len(Xdata)): if j > len(Ydata[k]) - 1: break TheMCE.GetOperandAt(3 * j + 3).GetOperandCell( 1 + k).DoubleValue = Ydata[k][j] TheMCE.AddOperand() # puts in VCX,VCY,VDX,VDY operands into MCE for n in range(len(Xdata[0])): TheMCE.InsertNewOperandAt(7 * n + 4) TheMCE.GetOperandAt(7 * n + 4).ChangeType( constants.MultiConfigOperandType_FVCX) TheMCE.GetOperandAt(7 * n + 4).Param1 = n TheMCE.InsertNewOperandAt(7 * n + 5) TheMCE.GetOperandAt(7 * n + 5).ChangeType( constants.MultiConfigOperandType_FVCY) TheMCE.GetOperandAt(7 * n + 5).Param1 = n TheMCE.InsertNewOperandAt(7 * n + 6) TheMCE.GetOperandAt(7 * n + 6).ChangeType( constants.MultiConfigOperandType_FVDX) TheMCE.GetOperandAt(7 * n + 6).Param1 = n TheMCE.InsertNewOperandAt(7 * n + 7) TheMCE.GetOperandAt(7 * n + 7).ChangeType( constants.MultiConfigOperandType_FVDY) TheMCE.GetOperandAt(7 * n + 7).Param1 = n # for each config, this sets all vignetting factors=0.9 then compputes it 4 times # (for accuracy ajustment), then fills the MCE operands with those values for k in range(len(Xdata)): TheMCE.SetCurrentConfiguration(k + 1) for m in range(len(Xdata[k])): TheSystemData.Fields.GetField(m + 1).VCX = 0.9 TheSystemData.Fields.GetField(m + 1).VCY = 0.9 TheSystemData.Fields.GetField(m + 1).VDX = 0.9 TheSystemData.Fields.GetField(m + 1).VDY = 0.9 TheSystemData.Fields.SetVignetting() TheSystemData.Fields.SetVignetting() TheSystemData.Fields.SetVignetting() TheSystemData.Fields.SetVignetting() VCX = [] VCY = [] VDX = [] VDY = [] for q in range(len(Xdata[k])): VCX.append(TheSystemData.Fields.GetField(q + 1).VCX) VCY.append(TheSystemData.Fields.GetField(q + 1).VCY) VDX.append(TheSystemData.Fields.GetField(q + 1).VDX) VDY.append(TheSystemData.Fields.GetField(q + 1).VDY) for p in range(len(Xdata[k])): # colby says to hand modify these # TheMCE.GetOperandAt(7*p+4).GetOperandCell(k+1).DoubleValue = VCX[p] # TheMCE.GetOperandAt(7*p+5).GetOperandCell(k+1).DoubleValue = VCY[p] TheMCE.GetOperandAt(7 * p + 4).GetOperandCell(k + 1).DoubleValue = 0.98 TheMCE.GetOperandAt(7 * p + 5).GetOperandCell(k + 1).DoubleValue = 0.98 TheMCE.GetOperandAt(7 * p + 6).GetOperandCell(k + 1).DoubleValue = VDX[p] TheMCE.GetOperandAt(7 * p + 7).GetOperandCell(k + 1).DoubleValue = VDY[p] #### Inputs Here ##### configs = TheMCE.NumberOfConfigurations #points per configuration points = TheSystemData.Fields.NumberOfFields SampleSize = 80 DENC_Sample_Size = 3 DENC_I_Sample_Size = 3 ImageSurface = TheLDE.NumberOfSurfaces - 1 print("configs", configs) # adds a cenx and ceny operand for each point # surface = 24, wave = 1, pol = 0, weight = 1 # other are what are specified in Inputs for j in range(len(Xdata)): TheMCE.SetCurrentConfiguration(j + 1) for i in range(points): x = 50 * 2 * j + 2 * i + 3 y = 50 * 2 * j + 2 * i + 4 TheMFE.AddOperand() TheMFE.GetOperandAt( (x)).ChangeType(constants.MeritOperandType_CENX) CastTo(TheMFE.GetOperandAt(x), 'IEditorRow').GetCellAt(2).IntegerValue = ImageSurface CastTo(TheMFE.GetOperandAt(x), 'IEditorRow').GetCellAt(3).IntegerValue = 1 CastTo(TheMFE.GetOperandAt(x), 'IEditorRow').GetCellAt(4).IntegerValue = i + 1 CastTo(TheMFE.GetOperandAt(x), 'IEditorRow').GetCellAt(6).IntegerValue = SampleSize CastTo(TheMFE.GetOperandAt(x), 'IEditorRow').GetCellAt(11).DoubleValue = 0 TheMFE.AddOperand() TheMFE.GetOperandAt(y).ChangeType( constants.MeritOperandType_CENY) CastTo(TheMFE.GetOperandAt(y), 'IEditorRow').GetCellAt(2).IntegerValue = ImageSurface CastTo(TheMFE.GetOperandAt(y), 'IEditorRow').GetCellAt(3).IntegerValue = 1 CastTo(TheMFE.GetOperandAt(y), 'IEditorRow').GetCellAt(4).IntegerValue = i + 1 CastTo(TheMFE.GetOperandAt(y), 'IEditorRow').GetCellAt(6).IntegerValue = SampleSize CastTo(TheMFE.GetOperandAt(y), 'IEditorRow').GetCellAt(11).DoubleValue = 0 TheMFE.RemoveOperandAt(2) for i in range(1, len(Xdata)): TheMFE.InsertNewOperandAt(len(Xdata[1]) * 2 * i + 1 + i) TheMFE.GetOperandAt((len(Xdata[1]) * 2 * i + 1 + i)).ChangeType( constants.MeritOperandType_CONF) CastTo(TheMFE.GetOperandAt(len(Xdata[1]) * 2 * i + 1 + i), 'IEditorRow').GetCellAt(2).IntegerValue = i + 1 # calculates merit funtion for further use TheMFE.CalculateMeritFunction() # output values for centroids # first converts to strings then floats because of how Zemax stores data xVals = [] yVals = [] print("points", points) for j in range(len(Xdata)): #print("j",j) for i in range(points): #print("i",i) _xVals = (str( CastTo(TheMFE.GetOperandAt(50 * 2 * j + 2 * i + 2 + j), 'IEditorRow').GetCellAt(12))) _yVals = (str( CastTo(TheMFE.GetOperandAt(50 * 2 * j + 2 * i + 3 + j), 'IEditorRow').GetCellAt(12))) xVals.append((str( CastTo(TheMFE.GetOperandAt(50 * 2 * j + 2 * i + 2 + j), 'IEditorRow').GetCellAt(12)))) yVals.append((str( CastTo(TheMFE.GetOperandAt(50 * 2 * j + 2 * i + 3 + j), 'IEditorRow').GetCellAt(12)))) #print("_xVals",_xVals) #print("_yVals",_yVals) #print("") num_to_cut = 50 * len(Xdata) - (50 - len(Xdata[len(Xdata) - 1])) xVals = xVals[0:totalPoints] yVals = yVals[0:totalPoints] for i in range(len(xVals)): #print("i",i,xVals[i],yVals[i],type(xVals[i]),type(yVals[i]),) try: _xVal = float(xVals[i]) _yVal = float(yVals[i]) except: _xVal = np.nan _yVal = np.nan xVals[i] = _xVal yVals[i] = _yVal # sets up and writes original telescope focal plane corrdinates and computed centroid values to csv file # fpX/Y = focal plane X/Y coordinates in mm # fvcX/Y = fiber view camera X/Y coordinates in pixels (divided by 0.006 mm below) fpX = [] fpY = [] for i in range(len(Xdata)): fpX.extend(Xdata[i]) fpY.extend(Ydata[i]) fpX = np.array(fpX) fpY = np.array(fpY) fvcX = [xVals[i] / 0.006 for i in range(len(xVals))] fvcY = [yVals[i] / 0.006 for i in range(len(yVals))] fvcX = np.array(fvcX) fvcY = np.array(fvcY) print("shapes", fpX.shape, fpY.shape, fvcX.shape, fvcY.shape) with open(outputDataFile, 'w', newline='') as file: writer = csv.writer(file, delimiter=',') names = np.array([ 'fpX', 'fpY', 'fvcX', 'fvcY' #,'FWHM' ]) numbers = np.array([ fpX, fpY, fvcX, fvcY #,FWHM ]).T data = np.append([names], numbers, axis=0) writer.writerows(data)
def queryInterface(self, oIUnknown, sClassName): from win32com.client import CastTo return CastTo(oIUnknown, sClassName)
# Adding Rays to Batch, varying normalised object height hy normUnPolData.ClearData() waveNumber = 1 ray_counter = 0 for pxpy in pxpys: px, py = pxpy for j in range(len(hx_arr)): px_output[ray_counter], py_output[ray_counter] = px, py hx_output[ray_counter], hy_output[ray_counter] = hx_arr[j], hy_arr[j] # noqa normUnPolData.AddRay(waveNumber, hx_arr[j], hy_arr[j], px, py, constants.OPDMode_None) # noqa ray_counter += 1 print('running raytrace...') baseTool = CastTo(raytrace, 'ISystemTool') baseTool.RunAndWaitForCompletion() # Read batch raytrace and display results normUnPolData.StartReadingResults() output = normUnPolData.ReadNextResult() j = 0 while output[0]: # success error_code[j] = output[2] vignette_code[j] = output[3] x_ary[j] = output[4] # X y_ary[j] = output[5] # Y l[j] = output[7] m[j] = output[8] n[j] = output[9]