Вы находитесь на странице: 1из 17

ProgrammingforDaVisABasicGuide

Summer2012Coopworktermreport

PreparedforDr.Spinello

UndersupervisionofDr.Fenech

ByFrederickFahim(4874185)

Contents
Introduction .................................................................................................................................................. 1
Support...................................................................................................................................................... 1
SelfHelp.................................................................................................................................................... 1
Macros .......................................................................................................................................................... 2
CLFiles....................................................................................................................................................... 2
.setFiles .................................................................................................................................................... 2
CustomBatchOperations ......................................................................................................................... 2
UsingDLLs ................................................................................................................................................. 2
.SetFiles ........................................................................................................................................................ 3
Definition .................................................................................................................................................. 3
AcquisitionLoopsZaxisLoop ................................................................................................................ 3
Motivation............................................................................................................................................. 3
Implementation .................................................................................................................................... 3
NguyenBatchProcessing.......................................................................................................................... 4
Motivation............................................................................................................................................. 4
Development......................................................................................................................................... 5
DLLs ............................................................................................................................................................... 6
Motivation................................................................................................................................................. 6
RequiredFormat ....................................................................................................................................... 6
DaVis/DLLInterface................................................................................................................................... 6
DaVis ..................................................................................................................................................... 6
DLL......................................................................................................................................................... 6
LanguageConsiderations .......................................................................................................................... 7
InterfacingDaViswithMatlab ...................................................................................................................... 8
ThroughtheMatlabEngine ...................................................................................................................... 8
ThroughMEXFiles .................................................................................................................................... 8
MatView................................................................................................................................................ 8
UsefulDaVisObjectsandFunctions ........................................................................................................... 11
Buffers..................................................................................................................................................... 11

Dimensions.......................................................................................................................................... 11
Access.................................................................................................................................................. 11
Allocation ............................................................................................................................................ 11
Properties............................................................................................................................................ 12
StageControl........................................................................................................................................... 12
MotorControl ..................................................................................................................................... 12
MovingMiTasDiagonally.................................................................................................................... 13

Introduction
Thisguide,thetoolsdeveloped,theuserguides,sourcecodeandusefulprogramsareavailableon
LD511sinternalwebsiteunderthefilenameDaVis.ThesoftwareusedisDaVis7.2,MatlabR2010band
VisualStudio2010scompiler.

DaVis7.2isaprogramusedinPIVandPIV.LabD511makesuseofitalongwiththeMiTasstageanda
dualpulseYaGlaser.Seeingasitisnotthoroughlytestedcommercialsoftware,bugsarenotunheardof.
Ifafunctionssyntaxseemstobecorrectbutitdoesnotbehavepredictably,itmaybeagoodideato
contactLaVisionssupportteam.

Support
ItsproducersareGerman,soanyquestionaskedbyemailtoitsprogrammersistypicallyanswered
overnightifitcanatallbeansweredwithin24hours.Fornewprogrammingquestionsitis
recommendedtocallfirst,asLD511ssupport(RichardPrevost)willpinpointtheprogrammermost
intimatewiththeissue.

Phone:18772644697

Email:service@lavision.com,rprevost@lavisioninc.com

SelfHelp
ThelistofCLattributes,dialogs,subroutinesetc.hasbeenprovidedbyLaVision,howeverpleasenote
thatitisinnowayexhaustive:fromwithinDaVisanimmediatewindowandsearchablecommandlist
canbeaccessedbypressingF7andCtrl+F7,respectively.

IfaCLfileisbeingdeveloped,adebuggerisavailablethroughtheMacromenuorthroughaCLcallto
SetupDialogDebugger().

Macros
MacrosarefilescontainingaCommandLinefunctiondefinedCstylethat,whenloadedbyDaVis,canbe
calledbyusersiftheyarepublic.DaVismakesuseofClikesyntaxinitsCLlanguagetoprovidequite
someflexibilityandextensibility,aswellasaninterfacebetweenallitsworkingparts.

CLFiles
AllmacroscreatedcanbestoredinoneormanyCLfiles(e.g.User.CL)tobeloadedautomaticallywhen
DaVisstarts.ThesefilesarelocatedintheDaVisdirectoryunderthefoldercalledcl,andprovidemost
oftheundocumentedfunctionsmentionedinthisguidesintroduction.

.setFiles
Setfilescanbeloadedbythemacrotobeusedasparametersforvariouscommandsinvolvingmovies,
acquisition,batchoperationsetc.TheCLmanualdetailshowthesefilescanbemanipulated
programmatically.

CustomBatchOperations
Thereisanextensivesetofpredefinedbatchoperationsthatshouldprovideenoughfunctionalityfor
thetypicaluserbutifneeded,custombatchoperationscanbecreatedbyfollowingtheinstructions
fromtheCLmanualinSimplemodeorusingDaViscallbackfunctions(flowchart)inAdvancedmode.

UsingDLLs
DLLscanbecalledbymacrostocompletevarioustaskswhenmorefunctionalityorspeedisneeded.
Moreinformationcanbefoundinthisguide.

.SetFiles

Definition
SetfilesareakindoffileusedbyDaVistostoresettings.Thesefilesusuallyhavethe.setextension.
Setfilescanbeusedtoloadcustomsettingsforeverythingfromacquisitiontoprocessing,andmake
useofexistingfunctions(userdefinedorpackagedwithDaVis).Theymaybeaccessedprogrammatically
tospecifyhowaparticularactionistobecarriedout(e.g.whileautomatingacquisitionasetfilemaybe
loadedtoprovidetheloop).

AcquisitionLoopsZaxisLoop
Motivation
CoworkersusingDaVisandtheMiTasstageforPIVoftenhavetofindthestagepositionatwhichthe
camerasfocalplaneisthechannelsmidheight,wheretheflowsvelocityishighest.Thisinvolves
performingPIVatmultiplestageheights,whichisverytedioustodobyhand.Belowandlinkedisthe
implementationofasimpleacquisitionloopthatwillcaptureaspecifiednumberofpicturesstartingata
certainheight,ateverystep,untilacertainheight.Auserguidecanbefoundlinked.

Implementation
IntheacquisitionsectionoftheRecordingdialog(boxedinred,below),onecanseethattheprocedure
iscustomizablewithloops,commands,etc.Foranytaskstobeperformedduringacquisition,thisisthe
placeoperationswillbespecified.ChoosingaMiTasStageZLoopfromthelistofavailablecommands
andplacingtheImageAcquisitioncommandsubordinatetoityieldsthedesiredresults.

NguyenBatchProcessing
Motivation
TheNguyenmethodisusedtoacceleratebatchprocessingandcrosscorrelationbymakingaverages
whenPIVisperformedbyadoublepulsecamera.Themaximumintensityateachpixelacrossallthe
firstpulsepicturesistaken,asisdonewiththesecondpulse.Onesinglecrosscorrelationofthetwo
resultingpicturesgivesaveragedvelocitieswhilefilteringoutstaticparticleswhichmaybestuckonthe
channel,andwhenappliedwithapixelmask(whichcanbeturnedonoroffinthePIVoperationofa
batchprocessing)cancutprocessingtimeinhalformore.Theimplementationcanbefoundlinked,as
wellastheuserguideandmoreinformationontheNguyenmethod.

Development
Batchprocessingoperationlistsarelistsofcommonlyusedprocessingfunctions,wheretheoutputof
eachoperationisusedasinputforthenextoperation.Assuch,theNguyenmethodshouldbeamong
thefirstonthelist.

BecausetheNguyenmethodcompilespictures,thekindofbatchoperationwillbeunderStatistics.
TheNguyenmethodcallsforthemaximumintensityofeachpixel,sotheboxtocheckisMaximum.

I
tshouldbenotedthatcustombatchoperationscanbedefinedbutoftennecessarytoolsarepre
existing.

DLLs
ADynamicallyLinkedLibraryisanexecutablethatcannotrunonitsown,butrathercontainscompiled
functionscallablefromrunningprograms.Thisisaformofmodularizationthatisbecomingincreasingly
popularforpluginsandaddons.

ForcommunicationwithotherPCsandsoftware(Ex:DaVis,LabView,etc.)DaVishasRemote.DLL,a
modulewhichhandlesnetworkprotocols,datatransferandremotecommands.Thereismore
informationabouttheseoperationsintheCLmanual.

AusefultoolforthescrutinyandtestingofDLLsiscalledtheDependencyWalker,itcanbeusedtosee
allthefunctionsimplementedintheDLLandthestyleinwhichtheyarespecified.

Motivation
AsDaVismacrosmustbeinterpretedbythesoftware,theymaynotrunasquicklyascanberequiredfor
certainapplicationsandtheusermaysometimesrequirefunctionsnotimplementedinthesoftware.In
thesecases,programmersmaycompiletheirownDLLsforDaVistouse.

RequiredFormat
WhenloadingaDLL,DaViswillcallaninitializationfunctionintheDLLandpassitfunctionhandlesto
manytypicalDaViscommands,allowingtheDLLtocontrolDaVis.Toallowthis,theDLLmustcontainthe
interfacefilewhichdefinesthesehandlesasconstants.AcalltothefunctionInitDllwithinthe
CL_DLL_Interfaceismade,attheendofwhichInitDll callsafunctionMyInitDllExtensionsfor
custominitialization(thiscallcanbecommentedout,asitisfortheprogrammersconvenience).

Note:ForfunctionstobecallablebyDaVis,theDLLmustexporttheminCstyle(flat).Forthe
programmersconvenience,CL_DLL_Interfacedefinesamacro

extern C <return_type> EXPORT <function_name>

whichdoesthisindependentlyofthecompilerused.

DaVis/DLLInterface
DaVis
FunctionsintheDLLmaybecalledusingtheCLcommands

int CallDll(string DLL_Name, string Function_Name, int/float & Pars)

int CallDllEx(string DLL_Name, string Function_Name, int & IntPars, float &
FloatPars, string & StringPars)

DLL
PassingmessagesisachievedthroughthestandardCLfunctions

void InfoText(string Message)

void StatusText(string Message)

andworkaroundsforstringpassinghavebeendetailedbyLaVision.

Accessingbufferdataisachievedwiththefunction

Void * GetBufferRowPtr(int buffer, int row);

AndanyCLcommandcanbeexecutedbyDaViswithacallto

Void ExecuteCommand(char * cmd);

LanguageConsiderations
WhileC++isthefirstlanguagethatshouldcometomindduetoitsuseintheCL_DLL_Interface,quite
someflexibilitymaybegrantedthroughtheuseofaprecompiledCL_DLL_Interfacelibraryandfunction
wrappers.

CertainconsiderationsshouldbemadeastowhichlanguageisusedtoproducetheDLL:

Ifprocessingspeedisanissue(realtimeortimecriticalapplications),C++shouldbeusedto
minimizeoverhead.
Ifthefunctioniscomplex,Matlabmaybebestduetoitsscientificnatureandtoolboxes.

AlsoincludedinthisguideisasectionforMatlabgeneratedDLLs.

ItshouldbementionedthatwhileMatlabisstillquiteafastlanguage,itsuseduringhighspeed
acquisitionandsuchmaybequestionable.Toillustrate,asnapshotofMatViewsDependencyTreeis
shownbelow.

ItcanbeseenthatMatViewanditsoperationalcore(PLOTTER.DLL),beingMatlabgenerated,depend
onMatlabs(MCLMCRRT),MicrosoftCs(MSVCR)andVisualC++s(MSVCP)runtimes.Thismeansthat
C++codecallingMatlabmustfirstpassthroughMSVCP,MSVCRandthenMCLMCRRT.

InterfacingDaViswithMatlab
Themethodsdetailedbelowoperateatapproximatelythesamespeed(detailsandspeedoptimizations
aswellasrelatedconsiderationsmaybefoundontheMathWorkssite),whichisnoticeablyslowerthan
C++.

ThroughtheMatlabEngine
ForanythingtobedonewiththeMatlabEngine,Matlabmustbeinstalledonthecomputer.

DaViscontainsafewfunctionswithintheMATLAB.CLsystemfile(includedforconvenience)whichallow
directexecutionofMatlabcommandsbyanEngineinstancefromwithinDaVis.

ThroughMEXFiles
ForMatlabgeneratedmodules,bothMatlabsMCRandVisualC++sredistributablesmustbeinstalled
onthecomputer.

Matlabcanbeusedtoproduceexecutablesandlibrarieswhichmayrunonanycomputer.Itshouldbe
notedthatsincethedefaultcompilerforMatlabsmbuildcommandisaConeandtheInterfacefilesare
C++,VisualC++scompiler(supportedbyMatlab)mustbeusedinstead.

MatView

Motivation
MatViewisanextensionoftheZAxisloopdevelopedearliertopermitPIVuserstovisualize3D
velocityprofilesandexportthemtoMatlabforfurtheranalysis.Asitshowsa3Dprofileimmediately
afterbatchprocessing,itallowsuserstoquicklyspotthemidchannelfocalplane.Italsoservesasa
goodintroductiononinterfacingDaVisandMatlabastheMatlabfunctioninvolvedisverybasic.

Development

MatlabCodetoCSharedLibrary
ThecommandinMatlabneededtodisplaya3Dsurfaceplotsuchastheoneobtainedbycombiningall
ofthewidthvelocityprofilesobtainedthroughbatchprocessingisthefollowing:

Handle = surf(X,Y,Z)

Sincethiscommandneedstobecompiledintoalibraryitissavedasplot_intensitiesandnowbecomes
acallablefunction.Tocompileitintothelibrarytypeneeded,theproperMatlabcommandis

mcc -B csharedlib:Plotter Plotter\plot_intensities.m

wherePlotterwillbethenameofthesharedlibrary.

CSharedLibraryandMatlabinC++Code

Includes
OfthefilesproducedbytheMCC,onewillneedtobeincludedintheC++wrapper:Plotter.h.IntheC++
code,thefollowingincludesmustthenbemade

#include "Plotter.h"
#include "CL_DLL_Interface.h"
#include "matrix.h"
#include <list>

Wherematrix.hisusedtocreateMatlabmatrices.Listsareusedtoaccumulatethedatapassedto
MatViewfromDaVisduringbatchprocessing,sothateverythingcanbeprocessedbyMatView
afterwards.Thereseemstobenorestrictionsregardingwhethercodeismanagedornot,using
unmanagedcodewassimplyachoice.

Matrices
Oncematrix.hisincluded,Matlabdoubleprecisionrealmatricesmaybedeclared,

mxArray * array_name;

instanced,

array_name = mxCreateDoubleMatrix(int rows, int cols, mxREAL);

andinitializedusing

memcpy(mxGetPr(array_name), double * data_ptr, int data_size * sizeof(double));

wheredata_ptrisapointertoapreexistingarrayofdoubles,anddata_sizeisthesizeofthisarray.It
shouldbenotedthatMatlabwillreada1Darraycolumnwiseintoa2Dmatrix.

CompiledLibraryApplication
WhencomestimetoinvoketheMatlabfunctionscompiled,firstacalltoinitializeanewMCRinstance
mustbemade

mclInitializeApplication(NULL, 0);

mustbemadetotelltheMCRtoinitializeanewMatlabapplication.Then

PlotterInitialize();

iscalledtoinitializethePlotterlibrary,afterwhich

mlfPlot_intensities(mxArray X, mxArray Y, mxArray Z);


mclWaitForFiguresToDie(NULL);

maybecalled.Notethattheplot_intensitiescommandinMatlabhasnowbecomemlfPlot_intensities:
MatlabcommandsnamesaredefinedinC/C++suchthattheybeginwithmlfandacapitalfirstletter.

mclWaitforFiguresToDie(NULL)simplytellstheMatlabapplicationnottoclosethefigureorterminate
untilitisclosed.

WheneverythingthatneededdoinginMatlabhasbeendone,acallto

PlotterTerminate();
mclTerminateApplication();

shouldbemadetoterminatethePlotterlibraryandtheMCRInstance,respectively.

CompilingtheC++Wrapper(MatView)
TospecifywhichfunctionsintheDLLshouldbemadepublic,.exportsfilesneedtobecreatedforeach
CPPfileinvolved.BelowisCL_DLL_Interface.exports:

InitDll

andMatView.exports:

add_depth
add_profile
set_verbose
process

Onlythenameisstatedandthefilesendwithanewline.

ThewrappercanthenbecompiledusingMatlabscommandline:

mcc W lib:MatView CL_DLL_Interface.cpp MatView.cpp Plotter.lib


CL_DLL_Interface.exports MatView.exports

CPPfilesgofirst,libraryfilesnextandexportsattheend.

Matlabwillthenevokethecompilerandpassonanymessages.Finally,aDLLisproduced.When
migratingittothetargetcomputer,itshouldbecopiedwithitsinternallibraryaswell(Plotter.dllinthis
case)andregisteredusingthecommandlinetoolregsvr32.

10

UsefulDaVisObjectsandFunctions

Buffers
BuffersareusedbyDaVistoholdinformationaboutasingleinstantintime.Forpulsedcameras,allthe
pulsesarestoredinonebufferwithmultipleframes:foradoublepulsecamerataking100shots,there
willbe100buffersoftwoframeseachoneframeforeachpulseandonebufferforeachsnapshot.

BuffersarestoredwithinDaVisglobalmemory,andpointerstothemmaybepassedtocommandsinCL
asintegers.Typicallybuffers0and1arereservedfortheprogram,andtemporarybuffersseemtobe
around500.MoreinformationonbuffersandtheoperationssupportedcanbefoundintheCLmanual.

Dimensions
Theyarecomposedof5dimensions,thoughthesedimensionsmustbeaccessedthroughfunctions.

X
Y
Z
Frame
Intensityorvector

Access
BufferscanbedesignatedbytheCLstatement

B[index];

Andpixelswithinthebuffercanbedesignatedby

Pix[index, x, y];

indexbeingthenumberofthebuffer.Whendealingwith3Dbuffersorvectorbuffers,voxelswillbe
usedinstead.

Allocation
Whenperformingprocessingonbuffers,DaViswillfrequentlystoretheresultsofeachoperationinto
thesamebufferinanefforttominimizememoryusage.ThiskindofbufferiscalledaTemporaryBuffer,
andcanbemanuallyallocatedwiththecommand

int GetTempBuffer();

If,however,aReservedBufferwhichpersistsuntilDaVisclosesshouldbeallocated,thefollowing
commandcanbeusedinstead

int GetReservedBuffer();

TemporaryandReservedbufferscanbelockedtopreventchangestothemandlaterunlocked:

11

void LockBuffer(int buffnum);

void UnlockBuffer(int buffnum);

Copying
Copiesofexistingbufferscanbeautomaticallymadeandallocatedusingthecommand

int GetTempBufferCopy();

Deallocation
Whentemporaryandreservedbuffersarenolongerneeded,theyshouldbedeallocated(toavoid
memoryleaks)withthefollowingcommands,respectively

FreeBuffer(int buffer);

FreeReservedBuffer(int buffer);

Properties
InformationaboutbufferscanberetrievedthroughvariousfunctionsprovidedbyDaVis.A
comprehensivelistoftheseattributesmaybefoundlinked.

RealWorldPositions
Itcanbeusefultoknowtheactualstagepositionatwhichaframewasacquired:thiscanbedone
throughthefollowingcommand,alsoavailableforYandZcoordinates*.

Buffer_GetRealWorldFramePositionX(int theBuffer, int theFrame, float&


thePosition, string& theUnit, string& theLabel)

*DuetobugsinDaVis7.2,thiscommandreturnsnothinguseful.LaVisioniscurrentlyworkingona
solution.

CustomAttributes
Ifaparameterisencodedtothefilenameduringacquisitioninthefollowingformat
ParameterName=ParameterValue,acorrespondingattributewiththename
ExpPathValue_ParameterNameisautomaticallycreated.Thisspecificattributecanthenberetrieved
using:

string sValue = GetBufferAttribute(int buffer, char * attribute);

StageControl
MotorControl
DaVisallowsforprogrammaticcontroloftheMiTasstagethroughtwomacros*

void RotateSteps(int motor, int steps);

void SetStepMotor(int motor, float pos);

*fornow,RotateSteps()seemstohaveabuginitandwillnotdoanything.LaVisioniscurrentlyworking
onthis.

12

Formotorcontrolatthesoftwarelevelduringtheacquisitionstage,seetheZAxisLoopexampleand
themanualsacquisitionmacrossection.Ifitistohappenatthehardwarelevel,consider.ACQfiles.

MovingMiTasDiagonally
ThePIVmachinewillbeusedtotrackparticles(redbloodcellaggregations,bubblesetc.)while
studyingthemandtheflowsurroundingthem.TodosotheMiTasstageneedstobeabletomove
diagonallysometimes,afunctionwhichisnotimplementedbyLaVisioninourcurrentsoftwarepackage
asmotorshavetobemovedseparately.

Asaremedy,abasic2Ddiagonallinefunctionwascreatedusingsimpleloopsandintegermath.Ithas
beenimplementedinMatlabtobeabletohandleanyangleandfollowastraightlinetoitsdestination
ascloselyaspossiblesothatitmaybeusedincombinationwithahighspeedcamera.Itdoes
occasionallydriftawayfromthetruediagonalandcoulduseimprovementbutifneeded,thecodecan
easilybetranslatedtoCLandmadetohandle3Ddiagonals.

>> GoSteps(10,50)

>> GoSteps(-60,31)

>> GoSteps(50, -52)

>> GoSteps(-50, -29)

>> GoSteps(50,0)

Yieldsthefollowingpathsandshowsmoreextremecasesofdeviation(truepathsinred,motorstepsin
black).

13

14

Вам также может понравиться