ZEMAXandMatlab:APowerfulPair
ZEMAXfeaturesabuilt-inDDE(DynamicDataExchange)serverthatallowsotherWindows?applicationsaccesstoZEMAXfunctions.ProgrammingDDEapplicationscanbesomewhatcomplexifyouareworkinginacompiledlanguagesuchasC++.AnalternativeistouseoneofthescriptinglanguagessuchasTcl,PythonorMatlab.Matlabisagreatchoicesinceitismuchmorethanascriptinglanguage.MatlabprovidesawealthoffunctionsforprocessingandvisualizingscientificandengineeringdataandtherearetoolboxesforMatlabthatextendthebasiccapabilitiesintoawidevarietyofmorespecializedareasanddisciplines.
WhatIsDDE?
DDEisafacilityandaprotocolprovidedbyWindowstoallowapplicationstocommunicate.ThereareafewmodesofDDEinteraction,thesimplestbeingtheexchangeoftextstringsofdata.Oneoftheapplicationsmustsetitselfupasaserver.ZEMAXistheDDEserverinthiscase,soyoudon''thavetodoanythingexceptstartZEMAX.OnceyouhavestartedZEMAX,theDDEserverisreadyandwaitingforaclienttoconnectandmakerequestsforservices.TheclientapplicationinthiscaseisMatlab.
AccessingZEMAXfromMatLab
IfyoulookintheZEMAXmanualinthechapteron"ZEMAXExtensions"inthesectioncalled"TheDataItems",youwillseethevariousrequeststringsyoucansendtoZEMAXfromMatlab(orfromotherDDEclients).ThemanualalsodocumentsthereplythatZEMAXwillsendbacktotheclientapplication.TherequestscanbeforZEMAXtoperformaparticularfunctionorcomputation,orsimplytosendbackdataonthelenscurrentlystoredintheZEMAXDDEserver.
Nowhereisanimportantpointtonote.ZEMAXalwaysmaintainsaseparatecopyofthelensdataintheDDEservermemorytothatavailabletotheuserintheZEMAXLensDataEditor(LDE).Thisisaverygoodpolicy,sinceyoudon''twantsomeDDEclientcominginunexpectedlyandalteringyourlensdata.TherearefunctionsthatexplicitlycopythelensintheLDEtotheDDEserverortheotherwayaround.ThePushLensiteminstructsZEMAXtocopythelensdataintheZEMAXDDEserverintotheLDE,andtheGetRefreshitemwillcopythelensdataintheLDEintotheDDEserver.AsyoudevelopyourapplicationinMatlab,itisimportanttokeeptrackofyourdataandtakecarehowyouusethePushLensandGetRefreshitems.
FromtheZEMAXPreferencesdialog,youhavecontroloverwhetherextensions(Matlabinthiscase)areallowedtotellZEMAXtopushlensdatafromtheDDEserverintotheLDE.GototheEditorstabonthePreferencesdialogandlookforacheckboxlabeled"AllowExtensionstoPushLenses".
MatlabhasafewbasicfunctionsforperformingDDEclientoperations.Theyincludethefollowing.
ddeinit-ThisfunctionisusedtoinitiateaDDEconversationddereq-UsedtorequestdatafromtheDDEserverddeterm-TerminatestheDDElink
ThebasicsequenceforaccessingZEMAXfromMatlabis
1)StartZEMAXandMatlab.2)InitiatetheDDElinkfromMatlabusingtheddeinitfunction.3)SendrequestsandobtainrepliesfromZEMAXusingtheddereqfunction.4)TerminatethelinktoZEMAXusingtheddetermfunction.
Theddereqfunctionisusedinthetextmode,thatis,yousenddatatoZEMAXintheformofatextstringandtheanswerisreturnedintheformofanotherstring.TogetthestringsintoobjectclassesthataremoreusefulinMatlab(floats,doubles,integersetc.)youwillusethesscanffunctionorotherfunctionsforstringdataconversione.g.str2num.
TheZEMAXDDEToolboxforMatlab
YoucansaveyourselfsomeeffortbydownloadingtheZEMAXDDEtoolboxfromtheMathworksCentralFileExchange.ThistoolboxisopensourceundertheGPLandimplementsaMatlabfunctionforeachofthedataitemsdocumentedintheZEMAXmanualinthechapteronZEMAXExtensions.ThecorrespondingMatlabfunctioninthetoolboxhasthesamenameasthedataitem,butprefixedwith"z".Togetstarted,performthefollowingsteps.
Downloadthetoolboxarchive(.zipfile).
Unzipthearchivetoasub-directorycalledMZDDEanywhereonyourlocaldisk.
StartZEMAXandMatlab.
AddthedirectoryMZDDEtoyourMatlabpathtoenableMatlabtofindthenewfunctions(gototheFilemenuandselectSetPath...)
IfyoutypehelpmzddeattheMatlabprompt,youshouldgetalistofallthefunctionsinthetoolboxandashortdescriptionofeachfunction.Ifso,youarereadytousethetoolbox.
UsethefunctionzDDEInittoopentheDDElinktoZEMAX.Thisstepisimportant.Ifyoudon''tdothisbeforetryingtoexecuteothercallsinthetoolbox,MatlabwillissueaverboseerrormessagesuggestingthatsomethingterriblehashappenedandthatyoushouldcontacttheMathworkstechnicalsupportstaff.Ifthishappens,justignoretheerrorandmakethecalltozDDEInit.
Callotherfunctionsinthetoolboxasrequired,makingjudicioususeofzPushLensandzGetRefreshifyouneedtointeractwiththeZEMAXuserinterface.Ofcourse,youcancallthefunctionsfromtheMatlabcommandline,orincorporatethemintoyourMatlabfunctionsandscripts.
FinishoffbycallingzDDEClose.Thisisnotimportantinmostcases,andyoucanjustterminateMatlabandZEMAXwithoutclosingtheDDElink.
Notethatthetoolboxfunctionnamesarecapitalizedforreadability.MatlabfunctionnamesarecaseinsensitiveunderWindows?,sothatzddeinitisequivalenttozDDEInit.ThisisconvenientattheMatlabcommandline,butthecapitalizationhelpsforreadabilityinfunctionsandscripts.Thesourcecodeforallofthefunctionsisavailableformodificationandreuse,andyoucanexaminethesourcetoseehowthebasicMatlabDDEcallsareused.
TimeoutsEveryDDEcallmadebyMatlabtoZEMAXissubjecttoatimeoutlimit.ThedefaultissetinthezDDEInitfunctionto3seconds.Thatis,ifZEMAXdoesnotrespondtotheDDErequestwithin3seconds,theMatlabcallwillreturnempty-handed.YouwillwanttoincreasethetimeoutlimitifyouarecallingonZEMAXtodotime-consumingcomputations.ThiscanbedoneusingthezSetTimeoutfunctioncall.
ExampleHereisasimpleexampleofaninteractionwithZEMAXattheMatlabprompt.HavingstartedZEMAXintheusualway,enterthefollowingcommandsinMatlab.
>>zddeinit
ans=
????0
>>zLoadFile(''C:/ZEMAX/Samples/Sequential/Objectives/Cooke40degreefield.zmx'')
ans=
????0
>>zpushlens(1)
ans=
????0
>>[x,y]=SpiralSpot(0.4,0,1,10,10000);>>plot(x,y)
Youshouldgetaplotsomethinglikethis...
FirstlytheDDElinkwasinitializedandtheresultof0indicatedsuccess,thenZEMAXwasaskedtoloadalensintotheDDEserverwiththezLoadFilefunctioncall.Now,aprettywayofrepresentingaspotdiagramistotraceaspiralofraysthroughthelenspupilandtoplottherayinterceptsattheimageplane.ThisisimplementedinatoolboxfunctioncalledSpiralSpot.GethelpforthefunctionbytypinghelpspiralspotattheMatlabprompt.BecauseSpiralSpotactsonthelensintheLDEbystartingoutwithazGetRefresh,itisnecessarytoperformazPushLensbeforecallingSpiralSpot.Atimeoutof1secondwasspecifiedforzPushLenstocompleteinthiscase.
NotethatinthisexampleyouwouldgetthesameresultifyouhadloadedthesamelensintoZEMAXfromtheZEMAXFilemenuratherthanusingthezLoadFilecall.
TracingLargeNumbersofRays
ThestandardtextmodeoftheDDEcallisadequateformanypurposes,butnotwhenlargeamountsofdatahavetobeexchangedbetweentheclientandtheserver.Thissituationariseswhenyouneedtotracealargenumberofrays.Insteadoftracingtheraysoneatatime,anarraycontainingalistofalltheraystobetracediscreated,andthentheentirearrayis?passedtoZEMAXatonetime.ZEMAXthentracesalltherays,andpassestheentirearraybacktotheclient.RatherthantransferringallthisdataoverDDE,apointertothelocationinmemoryofthearrayispassedinstead.ThiseliminatesthebottlenexckofDDEcommunicationwhentracinglargenumbersofrays.Unfortunately,atthetimeofwritingthetoolbox,MatlabdidnotallowDDEmodesotherthantext.Tocircumventthisproblem,itwasnecessarytowritesomeCcodeinmex(Matlabexecutable)format.?Theresulting.dlliscalledzArrayTrace.
TypehelpzArrayTracetogetmoreinformationonbulkraytracing.ItwillalsobeusefultoconsultthecorrespondingsectionintheZEMAXmanual.TohelpsetuptherayinputdataforzArrayTracemode0,thereisafunctioncalledgenRayDataMode0.
CompilingStandaloneZEMAXExtensionswritteninMatlab
IfyouhavetheMatlabcompiler,itispossibletocompileyourMatlabscriptswrittenusingthetoolboxtostandaloneextensionsthatcanberunfromtheZEMAXExtensionsmenu.Thereareafewtrapsthatmustbeavoidedwhenattemptingthis.Firstly,thereareafewMatlabfunctionsthatcannotbecompiled,andyouwillhavetothinkofworkaroundsforsuchfunctions(fortunatelynotmany).Secondly,whileyourstandaloneextensionshouldrunfineonamachineonwhichMatlabisinstalled,itwillnotrunonamachinethatdoesnothavetheMatlabruntimelibraries.YoumustthereforepackageyourextensiontogetherwiththeMatlabruntimelibrariestomakeitfullyportable.Mathworksmakesthiseasierbypackagingmostoftherequiredruntimelibrariesinaself-extractingarchivecalledmglinstaller.exe(typicallyfoundinC:/MATLAB/extern/lib/win32orthereabouts).ThefinaltrapisthattheregularMatlabruntimelibrariesdonotcontainthecodefortheDDEfunctionsmentionedabove.These.dllfilescanbefoundbysearchingyourMatlabinstallationforfilesmatchingdde.dll(typicallyC:/MATLAB/Toolbox/matlab/winfunorthereabouts).Theruntimelibraries,includingtheDDElibraries,mustbeinstalledtoadirectorythatisontheWindowssearchpath.
ThingstoRememberwhenusingtheToolbox
1)YourfirstcallafterstartingupZEMAXandMatlabmustbetozDDEInit.2)Timeoutscanbeaproblem.IncreasetheDDEtimeoutlimitusingzSetTimeoutifnecessary.3)ZEMAXhastwocopiesofthelensdata,onedisplayedintheLensDataEditor,andtheotherstoredintheDDEserver.YourcancopytheonetotheotherusingthezPushLensandzGetRefreshfunctions.zPushLensalwaysrequiresasingleparametergivingthetimeoutinseconds.4)zPushLenswillonlyworkifyouhavegrantedZEMAXextensionspermissiontopushlensesbycheckingtheboxontheEditorstaboftheZEMAXPreferencesdialog.
|
|