licenses
sequencelengths
1
3
version
stringclasses
677 values
tree_hash
stringlengths
40
40
path
stringclasses
1 value
type
stringclasses
2 values
size
stringlengths
2
8
text
stringlengths
25
67.1M
package_name
stringlengths
2
41
repo
stringlengths
33
86
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
11864
# SIAMFANLEquations.jl [C. T. Kelley](https://ctk.math.ncsu.edu) [SIAMFANLEquations.jl](https://github.com/ctkelley/SIAMFANLEquations.jl) is the package of solvers and test problems for the book __Solving Nonlinear Equations with Iterative Methods:__ __Solvers and Examples in Julia__ This documentation is sketchy and designed to get you going, but the real deal is the [IJulia notebook](https://github.com/ctkelley/NotebookSIAMFANL) ## Scalar Equations: Chapter 1 ### Algorithms The examples in the first chapter are scalar equations that illustrate many of the important ideas in nonlinear solvers. 1. infrequent reevaluation of the derivative 2. secant equation approximation of the derivative 2. line searches 3. pseudo-transient continuation Leaving out the kwargs, the calling sequence for getting nsolsc to solve ``f(x) = 0`` is ```julia nsolsc(f,x, fp=difffp) ``` Here x is the initial iterate and fp (optional) is the function for evaluating the derivative. If you leave fp out, nsold uses a forward difference approximation. See the code overview or the notebook for details. Here are a couple of simple examples. Solve ``atan(x) = 0`` with ``x_0 = 0`` as the initial iterate and a finite difference approximation to the derivative. The output of nsolsc is a tuple. The history vector contains the nonlinear residual norm. In this example I've limited the number of iterations to 5, so history has 6 components (including the initial residual, iteration 0). ```julia julia> nsolout=nsolsc(atan,1.0;maxit=5,atol=1.e-12,rtol=1.e-12); julia> nsolout.history 6-element Array{Float64,1}: 7.85398e-01 5.18669e-01 1.16332e-01 1.06102e-03 7.96200e-10 2.79173e-24 ``` Now try the same problem with the secant method. I'll need one more iteration to meet the termination criterion. ```julia julia> secout=secant(atan,1.0;maxit=6,atol=1.e-12,rtol=1.e-12); julia> secout.history 7-element Array{Float64,1}: 7.85398e-01 5.18729e-01 5.39030e-02 4.86125e-03 4.28860e-06 3.37529e-11 2.06924e-22 ``` In this example I define a function and its derivative and send that to nsolsc. I print both the history vectors and the solution history. ```julia julia> fs(x)=x^2-4.0; fsp(x)=2x; julia> nsolout=nsolsc(fs,1.0,fsp; maxit=5,atol=1.e-9,rtol=1.e-9); julia> [nsolout.solhist.-2 nsolout.history] 6×2 Array{Float64,2}: -1.00000e+00 3.00000e+00 5.00000e-01 2.25000e+00 5.00000e-02 2.02500e-01 6.09756e-04 2.43940e-03 9.29223e-08 3.71689e-07 2.22045e-15 8.88178e-15 ``` ## Nonlinear systems with direct linear solvers: Chapter 2 The solvers ```nsoli.jl``` and ```ptcsol.jl``` solve systems of nonlinear equations ``F(x) = 0`` The ideas from Chapter 1 remain important here. For systems the Newton step is the solution of the linear system ``F'(x) s = - F(x)`` This chapter is about solving the equation for the Newton step with Gaussian elimination. Infrequent reevaluation of the Jacobian ``F'``means that we also factor ``F'`` infrequently, so the impact of this idea is greater. Even better, there is typically no loss in the nonlinear iteration if we do that factorization in single precision. You an make that happen by giving nsold and ptcsold the single precision storage for the Jacobian. Half precision is also possible, but is a very, very bad idea. Bottom line: __single precision can cut the linear algebra cost in half with no loss in the quality of the solution or the number of nonlinear iterations it takes to get there.__ The calling sequence for solving ```F(x) = 0``` with ```nsol.jl```, leaving out the kwargs, is ```julia nsol(F!, x0, FS, FPS, J!=diffjac!) ``` FS and FPS are arrays for storage of the function and Jacobian. F! is the call to ``F``. The ```!``` signifies that you must overwrite FS with the value of ``F(x)``. J! is the function for Jacobian evaluation. It overwrites the storage you have allocated for the Jacobian. The default is a finite-difference Jacobian. So to call nsol and use the default Jacobian you'd do this ```julia nsol(F!, x0, FS, FPS) ``` Here is an extremely simple example from the book. The function and Jacobian codes are ```julia """ simple!(FV,x) This is the function for Figure 2.1 in the book. Note that simple! takes two inputs and overwrites the first with the nonlinear residual. This example is in the TestProblems submodule, so you should not have to define simple! and jsimple! if you are using that submodule. """ function simple!(FV, x) FV[1] = x[1] * x[1] + x[2] * x[2] - 2.0 FV[2] = exp(x[1] - 1) + x[2] * x[2] - 2.0 end function jsimple!(JacV, FV, x) JacV[1, 1] = 2.0 * x[1] JacV[1, 2] = 2.0 * x[2] JacV[2, 1] = exp(x[1] - 1) JacV[2, 2] = 2 * x[2] end ``` We will solve the equation with an initial iterate that will need the line search. Then we will show the iteration history. Note that we allocate storage for the Jacobian and the nonlinear residual. We're using Newton's method so must set ```sham=1```. ```julia julia> x0=[2.0,.5]; julia> FS=zeros(2,); julia> FPS=zeros(2,2); julia> nout=nsol(simple!, x0, FS, FPS, jsimple!; sham=1); julia> nout.history 6-element Array{Float64,1}: 2.44950e+00 2.17764e+00 7.82402e-01 5.39180e-02 4.28404e-04 3.18612e-08 julia> nout.stats.iarm' 1×6 Adjoint{Int64,Array{Int64,1}}: 0 2 0 0 0 0 ``` This history vector shows quadratic convergence. The iarm vector shows that the line search took two steplength reductions on the first iteration. We can do the linear algebra in single precision by storing the Jacobian in Float32 and use a finite difference Jacobian by omitting ```jsimple!```. So ... ```julia julia> FP32=zeros(Float32,2,2); julia> nout32=nsol(simple!, x0, FS, FP32; sham=1); julia> nout32.history 6-element Array{Float64,1}: 2.44950e+00 2.17764e+00 7.82403e-01 5.39180e-02 4.28410e-04 3.19098e-08 ``` As you can see, not much has happened. ```ptcsol.jl``` finds steady state solutions of initial value problems ``dx/dt = -F(x), x(0)=x0`` The iteration differs from Newton in that there is no line search. Instead the iteration is updated with the step ``s`` where `` (\delta + F'(x) ) s = - F(x) `` Our codes update ``\delta`` via the SER formula `` \delta_+ = \delta_0 \| F(x_0 \|/\| F(x_n)\| `` The calling sequence for ```ptcsol``` is, leaving out the kwargs and taking the default finite-difference Jacobian ```julia ptcsol(F!, x0, FS, FPS) ``` and the inputs are the same as for ```nsol.jl``` ## Nonlinear systems with Krylov linear solvers: Chapter 3 The methods in this chapter use Krylov iterative solvers to compute The solvers are ```nsoli.jl``` and ```ptcsoli.jl```. The calling sequence for solving ```F(x) = 0``` with ```nsoli.jl```, leaving out the kwargs, is ```julia nsoli(F!, x0, FS, FPS, Jvec=dirder) ``` FS and FPS are arrays for storage of the function and the Krylov basis. ```Jvec``` is the function for a Jacobian-vector project. The default is a finite difference Jacobian-vector project. If you want to take m GMRES iterations with no restarts you must give FPS at least m+1 columns. F! is the call to ``F``, exactly as in Chapter 2. We will do the simple example again with an analytic Jacobian-vector product. One important kwarg is ```lmaxit```, the maximum number of Krylov iterations. For now FPS must have a least lmaxit+1 columns or the solver will complain. The default is 5, which may change as I get better organized. For the two-dimensional Another kwarg that needs attention is ```eta```. The default is constant ```eta = .1```. One can turn on Eisenstat-Walker by setting ```fixedeta=false```. In the Eisenstat-Walker case, ```eta``` is the upper bound on the forcing term. ```julia """ JVsimple(v, FV, x) Jacobian-vector product for simple!. There is, of course, no reason to use Newton-Krylov for this problem other than CI or demonstrating how to call nsoli.jl. """ function JVsimple(v, FV, x) jvec = zeros(2) jvec[1] = 2.0 * x' * v jvec[2] = v[1] * exp(x[1] - 1.0) + 2.0 * v[2] * x[2] return jvec end ``` So we call the solver with ```eta=1.e-10``` and see that with two GMRES iterations it's the same as what you got from nsol.jl. No surprise. ```julia ulia> x0=[2.0,.5]; julia> FS=zeros(2,); julia> FPS=zeros(2,3); julia> kout=nsoli(simple!, x0, FS, FPS, JVsimple; lmaxit=2, eta=1.e-10, fixedeta=true); julia> kout.history 6-element Array{Float64,1}: 2.44950e+00 2.17764e+00 7.82402e-01 5.39180e-02 4.28404e-04 3.18612e-08 ``` The pseudo-transient continuation code ```ptcsoli.jl``` takes the same inputs as ```nsoli.jl```. So the call to ```ptcsoli.jl```, taking the defaults, is ```julia ptcsoli(F!,x0,FS,FPS) ``` The value of ``\delta_0`` is one of the kwargs. The default is ``10^{-6}``, which is very conservative and something you'll want to play with after reading the book. ## Solving fixed point problems with Anderson acceleration: Chapter 4 The solver is ```aasol.jl``` and one is solving ```x = GFix(x)```. The calling sequence, leaving out the kwargs, is ```julia aasol(GFix!, x0, m, Vstore) ``` Here, similarly to the Newton solvers in Chapters 2 and 3, ```GFix!``` must have the calling sequence ```julia xout=GFix!(xout,xin) ``` or ```julia xout=GFix!(xout,xin,pdata) ``` where ```xout``` is the preallocated storage for the function value and pdata is any precomputed data that ```GFix!``` needs. ```x0``` is the initial iterate and ```m``` is the depth. The iteration must store ``2 m + 4`` vectors and ``3m+3`` is better You must allocate that in ```Vstore```. Use ``2m + 4`` only if storage is a major problem for your appliciation. The linear least squares problem for the optimization is typically very ill-conditioned and solving that in reduced precision is a bad idea. I do not offer that option in ```aasol.jl```. ## Overview of the Codes The solvers for scalar equations in Chapter 1 are wrappers for the codes from Chapter 2 with the same interface. The solvers from Chapter 3 use Krylov iterative methods for the linear solves. The logic is different enough that it's best to make them stand-alone codes. ### Scalar Equations: Chapter 1 There are three codes for the methods in this chapter 1. nsolsc.jl is all variations of Newton's method __except__ pseudo transient continuation. The methods are - Newton's method - The Shamanskii method, where the derivative evaluation is done every m iterations. ``m=1`` is Newton and ``m=\infty`` is chord. - I do an Armijo line search for all the methods unless the method is chord or you tell me not to. 2. secant.jl is the scalar secant method. 3. ptcsolsc.jl is pseudo-transient continuation. ### Nonlinear systems with direct linear solvers: Chapter 2 This is the same story as it was for scalar equations, 'ceptin for the linear algebra. The linear solvers for this chapter are the matrix factorizations that live in LinearAlgebra, SuiteSparse, or BandedMatrices. The solvers 1. nsol.jl is is all variations of Newton's method __except__ pseudo transient continuation. The methods are - Newton's method - The Shamanskii method, where the derivative evaluation is done every m iterations. ``m=1`` is Newton and ``m=\infty`` is chord. - I do an Armijo line search for all the methods unless the method is chord or you tell me not to. 2. ptcsol.jl is pseudo-transient continuation. ### Nonlinear systems with iterative linear solvers: Chapter 3 1. The Newton-Krylov linear solver is nsoli.jl. The linear solvers are GMRES(m) and BiCGstab. 2. ptcsoli.jl is the Newton-Krylov pseudo-transient continuation code. ### Anderson Acceleration: Chapter 4 The solver is aasol.jl. Keep in mind that you are solving fixed point problems ``x = G(x)`` so you send the solver the fixed point map ``G``. ### Case Studies: Chapter 5 This chapter has two case studies. Please look at the notebook.
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
104
# aasol: solve fixed point prolbems with Anderson acceleration ```@docs aasol(GFix!, x0, m, Vstore) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
95
# kl_bigstab: BiCGSTAB linear solver ```@docs kl_bicgstab(x0, b, atv, V, eta, ptv=nothing) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
86
# kl_gmres: GMRES linear solver ```@docs kl_gmres(x0, b, atv, V, eta, ptv=klnopc) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
105
# nsol: systems of equations with direct linear solvers ```@docs nsol(F!, x0, FS, FPS, J!=diffjac!) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
107
# nsoli: systems of equations with Krylov linear solvers ```@docs nsoli(F!, x0, FS, FPS, Jvec=dirder) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
58
# nsolsc: scalar equation solver ```@docs nsolsc(f,x) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
97
# ptcsol: Pseudo-Transient Continuation Solver ```@docs ptcsol(F!, x0, FS, FPS, J!=diffjac!) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
113
# ptcsoli: Pseudo-Transient Continuation Newton-Krylov Solver ```@docs ptcsoli(F!, x0, FS, FPS, Jvec=dirder) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
69
# ptcsolsc: pseudo-transient continuation ```@docs ptcsolsc(x,f) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.0.2
1c7ffc244c458bb52e2b311dd6e0902b2b13fc14
docs
58
# secant: scalar equation solver ```@docs secant(f,x) ```
SIAMFANLEquations
https://github.com/ctkelley/SIAMFANLEquations.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
584
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # examples/exposure.jl: example to configure manual exposure using Spinnaker camlist = CameraList() cam = camlist[0] triggersource!(cam, "Software") triggermode!(cam, "On") gain!(cam, 0) acquisitionmode!(cam, "Continuous") start!(cam) for expval in 0:1e5:2e6 expact = exposure!(cam, expval) @info "Exposure set to $(expact/1e6)s" trigger!(cam) saveimage(cam, joinpath(@__DIR__, "exposure_$(expval/1e6)s.png"), spinImageFileFormat(6)) @info "Image saved" end stop!(cam)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
647
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # examples/format.jl: example to configure advanced image format controls using Spinnaker camlist = CameraList() cam = camlist[0] gammenset = gammaenable!(cam, false) @assert gammenset == false adcbits!(cam, "Bit12") adcbits(cam) pixelformat(cam) pixelformat!(cam, "Mono12p") @assert pixelformat(cam) == "Mono12p" triggersource!(cam, "Software") triggermode!(cam, "On") acquisitionmode!(cam, "Continuous") gain!(cam, 12) exposure!(cam, 1e6) start!(cam) trigger!(cam) saveimage(cam, joinpath(@__DIR__, "iformat.png"), spinImageFileFormat(6)) stop!(cam)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
553
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 9 Samuel Powell # examples/gain.jl: example to configure manual gain using Spinnaker camlist = CameraList() cam = camlist[0] triggersource!(cam, "Software") triggermode!(cam, "On") exposure!(cam, 1e5) acquisitionmode!(cam, "Continuous") start!(cam) for gainval in 0:2:48 gain!(cam, gainval) @info "Gain set to $(gainval)dB" trigger!(cam) saveimage(cam, joinpath(@__DIR__, "gain_$(gainval)dB.png"), spinImageFileFormat(6)) @info "Image saved" end stop!(cam)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
627
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # examples/imagedata.jl: example to extract image data to AbstractArray using Spinnaker camlist = CameraList() cam = camlist[0] gammenset = gammaenable!(cam, false) @assert gammenset == false adcbits!(cam, "Bit12") adcbits(cam) pixelformat(cam) pixelformat!(cam, "Mono16") @assert pixelformat(cam) == "Mono16" triggersource!(cam, "Software") triggermode!(cam, "On") acquisitionmode!(cam, "Continuous") gain!(cam, 12.0) exposure!(cam, 1e6) start!(cam) trigger!(cam) image = getimage(cam) stop!(cam) arr = CameraImage(image, Float64)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
377
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # examples/trigger.jl: example to configure manual trigger using Spinnaker camlist = CameraList() cam = camlist[0] triggersource!(cam, "Software") triggermode!(cam, "On") start!(cam) trigger!(cam) saveimage(cam, joinpath(@__DIR__, "trigger.png"), spinImageFileFormat(6)) stop!(cam)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
5472
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # acquistion.jl: replicate Acquisition_C Spinnaker SDK example with low-level library using Spinnaker outpath = joinpath(@__DIR__, "output") mkpath(outpath) using Spinnaker import Spinnaker: bool8_t, MAX_BUFFER_LEN # Get system interface and library version hSystem = Ref(spinSystem(C_NULL)) spinSystemGetInstance(hSystem) hLibraryVersion = Ref(spinLibraryVersion(0,0,0,0)) spinSystemGetLibraryVersion(hSystem[], hLibraryVersion) libver = VersionNumber(hLibraryVersion[].major, hLibraryVersion[].minor, hLibraryVersion[].type) @info "Spinnaker library version: $libver, build $(hLibraryVersion[].build)" # Retrieve camera list (from system object) hCameraList = Ref(spinCameraList(C_NULL)) nCameras = Ref(Csize_t(0)) spinCameraListCreateEmpty(hCameraList) spinSystemGetCameras(hSystem[], hCameraList[]) spinCameraListGetSize(hCameraList[], nCameras) @info "Discovered $(nCameras[]) cameras" function readable(hNode, nodeName) pbAvailable = Ref(bool8_t(false)) pbReadable = Ref(bool8_t(false)) spinNodeIsAvailable(hNode, pbAvailable) spinNodeIsReadable(hNode, pbReadable) return (pbReadable[] == 1) && (pbAvailable[] == 1) end function writable(hNode, nodeName) pbAvailable = Ref(bool8_t(false)) pbReadable = Ref(bool8_t(false)) spinNodeIsAvailable(hNode, pbAvailable) spinNodeIsWritable(hNode, pbReadable) return (pbReadable[] == 1) && (pbAvailable[] == 1) end function acquire_images(hCam, hNodeMap, hNodeMapTLDevice) # Set acquisition mode hAcquisitionMode = Ref(spinNodeHandle(C_NULL)) hAcquisitionModeContinuous = Ref(spinNodeHandle(C_NULL)) acquisitionModeContinuous = Ref(Int64(0)) spinNodeMapGetNode(hNodeMap[], "AcquisitionMode", hAcquisitionMode) if readable(hAcquisitionMode[], "AcquisitionMode") spinEnumerationGetEntryByName(hAcquisitionMode[], "Continuous", hAcquisitionModeContinuous) else @error "Unable to retrieve acquistion mode enumeration" end if readable(hAcquisitionModeContinuous[], "AcquisitionModeContinuous") spinEnumerationEntryGetIntValue(hAcquisitionModeContinuous[], acquisitionModeContinuous); else @error "Unable to retrieve continuous acquistion enumeration" end if writable(hAcquisitionMode[], "AcquisitionMode") spinEnumerationSetIntValue(hAcquisitionMode[], acquisitionModeContinuous[]) else @info "Unable to set continuous acquistion mode" end @info "Acquistion mode set to continuous" # Begin acquistion spinCameraBeginAcquisition(hCam[]) @info "Started camera acquistion" # Get serial number hDeviceSerialNumber = Ref(spinNodeHandle(C_NULL)) deviceSerialNumber = Vector{UInt8}(undef, MAX_BUFFER_LEN) lenDeviceSerialNumber = Ref(Csize_t(MAX_BUFFER_LEN)) spinNodeMapGetNode(hNodeMapTLDevice[], "DeviceSerialNumber", hDeviceSerialNumber) if readable(hDeviceSerialNumber[], "DeviceSerialNumber") spinStringGetValue(hDeviceSerialNumber[], deviceSerialNumber, lenDeviceSerialNumber) else @info "Cannot receive camera serial number" end @info "Camera serial number: $(unsafe_string(pointer(deviceSerialNumber)))" # Retrieve, convert, and save images for imageCnt in 1:10 hResultImage = Ref(spinImage(C_NULL)) spinCameraGetNextImage(hCam[], hResultImage); isIncomplete = Ref(bool8_t(false)) hasFailed = Ref(bool8_t(false)) spinImageIsIncomplete(hResultImage[], isIncomplete); if (isIncomplete == true) imageStatus = Ref(spinImageStatus(IMAGE_NO_ERROR)) spinImageGetStatus(hResultImage[], imageStatus) @info "Image incomplete with error $(imageStatus)" hasFailed = true end if (hasFailed == true) spinImageRelease(hResultImage[]); end # Get image dimensions width = Ref(Csize_t(0)) height = Ref(Csize_t(0)) spinImageGetWidth(hResultImage[], width); spinImageGetHeight(hResultImage[], height); @info "Grabbed image $imageCnt, width: $(width[]), height: $(height[])" # Convert image to MONO8 hConvertedImage = Ref(spinImage(C_NULL)) spinImageCreateEmpty(hConvertedImage); spinImageConvert(hResultImage[], Spinnaker.PixelFormat_Mono8, hConvertedImage[]); @info "Converted image to MONO 8" # Save to disc filename = joinpath(outpath, "acquistion_" * unsafe_string(pointer(deviceSerialNumber)) * string(imageCnt) * ".jpg") spinImageSave(hConvertedImage[], filename, Spinnaker.JPEG); @info "Image Saved to $filename" # Destroy converted image and release camera image spinImageDestroy(hConvertedImage[]); spinImageRelease(hResultImage[]); end spinCameraEndAcquisition(hCam[]) @info "Stopped camera acquistion" return nothing end function run_camera(hCam) hNodeMapTLDevice = Ref(spinNodeMapHandle(C_NULL)) hNodeMap = Ref(spinNodeMapHandle(C_NULL)) spinCameraGetTLDeviceNodeMap(hCam[], hNodeMapTLDevice); spinCameraInit(hCam[]); spinCameraGetNodeMap(hCam[], hNodeMap); acquire_images(hCam, hNodeMap, hNodeMapTLDevice); spinCameraDeInit(hCam[]); return nothing end if nCameras[] > 0 hCam = Ref(spinCamera(C_NULL)) for i in 0:nCameras[]-1 spinCameraListGet(hCameraList[], i, hCam); run_camera(hCam) spinCameraRelease(hCam[]) end else # Finish if there are no cameras @info "No cameras, finishing" end spinCameraListClear(hCameraList[]) spinCameraListDestroy(hCameraList[]) spinSystemReleaseInstance(hSystem[])
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
5253
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # enumeration.jl: replicate Enumeration_C Spinnaker SDK example with low-level library using Spinnaker import Spinnaker: bool8_t, MAX_BUFFER_LEN # Get system interface and library version hSystem = Ref(spinSystem(C_NULL)) spinSystemGetInstance(hSystem) hLibraryVersion = Ref(spinLibraryVersion(0,0,0,0)) spinSystemGetLibraryVersion(hSystem[], hLibraryVersion) libver = VersionNumber(hLibraryVersion[].major, hLibraryVersion[].minor, hLibraryVersion[].type) @info "Spinnaker library version: $libver, build $(hLibraryVersion[].build)" # Retrieve list of interfaces hInterfaceList = Ref(spinInterfaceList(C_NULL)) nInterfaces = Ref(Csize_t(0)) spinInterfaceListCreateEmpty(hInterfaceList) spinSystemGetInterfaces(hSystem[], hInterfaceList[]) spinInterfaceListGetSize(hInterfaceList[], nInterfaces) @info "Discovered $(nInterfaces[]) interfaces" # Retrieve camera list (from system object) hCameraList = Ref(spinCameraList(C_NULL)) nCameras = Ref(Csize_t(0)) spinCameraListCreateEmpty(hCameraList) spinSystemGetCameras(hSystem[], hCameraList[]) spinCameraListGetSize(hCameraList[], nCameras) @info "Discovered $(nCameras[]) cameras" # Examine a given interface function query_interface(hInterface) # Get interface and print details hNodeMapInterface = Ref(spinNodeMapHandle(C_NULL)) hInterfaceDisplayName = Ref(spinNodeHandle(C_NULL)) interfaceDisplayNameIsAvailable = Ref(bool8_t(false)) interfaceDisplayNameIsReadable = Ref(bool8_t(false)) spinInterfaceGetTLNodeMap(hInterface, hNodeMapInterface); spinNodeMapGetNode(hNodeMapInterface[], "InterfaceDisplayName", hInterfaceDisplayName); spinNodeIsAvailable(hInterfaceDisplayName[], interfaceDisplayNameIsAvailable); spinNodeIsReadable(hInterfaceDisplayName[], interfaceDisplayNameIsReadable); interfaceDisplayName = Vector{UInt8}(undef, MAX_BUFFER_LEN) lenInterfaceDisplayName = Ref(Csize_t(MAX_BUFFER_LEN)) if (interfaceDisplayNameIsAvailable[] == true) && (interfaceDisplayNameIsReadable[] == true) spinStringGetValue(hInterfaceDisplayName[], interfaceDisplayName, lenInterfaceDisplayName); @info "$(unsafe_string(pointer(interfaceDisplayName)))" else @info "Interface display name not readable" end hCameraList = Ref(spinCameraList(C_NULL)) nCameras = Ref(Csize_t(0)) spinCameraListCreateEmpty(hCameraList) spinInterfaceGetCameras(hInterface, hCameraList[]); spinCameraListGetSize(hCameraList[], nCameras); # Get cameras on interface nd print details if nCameras[] > 0 for i in 0:nCameras[]-1 hCam = Ref(spinCamera(C_NULL)) spinCameraListGet(hCameraList[], i, hCam); hNodeMapTLDevice = Ref(spinNodeMapHandle(C_NULL)) spinCameraGetTLDeviceNodeMap(hCam[], hNodeMapTLDevice); # Get camera vendor name hDeviceVendorName = Ref(spinNodeHandle(C_NULL)) deviceVendorNameIsAvailable = Ref(bool8_t(false)) deviceVendorNameIsReadable = Ref(bool8_t(false)) spinNodeMapGetNode(hNodeMapTLDevice[], "DeviceVendorName", hDeviceVendorName) spinNodeIsAvailable(hDeviceVendorName[], deviceVendorNameIsAvailable) spinNodeIsReadable(hDeviceVendorName[], deviceVendorNameIsReadable) deviceVendorName = Vector{UInt8}(undef, MAX_BUFFER_LEN) lenDeviceVendorName = Ref(Csize_t(MAX_BUFFER_LEN)) if (deviceVendorNameIsAvailable[] == true) && (deviceVendorNameIsReadable[] == true) spinStringGetValue(hDeviceVendorName[], deviceVendorName, lenDeviceVendorName); @info "$(unsafe_string(pointer(deviceVendorName)))" else @info "Camera vendor name not readable" end # Get camera model name hDeviceModelName = Ref(spinNodeHandle(C_NULL)) deviceModelNameIsAvailable = Ref(bool8_t(false)) deviceModelNameIsReadable = Ref(bool8_t(false)) spinNodeMapGetNode(hNodeMapTLDevice[], "DeviceModelName", hDeviceModelName); spinNodeIsAvailable(hDeviceModelName[], deviceModelNameIsAvailable); spinNodeIsReadable(hDeviceModelName[], deviceModelNameIsReadable); deviceModelName = Vector{UInt8}(undef, MAX_BUFFER_LEN) lenDeviceModelName = Ref(Csize_t(MAX_BUFFER_LEN)) if (deviceModelNameIsAvailable[] == true) && (deviceModelNameIsReadable[] == true) spinStringGetValue(hDeviceModelName[], deviceModelName, lenDeviceModelName); @info "$(unsafe_string(pointer(deviceModelName)))" else @info "Camera model name not readable" end spinCameraRelease(hCam[]); end else @info "No cameras detected" end spinCameraListClear(hCameraList[]); spinCameraListDestroy(hCameraList[]); return nothing end # Examine cameras on each interface if nCameras[] > 0 for i in 0:nInterfaces[]-1 hInterface = Ref(spinInterface(C_NULL)) spinInterfaceListGet(hInterfaceList[], i, hInterface) query_interface(hInterface[]) spinInterfaceRelease(hInterface[]) end else # Finish if there are no cameras @info "No cameras, finishing" end # Cleanup spinCameraListClear(hCameraList[]) spinCameraListDestroy(hCameraList[]) spinInterfaceListClear(hInterfaceList[]) spinInterfaceListDestroy(hInterfaceList[]) spinSystemReleaseInstance(hSystem[])
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
3633
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # wrap.jl: automatically wrap C API using Clang.jl # This wrapper uses the Gnuic/refactor branch of Clang.jl to provide proper enumeration # support. Implementation guided by: # https://github.com/JuliaDiffEq/Sundials.jl (general) # https://github.com/JuliaAttic/CUDArt.jl/ (error rewriter) using Clang: init const incpath = normpath("/usr/include/spinnaker/spinc") if !isdir(incpath) error("Spinnaker SDK C header not found, please install manually.") end const outpath = normpath(@__DIR__, "..", "src", "wrapper") mkpath(outpath) const spinnaker_headers = readdir(incpath) const clang_path = "/usr/lib/clang/6.0" const clang_includes = [joinpath(clang_path, "include")] # TODO: should we use actually use Clang.jl installation here? # const CLANG_INCLUDE = joinpath(@__DIR__, "..", "deps", "usr", "include", "clang-c") |> normpath # const CLANG_HEADERS = [joinpath(CLANG_INCLUDE, cHeader) for cHeader in readdir(CLANG_INCLUDE) if endswith(cHeader, ".h")] headerlibmap = Dict("SpinnakerC.h" => "libSpinnaker_C", "QuickSpinC.h" => "libSpinnaker_C", "SpinnakerGenApiC.h" => "libSpinnaker_C", "SpinVideoC.h" => "libSpinVideo_C") function library_file(header::AbstractString) header_name = basename(header) if(haskey(headerlibmap, header_name)) return headerlibmap[header_name] else @warn "$header has unknown library association, using libSpinnaker_C" return "libSpinnaker_C" end end # Test if header should be wrapped function header_filter(top_hdr::AbstractString, cursor_header::AbstractString) return (top_hdr == cursor_header) # Do not wrap nested includes end # Test if element should be wrapped function cursor_filter(name::AbstractString, cursor) return true end # # if typeof(cursor) == Clang.LibClang.CXCursor # # Wrap only spin, and quickSpin prefaced functions # return occursin(r"^(quickSpin|spin)", name) # else # # Else, wrap everything # return true # end # Add error checking to generated functions rewriter(arg) = arg # rewriter(A::Array) = [rewriter(a) for a in A] # rewriter(s::Symbol) = string(s) const skip_expr = [] const skip_error_check = [] function rewriter(ex::Expr) # Skip sepcified expressions if in(ex, skip_expr) return :() end # Only process function calls ex.head == :function || return ex decl, body = ex.args[1], ex.args[2] ccallexpr = body.args[1] rettype = ccallexpr.args[3] if rettype == :spinError fname = decl.args[1] if !in(fname, skip_error_check) body.args[1] = Expr(:call, :checkerror, deepcopy(ccallexpr)) end end return ex end # Build wrapping context const context = init( headers = map(x -> joinpath(incpath, x), spinnaker_headers), output_file = joinpath(outpath, "spin_api.jl"), common_file = joinpath(outpath, "spin_common.jl"), clang_args = [ "-D", "__STDC_LIMIT_MACROS", "-D", "__STDC_CONSTANT_MACROS", "-v" ], clang_diagnostics = true, clang_includes = [clang_includes; incpath], header_library = library_file, header_wrapped = header_filter, cursor_wrapped = cursor_filter, rewriter = rewriter ) run(context) # Manual changes @warn "Manual changes to wrapper are required, see wrap.jl" # spinStringGetValue Cstring -> Ptr{UInt8} # spinEnumerationEntryGetSymbolic Cstrong -> Ptr{UInt8} # Remove unused files rm(joinpath(outpath, "LibTemplate.jl")) rm(joinpath(outpath, "ctypes.jl")) @info "Warpper written to $outpath"
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
14095
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # Camera.jl: interface to Camera objects export serial, model, vendor, isrunning, start!, stop!, getimage, getimage!, saveimage, triggermode, triggermode!, triggersource, triggersource!, trigger!, exposure, exposure!, exposure_limits, autoexposure_limits, autoexposure_limits!, framerate, framerate!, framerate_limits, gain, gain!, gain_limits, adcbits, adcbits!, gammaenable!, pixelformat, pixelformat!, acquisitionmode, acquisitionmode!, sensordims, imagedims, imagedims!, imagedims_limits, offsetdims, offsetdims!, offsetdims_limits, buffercount, buffercount!, buffermode, buffermode!, bufferunderrun, bufferfailed, reset!, powersupplyvoltage """ Spinnaker SDK Camera object Create a camera object by referencing a CameraList, e.g., `cl = CameraList() cam = cl[0]` The camera is initialised when created and deinitialised when garbage collected. """ mutable struct Camera handle::spinCamera names::Dict{String, String} function Camera(handle) @assert spinsys.handle != C_NULL @assert handle != C_NULL spinCameraDeInit(handle) spinCameraInit(handle) names = Dict{String, String}() cam = new(handle, names) finalizer(_release!, cam) # Activate chunk mode set!(SpinBooleanNode(cam, "ChunkModeActive"), true) _chunkselect(cam, ["FrameID", "FrameCounter"], "frame indentification") _chunkselect(cam, ["ExposureTime"], "exposure time") _chunkselect(cam, ["Timestamp"], "timestamps") # Discover ambiguous names cam.names["AutoExposureTimeLowerLimit"] = "AutoExposureTimeLowerLimit" cam.names["AutoExposureTimeUpperLimit"] = "AutoExposureTimeUpperLimit" cam.names["AcquisitionFrameRateEnabled"] = "AcquisitionFrameRateEnabled" try Spinnaker.get(Spinnaker.SpinFloatNode(cam, "AutoExposureTimeLowerLimit")) catch cam.names["AutoExposureTimeLowerLimit"] = "AutoExposureExposureTimeLowerLimit" cam.names["AutoExposureTimeUpperLimit"] = "AutoExposureExposureTimeUpperLimit" end try Spinnaker.get(Spinnaker.SpinBooleanNode(cam, "AcquisitionFrameRateEnabled")) catch cam.names["AcquisitionFrameRateEnabled"] = "AcquisitionFrameRateEnable" end return cam end end # Attempt to activate chunk data for each entry in chunknames # - this allows chunk names to differ on cameras function _chunkselect(cam::Camera, chunknames::Vector{String}, desc::String) fail = true i = 1 while fail == true try fail = false set!(SpinEnumNode(cam, "ChunkSelector"), chunknames[i]) set!(SpinBooleanNode(cam, "ChunkEnable"), true) catch e fail = true end i += 1 end if fail @warn "Unable to enable chunk data for $(desc), tried $(chunknames), metadata may be incorrect" end end unsafe_convert(::Type{spinCamera}, cam::Camera) = cam.handle unsafe_convert(::Type{Ptr{spinCamera}}, cam::Camera) = pointer_from_objref(cam) function _reinit(cam::Camera) spinCameraDeInit(cam) spinCameraInit(cam) return cam end # Release handle to system function _release!(cam::Camera) if cam.handle != C_NULL try stop!(cam) catch e end spinCameraDeInit(cam) spinCameraRelease(cam) cam.handle = C_NULL end return nothing end """ isinitialized(cam::Camera) -> Bool Determine if the camera is initialized. """ function isinitialized(cam::Camera) pbIsInitialized = Ref(bool8_t(false)) spinCameraIsInitialized(cam, pbIsInitialized) return (pbIsInitialized[] == 0x01) end """ reset!(cam::Camera; wait = false, timeout = nothing) Immediately reset and reboot the camera, after which the camera will need re-initialization via `CameraList`. Or to automatically wait to reconnect to a camera with the same serial number set `wait` to `true`, and a maximum timeout in seconds via `timeout`. """ function reset!(cam::Camera; wait::Bool = false, timeout::Union{Int,Nothing} = nothing) # get these before resetting timeout_secs = if wait isnothing(timeout) ? get(SpinIntegerNode(cam, "MaxDeviceResetTime")) / 1e3 : timeout end sn = wait ? serial(cam) : nothing hNodeMap = Ref(spinNodeMapHandle(C_NULL)) spinCameraGetNodeMap(cam, hNodeMap) hDeviceReset = Ref(spinNodeHandle(C_NULL)) spinNodeMapGetNode(hNodeMap[], "DeviceReset", hDeviceReset); spinCommandExecute(hDeviceReset[]) if wait timeout = Timer(timeout_secs) while isopen(timeout) try cam = find_cam_with_serial(CameraList(), sn) isnothing(cam) || return cam catch ex @debug "waiting during reset!" exception = ex sleep(0.5) end end isopen(timeout) || error("Spinnaker timed out waiting for the camera with serial number $(sn) to reappear after reset") end return cam end # Include subfiles include(joinpath("camera", "acquisition.jl")) include(joinpath("camera", "analog.jl")) include(joinpath("camera", "format.jl")) include(joinpath("camera", "stream.jl")) include(joinpath("camera", "digitalio.jl")) # # Device metadata # """ serial(::Camera) -> String Return camera serial number (string) """ serial(cam::Camera) = get(SpinStringNode(cam, "DeviceSerialNumber", CameraTLDeviceNodeMap())) """ vendor(::Camera) -> String Return vendor name of specified camera. """ vendor(cam::Camera) = get(SpinStringNode(cam, "DeviceVendorName", CameraTLDeviceNodeMap())) """ model(::Camera) -> String Return model name of specified camera. """ model(cam::Camera) = get(SpinStringNode(cam, "DeviceModelName", CameraTLDeviceNodeMap())) """ show(::IO, ::Camera) Write details of camera to supplied IO. """ function show(io::IO, cam::Camera) vendorname = vendor(cam) modelname = model(cam) serialno = serial(cam) write(io, "$vendorname $modelname ($serialno)") end # # Device status # """ devicetemperature(cam::Camera, location::String) -> Float Return the temperature of the specified device location. """ function devicetemperature(cam::Camera, location::String) set!(SpinEnumNode(cam, "DeviceTemperatureSelector"), location) return Spinnaker.get(Spinnaker.SpinFloatNode(cam, "DeviceTemperature")) end """ powersupplyvoltage(cam::Camera) -> Float Return the device power supply voltage in Volts. """ powersupplyvoltage(cam::Camera) = Spinnaker.get(Spinnaker.SpinFloatNode(cam, "PowerSupplyVoltage")) # # Image acquistion # """ acquisitionmode(::Camera) -> String Return camera acquistion mode. """ acquisitionmode(cam::Camera) = get(SpinEnumNode(cam, "AcquisitionMode")) """ acquisitionmode!(::Camera, ::AbstractString) -> String Set camera acquistion mode, returns set mode. """ acquisitionmode!(cam::Camera, mode) = set!(SpinEnumNode(cam, "AcquisitionMode"), mode) function _isimagecomplete(himage_ref) isIncomplete = Ref(bool8_t(false)) spinImageIsIncomplete(himage_ref[], isIncomplete); if isIncomplete == true imageStatus = Ref(spinImageStatus(IMAGE_NO_ERROR)) spinImageGetStatus(himage_ref[], imageStatus) spinImageRelease(himage_ref[]) @warn "Image incomplete with error $(imageStatus)" return false else return true end end # # Image retrieval -> SpinImage # """ getimage(::Camer; release=true, timeout=-1) -> Image Copy the next image from the specified camera, blocking until available unless a timeout of >= 0 (ms) is specified. If release is false, the image buffer is not released. """ getimage(cam::Camera; release=true, timeout=-1) = getimage!(cam, SpinImage(), release=release, timeout=timeout) """ getimage!(::Camera, ::SpinImage; release=true, timeout=-1) -> Image Copy the next image from the specified camera, blocking until available unless a timeout of >= 0 (ms) is specified, overwriting existing. If releaseis false, the image buffer is not released. """ function getimage!(cam::Camera, image::SpinImage; release=true, timeout=-1) # Get image handle and check it's complete himage_ref = Ref(spinImage(C_NULL)) if timeout == -1 spinCameraGetNextImage(cam, himage_ref); else spinCameraGetNextImageEx(cam, timeout, himage_ref); end @assert _isimagecomplete(himage_ref) # Create output image, copy and release buffer spinImageDeepCopy(himage_ref[], image) if release spinImageRelease(himage_ref[]) end return image end # # Image retrieval -> CameraImage # """ getimage(::Camera, ::Type{T}; normalize=true; release=true, timeout=-1) -> CameraImage Copy the next image from the specified camera, converting the image data to the specified array format, blocking until available unless a timeout of >= 0 (ms) is specified. If release is false, the image buffer is not released. If `normalize == false`, the input data from the camera is interpreted as a number in the range of the underlying type, e.g., for a camera operating in Mono8 pixel format, a call `getimage!(cam, Float64, normalize=false)` will return an array of dobule precision numbers in the range [0, 255]. `If normalize == true` the input data is interpreted as an associated fixed point format, and thus the array will be in the range [0,1]. To return images compatible with Images.jl, one can request a Gray value, e.g., `getimage!(cam, Gray{N0f8}, normalize=true)`. Function also returns image ID and timestamp metadata. """ function getimage(cam::Camera, ::Type{T}; normalize=true, release=true, timeout=-1) where T himage_ref, width, height, id, timestamp, exposure = _pullim(cam, timeout=timeout) imdat = Array{T,2}(undef, (width,height)) camim = CameraImage(imdat, id, timestamp, exposure) _copyimage!(himage_ref[], width, height, camim, normalize) if release spinImageRelease(himage_ref[]) end return camim end """ getimage!(::Camera, ::CameraImage{T,2}; normalize=false; release=true, timeout=-1) Copy the next iamge from the specified camera, converting to the format of, and overwriting the provided CameraImage, blocking until available unless a timeout of >= 0 (ms) is specified. If release is false, the image buffer is not released. If `normalize == false`, the input data from the camera is interpreted as a number in the range of the underlying type, e.g., for a camera operating in Mono8 pixel format, a call `getimage!(cam, Float64, normalize=false)` will return an array of dobule precision numbers in the range [0, 255]. `If normalize == true` the input data is interpreted as an associated fixed point format, and thus the array will be in the range [0,1]. To return images compatible with Images.jl, one can request a Gray value, e.g., `getimage!(cam, Gray{N0f8}, normalize=true)`. """ function getimage!(cam::Camera, image::CameraImage{T,2}; normalize=true, release=true, timeout=-1) where T himage_ref, width, height, id, timestamp, exposure = _pullim(cam, timeout=timeout) camim = CameraImage(image.data, id, timestamp, exposure) _copyimage!(himage_ref[], width, height, camim, normalize) if release spinImageRelease(himage_ref[]) end return camim end function _pullim(cam::Camera;timeout=-1) # Get image handle and check it's complete himage_ref = Ref(spinImage(C_NULL)) if timeout == -1 spinCameraGetNextImage(cam, himage_ref); else spinCameraGetNextImageEx(cam, timeout, himage_ref); end if !_isimagecomplete(himage_ref) spinImageRelease(himage_ref[]) throw(ErrorException("Image not complete")) end # Get image dimensions, ID and timestamp width = Ref(Csize_t(0)) height = Ref(Csize_t(0)) id = Ref(Int64(0)) timestamp = Ref(Int64(0)) exposure = Ref(Float64(0)) spinImageGetWidth(himage_ref[], width) spinImageGetHeight(himage_ref[], height) spinImageChunkDataGetIntValue(himage_ref[], "ChunkFrameID", id); spinImageChunkDataGetFloatValue(himage_ref[], "ChunkExposureTime", exposure); spinImageChunkDataGetIntValue(himage_ref[], "ChunkTimestamp", timestamp) return himage_ref, Int(width[]), Int(height[]), id[], timestamp[], exposure[] end # # Image retrieval -> Array # """ getimage!(::Camera, ::AbstractArray{T,2}; normalize=false, release=true, timeout=-1) Copy the next iamge from the specified camera, converting to the format of, and overwriting the provided abstract array, blocking until available unless a timeout of >= 0 (ms) is specified. If release is false, the image buffer is not released. If `normalize == false`, the input data from the camera is interpreted as a number in the range of the underlying type, e.g., for a camera operating in Mono8 pixel format, a call `getimage!(cam, Array{Float64}(undef, dims...), normalize=false)` will return an array of dobule precision numbers in the range [0, 255]. `If normalize == true` the input data is interpreted as an associated fixed point format, and thus the array will be in the range [0,1]. """ function getimage!(cam::Camera, image::AbstractArray{T,2}; normalize=true, release=true, timeout=-1) where T himage_ref, width, height, id, timestamp, exposure = _pullim(cam, timeout=timeout) _copyimage!(himage_ref[], width, height, image, normalize) if release spinImageRelease(himage_ref[]) end return id, timestamp, exposure end # # Image retrieval -> File # """ saveimage()::Camera, fn::AbstractString, ::spinImageFileFormat; release=true, timeout=-1) Save the next image from the specified camera to file `fn`, blocking until available unless a timeout of >= 0 (ms) is specified. If release is false, the image buffer is not released. """ function saveimage(cam::Camera, fn::AbstractString, fmt::spinImageFileFormat; release=true, timeout=-1) # Get image handle and check it's complete himage_ref = Ref(spinImage(C_NULL)) if timeout == -1 spinCameraGetNextImage(cam, himage_ref); else spinCameraGetNextImageEx(cam, timeout, himage_ref); end @assert _isimagecomplete(himage_ref) spinImageSave(himage_ref[], fn, fmt) if release spinImageRelease(himage_ref[]) end end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
3248
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # CameraImage.jl: an AbstractArray interface to Image object data import Base: size, getindex, setindex!, IndexStyle export CameraImage # Raw format map # Fefine how pixel formats relate to native integers const raw_fmtmap = Dict(PixelFormat_Mono8 => UInt8, PixelFormat_Mono10 => UInt16, PixelFormat_Mono12 => UInt16, PixelFormat_Mono14 => UInt16, PixelFormat_Mono16 => UInt16) # Normalised format map # Define how pixel formats relate to normalised fixed point types const nrm_fmtmap = Dict(PixelFormat_Mono8 => N0f8, PixelFormat_Mono10 => N6f10, PixelFormat_Mono12 => N4f12, PixelFormat_Mono14 => N2f14, PixelFormat_Mono16 => N0f16) struct CameraImage{T,N} <: AbstractArray{T,N} data::Array{T,N} id::Int64 timestamp::Int64 exposure::Float64 end size(a::CameraImage) = size(a.data) getindex(a::CameraImage, i::Int) = a.data[i] setindex!(a::CameraImage, v, i::Int) = (a.data[i] = v) IndexStyle(::Type{<:CameraImage}) = IndexLinear() id(image::CameraImage) = image.id timestamp(image::CameraImage) = image.timestamp exposure(image::CameraImage) = image.exposure """ CameraImage(::SpinImage, ::Type{T}, normalize=false) Convert SpinImage to CameraImage, with type conversion and optional normalisation. See `getimage` for details of options. """ function CameraImage(spinim::SpinImage, ::Type{T}; normalize=false) where T width, height = size(spinim) imdat = Array{T,2}(undef, width, height) _copyimage!(spinim.handle, width, height, imdat, normalize) return CameraImage(imdat, id(spinim), timestamp(spinim), exposure(spinim)) end function _copyimage!(himage_ref::spinImage, width::Integer, height::Integer, image::AbstractArray{T,2}, normalize::Bool) where T @assert prod(size(image)) == width*height hpixfmt = Ref(spinPixelFormatEnums(0)) spinImageGetPixelFormat(himage_ref, hpixfmt) # Map the pixel format to a native integer format. For un-normalized output this is # just an unsigned integer of the correct size. For a normalized output a number type # from FixedPointNumbers is used to maintain normalisation. Ti = UInt8 if(normalize) try Ti = nrm_fmtmap[hpixfmt[]] catch e spinImageRelease(himage_ref) throw(e) end else try Ti = raw_fmtmap[hpixfmt[]] catch e spinImageRelease(himage_ref) throw(e) end end # Make sure this is a good idea sz = Ref(Csize_t(0)) spinImageGetBufferSize(himage_ref, sz) @assert (sizeof(Ti)*width*height) <= sz[] # Wrap the image data in an array of the correct pointer type rawptr = Ref(Ptr{Cvoid}(0)) spinImageGetData(himage_ref, rawptr) data = unsafe_wrap(Array, Ptr{Ti}(rawptr[]), (width, height)); # Convert and copy data from buffer copyto!(image, T.(data)) return image end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
2740
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # CameraList.jl: interface to CameraList objects export find_cam_with_serial """ CameraList(::System) Spinnaker SDK Camera List object constructor. Returns new Camera List object which enumerates available devices. """ mutable struct CameraList handle::spinCameraList function CameraList() init() hcamlist_ref = Ref(spinCameraList(C_NULL)) spinCameraListCreateEmpty(hcamlist_ref) @assert hcamlist_ref[] != C_NULL camlist = new(hcamlist_ref[]) _refresh!(camlist) finalizer(_release!, camlist) return camlist end end """ find_cam_with_serial(camlist::CameraList, sn) Finds and returns a camera with the given serial number, or returns nothing. """ function find_cam_with_serial(camlist::CameraList, sn) for i in 0:length(camlist)-1 cam = camlist[i] if serial(cam) == sn return cam end end return nothing end unsafe_convert(::Type{spinCameraList}, camlist::CameraList) = camlist.handle unsafe_convert(::Type{Ptr{spinCameraList}}, camlist::CameraList) = pointer_from_objref(camlist) # Clear list and release handle function _release!(camlist::CameraList) if camlist.handle != C_NULL spinCameraListClear(camlist) spinCameraListDestroy(camlist) camlist.handle = C_NULL end return nothing end # Clear the list and reload enumerated cameras function _refresh!(camlist::CameraList) spinCameraListClear(camlist) spinSystemGetCameras(spinsys, camlist) end """ length(::CameraList) -> Int Refresh the CameraList object and return the number of enumerated devices. """ function length(camlist::CameraList) _refresh!(camlist) nc = Ref(Csize_t(0)) spinCameraListGetSize(camlist, nc) return Int(nc[]) end """ show(::IO, ::CameraList) Write list of enumerated devices to supplied IO. """ function show(io::IO, camlist::CameraList) nc = length(camlist) # This call will refresh the list write(io, "CameraList with $(nc[]) enumerated devices:\n") write(io, "ID\tSerial No.\tDescription\n") for i in 0:nc-1 cam = camlist[i] vendorname = vendor(cam) modelname = model(cam) serialno = serial(cam) write(io, "$i\t$serialno\t$vendorname $modelname") _release!(cam) # Make sure this is cleaned up immediately end end """ getindex(::CameraList, ::Int) -> Camera Return camera by ID in specified CameraList. Note that IDs are zero-indexed. """ function getindex(camlist::CameraList, id::Int) nc = length(camlist) if (id >= 0) && (id < nc) hcam_ref = Ref(spinCamera(C_NULL)) spinCameraListGet(camlist, id, hcam_ref) return Camera(hcam_ref[]) else @error "Invalid camera index" end end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
647
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # Node.jl: helper function to access node maps abstract type AbstractNodeMap end struct CameraNodeMap <: AbstractNodeMap end function _nodemap!(cam, hNodeMap, nm::CameraNodeMap) spinCameraGetNodeMap(cam, hNodeMap) end struct CameraTLDeviceNodeMap <: AbstractNodeMap end function _nodemap!(cam, hNodeMap, nm::CameraTLDeviceNodeMap) spinCameraGetTLDeviceNodeMap(cam, hNodeMap) end struct CameraTLStreamNodeMap <: AbstractNodeMap end function _nodemap!(cam, hNodeMap, nm::CameraTLStreamNodeMap) spinCameraGetTLStreamNodeMap(cam, hNodeMap) end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
6583
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # Node.jl: helper function to access interface to Camera nodes # Utility functions function implemented(name, hNode) pbImplemented = Ref(bool8_t(false)) try spinNodeIsImplemented(hNode[], pbImplemented) catch err if occursin("SPINNAKER_ERR_INVALID_HANDLE(-1006)", "$err") throw(ErrorException("Node $(name) does not have a valid handle\n$err")) else throw(err) end end return (pbImplemented[] == 1) end function available(name, hNode) if implemented(name, hNode) pbAvailable = Ref(bool8_t(false)) spinNodeIsAvailable(hNode[], pbAvailable) return (pbAvailable[] == 1) else throw(ErrorException("Node $(name) is not implemented")) end end function readable(name, hNode) if available(name, hNode) pbReadable = Ref(bool8_t(false)) spinNodeIsReadable(hNode[], pbReadable) return (pbReadable[] == 1) else return false end end function writable(name, hNode) if available(name, hNode) pbWriteable = Ref(bool8_t(false)) spinNodeIsWritable(hNode[], pbWriteable) return (pbWriteable[] == 1) else return false end end function _getnode(cam, name::String, nodemap) hNodeMap = Ref(spinNodeMapHandle(C_NULL)) _nodemap!(cam, hNodeMap, nodemap) hNode = Ref(spinNodeHandle(C_NULL)) spinNodeMapGetNode(hNodeMap[], name, hNode); return hNode end abstract type AbstractSpinNode end # # String nodes # struct SpinStringNode <: AbstractSpinNode name::String hNode::Ref{spinNodeHandle} SpinStringNode(cam, name::String, nodemap=CameraNodeMap()) = new(name, _getnode(cam, name, nodemap)) end function get(node::SpinStringNode) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end strbuf = Vector{UInt8}(undef, MAX_BUFFER_LEN) strlen = Ref(Csize_t(MAX_BUFFER_LEN)) spinStringGetValue(node.hNode[], strbuf, strlen) return unsafe_string(pointer(strbuf)) end # # Integer nodes # struct SpinIntegerNode <: AbstractSpinNode name::String hNode::Ref{spinNodeHandle} SpinIntegerNode(cam, name::String, nodemap=CameraNodeMap()) = new(name, _getnode(cam, name, nodemap)) end function range(node::SpinIntegerNode) hMin = Ref(Int64(0.0)) hMax = Ref(Int64(0.0)) spinIntegerGetMin(node.hNode[], hMin) spinIntegerGetMax(node.hNode[], hMax) return (hMin[], hMax[]) end function set!(node::SpinIntegerNode, value::Number; clampwarn::Bool = true) if !writable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not writable")) end noderange = range(node) if clampwarn value < noderange[1] && @warn "Requested value ($value) for $(node.name) is smaller than minimum ($(noderange[1])), value will be clamped." value > noderange[2] && @warn "Requested value ($value) for $(node.name) is greater than maximum ($(noderange[2])), value will be clamped." end spinIntegerSetValue(node.hNode[], Int64(clamp(value, noderange[1], noderange[2]))) get(node) end function get(node::SpinIntegerNode) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end hval = Ref(Int64(0)) spinIntegerGetValue(node.hNode[], hval) return hval[] end # # Floating point nodes # struct SpinFloatNode <: AbstractSpinNode name::String hNode::Ref{spinNodeHandle} SpinFloatNode(cam, name::String, nodemap=CameraNodeMap()) = new(name, _getnode(cam, name, nodemap)) end function range(node::SpinFloatNode) hMin = Ref(Float64(0.0)) hMax = Ref(Float64(0.0)) spinFloatGetMin(node.hNode[], hMin) spinFloatGetMax(node.hNode[], hMax) return (hMin[], hMax[]) end function set!(node::SpinFloatNode, value::Number; clampwarn::Bool = true) if !writable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not writable")) end noderange = range(node) if clampwarn value < noderange[1] && @warn "Requested value ($value) for $(node.name) is smaller than minimum ($(noderange[1])), value will be clamped." value > noderange[2] && @warn "Requested value ($value) for $(node.name) is greater than maximum ($(noderange[2])), value will be clamped." end spinFloatSetValue(node.hNode[], Float64(clamp(value, noderange[1], noderange[2]))) get(node) end function get(node::SpinFloatNode) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end hval = Ref(Float64(0)) spinFloatGetValue(node.hNode[], hval) return hval[] end # # Integer enumeration nodes # struct SpinEnumNode <: AbstractSpinNode name::String hNode::Ref{spinNodeHandle} SpinEnumNode(cam, name::String, nodemap=CameraNodeMap()) = new(name, _getnode(cam, name, nodemap)) end function get(node::SpinEnumNode) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end hNodeEntry = Ref(spinNodeHandle(C_NULL)) strbuf = Vector{UInt8}(undef, MAX_BUFFER_LEN) strlen = Ref(Csize_t(MAX_BUFFER_LEN)) spinEnumerationGetCurrentEntry(node.hNode[], hNodeEntry) spinEnumerationEntryGetSymbolic(hNodeEntry[], strbuf, strlen) return unsafe_string(pointer(strbuf)) end function set!(node::SpinEnumNode, value) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end hNodeEntry = Ref(spinNodeHandle(C_NULL)) hNodeVal = Ref(Int64(0)) spinEnumerationGetEntryByName(node.hNode[], value, hNodeEntry) # Get integer value from string if !readable(node.name, hNodeEntry) throw(ErrorException("Node $(node.name) entry is not readable")) end spinEnumerationEntryGetIntValue(hNodeEntry[], hNodeVal) # Set value if !writable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not writable")) end spinEnumerationSetIntValue(node.hNode[], hNodeVal[]) # Readback get(node) end # # Boolean mnodes # struct SpinBooleanNode <: AbstractSpinNode name::String hNode::Ref{spinNodeHandle} SpinBooleanNode(cam, name::String, nodemap=CameraNodeMap()) = new(name, _getnode(cam, name, nodemap)) end function get(node::SpinBooleanNode) if !readable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not readable")) end hval = Ref(bool8_t(0)) spinBooleanGetValue(node.hNode[], hval) return hval[] == 1 ? true : false end function set!(node::SpinBooleanNode, value::Bool) if !writable(node.name, node.hNode) throw(ErrorException("Node $(node.name) is not writable")) end spinBooleanSetValue(node.hNode[], value) get(node) end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
4030
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # SpinImage.jl: interface to Image objects export SpinImage, bpp, id, offset, padding, save, timestamp """ Spinnaker SDK Image object """ mutable struct SpinImage handle::spinImage function SpinImage(handle) image = new(handle) finalizer(_release!, image) return image end end unsafe_convert(::Type{spinImage}, image::SpinImage) = image.handle unsafe_convert(::Type{Ptr{spinImage}}, image::SpinImage) = pointer_from_objref(image) function SpinImage() @assert spinsys.handle != C_NULL himage_ref = Ref(spinImage(C_NULL)) spinImageCreateEmpty(himage_ref) return SpinImage(himage_ref[]) end # Release handle to image function _release!(image::SpinImage) spinImageDestroy(image) image.handle = C_NULL return nothing end """ show(::IO, ::SpinImage) Write details of camera to supplied IO. """ function show(io::IO, image::SpinImage) pixfmt = Ref(spinPixelFormatEnums(0)) spinImageGetPixelFormat(image, pixfmt) write(io, "Spinnaker Image, $(size(image)), $(bpp(image))bpp, $(pixfmt[])") end # Return size of image data buffer. Note that this may include metadata. function _buffersize(image::SpinImage) sz = Ref(Csize_t(0)) spinImageGetBufferSize(image, sz) return Int(sz[]) end # Return a pointer to the data buffer of the input image. function _bufferptr(image::SpinImage) ptr = Ref(Ptr{Cvoid}(0)) spinImageGetData(image, ptr) return Ptr{UInt8}(ptr[]) end """ convert(::SpinImage, ::spinPixelFormatEnums) -> ::SpinImage Convert input image to specified pixel format and return new image. """ function convert(image::SpinImage, fmt::spinPixelFormatEnums) out = SpinImage() spinImageConvert(out, fmt, image); return out end """ bpp(::SpinImage) -> Int Return bits per pixel of input image. """ function bpp(image::SpinImage) bpp = Ref(Csize_t(0)) spinImageGetBitsPerPixel(image, bpp) return Int(bpp[]) end """ offset(::SpinImage) -> Tuple{Int} Return image offset as tuple (x_offset, y_offset). """ function offset(image::SpinImage) xoff = Ref(Csize_t(0)) yoff = Ref(Csize_t(0)) spinImageGetOffsetX(image, xoff) spinImageGetOffsetY(image, yoff) return (Int(xoff[]), Int(yoff[])) end """ padding(::SpinImage) -> Tuple{Int} Return image padding as tuple (x_pad, y_pad). """ function padding(image::SpinImage) xpad = Ref(Csize_t(0)) ypad = Ref(Csize_t(0)) spinImageGetPaddingX(image, xpad) spinImageGetPaddingY(image, ypad) return (Int(xpad[]), Int(ypad[])) end """ size(::SpinImage) -> Tuple{Int} Return image size as tuple (width, height). """ function size(image::SpinImage) width = Ref(Csize_t(0)) height = Ref(Csize_t(0)) spinImageGetWidth(image, width) spinImageGetHeight(image, height) return (Int(width[]), Int(height[])) end """ timestamp(::SpinImage) -> Int64 Return image timestamp from chunk data in nanoseconds since the last timeclock reset (i.e. at camera boot). """ function timestamp(image::SpinImage) timestamp_ref = Ref(Int64(0)) spinImageChunkDataGetIntValue(image, "ChunkTimestamp", timestamp_ref) return timestamp_ref[] end """ id(::SpinImage) -> Int64 Return image id from image chunk data. """ function id(image::SpinImage) id_ref = Ref(Int64(0)) spinImageChunkDataGetIntValue(image, "ChunkFrameID", id_ref); return id_ref[] end """ exposure(::SpinImage) -> Float64 Return exposure time from image chunk data. """ function exposure(image::SpinImage) hExposure = Ref(Float64(0)) spinImageChunkDataGetFloatValue(image, "ChunkExposureTime", hExposure); return hExposure[] end """ save(fn::AbstractString, ::SpinImage, ::spinImageFileFormat) Save the input image to file `fn` in specified format. """ function save(image::SpinImage, fn::AbstractString, fmt::spinImageFileFormat) spinImageSave(image, fn, fmt) end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
3792
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell module Spinnaker using FixedPointNumbers using Libdl import Base: unsafe_convert, show, length, getindex, size, convert, range, showerror export System, Camera, CameraList, SpinError const libSpinnaker_C = Ref{String}("") const libSpinVideo_C = Ref{String}("") const MAX_BUFFER_LEN = Csize_t(1023) # include API wrapper include("wrapper/CEnum.jl") using .CEnum include("wrapper/spin_common.jl") struct SpinError <: Exception val::spinError end showerror(io::IO, ex::SpinError) = print(io, "Spinnaker SDK error: ", ex.val) function checkerror(err::spinError) if err != spinError(0) throw(SpinError(err)) end return nothing end include("wrapper/spin_api.jl") # export everything spin* foreach(names(@__MODULE__, all=true)) do s if startswith(string(s), "spin") @eval export $s end end # Include interface include("SpinImage.jl") include("CameraImage.jl") include("System.jl") include("Camera.jl") include("CameraList.jl") include("NodeMap.jl") include("Nodes.jl") get_bool_env(name::String; default::String="false") = lowercase(Base.get(ENV, name, default)) in ("t", "true", "y", "yes", "1") const _system_initialized = Ref(false) const _init_lock = ReentrantLock() # Create a System object at runtime function init() lock(_init_lock) do if _system_initialized[] return end if haskey(ENV, "JULIA_SPINNAKER_MANUAL_INIT") @warn """ The environment variable `JULIA_SPINNAKER_MANUAL_INIT` is deprecated. Spinnaker is initialized during first CameraList usage""" maxlog=1 end @static if Sys.iswindows() paths = [joinpath(ENV["ProgramFiles"], "Point Grey Research", "Spinnaker", "bin", "vs2015")] libspinnaker = "SpinnakerC_v140.dll" libspinvideo = "" elseif Sys.islinux() paths = ["/usr/lib" "/opt/spinnaker/lib"] libspinnaker = "libSpinnaker_C.so" libspinvideo = "libSpinVideo_C.so" elseif Sys.isapple() paths = ["/usr/local/lib"] libspinnaker = "libSpinnaker_C.dylib" libspinvideo = "libSpinVideo_C.dylib" else error("Spinnaker SDK is only supported on Linux, Windows and MacOS platforms") end libSpinnaker_C_path = "" libSpinVideo_C_path = "" for path in paths libSpinnaker_C_path = joinpath(path, libspinnaker) libSpinVideo_C_path = joinpath(path, libspinvideo) if isfile(libSpinnaker_C_path) && isfile(libSpinVideo_C_path) libSpinnaker_C[] = libSpinnaker_C_path libSpinVideo_C[] = libSpinVideo_C_path end end if libSpinnaker_C[] == "" || libSpinVideo_C[] == "" error("Spinnaker SDK cannot be found.") end try libSpinnaker_C_handle = dlopen(libSpinnaker_C[]) !Sys.iswindows() && (libSpinVideo_C_handle = dlopen(libSpinVideo_C[])) catch @error "Spinnaker SDK cannot be dlopen-ed" rethrow() end try global spinsys = System() catch bt = catch_backtrace() @error "Spinnaker SDK loaded but Spinnaker.jl failed to initialize" if !haskey(ENV, "FLIR_GENTL64_CTI") @warn "The environment is missing the variable `FLIR_GENTL64_CTI`, which may be the cause of this error. Check that it is set to the path to `FLIR_GenTL.cti` (e.g. `/opt/spinnaker/lib/flir-gentl/FLIR_GenTL.cti`)." elseif !endswith(ENV["FLIR_GENTL64_CTI"], "FLIR_GenTL.cti") @warn "The environment has the variable `FLIR_GENTL64_CTI`, but it does not point to `FLIR_GenTL.cti`, which may be the cause of this error. Check that it is set to the path to `FLIR_GenTL.cti` (e.g. `/opt/spinnaker/lib/flir-gentl/FLIR_GenTL.cti`)." end rethrow() end _system_initialized[] = true end end end # module
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
1233
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # System.jl: interface to Spinnaker system """ Spinnaker SDK system object. System() returns new System object from which interfaces and devices can be discovered. """ mutable struct System handle::spinSystem function System() hsystem_ref = Ref(spinSystem(C_NULL)) spinSystemGetInstance(hsystem_ref) @assert hsystem_ref[] != C_NULL sys = new(hsystem_ref[]) finalizer(_release!, sys) return sys end end unsafe_convert(::Type{spinSystem}, sys::System) = sys.handle unsafe_convert(::Type{Ptr{spinSystem}}, sys::System) = pointer_from_objref(sys) # Release handle to system function _release!(sys::System) spinSystemReleaseInstance(sys) sys.handle = C_NULL return nothing end """ version(::System)-> version, build Query the version number of the Spinnaker library in use. Returns a VersionNumber object and seperate build number. """ function version(sys::System) hlibver_ref = Ref(spinLibraryVersion(0,0,0,0)) spinSystemGetLibraryVersion(sys, hlibver_ref) libver = VersionNumber(hlibver_ref[].major, hlibver_ref[].minor, hlibver_ref[].type) return libver, hlibver_ref[].build end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
5825
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # camera/acquisition.jl: Camera object acquistion features """ isrunning(::Camera) -> Bool Determine if the camera is currently acquiring images. """ function isrunning(cam::Camera) pbIsStreaming = Ref(bool8_t(false)) spinCameraIsStreaming(cam, pbIsStreaming) return (pbIsStreaming[] == 0x01) end """ start!(::Camera) Start acquistion on specified camera. """ function start!(cam::Camera) spinCameraBeginAcquisition(cam) return cam end """ stop!(::Camera) Stop acquistion on specified camera. """ function stop!(cam::Camera) spinCameraEndAcquisition(cam) return cam end """ triggermode(::Camera) -> String Camera trigger mode. """ triggermode(cam::Camera) = get(SpinEnumNode(cam, "TriggerMode")) """ triggermode!(::Camera, ::String) -> String Set camera trigger mode, returns set mode. """ triggermode!(cam::Camera, mode) = set!(SpinEnumNode(cam, "TriggerMode"), mode) """ triggersource!(::Camera, ::AbstractString) -> String Set camera to use specified trigger source. Trigger mode is disabled during update and restored after new source is set. Method returns set trigger source. """ function triggersource!(cam::Camera, src) initmode = triggermode(cam) # Save current trigger mode setsrc = set!(SpinEnumNode(cam, "TriggerSource"), src) triggermode!(cam, initmode) # Restore initial trigger mode return setsrc end """ triggersource(::Camera) -> String Return current camera trigger source. """ triggersource(cam::Camera) = get(SpinEnumNode(cam, "TriggerSource")) """ trigger!(::Camera) Emit software trigger to specified camera. """ function trigger!(cam::Camera) if triggersource(cam) != "Software" @error "Camera is not set to software trigger source" end if triggermode(cam) != "On" @error "Camera is not set to trigger mode" end hNodeMap = Ref(spinNodeMapHandle(C_NULL)) spinCameraGetNodeMap(cam, hNodeMap) hTriggerSoftware = Ref(spinNodeHandle(C_NULL)) spinNodeMapGetNode(hNodeMap[], "TriggerSoftware", hTriggerSoftware); spinCommandExecute(hTriggerSoftware[]) end """ exposure(::Camera) -> Float, String Camera exposure time and mode. """ exposure(cam::Camera) = (get(SpinFloatNode(cam, "ExposureTime")), get(SpinEnumNode(cam, "ExposureAuto"))) """ exposure!(::Camera) Activate (continuous) automatic exposure control on specified camera. """ exposure!(cam::Camera) = set!(SpinEnumNode(cam, "ExposureAuto"), "Continuous") """ exposure!(::Camera, ::Number) -> Float Set exposure time on camera to specified number of microseconds. The requested value is clamped to range supported by the camera, and the actual set value is returned. This function disables automatic exposure. """ function exposure!(cam::Camera, t) set!(SpinEnumNode(cam, "ExposureAuto"), "Off") set!(SpinFloatNode(cam, "ExposureTime"), t) end """ exposure_range(::Camera) -> (Float, Float) Exposure time limits in microseconds. """ exposure_limits(cam::Camera) = range(SpinFloatNode(cam, "ExposureTime")) """ autoexposure_limits!(::Camera, (lower, upper); clampwarn=true) -> (Float, Float) Write lower and upper limits of the Auto Exposure Time (us) value. Values exceeding range are clamped to the allowable extrema and returned, and a warning is given, which can be disabled with `clampwarn=false`. """ function autoexposure_limits!(cam::Camera, lims; clampwarn=true) set!(SpinFloatNode(cam, cam.names["AutoExposureTimeLowerLimit"]), lims[1], clampwarn=clampwarn) set!(SpinFloatNode(cam, cam.names["AutoExposureTimeUpperLimit"]), lims[2], clampwarn=clampwarn) autoexposure_limits(cam) end """ autoexposure_limits(::Camera) -> (Float, Float) Lower and upper limits of the Auto Exposure Time (us) value. """ function autoexposure_limits(cam::Camera) (get(SpinFloatNode(cam, cam.names["AutoExposureTimeLowerLimit"])), get(SpinFloatNode(cam, cam.names["AutoExposureTimeUpperLimit"]))) end """ autoexposure_control_priority!(cam::Camera, priority) Select whether to adjust gain or exposure first. `priority` can be one of `"Gain"`, `"ExposureTime"`. See Spinnaker SDK docs section 12.6.2.6 `enum AutoExposureControlPriorityEnums` for more information. """ function autoexposure_control_priority!(cam::Camera, priority) set!(SpinEnumNode(cam, "AutoExposureControlPriority"), priority) autoexposure_control_priority(cam) end """ autoexposure_control_priority(cam::Camera) Get the auto-exposure control priority. One of `"Gain"`, `"ExposureTime"`. See Spinnaker SDK docs section 12.6.2.6 `enum AutoExposureControlPriorityEnums` for more information. """ function autoexposure_control_priority(cam::Camera) get(SpinEnumNode(cam, "AutoExposureControlPriority")) end """ framerate(::Camera) -> Float Camera frame rate. """ function framerate(cam::Camera) get(SpinFloatNode(cam, "AcquisitionFrameRate")) end """ framerate!(::Camera) Activate (continuous) automatic framerate control on specified camera. """ framerate!(cam::Camera) = set!(SpinEnumNode(cam, "AcquisitionFrameRateAuto"), "Continuous") """ framerate!(::Camera, ::Number) -> Float Set framerate on camera to specified number of frames per second. The requested value is clamped to range supported by the camera, and the actual set value is returned. """ function framerate!(cam::Camera, fps) try set!(SpinEnumNode(cam, "AcquisitionFrameRateAuto"), "Off") catch e end set!(SpinBooleanNode(cam, cam.names["AcquisitionFrameRateEnabled"]), true) set!(SpinFloatNode(cam, "AcquisitionFrameRate"), fps) end """ framerate_limits(::Camera) -> (Float, Float) Framerate limits in microseconds. """ framerate_limits(cam::Camera) = range(SpinFloatNode(cam, "AcquisitionFrameRate"))
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
2092
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # camera/analog.jl: Camera object analog features """ gain(::Camera) -> (Float,String) Camera exposure gain number (dB) and automatic gain mode. """ gain(cam::Camera) = (get(SpinFloatNode(cam, "Gain")), get(SpinEnumNode(cam, "GainAuto"))) """ gain!(::Camera) Set automatic exposure gain on camera. """ gain!(cam::Camera) = set!(SpinEnumNode(cam, "GainAuto"), "Continuous") """ gain!(::Camera, ::Number) -> Float Set exposure gain on camera to specified number (dB). Gain is clamped to range supported by camera. This function disables automatic gain. """ function gain!(cam::Camera, g) set!(SpinEnumNode(cam, "GainAuto"), "Off") set!(SpinFloatNode(cam, "Gain"), g) end """ gain_limits(::Camera) -> (Float, Float) Camera gain limits in dB. """ gain_limits(cam::Camera) = range(SpinFloatNode(cam,"Gain")) """ autogain_limits!(::Camera, (lower, upper); clampwarn=true) -> (Float, Float) Write lower and upper limits of the Auto Gain Time (us) value. Values exceeding range are clamped to the allowable extrema and returned, and a warning is given, which can be disabled with `clampwarn=false`. """ function autogain_limits!(cam::Camera, lims; clampwarn=true) set!(SpinFloatNode(cam, "AutoExposureGainLowerLimit"), lims[1], clampwarn=clampwarn) set!(SpinFloatNode(cam, "AutoExposureGainUpperLimit"), lims[2], clampwarn=clampwarn) autogain_limits(cam) end """ autogain_limits(::Camera) -> (Float, Float) Lower and upper limits of the Auto Gain Time (us) value. """ function autogain_limits(cam::Camera) (get(SpinFloatNode(cam, "AutoExposureGainLowerLimit")), get(SpinFloatNode(cam, "AutoExposureGainUpperLimit"))) end """ gammaenable(::Camera) -> Bool Return status of gamma correction """ gammaenable(cam::Camera) = get(SpinBooleanNode(cam, "GammaEnable")) """ gammaenable!(::Camera, ::Bool) -> Bool Enable or disable gamma correction on camera. """ gammaenable!(cam::Camera, en::Bool) = set!(SpinBooleanNode(cam, "GammaEnable"), en)
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
1593
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # camera/digitalio.jl: Camera object digital io features export line_mode!, line_mode, line_inverter!, line_inverter, v3_3_enable!, v3_3_enable """ line_mode!(::Camera, state::Symbol) Sets the DigitalIO Line Mode. State can either be "Input" or "Output" """ function line_mode!(cam::Camera, state::String) @assert state in ["Input", "Output"] "State can only be either \"Input\" or \"Output\"" set!(SpinEnumNode(cam, "LineMode"), state) return nothing end @deprecate line_mode(cam::Camera, state::String) line_mode!(cam::Camera, state::String) """ line_mode(::Camera) Gets the DigitalIO Line Mode. State can either be "Input" or "Output" """ line_mode(cam::Camera) = get(SpinEnumNode(cam, "LineMode")) """ line_inverter!(::Camera, enable::Bool) Sets the DigitalIO LineInverter state. """ function line_inverter!(cam::Camera, state::Bool) set!(SpinBooleanNode(cam, "LineInverter"), state) return nothing end """ line_inverter(::Camera) Read the DigitalIO LineInverter state. """ line_inverter(cam::Camera) = get(SpinBooleanNode(cam, "LineInverter")) """ v3_3_enable!(::Camera, state::Bool) Sets the DigitalIO 3.3V line state. """ v3_3_enable!(cam::Camera, state::Bool) = set!(SpinBooleanNode(cam, "V3_3Enable"), state) @deprecate v3_3_enable(cam::Camera, state::Bool) v3_3_enable!(cam::Camera, state::Bool) """ v3_3_enable(::Camera) Gets the DigitalIO 3.3V line state. """ v3_3_enable(cam::Camera) = get(SpinBooleanNode(cam, "V3_3Enable"))
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
2375
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # camera/format.jl: Camera object image format features """ adcbits(::Camera) -> String Return ADC bit depth. """ adcbits(cam::Camera) = get(SpinEnumNode(cam, "AdcBitDepth")) """ adcbits!(::Camera, ::AbstractString) -> String Set ADC bit depth, returns set depth. """ adcbits!(cam::Camera, bits) = set!(SpinEnumNode(cam, "AdcBitDepth"), bits) """ pixelformat(::Camera) -> String Return camera pixel format. """ pixelformat(cam::Camera) = get(SpinEnumNode(cam, "PixelFormat")) """ pixelformat!(::Camera, ::AbstractString) -> String Set camera pixel format, returns set format. """ pixelformat!(cam::Camera, fmt) = set!(SpinEnumNode(cam, "PixelFormat"), fmt) """ sensordims(::Camera) -> (Int, Int) Return the width and height of the sensor. """ sensordims(cam::Camera) = (get(SpinIntegerNode(cam, "SensorWidth")), get(SpinIntegerNode(cam, "SensorHeight"))) """ imagedims(::Camera) -> (Int, Int) Return the width and height of the image. """ imagedims(cam::Camera) = (get(SpinIntegerNode(cam, "Width")), get(SpinIntegerNode(cam, "Height"))) """ imagedims!(::Camera, (width, height)) -> (Int, Int) Set the width and height of the image, return the set values. """ function imagedims!(cam::Camera, dims) set!(SpinIntegerNode(cam, "Width"), dims[1]) set!(SpinIntegerNode(cam, "Height"), dims[2]) imagedims(cam) end """ imagedims_limits(::Camera) -> ((Int, Int), (Int, Int)) Image dimension limits in width, and height. """ imagedims_limits(cam::Camera) = (range(SpinIntegerNode(cam, "Width")), range(SpinIntegerNode(cam, "Height"))) """ offsetdims(::Camera) -> (Int, Int) Return the offset in x and y of the image. """ offsetdims(cam::Camera) = (get(SpinIntegerNode(cam, "OffsetX")), get(SpinIntegerNode(cam, "OffsetY"))) """ offsetdims!(::Camera, (X,Y)) -> (Int, Int) Set the image offset in x and y, return the set values. """ function offsetdims!(cam::Camera, dims) set!(SpinIntegerNode(cam, "OffsetX"), dims[1]) set!(SpinIntegerNode(cam, "OffsetY"), dims[2]) offsetdims(cam) end """ offsetdims_limits(::Camera) -> ((Int, Int), (Int, Int)) Image offsets limits in width, and height. """ offsetdims_limits(cam::Camera) = (range(SpinIntegerNode(cam, "OffsetX")), range(SpinIntegerNode(cam, "OffsetY")))
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
2218
# Spinnaker.jl: wrapper for FLIR/Point Grey Spinnaker SDK # Copyright (C) 2019 Samuel Powell # Stream.jl: functions to control stream interface """ buffermode(::Camera) -> String The current stream buffer mode of the camera. """ function buffermode(cam::Camera) get(SpinEnumNode(cam::Camera, "StreamBufferHandlingMode", CameraTLStreamNodeMap())) end """ buffermode!(::Camera, mode::String) -> String Set the stream buffer mode of the camera, options include: - OldestFirst - OldestFirstOverwrite - NewestFirst - NewestFirstOverwrite - NewestOnly See https://www.ptgrey.com/tan/11174 for more details. """ function buffermode!(cam::Camera, mode::String) set!(SpinEnumNode(cam, "StreamBufferHandlingMode", CameraTLStreamNodeMap()), mode) end """ buffercount(::Camera) -> (Int, String) Return the buffer count mode and specified number of buffers. """ function buffercount(cam::Camera) count = get(SpinIntegerNode(cam, "StreamBufferCountResult", CameraTLStreamNodeMap())) mode = get(SpinEnumNode(cam, "StreamBufferCountMode", CameraTLStreamNodeMap())) return Int(count), mode end """ buffercount!(::Camera) -> (Int, String) Set buffer count mode to automatic. Returns the buffer count and mode. """ function buffercount!(cam::Camera) set!(SpinEnumNode(cam, "StreamBufferCountMode", CameraTLStreamNodeMap()), "Auto") buffercount(cam) end """ buffercount!(::Camera, count) -> (Int, String) Set buffer count mode to manual, and specify the number of buffers. Returns the buffer count and mode. """ function buffercount!(cam::Camera, count) set!(SpinEnumNode(cam, "StreamBufferCountMode", CameraTLStreamNodeMap()), "Manual") set!(SpinIntegerNode(cam, "StreamBufferCountManual", CameraTLStreamNodeMap()), count) buffercount(cam) end """ bufferunderrun(::Camera) -> Int The number of buffer underruns on the camera stream. """ function bufferunderrun(cam::Camera) get(SpinIntegerNode(cam, "StreamBufferUnderrunCount", CameraTLStreamNodeMap())) end """ bufferfailed(::Camera) -> Int The number of failed (invalid) buffers on the camera stream. """ function bufferfailed(cam::Camera) get(SpinIntegerNode(cam, "StreamFailedBufferCount", CameraTLStreamNodeMap())) end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
3845
module CEnum abstract type Cenum{T} end Base.:|(a::T, b::T) where {T<:Cenum{UInt32}} = UInt32(a) | UInt32(b) Base.:&(a::T, b::T) where {T<:Cenum{UInt32}} = UInt32(a) & UInt32(b) Base.:(==)(a::Integer, b::Cenum{T}) where {T<:Integer} = a == T(b) Base.:(==)(a::Cenum, b::Integer) = b == a # typemin and typemax won't change for an enum, so we might as well inline them per type Base.typemax(::Type{T}) where {T<:Cenum} = last(enum_values(T)) Base.typemin(::Type{T}) where {T<:Cenum} = first(enum_values(T)) Base.convert(::Type{Integer}, x::Cenum{T}) where {T<:Integer} = Base.bitcast(T, x) Base.convert(::Type{T}, x::Cenum{T2}) where {T<:Integer,T2<:Integer} = convert(T, Base.bitcast(T2, x)) (::Type{T})(x::Cenum{T2}) where {T<:Integer,T2<:Integer} = T(Base.bitcast(T2, x))::T (::Type{T})(x) where {T<:Cenum} = convert(T, x) Base.write(io::IO, x::Cenum) = write(io, Int32(x)) Base.read(io::IO, ::Type{T}) where {T<:Cenum} = T(read(io, Int32)) enum_values(::T) where {T<:Cenum} = enum_values(T) enum_names(::T) where {T<:Cenum} = enum_names(T) is_member(::Type{T}, x::Integer) where {T<:Cenum} = is_member(T, enum_values(T), x) @inline is_member(::Type{T}, r::UnitRange, x::Integer) where {T<:Cenum} = x in r @inline function is_member(::Type{T}, values::Tuple, x::Integer) where {T<:Cenum} lo, hi = typemin(T), typemax(T) x<lo || x>hi && return false for val in values val == x && return true val > x && return false # is sorted end return false end function enum_name(x::T) where {T<:Cenum} index = something(findfirst(isequal(x), enum_values(T)), 0) if index != 0 return enum_names(T)[index] end error("Invalid enum: $(Int(x)), name not found") end Base.show(io::IO, x::Cenum) = print(io, enum_name(x), "($(Int(x)))") function islinear(array) isempty(array) && return false # false, really? it's kinda undefined? lastval = first(array) for val in Iterators.rest(array, 2) val-lastval == 1 || return false end return true end macro cenum(name, args...) if Meta.isexpr(name, :curly) typename, type = name.args typename = esc(typename) typesize = 8*sizeof(getfield(Base, type)) typedef_expr = :(primitive type $typename <: CEnum.Cenum{$type} $typesize end) elseif isa(name, Symbol) # default to UInt32 typename = esc(name) type = UInt32 typedef_expr = :(primitive type $typename <: CEnum.Cenum{UInt32} 32 end) else error("Name must be symbol or Name{Type}. Found: $name") end lastval = -1 name_values = map([args...]) do arg if isa(arg, Symbol) lastval += 1 val = lastval sym = arg elseif arg.head == :(=) || arg.head == :kw sym,val = arg.args else error("Expression of type $arg not supported. Try only symbol or name = value") end (sym, val) end sort!(name_values, by=last) # sort for values values = map(last, name_values) if islinear(values) # optimize for linear values values = :($(first(values)):$(last(values))) else values = :(tuple($(values...))) end value_block = Expr(:block) for (ename, value) in name_values push!(value_block.args, :(const $(esc(ename)) = $typename($value))) end expr = quote $typedef_expr function Base.convert(::Type{$typename}, x::Integer) is_member($typename, x) || Base.Enums.enum_argument_error($(Expr(:quote, name)), x) Base.bitcast($typename, convert($type, x)) end CEnum.enum_names(::Type{$typename}) = tuple($(map(x-> Expr(:quote, first(x)), name_values)...)) CEnum.enum_values(::Type{$typename}) = $values $value_block end expr end export @cenum end # module
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
53343
# Julia wrapper for header: /usr/include/spinnaker/spinc/CameraDefsC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/ChunkDataDefC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/QuickSpinC.h # Automatically generated using Clang.jl wrap_c function quickSpinInit(hCamera, pQuickSpin) checkerror(ccall((:quickSpinInit, libSpinnaker_C[]), spinError, (spinCamera, Ptr{quickSpin}), hCamera, pQuickSpin)) end function quickSpinInitEx(hCamera, pQuickSpin, pQuickSpinTLDevice, pQuickSpinTLStream) checkerror(ccall((:quickSpinInitEx, libSpinnaker_C[]), spinError, (spinCamera, Ptr{quickSpin}, Ptr{quickSpinTLDevice}, Ptr{quickSpinTLStream}), hCamera, pQuickSpin, pQuickSpinTLDevice, pQuickSpinTLStream)) end function quickSpinTLDeviceInit(hCamera, pQuickSpinTLDevice) checkerror(ccall((:quickSpinTLDeviceInit, libSpinnaker_C[]), spinError, (spinCamera, Ptr{quickSpinTLDevice}), hCamera, pQuickSpinTLDevice)) end function quickSpinTLStreamInit(hCamera, pQuickSpinTLStream) checkerror(ccall((:quickSpinTLStreamInit, libSpinnaker_C[]), spinError, (spinCamera, Ptr{quickSpinTLStream}), hCamera, pQuickSpinTLStream)) end function quickSpinTLInterfaceInit(hInterface, pQuickSpinTLInterface) checkerror(ccall((:quickSpinTLInterfaceInit, libSpinnaker_C[]), spinError, (spinInterface, Ptr{quickSpinTLInterface}), hInterface, pQuickSpinTLInterface)) end # Julia wrapper for header: /usr/include/spinnaker/spinc/QuickSpinDefsC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinVideoC.h # Automatically generated using Clang.jl wrap_c function spinVideoOpenUncompressed(phSpinVideo, pName, option) checkerror(ccall((:spinVideoOpenUncompressed, libSpinVideo_C[]), spinError, (Ptr{spinVideo}, Cstring, spinAVIOption), phSpinVideo, pName, option)) end function spinVideoOpenMJPG(phSpinVideo, pName, option) checkerror(ccall((:spinVideoOpenMJPG, libSpinVideo_C[]), spinError, (Ptr{spinVideo}, Cstring, spinMJPGOption), phSpinVideo, pName, option)) end function spinVideoOpenH264(phSpinVideo, pName, option) checkerror(ccall((:spinVideoOpenH264, libSpinVideo_C[]), spinError, (Ptr{spinVideo}, Cstring, spinH264Option), phSpinVideo, pName, option)) end function spinVideoAppend(hSpinVideo, hImage) checkerror(ccall((:spinVideoAppend, libSpinVideo_C[]), spinError, (spinVideo, spinImage), hSpinVideo, hImage)) end function spinVideoSetMaximumFileSize(hSpinVideo, size) checkerror(ccall((:spinVideoSetMaximumFileSize, libSpinVideo_C[]), spinError, (spinVideo, UInt32), hSpinVideo, size)) end function spinVideoClose(hSpinVideo) checkerror(ccall((:spinVideoClose, libSpinVideo_C[]), spinError, (spinVideo,), hSpinVideo)) end # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinnakerC.h # Automatically generated using Clang.jl wrap_c function spinErrorGetLast(pError) checkerror(ccall((:spinErrorGetLast, libSpinnaker_C[]), spinError, (Ptr{spinError},), pError)) end function spinErrorGetLastMessage(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastMessage, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastBuildDate(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastBuildDate, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastBuildTime(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastBuildTime, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastFileName(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastFileName, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastFullMessage(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastFullMessage, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastFunctionName(pBuf, pBufLen) checkerror(ccall((:spinErrorGetLastFunctionName, libSpinnaker_C[]), spinError, (Cstring, Ptr{Csize_t}), pBuf, pBufLen)) end function spinErrorGetLastLineNumber(pLineNum) checkerror(ccall((:spinErrorGetLastLineNumber, libSpinnaker_C[]), spinError, (Ptr{Int64},), pLineNum)) end function spinSystemGetInstance(phSystem) checkerror(ccall((:spinSystemGetInstance, libSpinnaker_C[]), spinError, (Ptr{spinSystem},), phSystem)) end function spinSystemReleaseInstance(hSystem) checkerror(ccall((:spinSystemReleaseInstance, libSpinnaker_C[]), spinError, (spinSystem,), hSystem)) end function spinSystemGetInterfaces(hSystem, hInterfaceList) checkerror(ccall((:spinSystemGetInterfaces, libSpinnaker_C[]), spinError, (spinSystem, spinInterfaceList), hSystem, hInterfaceList)) end function spinSystemGetCameras(hSystem, hCameraList) checkerror(ccall((:spinSystemGetCameras, libSpinnaker_C[]), spinError, (spinSystem, spinCameraList), hSystem, hCameraList)) end function spinSystemGetCamerasEx(hSystem, bUpdateInterfaces, bUpdateCameras, hCameraList) checkerror(ccall((:spinSystemGetCamerasEx, libSpinnaker_C[]), spinError, (spinSystem, bool8_t, bool8_t, spinCameraList), hSystem, bUpdateInterfaces, bUpdateCameras, hCameraList)) end function spinSystemSetLoggingLevel(hSystem, logLevel) checkerror(ccall((:spinSystemSetLoggingLevel, libSpinnaker_C[]), spinError, (spinSystem, spinnakerLogLevel), hSystem, logLevel)) end function spinSystemGetLoggingLevel(hSystem, pLogLevel) checkerror(ccall((:spinSystemGetLoggingLevel, libSpinnaker_C[]), spinError, (spinSystem, Ptr{spinnakerLogLevel}), hSystem, pLogLevel)) end function spinSystemRegisterLogEvent(hSystem, hLogEvent) checkerror(ccall((:spinSystemRegisterLogEvent, libSpinnaker_C[]), spinError, (spinSystem, spinLogEvent), hSystem, hLogEvent)) end function spinSystemUnregisterLogEvent(hSystem, hLogEvent) checkerror(ccall((:spinSystemUnregisterLogEvent, libSpinnaker_C[]), spinError, (spinSystem, spinLogEvent), hSystem, hLogEvent)) end function spinSystemUnregisterAllLogEvents(hSystem) checkerror(ccall((:spinSystemUnregisterAllLogEvents, libSpinnaker_C[]), spinError, (spinSystem,), hSystem)) end function spinSystemIsInUse(hSystem, pbIsInUse) checkerror(ccall((:spinSystemIsInUse, libSpinnaker_C[]), spinError, (spinSystem, Ptr{bool8_t}), hSystem, pbIsInUse)) end function spinSystemRegisterArrivalEvent(hSystem, hArrivalEvent) checkerror(ccall((:spinSystemRegisterArrivalEvent, libSpinnaker_C[]), spinError, (spinSystem, spinArrivalEvent), hSystem, hArrivalEvent)) end function spinSystemRegisterRemovalEvent(hSystem, hRemovalEvent) checkerror(ccall((:spinSystemRegisterRemovalEvent, libSpinnaker_C[]), spinError, (spinSystem, spinRemovalEvent), hSystem, hRemovalEvent)) end function spinSystemUnregisterArrivalEvent(hSystem, hArrivalEvent) checkerror(ccall((:spinSystemUnregisterArrivalEvent, libSpinnaker_C[]), spinError, (spinSystem, spinArrivalEvent), hSystem, hArrivalEvent)) end function spinSystemUnregisterRemovalEvent(hSystem, hRemovalEvent) checkerror(ccall((:spinSystemUnregisterRemovalEvent, libSpinnaker_C[]), spinError, (spinSystem, spinRemovalEvent), hSystem, hRemovalEvent)) end function spinSystemRegisterInterfaceEvent(hSystem, hInterfaceEvent) checkerror(ccall((:spinSystemRegisterInterfaceEvent, libSpinnaker_C[]), spinError, (spinSystem, spinInterfaceEvent), hSystem, hInterfaceEvent)) end function spinSystemUnregisterInterfaceEvent(hSystem, hInterfaceEvent) checkerror(ccall((:spinSystemUnregisterInterfaceEvent, libSpinnaker_C[]), spinError, (spinSystem, spinInterfaceEvent), hSystem, hInterfaceEvent)) end function spinSystemUpdateCameras(hSystem, pbChanged) checkerror(ccall((:spinSystemUpdateCameras, libSpinnaker_C[]), spinError, (spinSystem, Ptr{bool8_t}), hSystem, pbChanged)) end function spinSystemUpdateCamerasEx(hSystem, bUpdateInterfaces, pbChanged) checkerror(ccall((:spinSystemUpdateCamerasEx, libSpinnaker_C[]), spinError, (spinSystem, bool8_t, Ptr{bool8_t}), hSystem, bUpdateInterfaces, pbChanged)) end function spinSystemSendActionCommand(hSystem, iDeviceKey, iGroupKey, iGroupMask, iActionTime, piResultSize, results) checkerror(ccall((:spinSystemSendActionCommand, libSpinnaker_C[]), spinError, (spinSystem, Csize_t, Csize_t, Csize_t, Csize_t, Ptr{Csize_t}, Ptr{actionCommandResult}), hSystem, iDeviceKey, iGroupKey, iGroupMask, iActionTime, piResultSize, results)) end function spinSystemGetLibraryVersion(hSystem, hLibraryVersion) checkerror(ccall((:spinSystemGetLibraryVersion, libSpinnaker_C[]), spinError, (spinSystem, Ptr{spinLibraryVersion}), hSystem, hLibraryVersion)) end function spinInterfaceListCreateEmpty(phInterfaceList) checkerror(ccall((:spinInterfaceListCreateEmpty, libSpinnaker_C[]), spinError, (Ptr{spinInterfaceList},), phInterfaceList)) end function spinInterfaceListDestroy(hInterfaceList) checkerror(ccall((:spinInterfaceListDestroy, libSpinnaker_C[]), spinError, (spinInterfaceList,), hInterfaceList)) end function spinInterfaceListGetSize(hInterfaceList, pSize) checkerror(ccall((:spinInterfaceListGetSize, libSpinnaker_C[]), spinError, (spinInterfaceList, Ptr{Csize_t}), hInterfaceList, pSize)) end function spinInterfaceListGet(hInterfaceList, index, phInterface) checkerror(ccall((:spinInterfaceListGet, libSpinnaker_C[]), spinError, (spinInterfaceList, Csize_t, Ptr{spinInterface}), hInterfaceList, index, phInterface)) end function spinInterfaceListClear(hInterfaceList) checkerror(ccall((:spinInterfaceListClear, libSpinnaker_C[]), spinError, (spinInterfaceList,), hInterfaceList)) end function spinCameraListCreateEmpty(phCameraList) checkerror(ccall((:spinCameraListCreateEmpty, libSpinnaker_C[]), spinError, (Ptr{spinCameraList},), phCameraList)) end function spinCameraListDestroy(hCameraList) checkerror(ccall((:spinCameraListDestroy, libSpinnaker_C[]), spinError, (spinCameraList,), hCameraList)) end function spinCameraListGetSize(hCameraList, pSize) checkerror(ccall((:spinCameraListGetSize, libSpinnaker_C[]), spinError, (spinCameraList, Ptr{Csize_t}), hCameraList, pSize)) end function spinCameraListGet(hCameraList, index, phCamera) checkerror(ccall((:spinCameraListGet, libSpinnaker_C[]), spinError, (spinCameraList, Csize_t, Ptr{spinCamera}), hCameraList, index, phCamera)) end function spinCameraListClear(hCameraList) checkerror(ccall((:spinCameraListClear, libSpinnaker_C[]), spinError, (spinCameraList,), hCameraList)) end function spinCameraListRemove(hCameraList, index) checkerror(ccall((:spinCameraListRemove, libSpinnaker_C[]), spinError, (spinCameraList, Csize_t), hCameraList, index)) end function spinCameraListAppend(hCameraListBase, hCameraListToAppend) checkerror(ccall((:spinCameraListAppend, libSpinnaker_C[]), spinError, (spinCameraList, spinCameraList), hCameraListBase, hCameraListToAppend)) end function spinCameraListGetBySerial(hCameraList, pSerial, phCamera) checkerror(ccall((:spinCameraListGetBySerial, libSpinnaker_C[]), spinError, (spinCameraList, Cstring, Ptr{spinCamera}), hCameraList, pSerial, phCamera)) end function spinCameraListRemoveBySerial(hCameraList, pSerial) checkerror(ccall((:spinCameraListRemoveBySerial, libSpinnaker_C[]), spinError, (spinCameraList, Cstring), hCameraList, pSerial)) end function spinInterfaceUpdateCameras(hInterface, pbChanged) checkerror(ccall((:spinInterfaceUpdateCameras, libSpinnaker_C[]), spinError, (spinInterface, Ptr{bool8_t}), hInterface, pbChanged)) end function spinInterfaceGetCameras(hInterface, hCameraList) checkerror(ccall((:spinInterfaceGetCameras, libSpinnaker_C[]), spinError, (spinInterface, spinCameraList), hInterface, hCameraList)) end function spinInterfaceGetCamerasEx(hInterface, bUpdateCameras, hCameraList) checkerror(ccall((:spinInterfaceGetCamerasEx, libSpinnaker_C[]), spinError, (spinInterface, bool8_t, spinCameraList), hInterface, bUpdateCameras, hCameraList)) end function spinInterfaceGetTLNodeMap(hInterface, phNodeMap) checkerror(ccall((:spinInterfaceGetTLNodeMap, libSpinnaker_C[]), spinError, (spinInterface, Ptr{spinNodeMapHandle}), hInterface, phNodeMap)) end function spinInterfaceRegisterArrivalEvent(hInterface, hArrivalEvent) checkerror(ccall((:spinInterfaceRegisterArrivalEvent, libSpinnaker_C[]), spinError, (spinInterface, spinArrivalEvent), hInterface, hArrivalEvent)) end function spinInterfaceRegisterRemovalEvent(hInterface, hRemovalEvent) checkerror(ccall((:spinInterfaceRegisterRemovalEvent, libSpinnaker_C[]), spinError, (spinInterface, spinRemovalEvent), hInterface, hRemovalEvent)) end function spinInterfaceUnregisterArrivalEvent(hInterface, hArrivalEvent) checkerror(ccall((:spinInterfaceUnregisterArrivalEvent, libSpinnaker_C[]), spinError, (spinInterface, spinArrivalEvent), hInterface, hArrivalEvent)) end function spinInterfaceUnregisterRemovalEvent(hInterface, hRemovalEvent) checkerror(ccall((:spinInterfaceUnregisterRemovalEvent, libSpinnaker_C[]), spinError, (spinInterface, spinRemovalEvent), hInterface, hRemovalEvent)) end function spinInterfaceRegisterInterfaceEvent(hInterface, hInterfaceEvent) checkerror(ccall((:spinInterfaceRegisterInterfaceEvent, libSpinnaker_C[]), spinError, (spinInterface, spinInterfaceEvent), hInterface, hInterfaceEvent)) end function spinInterfaceUnregisterInterfaceEvent(hInterface, hInterfaceEvent) checkerror(ccall((:spinInterfaceUnregisterInterfaceEvent, libSpinnaker_C[]), spinError, (spinInterface, spinInterfaceEvent), hInterface, hInterfaceEvent)) end function spinInterfaceRelease(hInterface) checkerror(ccall((:spinInterfaceRelease, libSpinnaker_C[]), spinError, (spinInterface,), hInterface)) end function spinInterfaceIsInUse(hInterface, pbIsInUse) checkerror(ccall((:spinInterfaceIsInUse, libSpinnaker_C[]), spinError, (spinInterface, Ptr{bool8_t}), hInterface, pbIsInUse)) end function spinInterfaceSendActionCommand(hInterface, iDeviceKey, iGroupKey, iGroupMask, iActionTime, piResultSize, results) checkerror(ccall((:spinInterfaceSendActionCommand, libSpinnaker_C[]), spinError, (spinInterface, Csize_t, Csize_t, Csize_t, Csize_t, Ptr{Csize_t}, Ptr{actionCommandResult}), hInterface, iDeviceKey, iGroupKey, iGroupMask, iActionTime, piResultSize, results)) end function spinCameraInit(hCamera) checkerror(ccall((:spinCameraInit, libSpinnaker_C[]), spinError, (spinCamera,), hCamera)) end function spinCameraDeInit(hCamera) checkerror(ccall((:spinCameraDeInit, libSpinnaker_C[]), spinError, (spinCamera,), hCamera)) end function spinCameraGetNodeMap(hCamera, phNodeMap) checkerror(ccall((:spinCameraGetNodeMap, libSpinnaker_C[]), spinError, (spinCamera, Ptr{spinNodeMapHandle}), hCamera, phNodeMap)) end function spinCameraGetTLDeviceNodeMap(hCamera, phNodeMap) checkerror(ccall((:spinCameraGetTLDeviceNodeMap, libSpinnaker_C[]), spinError, (spinCamera, Ptr{spinNodeMapHandle}), hCamera, phNodeMap)) end function spinCameraGetTLStreamNodeMap(hCamera, phNodeMap) checkerror(ccall((:spinCameraGetTLStreamNodeMap, libSpinnaker_C[]), spinError, (spinCamera, Ptr{spinNodeMapHandle}), hCamera, phNodeMap)) end function spinCameraGetAccessMode(hCamera, pAccessMode) checkerror(ccall((:spinCameraGetAccessMode, libSpinnaker_C[]), spinError, (spinCamera, Ptr{spinAccessMode}), hCamera, pAccessMode)) end function spinCameraReadPort(hCamera, iAddress, pBuffer, iSize) checkerror(ccall((:spinCameraReadPort, libSpinnaker_C[]), spinError, (spinCamera, UInt64, Ptr{Cvoid}, Csize_t), hCamera, iAddress, pBuffer, iSize)) end function spinCameraWritePort(hCamera, iAddress, pBuffer, iSize) checkerror(ccall((:spinCameraWritePort, libSpinnaker_C[]), spinError, (spinCamera, UInt64, Ptr{Cvoid}, Csize_t), hCamera, iAddress, pBuffer, iSize)) end function spinCameraBeginAcquisition(hCamera) checkerror(ccall((:spinCameraBeginAcquisition, libSpinnaker_C[]), spinError, (spinCamera,), hCamera)) end function spinCameraEndAcquisition(hCamera) checkerror(ccall((:spinCameraEndAcquisition, libSpinnaker_C[]), spinError, (spinCamera,), hCamera)) end function spinCameraGetNextImage(hCamera, phImage) checkerror(ccall((:spinCameraGetNextImage, libSpinnaker_C[]), spinError, (spinCamera, Ptr{spinImage}), hCamera, phImage)) end function spinCameraGetNextImageEx(hCamera, grabTimeout, phImage) checkerror(ccall((:spinCameraGetNextImageEx, libSpinnaker_C[]), spinError, (spinCamera, UInt64, Ptr{spinImage}), hCamera, grabTimeout, phImage)) end function spinCameraGetUniqueID(hCamera, pBuf, pBufLen) checkerror(ccall((:spinCameraGetUniqueID, libSpinnaker_C[]), spinError, (spinCamera, Cstring, Ptr{Csize_t}), hCamera, pBuf, pBufLen)) end function spinCameraIsStreaming(hCamera, pbIsStreaming) checkerror(ccall((:spinCameraIsStreaming, libSpinnaker_C[]), spinError, (spinCamera, Ptr{bool8_t}), hCamera, pbIsStreaming)) end function spinCameraGetGuiXml(hCamera, pBuf, pBufLen) checkerror(ccall((:spinCameraGetGuiXml, libSpinnaker_C[]), spinError, (spinCamera, Cstring, Ptr{Csize_t}), hCamera, pBuf, pBufLen)) end function spinCameraRegisterDeviceEvent(hCamera, hDeviceEvent) checkerror(ccall((:spinCameraRegisterDeviceEvent, libSpinnaker_C[]), spinError, (spinCamera, spinDeviceEvent), hCamera, hDeviceEvent)) end function spinCameraRegisterDeviceEventEx(hCamera, hDeviceEvent, pName) checkerror(ccall((:spinCameraRegisterDeviceEventEx, libSpinnaker_C[]), spinError, (spinCamera, spinDeviceEvent, Cstring), hCamera, hDeviceEvent, pName)) end function spinCameraUnregisterDeviceEvent(hCamera, hDeviceEvent) checkerror(ccall((:spinCameraUnregisterDeviceEvent, libSpinnaker_C[]), spinError, (spinCamera, spinDeviceEvent), hCamera, hDeviceEvent)) end function spinCameraRegisterImageEvent(hCamera, hImageEvent) checkerror(ccall((:spinCameraRegisterImageEvent, libSpinnaker_C[]), spinError, (spinCamera, spinImageEvent), hCamera, hImageEvent)) end function spinCameraUnregisterImageEvent(hCamera, hImageEvent) checkerror(ccall((:spinCameraUnregisterImageEvent, libSpinnaker_C[]), spinError, (spinCamera, spinImageEvent), hCamera, hImageEvent)) end function spinCameraRelease(hCamera) checkerror(ccall((:spinCameraRelease, libSpinnaker_C[]), spinError, (spinCamera,), hCamera)) end function spinCameraIsValid(hCamera, pbValid) checkerror(ccall((:spinCameraIsValid, libSpinnaker_C[]), spinError, (spinCamera, Ptr{bool8_t}), hCamera, pbValid)) end function spinCameraIsInitialized(hCamera, pbInit) checkerror(ccall((:spinCameraIsInitialized, libSpinnaker_C[]), spinError, (spinCamera, Ptr{bool8_t}), hCamera, pbInit)) end function spinCameraDiscoverMaxPacketSize(hCamera, pMaxPacketSize) checkerror(ccall((:spinCameraDiscoverMaxPacketSize, libSpinnaker_C[]), spinError, (spinCamera, Ptr{UInt32}), hCamera, pMaxPacketSize)) end function spinImageCreateEmpty(phImage) checkerror(ccall((:spinImageCreateEmpty, libSpinnaker_C[]), spinError, (Ptr{spinImage},), phImage)) end function spinImageCreate(hSrcImage, phDestImage) checkerror(ccall((:spinImageCreate, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinImage}), hSrcImage, phDestImage)) end function spinImageCreateEx(phImage, width, height, offsetX, offsetY, pixelFormat, pData) checkerror(ccall((:spinImageCreateEx, libSpinnaker_C[]), spinError, (Ptr{spinImage}, Csize_t, Csize_t, Csize_t, Csize_t, spinPixelFormatEnums, Ptr{Cvoid}), phImage, width, height, offsetX, offsetY, pixelFormat, pData)) end function spinImageDestroy(hImage) checkerror(ccall((:spinImageDestroy, libSpinnaker_C[]), spinError, (spinImage,), hImage)) end function spinImageSetDefaultColorProcessing(algorithm) checkerror(ccall((:spinImageSetDefaultColorProcessing, libSpinnaker_C[]), spinError, (spinColorProcessingAlgorithm,), algorithm)) end function spinImageGetDefaultColorProcessing(pAlgorithm) checkerror(ccall((:spinImageGetDefaultColorProcessing, libSpinnaker_C[]), spinError, (Ptr{spinColorProcessingAlgorithm},), pAlgorithm)) end function spinImageGetColorProcessing(hImage, pAlgorithm) checkerror(ccall((:spinImageGetColorProcessing, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinColorProcessingAlgorithm}), hImage, pAlgorithm)) end function spinImageConvert(hSrcImage, pixelFormat, hDestImage) checkerror(ccall((:spinImageConvert, libSpinnaker_C[]), spinError, (spinImage, spinPixelFormatEnums, spinImage), hSrcImage, pixelFormat, hDestImage)) end function spinImageConvertEx(hSrcImage, pixelFormat, algorithm, hDestImage) checkerror(ccall((:spinImageConvertEx, libSpinnaker_C[]), spinError, (spinImage, spinPixelFormatEnums, spinColorProcessingAlgorithm, spinImage), hSrcImage, pixelFormat, algorithm, hDestImage)) end function spinImageReset(hImage, width, height, offsetX, offsetY, pixelFormat) checkerror(ccall((:spinImageReset, libSpinnaker_C[]), spinError, (spinImage, Csize_t, Csize_t, Csize_t, Csize_t, spinPixelFormatEnums), hImage, width, height, offsetX, offsetY, pixelFormat)) end function spinImageResetEx(hImage, width, height, offsetX, offsetY, pixelFormat, pData) checkerror(ccall((:spinImageResetEx, libSpinnaker_C[]), spinError, (spinImage, Csize_t, Csize_t, Csize_t, Csize_t, spinPixelFormatEnums, Ptr{Cvoid}), hImage, width, height, offsetX, offsetY, pixelFormat, pData)) end function spinImageGetID(hImage, pId) checkerror(ccall((:spinImageGetID, libSpinnaker_C[]), spinError, (spinImage, Ptr{UInt64}), hImage, pId)) end function spinImageGetData(hImage, ppData) checkerror(ccall((:spinImageGetData, libSpinnaker_C[]), spinError, (spinImage, Ptr{Ptr{Cvoid}}), hImage, ppData)) end function spinImageGetPrivateData(hImage, ppData) checkerror(ccall((:spinImageGetPrivateData, libSpinnaker_C[]), spinError, (spinImage, Ptr{Ptr{Cvoid}}), hImage, ppData)) end function spinImageGetBufferSize(hImage, pSize) checkerror(ccall((:spinImageGetBufferSize, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pSize)) end function spinImageDeepCopy(hSrcImage, hDestImage) checkerror(ccall((:spinImageDeepCopy, libSpinnaker_C[]), spinError, (spinImage, spinImage), hSrcImage, hDestImage)) end function spinImageGetWidth(hImage, pWidth) checkerror(ccall((:spinImageGetWidth, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pWidth)) end function spinImageGetHeight(hImage, pHeight) checkerror(ccall((:spinImageGetHeight, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pHeight)) end function spinImageGetOffsetX(hImage, pOffsetX) checkerror(ccall((:spinImageGetOffsetX, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pOffsetX)) end function spinImageGetOffsetY(hImage, pOffsetY) checkerror(ccall((:spinImageGetOffsetY, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pOffsetY)) end function spinImageGetPaddingX(hImage, pPaddingX) checkerror(ccall((:spinImageGetPaddingX, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pPaddingX)) end function spinImageGetPaddingY(hImage, pPaddingY) checkerror(ccall((:spinImageGetPaddingY, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pPaddingY)) end function spinImageGetFrameID(hImage, pFrameID) checkerror(ccall((:spinImageGetFrameID, libSpinnaker_C[]), spinError, (spinImage, Ptr{UInt64}), hImage, pFrameID)) end function spinImageGetTimeStamp(hImage, pTimeStamp) checkerror(ccall((:spinImageGetTimeStamp, libSpinnaker_C[]), spinError, (spinImage, Ptr{UInt64}), hImage, pTimeStamp)) end function spinImageGetPayloadType(hImage, pPayloadType) checkerror(ccall((:spinImageGetPayloadType, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pPayloadType)) end function spinImageGetTLPayloadType(hImage, pPayloadType) checkerror(ccall((:spinImageGetTLPayloadType, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinPayloadTypeInfoIDs}), hImage, pPayloadType)) end function spinImageGetPixelFormat(hImage, pPixelFormat) checkerror(ccall((:spinImageGetPixelFormat, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinPixelFormatEnums}), hImage, pPixelFormat)) end function spinImageGetTLPixelFormat(hImage, pPixelFormat) checkerror(ccall((:spinImageGetTLPixelFormat, libSpinnaker_C[]), spinError, (spinImage, Ptr{UInt64}), hImage, pPixelFormat)) end function spinImageGetTLPixelFormatNamespace(hImage, pPixelFormatNamespace) checkerror(ccall((:spinImageGetTLPixelFormatNamespace, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinPixelFormatNamespaceID}), hImage, pPixelFormatNamespace)) end function spinImageGetPixelFormatName(hImage, pBuf, pBufLen) checkerror(ccall((:spinImageGetPixelFormatName, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{Csize_t}), hImage, pBuf, pBufLen)) end function spinImageIsIncomplete(hImage, pbIsIncomplete) checkerror(ccall((:spinImageIsIncomplete, libSpinnaker_C[]), spinError, (spinImage, Ptr{bool8_t}), hImage, pbIsIncomplete)) end function spinImageGetValidPayloadSize(hImage, pSize) checkerror(ccall((:spinImageGetValidPayloadSize, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pSize)) end function spinImageSave(hImage, pFilename, format) checkerror(ccall((:spinImageSave, libSpinnaker_C[]), spinError, (spinImage, Cstring, spinImageFileFormat), hImage, pFilename, format)) end function spinImageSaveFromExt(hImage, pFilename) checkerror(ccall((:spinImageSaveFromExt, libSpinnaker_C[]), spinError, (spinImage, Cstring), hImage, pFilename)) end function spinImageSavePng(hImage, pFilename, pOption) checkerror(ccall((:spinImageSavePng, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinPNGOption}), hImage, pFilename, pOption)) end function spinImageSavePpm(hImage, pFilename, pOption) checkerror(ccall((:spinImageSavePpm, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinPPMOption}), hImage, pFilename, pOption)) end function spinImageSavePgm(hImage, pFilename, pOption) checkerror(ccall((:spinImageSavePgm, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinPGMOption}), hImage, pFilename, pOption)) end function spinImageSaveTiff(hImage, pFilename, pOption) checkerror(ccall((:spinImageSaveTiff, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinTIFFOption}), hImage, pFilename, pOption)) end function spinImageSaveJpeg(hImage, pFilename, pOption) checkerror(ccall((:spinImageSaveJpeg, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinJPEGOption}), hImage, pFilename, pOption)) end function spinImageSaveJpg2(hImage, pFilename, pOption) checkerror(ccall((:spinImageSaveJpg2, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinJPG2Option}), hImage, pFilename, pOption)) end function spinImageSaveBmp(hImage, pFilename, pOption) checkerror(ccall((:spinImageSaveBmp, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{spinBMPOption}), hImage, pFilename, pOption)) end function spinImageGetChunkLayoutID(hImage, pId) checkerror(ccall((:spinImageGetChunkLayoutID, libSpinnaker_C[]), spinError, (spinImage, Ptr{UInt64}), hImage, pId)) end function spinImageCalculateStatistics(hImage, hStatistics) checkerror(ccall((:spinImageCalculateStatistics, libSpinnaker_C[]), spinError, (spinImage, spinImageStatistics), hImage, hStatistics)) end function spinImageGetStatus(hImage, pStatus) checkerror(ccall((:spinImageGetStatus, libSpinnaker_C[]), spinError, (spinImage, Ptr{spinImageStatus}), hImage, pStatus)) end function spinImageGetStatusDescription(status, pBuf, pBufLen) checkerror(ccall((:spinImageGetStatusDescription, libSpinnaker_C[]), spinError, (spinImageStatus, Cstring, Ptr{Csize_t}), status, pBuf, pBufLen)) end function spinImageRelease(hImage) checkerror(ccall((:spinImageRelease, libSpinnaker_C[]), spinError, (spinImage,), hImage)) end function spinImageHasCRC(hImage, pbHasCRC) checkerror(ccall((:spinImageHasCRC, libSpinnaker_C[]), spinError, (spinImage, Ptr{bool8_t}), hImage, pbHasCRC)) end function spinImageCheckCRC(hImage, pbCheckCRC) checkerror(ccall((:spinImageCheckCRC, libSpinnaker_C[]), spinError, (spinImage, Ptr{bool8_t}), hImage, pbCheckCRC)) end function spinImageGetBitsPerPixel(hImage, pBitsPerPixel) checkerror(ccall((:spinImageGetBitsPerPixel, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pBitsPerPixel)) end function spinImageGetSize(hImage, pImageSize) checkerror(ccall((:spinImageGetSize, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pImageSize)) end function spinImageGetStride(hImage, pStride) checkerror(ccall((:spinImageGetStride, libSpinnaker_C[]), spinError, (spinImage, Ptr{Csize_t}), hImage, pStride)) end function spinDeviceEventCreate(phDeviceEvent, pFunction, pUserData) checkerror(ccall((:spinDeviceEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinDeviceEvent}, spinDeviceEventFunction, Ptr{Cvoid}), phDeviceEvent, pFunction, pUserData)) end function spinDeviceEventDestroy(hDeviceEvent) checkerror(ccall((:spinDeviceEventDestroy, libSpinnaker_C[]), spinError, (spinDeviceEvent,), hDeviceEvent)) end function spinImageEventCreate(phImageEvent, pFunction, pUserData) checkerror(ccall((:spinImageEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinImageEvent}, spinImageEventFunction, Ptr{Cvoid}), phImageEvent, pFunction, pUserData)) end function spinImageEventDestroy(hImageEvent) checkerror(ccall((:spinImageEventDestroy, libSpinnaker_C[]), spinError, (spinImageEvent,), hImageEvent)) end function spinArrivalEventCreate(phArrivalEvent, pFunction, pUserData) checkerror(ccall((:spinArrivalEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinArrivalEvent}, spinArrivalEventFunction, Ptr{Cvoid}), phArrivalEvent, pFunction, pUserData)) end function spinArrivalEventDestroy(hArrivalEvent) checkerror(ccall((:spinArrivalEventDestroy, libSpinnaker_C[]), spinError, (spinArrivalEvent,), hArrivalEvent)) end function spinRemovalEventCreate(phRemovalEvent, pFunction, pUserData) checkerror(ccall((:spinRemovalEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinRemovalEvent}, spinRemovalEventFunction, Ptr{Cvoid}), phRemovalEvent, pFunction, pUserData)) end function spinRemovalEventDestroy(hRemovalEvent) checkerror(ccall((:spinRemovalEventDestroy, libSpinnaker_C[]), spinError, (spinRemovalEvent,), hRemovalEvent)) end function spinInterfaceEventCreate(phInterfaceEvent, pArrivalFunction, pRemovalFunction, pUserData) checkerror(ccall((:spinInterfaceEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinInterfaceEvent}, spinArrivalEventFunction, spinRemovalEventFunction, Ptr{Cvoid}), phInterfaceEvent, pArrivalFunction, pRemovalFunction, pUserData)) end function spinInterfaceEventDestroy(hInterfaceEvent) checkerror(ccall((:spinInterfaceEventDestroy, libSpinnaker_C[]), spinError, (spinInterfaceEvent,), hInterfaceEvent)) end function spinLogEventCreate(phLogEvent, pFunction, pUserData) checkerror(ccall((:spinLogEventCreate, libSpinnaker_C[]), spinError, (Ptr{spinLogEvent}, spinLogEventFunction, Ptr{Cvoid}), phLogEvent, pFunction, pUserData)) end function spinLogEventDestroy(hLogEvent) checkerror(ccall((:spinLogEventDestroy, libSpinnaker_C[]), spinError, (spinLogEvent,), hLogEvent)) end function spinImageStatisticsCreate(phStatistics) checkerror(ccall((:spinImageStatisticsCreate, libSpinnaker_C[]), spinError, (Ptr{spinImageStatistics},), phStatistics)) end function spinImageStatisticsDestroy(hStatistics) checkerror(ccall((:spinImageStatisticsDestroy, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsEnableAll(hStatistics) checkerror(ccall((:spinImageStatisticsEnableAll, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsDisableAll(hStatistics) checkerror(ccall((:spinImageStatisticsDisableAll, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsEnableGreyOnly(hStatistics) checkerror(ccall((:spinImageStatisticsEnableGreyOnly, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsEnableRgbOnly(hStatistics) checkerror(ccall((:spinImageStatisticsEnableRgbOnly, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsEnableHslOnly(hStatistics) checkerror(ccall((:spinImageStatisticsEnableHslOnly, libSpinnaker_C[]), spinError, (spinImageStatistics,), hStatistics)) end function spinImageStatisticsGetChannelStatus(hStatistics, channel, pbEnabled) checkerror(ccall((:spinImageStatisticsGetChannelStatus, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{bool8_t}), hStatistics, channel, pbEnabled)) end function spinImageStatisticsSetChannelStatus(hStatistics, channel, bEnable) checkerror(ccall((:spinImageStatisticsSetChannelStatus, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, bool8_t), hStatistics, channel, bEnable)) end function spinImageStatisticsGetRange(hStatistics, channel, pMin, pMax) checkerror(ccall((:spinImageStatisticsGetRange, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{UInt32}, Ptr{UInt32}), hStatistics, channel, pMin, pMax)) end function spinImageStatisticsGetPixelValueRange(hStatistics, channel, pMin, pMax) checkerror(ccall((:spinImageStatisticsGetPixelValueRange, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{UInt32}, Ptr{UInt32}), hStatistics, channel, pMin, pMax)) end function spinImageStatisticsGetNumPixelValues(hStatistics, channel, pNumValues) checkerror(ccall((:spinImageStatisticsGetNumPixelValues, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{UInt32}), hStatistics, channel, pNumValues)) end function spinImageStatisticsGetMean(hStatistics, channel, pMean) checkerror(ccall((:spinImageStatisticsGetMean, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{Cfloat}), hStatistics, channel, pMean)) end function spinImageStatisticsGetHistogram(hStatistics, channel, ppHistogram) checkerror(ccall((:spinImageStatisticsGetHistogram, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{Ptr{Cint}}), hStatistics, channel, ppHistogram)) end function spinImageStatisticsGetAll(hStatistics, channel, pRangeMin, pRangeMax, pPixelValueMin, pPixelValueMax, pNumPixelValues, pPixelValueMean, ppHistogram) checkerror(ccall((:spinImageStatisticsGetAll, libSpinnaker_C[]), spinError, (spinImageStatistics, spinStatisticsChannel, Ptr{UInt32}, Ptr{UInt32}, Ptr{UInt32}, Ptr{UInt32}, Ptr{UInt32}, Ptr{Cfloat}, Ptr{Ptr{Cint}}), hStatistics, channel, pRangeMin, pRangeMax, pPixelValueMin, pPixelValueMax, pNumPixelValues, pPixelValueMean, ppHistogram)) end function spinLogDataGetCategoryName(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetCategoryName, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinLogDataGetPriority(hLogEventData, pValue) checkerror(ccall((:spinLogDataGetPriority, libSpinnaker_C[]), spinError, (spinLogEventData, Ptr{Int64}), hLogEventData, pValue)) end function spinLogDataGetPriorityName(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetPriorityName, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinLogDataGetTimestamp(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetTimestamp, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinLogDataGetNDC(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetNDC, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinLogDataGetThreadName(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetThreadName, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinLogDataGetLogMessage(hLogEventData, pBuf, pBufLen) checkerror(ccall((:spinLogDataGetLogMessage, libSpinnaker_C[]), spinError, (spinLogEventData, Cstring, Ptr{Csize_t}), hLogEventData, pBuf, pBufLen)) end function spinDeviceEventGetId(hDeviceEventData, pEventId) checkerror(ccall((:spinDeviceEventGetId, libSpinnaker_C[]), spinError, (spinDeviceEventData, Ptr{UInt64}), hDeviceEventData, pEventId)) end function spinDeviceEventGetPayloadData(hDeviceEventData, pBuf, pBufSize) checkerror(ccall((:spinDeviceEventGetPayloadData, libSpinnaker_C[]), spinError, (spinDeviceEventData, Ptr{UInt8}, Ptr{Csize_t}), hDeviceEventData, pBuf, pBufSize)) end function spinDeviceEventGetPayloadDataSize(hDeviceEventData, pBufSize) checkerror(ccall((:spinDeviceEventGetPayloadDataSize, libSpinnaker_C[]), spinError, (spinDeviceEventData, Ptr{Csize_t}), hDeviceEventData, pBufSize)) end function spinDeviceEventGetName(hDeviceEventData, pBuf, pBufLen) checkerror(ccall((:spinDeviceEventGetName, libSpinnaker_C[]), spinError, (spinDeviceEventData, Cstring, Ptr{Csize_t}), hDeviceEventData, pBuf, pBufLen)) end function spinAVIRecorderOpenUncompressed(phRecorder, pName, option) checkerror(ccall((:spinAVIRecorderOpenUncompressed, libSpinnaker_C[]), spinError, (Ptr{spinAVIRecorder}, Cstring, spinAVIOption), phRecorder, pName, option)) end function spinAVIRecorderOpenMJPG(phRecorder, pName, option) checkerror(ccall((:spinAVIRecorderOpenMJPG, libSpinnaker_C[]), spinError, (Ptr{spinAVIRecorder}, Cstring, spinMJPGOption), phRecorder, pName, option)) end function spinAVIRecorderOpenH264(phRecorder, pName, option) checkerror(ccall((:spinAVIRecorderOpenH264, libSpinnaker_C[]), spinError, (Ptr{spinAVIRecorder}, Cstring, spinH264Option), phRecorder, pName, option)) end function spinAVIRecorderAppend(hRecorder, hImage) checkerror(ccall((:spinAVIRecorderAppend, libSpinnaker_C[]), spinError, (spinAVIRecorder, spinImage), hRecorder, hImage)) end function spinAVISetMaximumSize(hRecorder, size) checkerror(ccall((:spinAVISetMaximumSize, libSpinnaker_C[]), spinError, (spinAVIRecorder, UInt32), hRecorder, size)) end function spinAVIRecorderClose(hRecorder) checkerror(ccall((:spinAVIRecorderClose, libSpinnaker_C[]), spinError, (spinAVIRecorder,), hRecorder)) end function spinImageChunkDataGetIntValue(hImage, pName, pValue) checkerror(ccall((:spinImageChunkDataGetIntValue, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{Int64}), hImage, pName, pValue)) end function spinImageChunkDataGetFloatValue(hImage, pName, pValue) checkerror(ccall((:spinImageChunkDataGetFloatValue, libSpinnaker_C[]), spinError, (spinImage, Cstring, Ptr{Cdouble}), hImage, pName, pValue)) end # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinnakerDefsC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinnakerGenApiC.h # Automatically generated using Clang.jl wrap_c function spinNodeMapGetNode(hNodeMap, pName, phNode) checkerror(ccall((:spinNodeMapGetNode, libSpinnaker_C[]), spinError, (spinNodeMapHandle, Cstring, Ptr{spinNodeHandle}), hNodeMap, pName, phNode)) end function spinNodeMapGetNumNodes(hNodeMap, pValue) checkerror(ccall((:spinNodeMapGetNumNodes, libSpinnaker_C[]), spinError, (spinNodeMapHandle, Ptr{Csize_t}), hNodeMap, pValue)) end function spinNodeMapGetNodeByIndex(hNodeMap, index, phNode) checkerror(ccall((:spinNodeMapGetNodeByIndex, libSpinnaker_C[]), spinError, (spinNodeMapHandle, Csize_t, Ptr{spinNodeHandle}), hNodeMap, index, phNode)) end function spinNodeMapPoll(hNodeMap, timestamp) checkerror(ccall((:spinNodeMapPoll, libSpinnaker_C[]), spinError, (spinNodeMapHandle, Int64), hNodeMap, timestamp)) end function spinNodeIsImplemented(hNode, pbResult) checkerror(ccall((:spinNodeIsImplemented, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbResult)) end function spinNodeIsReadable(hNode, pbResult) checkerror(ccall((:spinNodeIsReadable, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbResult)) end function spinNodeIsWritable(hNode, pbResult) checkerror(ccall((:spinNodeIsWritable, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbResult)) end function spinNodeIsAvailable(hNode, pbResult) checkerror(ccall((:spinNodeIsAvailable, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbResult)) end function spinNodeIsEqual(hNodeFirst, hNodeSecond, pbResult) checkerror(ccall((:spinNodeIsEqual, libSpinnaker_C[]), spinError, (spinNodeHandle, spinNodeHandle, Ptr{bool8_t}), hNodeFirst, hNodeSecond, pbResult)) end function spinNodeGetAccessMode(hNode, pAccessMode) checkerror(ccall((:spinNodeGetAccessMode, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinAccessMode}), hNode, pAccessMode)) end function spinNodeGetName(hNode, pBuf, pBufLen) checkerror(ccall((:spinNodeGetName, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinNodeGetNameSpace(hNode, pNamespace) checkerror(ccall((:spinNodeGetNameSpace, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinNameSpace}), hNode, pNamespace)) end function spinNodeGetVisibility(hNode, pVisibility) checkerror(ccall((:spinNodeGetVisibility, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinVisibility}), hNode, pVisibility)) end function spinNodeInvalidateNode(hNode) checkerror(ccall((:spinNodeInvalidateNode, libSpinnaker_C[]), spinError, (spinNodeHandle,), hNode)) end function spinNodeGetCachingMode(hNode, pCachingMode) checkerror(ccall((:spinNodeGetCachingMode, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinCachingMode}), hNode, pCachingMode)) end function spinNodeGetToolTip(hNode, pBuf, pBufLen) checkerror(ccall((:spinNodeGetToolTip, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinNodeGetDescription(hNode, pBuf, pBufLen) checkerror(ccall((:spinNodeGetDescription, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinNodeGetDisplayName(hNode, pBuf, pBufLen) checkerror(ccall((:spinNodeGetDisplayName, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinNodeGetType(hNode, pType) checkerror(ccall((:spinNodeGetType, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinNodeType}), hNode, pType)) end function spinNodeGetPollingTime(hNode, pPollingTime) checkerror(ccall((:spinNodeGetPollingTime, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pPollingTime)) end function spinNodeRegisterCallback(hNode, pCbFunction, phCb) checkerror(ccall((:spinNodeRegisterCallback, libSpinnaker_C[]), spinError, (spinNodeHandle, spinNodeCallbackFunction, Ptr{spinNodeCallbackHandle}), hNode, pCbFunction, phCb)) end function spinNodeDeregisterCallback(hNode, hCb) checkerror(ccall((:spinNodeDeregisterCallback, libSpinnaker_C[]), spinError, (spinNodeHandle, spinNodeCallbackHandle), hNode, hCb)) end function spinNodeGetImposedAccessMode(hNode, imposedAccessMode) checkerror(ccall((:spinNodeGetImposedAccessMode, libSpinnaker_C[]), spinError, (spinNodeHandle, spinAccessMode), hNode, imposedAccessMode)) end function spinNodeGetImposedVisibility(hNode, imposedVisibility) checkerror(ccall((:spinNodeGetImposedVisibility, libSpinnaker_C[]), spinError, (spinNodeHandle, spinVisibility), hNode, imposedVisibility)) end function spinNodeToString(hNode, pBuf, pBufLen) checkerror(ccall((:spinNodeToString, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinNodeToStringEx(hNode, bVerify, pBuf, pBufLen) checkerror(ccall((:spinNodeToStringEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Cstring, Ptr{Csize_t}), hNode, bVerify, pBuf, pBufLen)) end function spinNodeFromString(hNode, pBuf) checkerror(ccall((:spinNodeFromString, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring), hNode, pBuf)) end function spinNodeFromStringEx(hNode, bVerify, pBuf) checkerror(ccall((:spinNodeFromStringEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Cstring), hNode, bVerify, pBuf)) end function spinStringSetValue(hNode, pBuf) checkerror(ccall((:spinStringSetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring), hNode, pBuf)) end function spinStringSetValueEx(hNode, bVerify, pBuf) checkerror(ccall((:spinStringSetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Cstring), hNode, bVerify, pBuf)) end function spinStringGetValue(hNode, pBuf, pBufLen) checkerror(ccall((:spinStringGetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{UInt8}, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinStringGetValueEx(hNode, bVerify, pBuf, pBufLen) checkerror(ccall((:spinStringGetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Cstring, Ptr{Csize_t}), hNode, bVerify, pBuf, pBufLen)) end function spinStringGetMaxLength(hNode, pValue) checkerror(ccall((:spinStringGetMaxLength, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinIntegerSetValue(hNode, value) checkerror(ccall((:spinIntegerSetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Int64), hNode, value)) end function spinIntegerSetValueEx(hNode, bVerify, value) checkerror(ccall((:spinIntegerSetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Int64), hNode, bVerify, value)) end function spinIntegerGetValue(hNode, pValue) checkerror(ccall((:spinIntegerGetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinIntegerGetValueEx(hNode, bVerify, pValue) checkerror(ccall((:spinIntegerGetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Ptr{Int64}), hNode, bVerify, pValue)) end function spinIntegerGetMin(hNode, pValue) checkerror(ccall((:spinIntegerGetMin, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinIntegerGetMax(hNode, pValue) checkerror(ccall((:spinIntegerGetMax, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinIntegerGetInc(hNode, pValue) checkerror(ccall((:spinIntegerGetInc, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinIntegerGetRepresentation(hNode, pValue) checkerror(ccall((:spinIntegerGetRepresentation, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinRepresentation}), hNode, pValue)) end function spinFloatSetValue(hNode, value) checkerror(ccall((:spinFloatSetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Cdouble), hNode, value)) end function spinFloatSetValueEx(hNode, bVerify, value) checkerror(ccall((:spinFloatSetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Cdouble), hNode, bVerify, value)) end function spinFloatGetValue(hNode, pValue) checkerror(ccall((:spinFloatGetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Cdouble}), hNode, pValue)) end function spinFloatGetValueEx(hNode, bVerify, pValue) checkerror(ccall((:spinFloatGetValueEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Ptr{Cdouble}), hNode, bVerify, pValue)) end function spinFloatGetMin(hNode, pValue) checkerror(ccall((:spinFloatGetMin, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Cdouble}), hNode, pValue)) end function spinFloatGetMax(hNode, pValue) checkerror(ccall((:spinFloatGetMax, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Cdouble}), hNode, pValue)) end function spinFloatGetRepresentation(hNode, pValue) checkerror(ccall((:spinFloatGetRepresentation, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinRepresentation}), hNode, pValue)) end function spinFloatGetUnit(hNode, pBuf, pBufLen) checkerror(ccall((:spinFloatGetUnit, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinEnumerationGetNumEntries(hNode, pValue) checkerror(ccall((:spinEnumerationGetNumEntries, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Csize_t}), hNode, pValue)) end function spinEnumerationGetEntryByIndex(hNode, index, phEntry) checkerror(ccall((:spinEnumerationGetEntryByIndex, libSpinnaker_C[]), spinError, (spinNodeHandle, Csize_t, Ptr{spinNodeHandle}), hNode, index, phEntry)) end function spinEnumerationGetEntryByName(hNode, pName, phEntry) checkerror(ccall((:spinEnumerationGetEntryByName, libSpinnaker_C[]), spinError, (spinNodeHandle, Cstring, Ptr{spinNodeHandle}), hNode, pName, phEntry)) end function spinEnumerationGetCurrentEntry(hNode, phEntry) checkerror(ccall((:spinEnumerationGetCurrentEntry, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{spinNodeHandle}), hNode, phEntry)) end function spinEnumerationSetIntValue(hNode, value) checkerror(ccall((:spinEnumerationSetIntValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Int64), hNode, value)) end function spinEnumerationSetEnumValue(hNode, value) checkerror(ccall((:spinEnumerationSetEnumValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Csize_t), hNode, value)) end function spinEnumerationEntryGetIntValue(hNode, pValue) checkerror(ccall((:spinEnumerationEntryGetIntValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pValue)) end function spinEnumerationEntryGetEnumValue(hNode, pValue) checkerror(ccall((:spinEnumerationEntryGetEnumValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Csize_t}), hNode, pValue)) end function spinEnumerationEntryGetSymbolic(hNode, pBuf, pBufLen) checkerror(ccall((:spinEnumerationEntryGetSymbolic, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{UInt8}, Ptr{Csize_t}), hNode, pBuf, pBufLen)) end function spinBooleanSetValue(hNode, value) checkerror(ccall((:spinBooleanSetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t), hNode, value)) end function spinBooleanGetValue(hNode, pbValue) checkerror(ccall((:spinBooleanGetValue, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbValue)) end function spinCommandExecute(hNode) checkerror(ccall((:spinCommandExecute, libSpinnaker_C[]), spinError, (spinNodeHandle,), hNode)) end function spinCommandIsDone(hNode, pbValue) checkerror(ccall((:spinCommandIsDone, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{bool8_t}), hNode, pbValue)) end function spinCategoryGetNumFeatures(hNode, pValue) checkerror(ccall((:spinCategoryGetNumFeatures, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Csize_t}), hNode, pValue)) end function spinCategoryGetFeatureByIndex(hNode, index, phFeature) checkerror(ccall((:spinCategoryGetFeatureByIndex, libSpinnaker_C[]), spinError, (spinNodeHandle, Csize_t, Ptr{spinNodeHandle}), hNode, index, phFeature)) end function spinRegisterGet(hNode, pBuf, length) checkerror(ccall((:spinRegisterGet, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{UInt8}, Int64), hNode, pBuf, length)) end function spinRegisterGetEx(hNode, bVerify, bIgnoreCache, pBuf, length) checkerror(ccall((:spinRegisterGetEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, bool8_t, Ptr{UInt8}, Int64), hNode, bVerify, bIgnoreCache, pBuf, length)) end function spinRegisterGetAddress(hNode, pAddress) checkerror(ccall((:spinRegisterGetAddress, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pAddress)) end function spinRegisterGetLength(hNode, pLength) checkerror(ccall((:spinRegisterGetLength, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{Int64}), hNode, pLength)) end function spinRegisterSet(hNode, pBuf, length) checkerror(ccall((:spinRegisterSet, libSpinnaker_C[]), spinError, (spinNodeHandle, Ptr{UInt8}, Int64), hNode, pBuf, length)) end function spinRegisterSetEx(hNode, bVerify, pBuf, length) checkerror(ccall((:spinRegisterSetEx, libSpinnaker_C[]), spinError, (spinNodeHandle, bool8_t, Ptr{UInt8}, Int64), hNode, bVerify, pBuf, length)) end function spinRegisterSetReference(hNode, hRef) checkerror(ccall((:spinRegisterSetReference, libSpinnaker_C[]), spinError, (spinNodeHandle, spinNodeHandle), hNode, hRef)) end # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinnakerGenApiDefsC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/SpinnakerPlatformC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/TransportLayerDefsC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/TransportLayerDeviceC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/TransportLayerInterfaceC.h # Automatically generated using Clang.jl wrap_c # Julia wrapper for header: /usr/include/spinnaker/spinc/TransportLayerStreamC.h # Automatically generated using Clang.jl wrap_c
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
137595
# Automatically generated using Clang.jl wrap_c @cenum(_spinLUTSelectorEnums, LUTSelector_LUT1 = 0, NUM_LUTSELECTOR = 1, ) const spinLUTSelectorEnums = _spinLUTSelectorEnums @cenum(_spinExposureModeEnums, ExposureMode_Timed = 0, ExposureMode_TriggerWidth = 1, NUM_EXPOSUREMODE = 2, ) const spinExposureModeEnums = _spinExposureModeEnums @cenum(_spinAcquisitionModeEnums, AcquisitionMode_Continuous = 0, AcquisitionMode_SingleFrame = 1, AcquisitionMode_MultiFrame = 2, NUM_ACQUISITIONMODE = 3, ) const spinAcquisitionModeEnums = _spinAcquisitionModeEnums @cenum(_spinTriggerSourceEnums, TriggerSource_Software = 0, TriggerSource_Line0 = 1, TriggerSource_Line1 = 2, TriggerSource_Line2 = 3, TriggerSource_Line3 = 4, TriggerSource_UserOutput0 = 5, TriggerSource_UserOutput1 = 6, TriggerSource_UserOutput2 = 7, TriggerSource_UserOutput3 = 8, TriggerSource_Counter0Start = 9, TriggerSource_Counter1Start = 10, TriggerSource_Counter0End = 11, TriggerSource_Counter1End = 12, TriggerSource_LogicBlock0 = 13, TriggerSource_LogicBlock1 = 14, TriggerSource_Action0 = 15, NUM_TRIGGERSOURCE = 16, ) const spinTriggerSourceEnums = _spinTriggerSourceEnums @cenum(_spinTriggerActivationEnums, TriggerActivation_LevelLow = 0, TriggerActivation_LevelHigh = 1, TriggerActivation_FallingEdge = 2, TriggerActivation_RisingEdge = 3, TriggerActivation_AnyEdge = 4, NUM_TRIGGERACTIVATION = 5, ) const spinTriggerActivationEnums = _spinTriggerActivationEnums @cenum(_spinSensorShutterModeEnums, SensorShutterMode_Global = 0, SensorShutterMode_Rolling = 1, SensorShutterMode_GlobalReset = 2, NUM_SENSORSHUTTERMODE = 3, ) const spinSensorShutterModeEnums = _spinSensorShutterModeEnums @cenum(_spinTriggerModeEnums, TriggerMode_Off = 0, TriggerMode_On = 1, NUM_TRIGGERMODE = 2, ) const spinTriggerModeEnums = _spinTriggerModeEnums @cenum(_spinTriggerOverlapEnums, TriggerOverlap_Off = 0, TriggerOverlap_ReadOut = 1, TriggerOverlap_PreviousFrame = 2, NUM_TRIGGEROVERLAP = 3, ) const spinTriggerOverlapEnums = _spinTriggerOverlapEnums @cenum(_spinTriggerSelectorEnums, TriggerSelector_AcquisitionStart = 0, TriggerSelector_FrameStart = 1, TriggerSelector_FrameBurstStart = 2, NUM_TRIGGERSELECTOR = 3, ) const spinTriggerSelectorEnums = _spinTriggerSelectorEnums @cenum(_spinExposureAutoEnums, ExposureAuto_Off = 0, ExposureAuto_Once = 1, ExposureAuto_Continuous = 2, NUM_EXPOSUREAUTO = 3, ) const spinExposureAutoEnums = _spinExposureAutoEnums @cenum(_spinEventSelectorEnums, EventSelector_Error = 0, EventSelector_ExposureEnd = 1, EventSelector_SerialPortReceive = 2, NUM_EVENTSELECTOR = 3, ) const spinEventSelectorEnums = _spinEventSelectorEnums @cenum(_spinEventNotificationEnums, EventNotification_On = 0, EventNotification_Off = 1, NUM_EVENTNOTIFICATION = 2, ) const spinEventNotificationEnums = _spinEventNotificationEnums @cenum(_spinLogicBlockSelectorEnums, LogicBlockSelector_LogicBlock0 = 0, LogicBlockSelector_LogicBlock1 = 1, NUM_LOGICBLOCKSELECTOR = 2, ) const spinLogicBlockSelectorEnums = _spinLogicBlockSelectorEnums @cenum(_spinLogicBlockLUTInputActivationEnums, LogicBlockLUTInputActivation_LevelLow = 0, LogicBlockLUTInputActivation_LevelHigh = 1, LogicBlockLUTInputActivation_FallingEdge = 2, LogicBlockLUTInputActivation_RisingEdge = 3, LogicBlockLUTInputActivation_AnyEdge = 4, NUM_LOGICBLOCKLUTINPUTACTIVATION = 5, ) const spinLogicBlockLUTInputActivationEnums = _spinLogicBlockLUTInputActivationEnums @cenum(_spinLogicBlockLUTInputSelectorEnums, LogicBlockLUTInputSelector_Input0 = 0, LogicBlockLUTInputSelector_Input1 = 1, LogicBlockLUTInputSelector_Input2 = 2, LogicBlockLUTInputSelector_Input3 = 3, NUM_LOGICBLOCKLUTINPUTSELECTOR = 4, ) const spinLogicBlockLUTInputSelectorEnums = _spinLogicBlockLUTInputSelectorEnums @cenum(_spinLogicBlockLUTInputSourceEnums, LogicBlockLUTInputSource_Zero = 0, LogicBlockLUTInputSource_Line0 = 1, LogicBlockLUTInputSource_Line1 = 2, LogicBlockLUTInputSource_Line2 = 3, LogicBlockLUTInputSource_Line3 = 4, LogicBlockLUTInputSource_UserOutput0 = 5, LogicBlockLUTInputSource_UserOutput1 = 6, LogicBlockLUTInputSource_UserOutput2 = 7, LogicBlockLUTInputSource_UserOutput3 = 8, LogicBlockLUTInputSource_Counter0Start = 9, LogicBlockLUTInputSource_Counter1Start = 10, LogicBlockLUTInputSource_Counter0End = 11, LogicBlockLUTInputSource_Counter1End = 12, LogicBlockLUTInputSource_LogicBlock0 = 13, LogicBlockLUTInputSource_LogicBlock1 = 14, LogicBlockLUTInputSource_ExposureStart = 15, LogicBlockLUTInputSource_ExposureEnd = 16, LogicBlockLUTInputSource_FrameTriggerWait = 17, LogicBlockLUTInputSource_AcquisitionActive = 18, NUM_LOGICBLOCKLUTINPUTSOURCE = 19, ) const spinLogicBlockLUTInputSourceEnums = _spinLogicBlockLUTInputSourceEnums @cenum(_spinLogicBlockLUTSelectorEnums, LogicBlockLUTSelector_Value = 0, LogicBlockLUTSelector_Enable = 1, NUM_LOGICBLOCKLUTSELECTOR = 2, ) const spinLogicBlockLUTSelectorEnums = _spinLogicBlockLUTSelectorEnums @cenum(_spinColorTransformationSelectorEnums, ColorTransformationSelector_RGBtoRGB = 0, ColorTransformationSelector_RGBtoYUV = 1, NUM_COLORTRANSFORMATIONSELECTOR = 2, ) const spinColorTransformationSelectorEnums = _spinColorTransformationSelectorEnums @cenum(_spinRgbTransformLightSourceEnums, RgbTransformLightSource_General = 0, RgbTransformLightSource_Tungsten2800K = 1, RgbTransformLightSource_WarmFluorescent3000K = 2, RgbTransformLightSource_CoolFluorescent4000K = 3, RgbTransformLightSource_Daylight5000K = 4, RgbTransformLightSource_Cloudy6500K = 5, RgbTransformLightSource_Shade8000K = 6, RgbTransformLightSource_Custom = 7, NUM_RGBTRANSFORMLIGHTSOURCE = 8, ) const spinRgbTransformLightSourceEnums = _spinRgbTransformLightSourceEnums @cenum(_spinColorTransformationValueSelectorEnums, ColorTransformationValueSelector_Gain00 = 0, ColorTransformationValueSelector_Gain01 = 1, ColorTransformationValueSelector_Gain02 = 2, ColorTransformationValueSelector_Gain10 = 3, ColorTransformationValueSelector_Gain11 = 4, ColorTransformationValueSelector_Gain12 = 5, ColorTransformationValueSelector_Gain20 = 6, ColorTransformationValueSelector_Gain21 = 7, ColorTransformationValueSelector_Gain22 = 8, ColorTransformationValueSelector_Offset0 = 9, ColorTransformationValueSelector_Offset1 = 10, ColorTransformationValueSelector_Offset2 = 11, NUM_COLORTRANSFORMATIONVALUESELECTOR = 12, ) const spinColorTransformationValueSelectorEnums = _spinColorTransformationValueSelectorEnums @cenum(_spinDeviceRegistersEndiannessEnums, DeviceRegistersEndianness_Little = 0, DeviceRegistersEndianness_Big = 1, NUM_DEVICEREGISTERSENDIANNESS = 2, ) const spinDeviceRegistersEndiannessEnums = _spinDeviceRegistersEndiannessEnums @cenum(_spinDeviceScanTypeEnums, DeviceScanType_Areascan = 0, NUM_DEVICESCANTYPE = 1, ) const spinDeviceScanTypeEnums = _spinDeviceScanTypeEnums @cenum(_spinDeviceCharacterSetEnums, DeviceCharacterSet_UTF8 = 0, DeviceCharacterSet_ASCII = 1, NUM_DEVICECHARACTERSET = 2, ) const spinDeviceCharacterSetEnums = _spinDeviceCharacterSetEnums @cenum(_spinDeviceTLTypeEnums, DeviceTLType_GigEVision = 0, DeviceTLType_CameraLink = 1, DeviceTLType_CameraLinkHS = 2, DeviceTLType_CoaXPress = 3, DeviceTLType_USB3Vision = 4, DeviceTLType_Custom = 5, NUM_DEVICETLTYPE = 6, ) const spinDeviceTLTypeEnums = _spinDeviceTLTypeEnums @cenum(_spinDevicePowerSupplySelectorEnums, DevicePowerSupplySelector_External = 0, NUM_DEVICEPOWERSUPPLYSELECTOR = 1, ) const spinDevicePowerSupplySelectorEnums = _spinDevicePowerSupplySelectorEnums @cenum(_spinDeviceTemperatureSelectorEnums, DeviceTemperatureSelector_Sensor = 0, NUM_DEVICETEMPERATURESELECTOR = 1, ) const spinDeviceTemperatureSelectorEnums = _spinDeviceTemperatureSelectorEnums @cenum(_spinDeviceIndicatorModeEnums, DeviceIndicatorMode_Inactive = 0, DeviceIndicatorMode_Active = 1, DeviceIndicatorMode_ErrorStatus = 2, NUM_DEVICEINDICATORMODE = 3, ) const spinDeviceIndicatorModeEnums = _spinDeviceIndicatorModeEnums @cenum(_spinAutoExposureControlPriorityEnums, AutoExposureControlPriority_Gain = 0, AutoExposureControlPriority_ExposureTime = 1, NUM_AUTOEXPOSURECONTROLPRIORITY = 2, ) const spinAutoExposureControlPriorityEnums = _spinAutoExposureControlPriorityEnums @cenum(_spinAutoExposureMeteringModeEnums, AutoExposureMeteringMode_Average = 0, AutoExposureMeteringMode_Spot = 1, AutoExposureMeteringMode_Partial = 2, AutoExposureMeteringMode_CenterWeighted = 3, AutoExposureMeteringMode_HistgramPeak = 4, NUM_AUTOEXPOSUREMETERINGMODE = 5, ) const spinAutoExposureMeteringModeEnums = _spinAutoExposureMeteringModeEnums @cenum(_spinBalanceWhiteAutoProfileEnums, BalanceWhiteAutoProfile_Indoor = 0, BalanceWhiteAutoProfile_Outdoor = 1, NUM_BALANCEWHITEAUTOPROFILE = 2, ) const spinBalanceWhiteAutoProfileEnums = _spinBalanceWhiteAutoProfileEnums @cenum(_spinAutoAlgorithmSelectorEnums, AutoAlgorithmSelector_Awb = 0, AutoAlgorithmSelector_Ae = 1, NUM_AUTOALGORITHMSELECTOR = 2, ) const spinAutoAlgorithmSelectorEnums = _spinAutoAlgorithmSelectorEnums @cenum(_spinAutoExposureTargetGreyValueAutoEnums, AutoExposureTargetGreyValueAuto_Off = 0, AutoExposureTargetGreyValueAuto_Continuous = 1, NUM_AUTOEXPOSURETARGETGREYVALUEAUTO = 2, ) const spinAutoExposureTargetGreyValueAutoEnums = _spinAutoExposureTargetGreyValueAutoEnums @cenum(_spinAutoExposureLightingModeEnums, AutoExposureLightingMode_AutoDetect = 0, AutoExposureLightingMode_Backlight = 1, AutoExposureLightingMode_Frontlight = 2, AutoExposureLightingMode_Normal = 3, NUM_AUTOEXPOSURELIGHTINGMODE = 4, ) const spinAutoExposureLightingModeEnums = _spinAutoExposureLightingModeEnums @cenum(_spinGevIEEE1588StatusEnums, GevIEEE1588Status_Initializing = 0, GevIEEE1588Status_Faulty = 1, GevIEEE1588Status_Disabled = 2, GevIEEE1588Status_Listening = 3, GevIEEE1588Status_PreMaster = 4, GevIEEE1588Status_Master = 5, GevIEEE1588Status_Passive = 6, GevIEEE1588Status_Uncalibrated = 7, GevIEEE1588Status_Slave = 8, NUM_GEVIEEE1588STATUS = 9, ) const spinGevIEEE1588StatusEnums = _spinGevIEEE1588StatusEnums @cenum(_spinGevIEEE1588ModeEnums, GevIEEE1588Mode_Auto = 0, GevIEEE1588Mode_SlaveOnly = 1, NUM_GEVIEEE1588MODE = 2, ) const spinGevIEEE1588ModeEnums = _spinGevIEEE1588ModeEnums @cenum(_spinGevIEEE1588ClockAccuracyEnums, GevIEEE1588ClockAccuracy_Unknown = 0, NUM_GEVIEEE1588CLOCKACCURACY = 1, ) const spinGevIEEE1588ClockAccuracyEnums = _spinGevIEEE1588ClockAccuracyEnums @cenum(_spinGevCCPEnums, GevCCP_OpenAccess = 0, GevCCP_ExclusiveAccess = 1, GevCCP_ControlAccess = 2, NUM_GEVCCP = 3, ) const spinGevCCPEnums = _spinGevCCPEnums @cenum(_spinGevSupportedOptionSelectorEnums, GevSupportedOptionSelector_UserDefinedName = 0, GevSupportedOptionSelector_SerialNumber = 1, GevSupportedOptionSelector_HeartbeatDisable = 2, GevSupportedOptionSelector_LinkSpeed = 3, GevSupportedOptionSelector_CCPApplicationSocket = 4, GevSupportedOptionSelector_ManifestTable = 5, GevSupportedOptionSelector_TestData = 6, GevSupportedOptionSelector_DiscoveryAckDelay = 7, GevSupportedOptionSelector_DiscoveryAckDelayWritable = 8, GevSupportedOptionSelector_ExtendedStatusCodes = 9, GevSupportedOptionSelector_Action = 10, GevSupportedOptionSelector_PendingAck = 11, GevSupportedOptionSelector_EventData = 12, GevSupportedOptionSelector_Event = 13, GevSupportedOptionSelector_PacketResend = 14, GevSupportedOptionSelector_WriteMem = 15, GevSupportedOptionSelector_CommandsConcatenation = 16, GevSupportedOptionSelector_IPConfigurationLLA = 17, GevSupportedOptionSelector_IPConfigurationDHCP = 18, GevSupportedOptionSelector_IPConfigurationPersistentIP = 19, GevSupportedOptionSelector_StreamChannelSourceSocket = 20, GevSupportedOptionSelector_MessageChannelSourceSocket = 21, NUM_GEVSUPPORTEDOPTIONSELECTOR = 22, ) const spinGevSupportedOptionSelectorEnums = _spinGevSupportedOptionSelectorEnums @cenum(_spinBlackLevelSelectorEnums, BlackLevelSelector_All = 0, BlackLevelSelector_Analog = 1, BlackLevelSelector_Digital = 2, NUM_BLACKLEVELSELECTOR = 3, ) const spinBlackLevelSelectorEnums = _spinBlackLevelSelectorEnums @cenum(_spinBalanceWhiteAutoEnums, BalanceWhiteAuto_Off = 0, BalanceWhiteAuto_Once = 1, BalanceWhiteAuto_Continuous = 2, NUM_BALANCEWHITEAUTO = 3, ) const spinBalanceWhiteAutoEnums = _spinBalanceWhiteAutoEnums @cenum(_spinGainAutoEnums, GainAuto_Off = 0, GainAuto_Once = 1, GainAuto_Continuous = 2, NUM_GAINAUTO = 3, ) const spinGainAutoEnums = _spinGainAutoEnums @cenum(_spinBalanceRatioSelectorEnums, BalanceRatioSelector_Red = 0, BalanceRatioSelector_Blue = 1, NUM_BALANCERATIOSELECTOR = 2, ) const spinBalanceRatioSelectorEnums = _spinBalanceRatioSelectorEnums @cenum(_spinGainSelectorEnums, GainSelector_All = 0, NUM_GAINSELECTOR = 1, ) const spinGainSelectorEnums = _spinGainSelectorEnums @cenum(_spinDefectCorrectionModeEnums, DefectCorrectionMode_Average = 0, DefectCorrectionMode_Highlight = 1, DefectCorrectionMode_Zero = 2, NUM_DEFECTCORRECTIONMODE = 3, ) const spinDefectCorrectionModeEnums = _spinDefectCorrectionModeEnums @cenum(_spinUserSetSelectorEnums, UserSetSelector_Default = 0, UserSetSelector_UserSet0 = 1, UserSetSelector_UserSet1 = 2, NUM_USERSETSELECTOR = 3, ) const spinUserSetSelectorEnums = _spinUserSetSelectorEnums @cenum(_spinUserSetDefaultEnums, UserSetDefault_Default = 0, UserSetDefault_UserSet0 = 1, UserSetDefault_UserSet1 = 2, NUM_USERSETDEFAULT = 3, ) const spinUserSetDefaultEnums = _spinUserSetDefaultEnums @cenum(_spinSerialPortBaudRateEnums, SerialPortBaudRate_Baud300 = 0, SerialPortBaudRate_Baud600 = 1, SerialPortBaudRate_Baud1200 = 2, SerialPortBaudRate_Baud2400 = 3, SerialPortBaudRate_Baud4800 = 4, SerialPortBaudRate_Baud9600 = 5, SerialPortBaudRate_Baud14400 = 6, SerialPortBaudRate_Baud19200 = 7, SerialPortBaudRate_Baud38400 = 8, SerialPortBaudRate_Baud57600 = 9, SerialPortBaudRate_Baud115200 = 10, SerialPortBaudRate_Baud230400 = 11, SerialPortBaudRate_Baud460800 = 12, SerialPortBaudRate_Baud921600 = 13, NUM_SERIALPORTBAUDRATE = 14, ) const spinSerialPortBaudRateEnums = _spinSerialPortBaudRateEnums @cenum(_spinSerialPortParityEnums, SerialPortParity_None = 0, SerialPortParity_Odd = 1, SerialPortParity_Even = 2, SerialPortParity_Mark = 3, SerialPortParity_Space = 4, NUM_SERIALPORTPARITY = 5, ) const spinSerialPortParityEnums = _spinSerialPortParityEnums @cenum(_spinSerialPortSelectorEnums, SerialPortSelector_SerialPort0 = 0, NUM_SERIALPORTSELECTOR = 1, ) const spinSerialPortSelectorEnums = _spinSerialPortSelectorEnums @cenum(_spinSerialPortStopBitsEnums, SerialPortStopBits_Bits1 = 0, SerialPortStopBits_Bits1AndAHalf = 1, SerialPortStopBits_Bits2 = 2, NUM_SERIALPORTSTOPBITS = 3, ) const spinSerialPortStopBitsEnums = _spinSerialPortStopBitsEnums @cenum(_spinSerialPortSourceEnums, SerialPortSource_Line0 = 0, SerialPortSource_Line1 = 1, SerialPortSource_Line2 = 2, SerialPortSource_Line3 = 3, SerialPortSource_Off = 4, NUM_SERIALPORTSOURCE = 5, ) const spinSerialPortSourceEnums = _spinSerialPortSourceEnums @cenum(_spinSequencerModeEnums, SequencerMode_Off = 0, SequencerMode_On = 1, NUM_SEQUENCERMODE = 2, ) const spinSequencerModeEnums = _spinSequencerModeEnums @cenum(_spinSequencerConfigurationValidEnums, SequencerConfigurationValid_No = 0, SequencerConfigurationValid_Yes = 1, NUM_SEQUENCERCONFIGURATIONVALID = 2, ) const spinSequencerConfigurationValidEnums = _spinSequencerConfigurationValidEnums @cenum(_spinSequencerSetValidEnums, SequencerSetValid_No = 0, SequencerSetValid_Yes = 1, NUM_SEQUENCERSETVALID = 2, ) const spinSequencerSetValidEnums = _spinSequencerSetValidEnums @cenum(_spinSequencerTriggerActivationEnums, SequencerTriggerActivation_RisingEdge = 0, SequencerTriggerActivation_FallingEdge = 1, SequencerTriggerActivation_AnyEdge = 2, SequencerTriggerActivation_LevelHigh = 3, SequencerTriggerActivation_LevelLow = 4, NUM_SEQUENCERTRIGGERACTIVATION = 5, ) const spinSequencerTriggerActivationEnums = _spinSequencerTriggerActivationEnums @cenum(_spinSequencerConfigurationModeEnums, SequencerConfigurationMode_Off = 0, SequencerConfigurationMode_On = 1, NUM_SEQUENCERCONFIGURATIONMODE = 2, ) const spinSequencerConfigurationModeEnums = _spinSequencerConfigurationModeEnums @cenum(_spinSequencerTriggerSourceEnums, SequencerTriggerSource_Off = 0, SequencerTriggerSource_FrameStart = 1, NUM_SEQUENCERTRIGGERSOURCE = 2, ) const spinSequencerTriggerSourceEnums = _spinSequencerTriggerSourceEnums @cenum(_spinTransferQueueModeEnums, TransferQueueMode_FirstInFirstOut = 0, NUM_TRANSFERQUEUEMODE = 1, ) const spinTransferQueueModeEnums = _spinTransferQueueModeEnums @cenum(_spinTransferOperationModeEnums, TransferOperationMode_Continuous = 0, TransferOperationMode_MultiBlock = 1, NUM_TRANSFEROPERATIONMODE = 2, ) const spinTransferOperationModeEnums = _spinTransferOperationModeEnums @cenum(_spinTransferControlModeEnums, TransferControlMode_Basic = 0, TransferControlMode_Automatic = 1, TransferControlMode_UserControlled = 2, NUM_TRANSFERCONTROLMODE = 3, ) const spinTransferControlModeEnums = _spinTransferControlModeEnums @cenum(_spinChunkGainSelectorEnums, ChunkGainSelector_All = 0, ChunkGainSelector_Red = 1, ChunkGainSelector_Green = 2, ChunkGainSelector_Blue = 3, NUM_CHUNKGAINSELECTOR = 4, ) const spinChunkGainSelectorEnums = _spinChunkGainSelectorEnums @cenum(_spinChunkSelectorEnums, ChunkSelector_Image = 0, ChunkSelector_CRC = 1, ChunkSelector_FrameID = 2, ChunkSelector_OffsetX = 3, ChunkSelector_OffsetY = 4, ChunkSelector_Width = 5, ChunkSelector_Height = 6, ChunkSelector_ExposureTime = 7, ChunkSelector_Gain = 8, ChunkSelector_BlackLevel = 9, ChunkSelector_PixelFormat = 10, ChunkSelector_Timestamp = 11, ChunkSelector_SequencerSetActive = 12, ChunkSelector_SerialData = 13, ChunkSelector_ExposureEndLineStatusAll = 14, NUM_CHUNKSELECTOR = 15, ) const spinChunkSelectorEnums = _spinChunkSelectorEnums @cenum(_spinChunkBlackLevelSelectorEnums, ChunkBlackLevelSelector_All = 0, NUM_CHUNKBLACKLEVELSELECTOR = 1, ) const spinChunkBlackLevelSelectorEnums = _spinChunkBlackLevelSelectorEnums @cenum(_spinChunkPixelFormatEnums, ChunkPixelFormat_Mono8 = 0, ChunkPixelFormat_Mono12Packed = 1, ChunkPixelFormat_Mono16 = 2, ChunkPixelFormat_RGB8Packed = 3, ChunkPixelFormat_YUV422Packed = 4, ChunkPixelFormat_BayerGR8 = 5, ChunkPixelFormat_BayerRG8 = 6, ChunkPixelFormat_BayerGB8 = 7, ChunkPixelFormat_BayerBG8 = 8, ChunkPixelFormat_YCbCr601_422_8_CbYCrY = 9, NUM_CHUNKPIXELFORMAT = 10, ) const spinChunkPixelFormatEnums = _spinChunkPixelFormatEnums @cenum(_spinFileOperationStatusEnums, FileOperationStatus_Success = 0, FileOperationStatus_Failure = 1, FileOperationStatus_Overflow = 2, NUM_FILEOPERATIONSTATUS = 3, ) const spinFileOperationStatusEnums = _spinFileOperationStatusEnums @cenum(_spinFileOpenModeEnums, FileOpenMode_Read = 0, FileOpenMode_Write = 1, FileOpenMode_ReadWrite = 2, NUM_FILEOPENMODE = 3, ) const spinFileOpenModeEnums = _spinFileOpenModeEnums @cenum(_spinFileOperationSelectorEnums, FileOperationSelector_Open = 0, FileOperationSelector_Close = 1, FileOperationSelector_Read = 2, FileOperationSelector_Write = 3, FileOperationSelector_Delete = 4, NUM_FILEOPERATIONSELECTOR = 5, ) const spinFileOperationSelectorEnums = _spinFileOperationSelectorEnums @cenum(_spinFileSelectorEnums, FileSelector_UserSetDefault = 0, FileSelector_UserSet0 = 1, FileSelector_UserSet1 = 2, FileSelector_UserFile1 = 3, FileSelector_SerialPort0 = 4, NUM_FILESELECTOR = 5, ) const spinFileSelectorEnums = _spinFileSelectorEnums @cenum(_spinBinningSelectorEnums, BinningSelector_All = 0, BinningSelector_Sensor = 1, BinningSelector_ISP = 2, NUM_BINNINGSELECTOR = 3, ) const spinBinningSelectorEnums = _spinBinningSelectorEnums @cenum(_spinTestPatternGeneratorSelectorEnums, TestPatternGeneratorSelector_Sensor = 0, TestPatternGeneratorSelector_PipelineStart = 1, NUM_TESTPATTERNGENERATORSELECTOR = 2, ) const spinTestPatternGeneratorSelectorEnums = _spinTestPatternGeneratorSelectorEnums @cenum(_spinTestPatternEnums, TestPattern_Off = 0, TestPattern_Increment = 1, TestPattern_SensorTestPattern = 2, NUM_TESTPATTERN = 3, ) const spinTestPatternEnums = _spinTestPatternEnums @cenum(_spinPixelColorFilterEnums, PixelColorFilter_None = 0, PixelColorFilter_BayerRG = 1, PixelColorFilter_BayerGB = 2, PixelColorFilter_BayerGR = 3, PixelColorFilter_BayerBG = 4, NUM_PIXELCOLORFILTER = 5, ) const spinPixelColorFilterEnums = _spinPixelColorFilterEnums @cenum(_spinAdcBitDepthEnums, AdcBitDepth_Bit8 = 0, AdcBitDepth_Bit10 = 1, AdcBitDepth_Bit12 = 2, AdcBitDepth_Bit14 = 3, NUM_ADCBITDEPTH = 4, ) const spinAdcBitDepthEnums = _spinAdcBitDepthEnums @cenum(_spinDecimationHorizontalModeEnums, DecimationHorizontalMode_Discard = 0, NUM_DECIMATIONHORIZONTALMODE = 1, ) const spinDecimationHorizontalModeEnums = _spinDecimationHorizontalModeEnums @cenum(_spinBinningVerticalModeEnums, BinningVerticalMode_Sum = 0, BinningVerticalMode_Average = 1, NUM_BINNINGVERTICALMODE = 2, ) const spinBinningVerticalModeEnums = _spinBinningVerticalModeEnums @cenum(_spinPixelSizeEnums, PixelSize_Bpp1 = 0, PixelSize_Bpp2 = 1, PixelSize_Bpp4 = 2, PixelSize_Bpp8 = 3, PixelSize_Bpp10 = 4, PixelSize_Bpp12 = 5, PixelSize_Bpp14 = 6, PixelSize_Bpp16 = 7, PixelSize_Bpp20 = 8, PixelSize_Bpp24 = 9, PixelSize_Bpp30 = 10, PixelSize_Bpp32 = 11, PixelSize_Bpp36 = 12, PixelSize_Bpp48 = 13, PixelSize_Bpp64 = 14, PixelSize_Bpp96 = 15, NUM_PIXELSIZE = 16, ) const spinPixelSizeEnums = _spinPixelSizeEnums @cenum(_spinDecimationSelectorEnums, DecimationSelector_All = 0, DecimationSelector_Sensor = 1, NUM_DECIMATIONSELECTOR = 2, ) const spinDecimationSelectorEnums = _spinDecimationSelectorEnums @cenum(_spinImageCompressionModeEnums, ImageCompressionMode_Off = 0, ImageCompressionMode_Lossless = 1, NUM_IMAGECOMPRESSIONMODE = 2, ) const spinImageCompressionModeEnums = _spinImageCompressionModeEnums @cenum(_spinBinningHorizontalModeEnums, BinningHorizontalMode_Sum = 0, BinningHorizontalMode_Average = 1, NUM_BINNINGHORIZONTALMODE = 2, ) const spinBinningHorizontalModeEnums = _spinBinningHorizontalModeEnums @cenum(_spinPixelFormatEnums, PixelFormat_Mono8 = 0, PixelFormat_Mono16 = 1, PixelFormat_RGB8Packed = 2, PixelFormat_BayerGR8 = 3, PixelFormat_BayerRG8 = 4, PixelFormat_BayerGB8 = 5, PixelFormat_BayerBG8 = 6, PixelFormat_BayerGR16 = 7, PixelFormat_BayerRG16 = 8, PixelFormat_BayerGB16 = 9, PixelFormat_BayerBG16 = 10, PixelFormat_Mono12Packed = 11, PixelFormat_BayerGR12Packed = 12, PixelFormat_BayerRG12Packed = 13, PixelFormat_BayerGB12Packed = 14, PixelFormat_BayerBG12Packed = 15, PixelFormat_YUV411Packed = 16, PixelFormat_YUV422Packed = 17, PixelFormat_YUV444Packed = 18, PixelFormat_Mono12p = 19, PixelFormat_BayerGR12p = 20, PixelFormat_BayerRG12p = 21, PixelFormat_BayerGB12p = 22, PixelFormat_BayerBG12p = 23, PixelFormat_YCbCr8 = 24, PixelFormat_YCbCr422_8 = 25, PixelFormat_YCbCr411_8 = 26, PixelFormat_BGR8 = 27, PixelFormat_BGRa8 = 28, PixelFormat_Mono10Packed = 29, PixelFormat_BayerGR10Packed = 30, PixelFormat_BayerRG10Packed = 31, PixelFormat_BayerGB10Packed = 32, PixelFormat_BayerBG10Packed = 33, PixelFormat_Mono10p = 34, PixelFormat_BayerGR10p = 35, PixelFormat_BayerRG10p = 36, PixelFormat_BayerGB10p = 37, PixelFormat_BayerBG10p = 38, PixelFormat_Mono1p = 39, PixelFormat_Mono2p = 40, PixelFormat_Mono4p = 41, PixelFormat_Mono8s = 42, PixelFormat_Mono10 = 43, PixelFormat_Mono12 = 44, PixelFormat_Mono14 = 45, PixelFormat_BayerBG10 = 46, PixelFormat_BayerBG12 = 47, PixelFormat_BayerGB10 = 48, PixelFormat_BayerGB12 = 49, PixelFormat_BayerGR10 = 50, PixelFormat_BayerGR12 = 51, PixelFormat_BayerRG10 = 52, PixelFormat_BayerRG12 = 53, PixelFormat_RGBa8 = 54, PixelFormat_RGBa10 = 55, PixelFormat_RGBa10p = 56, PixelFormat_RGBa12 = 57, PixelFormat_RGBa12p = 58, PixelFormat_RGBa14 = 59, PixelFormat_RGBa16 = 60, PixelFormat_RGB8 = 61, PixelFormat_RGB8_Planar = 62, PixelFormat_RGB10 = 63, PixelFormat_RGB10_Planar = 64, PixelFormat_RGB10p = 65, PixelFormat_RGB10p32 = 66, PixelFormat_RGB12 = 67, PixelFormat_RGB12_Planar = 68, PixelFormat_RGB12p = 69, PixelFormat_RGB14 = 70, PixelFormat_RGB16 = 71, PixelFormat_RGB16_Planar = 72, PixelFormat_RGB565p = 73, PixelFormat_BGRa10 = 74, PixelFormat_BGRa10p = 75, PixelFormat_BGRa12 = 76, PixelFormat_BGRa12p = 77, PixelFormat_BGRa14 = 78, PixelFormat_BGRa16 = 79, PixelFormat_BGR10 = 80, PixelFormat_BGR10p = 81, PixelFormat_BGR12 = 82, PixelFormat_BGR12p = 83, PixelFormat_BGR14 = 84, PixelFormat_BGR16 = 85, PixelFormat_BGR565p = 86, PixelFormat_R8 = 87, PixelFormat_R10 = 88, PixelFormat_R12 = 89, PixelFormat_R16 = 90, PixelFormat_G8 = 91, PixelFormat_G10 = 92, PixelFormat_G12 = 93, PixelFormat_G16 = 94, PixelFormat_B8 = 95, PixelFormat_B10 = 96, PixelFormat_B12 = 97, PixelFormat_B16 = 98, PixelFormat_Coord3D_ABC8 = 99, PixelFormat_Coord3D_ABC8_Planar = 100, PixelFormat_Coord3D_ABC10p = 101, PixelFormat_Coord3D_ABC10p_Planar = 102, PixelFormat_Coord3D_ABC12p = 103, PixelFormat_Coord3D_ABC12p_Planar = 104, PixelFormat_Coord3D_ABC16 = 105, PixelFormat_Coord3D_ABC16_Planar = 106, PixelFormat_Coord3D_ABC32f = 107, PixelFormat_Coord3D_ABC32f_Planar = 108, PixelFormat_Coord3D_AC8 = 109, PixelFormat_Coord3D_AC8_Planar = 110, PixelFormat_Coord3D_AC10p = 111, PixelFormat_Coord3D_AC10p_Planar = 112, PixelFormat_Coord3D_AC12p = 113, PixelFormat_Coord3D_AC12p_Planar = 114, PixelFormat_Coord3D_AC16 = 115, PixelFormat_Coord3D_AC16_Planar = 116, PixelFormat_Coord3D_AC32f = 117, PixelFormat_Coord3D_AC32f_Planar = 118, PixelFormat_Coord3D_A8 = 119, PixelFormat_Coord3D_A10p = 120, PixelFormat_Coord3D_A12p = 121, PixelFormat_Coord3D_A16 = 122, PixelFormat_Coord3D_A32f = 123, PixelFormat_Coord3D_B8 = 124, PixelFormat_Coord3D_B10p = 125, PixelFormat_Coord3D_B12p = 126, PixelFormat_Coord3D_B16 = 127, PixelFormat_Coord3D_B32f = 128, PixelFormat_Coord3D_C8 = 129, PixelFormat_Coord3D_C10p = 130, PixelFormat_Coord3D_C12p = 131, PixelFormat_Coord3D_C16 = 132, PixelFormat_Coord3D_C32f = 133, PixelFormat_Confidence1 = 134, PixelFormat_Confidence1p = 135, PixelFormat_Confidence8 = 136, PixelFormat_Confidence16 = 137, PixelFormat_Confidence32f = 138, PixelFormat_BiColorBGRG8 = 139, PixelFormat_BiColorBGRG10 = 140, PixelFormat_BiColorBGRG10p = 141, PixelFormat_BiColorBGRG12 = 142, PixelFormat_BiColorBGRG12p = 143, PixelFormat_BiColorRGBG8 = 144, PixelFormat_BiColorRGBG10 = 145, PixelFormat_BiColorRGBG10p = 146, PixelFormat_BiColorRGBG12 = 147, PixelFormat_BiColorRGBG12p = 148, PixelFormat_SCF1WBWG8 = 149, PixelFormat_SCF1WBWG10 = 150, PixelFormat_SCF1WBWG10p = 151, PixelFormat_SCF1WBWG12 = 152, PixelFormat_SCF1WBWG12p = 153, PixelFormat_SCF1WBWG14 = 154, PixelFormat_SCF1WBWG16 = 155, PixelFormat_SCF1WGWB8 = 156, PixelFormat_SCF1WGWB10 = 157, PixelFormat_SCF1WGWB10p = 158, PixelFormat_SCF1WGWB12 = 159, PixelFormat_SCF1WGWB12p = 160, PixelFormat_SCF1WGWB14 = 161, PixelFormat_SCF1WGWB16 = 162, PixelFormat_SCF1WGWR8 = 163, PixelFormat_SCF1WGWR10 = 164, PixelFormat_SCF1WGWR10p = 165, PixelFormat_SCF1WGWR12 = 166, PixelFormat_SCF1WGWR12p = 167, PixelFormat_SCF1WGWR14 = 168, PixelFormat_SCF1WGWR16 = 169, PixelFormat_SCF1WRWG8 = 170, PixelFormat_SCF1WRWG10 = 171, PixelFormat_SCF1WRWG10p = 172, PixelFormat_SCF1WRWG12 = 173, PixelFormat_SCF1WRWG12p = 174, PixelFormat_SCF1WRWG14 = 175, PixelFormat_SCF1WRWG16 = 176, PixelFormat_YCbCr8_CbYCr = 177, PixelFormat_YCbCr10_CbYCr = 178, PixelFormat_YCbCr10p_CbYCr = 179, PixelFormat_YCbCr12_CbYCr = 180, PixelFormat_YCbCr12p_CbYCr = 181, PixelFormat_YCbCr411_8_CbYYCrYY = 182, PixelFormat_YCbCr422_8_CbYCrY = 183, PixelFormat_YCbCr422_10 = 184, PixelFormat_YCbCr422_10_CbYCrY = 185, PixelFormat_YCbCr422_10p = 186, PixelFormat_YCbCr422_10p_CbYCrY = 187, PixelFormat_YCbCr422_12 = 188, PixelFormat_YCbCr422_12_CbYCrY = 189, PixelFormat_YCbCr422_12p = 190, PixelFormat_YCbCr422_12p_CbYCrY = 191, PixelFormat_YCbCr601_8_CbYCr = 192, PixelFormat_YCbCr601_10_CbYCr = 193, PixelFormat_YCbCr601_10p_CbYCr = 194, PixelFormat_YCbCr601_12_CbYCr = 195, PixelFormat_YCbCr601_12p_CbYCr = 196, PixelFormat_YCbCr601_411_8_CbYYCrYY = 197, PixelFormat_YCbCr601_422_8 = 198, PixelFormat_YCbCr601_422_8_CbYCrY = 199, PixelFormat_YCbCr601_422_10 = 200, PixelFormat_YCbCr601_422_10_CbYCrY = 201, PixelFormat_YCbCr601_422_10p = 202, PixelFormat_YCbCr601_422_10p_CbYCrY = 203, PixelFormat_YCbCr601_422_12 = 204, PixelFormat_YCbCr601_422_12_CbYCrY = 205, PixelFormat_YCbCr601_422_12p = 206, PixelFormat_YCbCr601_422_12p_CbYCrY = 207, PixelFormat_YCbCr709_8_CbYCr = 208, PixelFormat_YCbCr709_10_CbYCr = 209, PixelFormat_YCbCr709_10p_CbYCr = 210, PixelFormat_YCbCr709_12_CbYCr = 211, PixelFormat_YCbCr709_12p_CbYCr = 212, PixelFormat_YCbCr709_411_8_CbYYCrYY = 213, PixelFormat_YCbCr709_422_8 = 214, PixelFormat_YCbCr709_422_8_CbYCrY = 215, PixelFormat_YCbCr709_422_10 = 216, PixelFormat_YCbCr709_422_10_CbYCrY = 217, PixelFormat_YCbCr709_422_10p = 218, PixelFormat_YCbCr709_422_10p_CbYCrY = 219, PixelFormat_YCbCr709_422_12 = 220, PixelFormat_YCbCr709_422_12_CbYCrY = 221, PixelFormat_YCbCr709_422_12p = 222, PixelFormat_YCbCr709_422_12p_CbYCrY = 223, PixelFormat_YUV8_UYV = 224, PixelFormat_YUV411_8_UYYVYY = 225, PixelFormat_YUV422_8 = 226, PixelFormat_YUV422_8_UYVY = 227, PixelFormat_Polarized8 = 228, PixelFormat_Polarized10p = 229, PixelFormat_Polarized12p = 230, PixelFormat_Polarized16 = 231, PixelFormat_BayerRGPolarized8 = 232, PixelFormat_BayerRGPolarized10p = 233, PixelFormat_BayerRGPolarized12p = 234, PixelFormat_BayerRGPolarized16 = 235, PixelFormat_Raw16 = 236, PixelFormat_Raw8 = 237, PixelFormat_R12_Jpeg = 238, PixelFormat_GR12_Jpeg = 239, PixelFormat_GB12_Jpeg = 240, PixelFormat_B12_Jpeg = 241, UNKNOWN_PIXELFORMAT = 242, NUM_PIXELFORMAT = 243, ) const spinPixelFormatEnums = _spinPixelFormatEnums @cenum(_spinDecimationVerticalModeEnums, DecimationVerticalMode_Discard = 0, NUM_DECIMATIONVERTICALMODE = 1, ) const spinDecimationVerticalModeEnums = _spinDecimationVerticalModeEnums @cenum(_spinLineModeEnums, LineMode_Input = 0, LineMode_Output = 1, NUM_LINEMODE = 2, ) const spinLineModeEnums = _spinLineModeEnums @cenum(_spinLineSourceEnums, LineSource_Off = 0, LineSource_Line0 = 1, LineSource_Line1 = 2, LineSource_Line2 = 3, LineSource_Line3 = 4, LineSource_UserOutput0 = 5, LineSource_UserOutput1 = 6, LineSource_UserOutput2 = 7, LineSource_UserOutput3 = 8, LineSource_Counter0Active = 9, LineSource_Counter1Active = 10, LineSource_LogicBlock0 = 11, LineSource_LogicBlock1 = 12, LineSource_ExposureActive = 13, LineSource_FrameTriggerWait = 14, LineSource_SerialPort0 = 15, LineSource_PPSSignal = 16, LineSource_AllPixel = 17, LineSource_AnyPixel = 18, NUM_LINESOURCE = 19, ) const spinLineSourceEnums = _spinLineSourceEnums @cenum(_spinLineInputFilterSelectorEnums, LineInputFilterSelector_Deglitch = 0, LineInputFilterSelector_Debounce = 1, NUM_LINEINPUTFILTERSELECTOR = 2, ) const spinLineInputFilterSelectorEnums = _spinLineInputFilterSelectorEnums @cenum(_spinUserOutputSelectorEnums, UserOutputSelector_UserOutput0 = 0, UserOutputSelector_UserOutput1 = 1, UserOutputSelector_UserOutput2 = 2, UserOutputSelector_UserOutput3 = 3, NUM_USEROUTPUTSELECTOR = 4, ) const spinUserOutputSelectorEnums = _spinUserOutputSelectorEnums @cenum(_spinLineFormatEnums, LineFormat_NoConnect = 0, LineFormat_TriState = 1, LineFormat_TTL = 2, LineFormat_LVDS = 3, LineFormat_RS422 = 4, LineFormat_OptoCoupled = 5, LineFormat_OpenDrain = 6, NUM_LINEFORMAT = 7, ) const spinLineFormatEnums = _spinLineFormatEnums @cenum(_spinLineSelectorEnums, LineSelector_Line0 = 0, LineSelector_Line1 = 1, LineSelector_Line2 = 2, LineSelector_Line3 = 3, NUM_LINESELECTOR = 4, ) const spinLineSelectorEnums = _spinLineSelectorEnums @cenum(_spinExposureActiveModeEnums, ExposureActiveMode_Line1 = 0, ExposureActiveMode_AnyPixels = 1, ExposureActiveMode_AllPixels = 2, NUM_EXPOSUREACTIVEMODE = 3, ) const spinExposureActiveModeEnums = _spinExposureActiveModeEnums @cenum(_spinCounterTriggerActivationEnums, CounterTriggerActivation_LevelLow = 0, CounterTriggerActivation_LevelHigh = 1, CounterTriggerActivation_FallingEdge = 2, CounterTriggerActivation_RisingEdge = 3, CounterTriggerActivation_AnyEdge = 4, NUM_COUNTERTRIGGERACTIVATION = 5, ) const spinCounterTriggerActivationEnums = _spinCounterTriggerActivationEnums @cenum(_spinCounterSelectorEnums, CounterSelector_Counter0 = 0, CounterSelector_Counter1 = 1, NUM_COUNTERSELECTOR = 2, ) const spinCounterSelectorEnums = _spinCounterSelectorEnums @cenum(_spinCounterStatusEnums, CounterStatus_CounterIdle = 0, CounterStatus_CounterTriggerWait = 1, CounterStatus_CounterActive = 2, CounterStatus_CounterCompleted = 3, CounterStatus_CounterOverflow = 4, NUM_COUNTERSTATUS = 5, ) const spinCounterStatusEnums = _spinCounterStatusEnums @cenum(_spinCounterTriggerSourceEnums, CounterTriggerSource_Off = 0, CounterTriggerSource_Line0 = 1, CounterTriggerSource_Line1 = 2, CounterTriggerSource_Line2 = 3, CounterTriggerSource_Line3 = 4, CounterTriggerSource_UserOutput0 = 5, CounterTriggerSource_UserOutput1 = 6, CounterTriggerSource_UserOutput2 = 7, CounterTriggerSource_UserOutput3 = 8, CounterTriggerSource_Counter0Start = 9, CounterTriggerSource_Counter1Start = 10, CounterTriggerSource_Counter0End = 11, CounterTriggerSource_Counter1End = 12, CounterTriggerSource_LogicBlock0 = 13, CounterTriggerSource_LogicBlock1 = 14, CounterTriggerSource_ExposureStart = 15, CounterTriggerSource_ExposureEnd = 16, CounterTriggerSource_FrameTriggerWait = 17, NUM_COUNTERTRIGGERSOURCE = 18, ) const spinCounterTriggerSourceEnums = _spinCounterTriggerSourceEnums @cenum(_spinCounterResetSourceEnums, CounterResetSource_Off = 0, CounterResetSource_Line0 = 1, CounterResetSource_Line1 = 2, CounterResetSource_Line2 = 3, CounterResetSource_Line3 = 4, CounterResetSource_UserOutput0 = 5, CounterResetSource_UserOutput1 = 6, CounterResetSource_UserOutput2 = 7, CounterResetSource_UserOutput3 = 8, CounterResetSource_Counter0Start = 9, CounterResetSource_Counter1Start = 10, CounterResetSource_Counter0End = 11, CounterResetSource_Counter1End = 12, CounterResetSource_LogicBlock0 = 13, CounterResetSource_LogicBlock1 = 14, CounterResetSource_ExposureStart = 15, CounterResetSource_ExposureEnd = 16, CounterResetSource_FrameTriggerWait = 17, NUM_COUNTERRESETSOURCE = 18, ) const spinCounterResetSourceEnums = _spinCounterResetSourceEnums @cenum(_spinCounterEventSourceEnums, CounterEventSource_Off = 0, CounterEventSource_MHzTick = 1, CounterEventSource_Line0 = 2, CounterEventSource_Line1 = 3, CounterEventSource_Line2 = 4, CounterEventSource_Line3 = 5, CounterEventSource_UserOutput0 = 6, CounterEventSource_UserOutput1 = 7, CounterEventSource_UserOutput2 = 8, CounterEventSource_UserOutput3 = 9, CounterEventSource_Counter0Start = 10, CounterEventSource_Counter1Start = 11, CounterEventSource_Counter0End = 12, CounterEventSource_Counter1End = 13, CounterEventSource_LogicBlock0 = 14, CounterEventSource_LogicBlock1 = 15, CounterEventSource_ExposureStart = 16, CounterEventSource_ExposureEnd = 17, CounterEventSource_FrameTriggerWait = 18, NUM_COUNTEREVENTSOURCE = 19, ) const spinCounterEventSourceEnums = _spinCounterEventSourceEnums @cenum(_spinCounterEventActivationEnums, CounterEventActivation_LevelLow = 0, CounterEventActivation_LevelHigh = 1, CounterEventActivation_FallingEdge = 2, CounterEventActivation_RisingEdge = 3, CounterEventActivation_AnyEdge = 4, NUM_COUNTEREVENTACTIVATION = 5, ) const spinCounterEventActivationEnums = _spinCounterEventActivationEnums @cenum(_spinCounterResetActivationEnums, CounterResetActivation_LevelLow = 0, CounterResetActivation_LevelHigh = 1, CounterResetActivation_FallingEdge = 2, CounterResetActivation_RisingEdge = 3, CounterResetActivation_AnyEdge = 4, NUM_COUNTERRESETACTIVATION = 5, ) const spinCounterResetActivationEnums = _spinCounterResetActivationEnums @cenum(_spinDeviceTypeEnums, DeviceType_Transmitter = 0, DeviceType_Receiver = 1, DeviceType_Transceiver = 2, DeviceType_Peripheral = 3, NUM_DEVICETYPE = 4, ) const spinDeviceTypeEnums = _spinDeviceTypeEnums @cenum(_spinDeviceConnectionStatusEnums, DeviceConnectionStatus_Active = 0, DeviceConnectionStatus_Inactive = 1, NUM_DEVICECONNECTIONSTATUS = 2, ) const spinDeviceConnectionStatusEnums = _spinDeviceConnectionStatusEnums @cenum(_spinDeviceLinkThroughputLimitModeEnums, DeviceLinkThroughputLimitMode_On = 0, DeviceLinkThroughputLimitMode_Off = 1, NUM_DEVICELINKTHROUGHPUTLIMITMODE = 2, ) const spinDeviceLinkThroughputLimitModeEnums = _spinDeviceLinkThroughputLimitModeEnums @cenum(_spinDeviceLinkHeartbeatModeEnums, DeviceLinkHeartbeatMode_On = 0, DeviceLinkHeartbeatMode_Off = 1, NUM_DEVICELINKHEARTBEATMODE = 2, ) const spinDeviceLinkHeartbeatModeEnums = _spinDeviceLinkHeartbeatModeEnums @cenum(_spinDeviceStreamChannelTypeEnums, DeviceStreamChannelType_Transmitter = 0, DeviceStreamChannelType_Receiver = 1, NUM_DEVICESTREAMCHANNELTYPE = 2, ) const spinDeviceStreamChannelTypeEnums = _spinDeviceStreamChannelTypeEnums @cenum(_spinDeviceStreamChannelEndiannessEnums, DeviceStreamChannelEndianness_Big = 0, DeviceStreamChannelEndianness_Little = 1, NUM_DEVICESTREAMCHANNELENDIANNESS = 2, ) const spinDeviceStreamChannelEndiannessEnums = _spinDeviceStreamChannelEndiannessEnums @cenum(_spinDeviceClockSelectorEnums, DeviceClockSelector_Sensor = 0, DeviceClockSelector_SensorDigitization = 1, DeviceClockSelector_CameraLink = 2, NUM_DEVICECLOCKSELECTOR = 3, ) const spinDeviceClockSelectorEnums = _spinDeviceClockSelectorEnums @cenum(_spinDeviceSerialPortSelectorEnums, DeviceSerialPortSelector_CameraLink = 0, NUM_DEVICESERIALPORTSELECTOR = 1, ) const spinDeviceSerialPortSelectorEnums = _spinDeviceSerialPortSelectorEnums @cenum(_spinDeviceSerialPortBaudRateEnums, DeviceSerialPortBaudRate_Baud9600 = 0, DeviceSerialPortBaudRate_Baud19200 = 1, DeviceSerialPortBaudRate_Baud38400 = 2, DeviceSerialPortBaudRate_Baud57600 = 3, DeviceSerialPortBaudRate_Baud115200 = 4, DeviceSerialPortBaudRate_Baud230400 = 5, DeviceSerialPortBaudRate_Baud460800 = 6, DeviceSerialPortBaudRate_Baud921600 = 7, NUM_DEVICESERIALPORTBAUDRATE = 8, ) const spinDeviceSerialPortBaudRateEnums = _spinDeviceSerialPortBaudRateEnums @cenum(_spinSensorTapsEnums, SensorTaps_One = 0, SensorTaps_Two = 1, SensorTaps_Three = 2, SensorTaps_Four = 3, SensorTaps_Eight = 4, SensorTaps_Ten = 5, NUM_SENSORTAPS = 6, ) const spinSensorTapsEnums = _spinSensorTapsEnums @cenum(_spinSensorDigitizationTapsEnums, SensorDigitizationTaps_One = 0, SensorDigitizationTaps_Two = 1, SensorDigitizationTaps_Three = 2, SensorDigitizationTaps_Four = 3, SensorDigitizationTaps_Eight = 4, SensorDigitizationTaps_Ten = 5, NUM_SENSORDIGITIZATIONTAPS = 6, ) const spinSensorDigitizationTapsEnums = _spinSensorDigitizationTapsEnums @cenum(_spinRegionSelectorEnums, RegionSelector_Region0 = 0, RegionSelector_Region1 = 1, RegionSelector_Region2 = 2, RegionSelector_All = 3, NUM_REGIONSELECTOR = 4, ) const spinRegionSelectorEnums = _spinRegionSelectorEnums @cenum(_spinRegionModeEnums, RegionMode_Off = 0, RegionMode_On = 1, NUM_REGIONMODE = 2, ) const spinRegionModeEnums = _spinRegionModeEnums @cenum(_spinRegionDestinationEnums, RegionDestination_Stream0 = 0, RegionDestination_Stream1 = 1, RegionDestination_Stream2 = 2, NUM_REGIONDESTINATION = 3, ) const spinRegionDestinationEnums = _spinRegionDestinationEnums @cenum(_spinImageComponentSelectorEnums, ImageComponentSelector_Intensity = 0, ImageComponentSelector_Color = 1, ImageComponentSelector_Infrared = 2, ImageComponentSelector_Ultraviolet = 3, ImageComponentSelector_Range = 4, ImageComponentSelector_Disparity = 5, ImageComponentSelector_Confidence = 6, ImageComponentSelector_Scatter = 7, NUM_IMAGECOMPONENTSELECTOR = 8, ) const spinImageComponentSelectorEnums = _spinImageComponentSelectorEnums @cenum(_spinPixelFormatInfoSelectorEnums, PixelFormatInfoSelector_Mono1p = 0, PixelFormatInfoSelector_Mono2p = 1, PixelFormatInfoSelector_Mono4p = 2, PixelFormatInfoSelector_Mono8 = 3, PixelFormatInfoSelector_Mono8s = 4, PixelFormatInfoSelector_Mono10 = 5, PixelFormatInfoSelector_Mono10p = 6, PixelFormatInfoSelector_Mono12 = 7, PixelFormatInfoSelector_Mono12p = 8, PixelFormatInfoSelector_Mono14 = 9, PixelFormatInfoSelector_Mono16 = 10, PixelFormatInfoSelector_BayerBG8 = 11, PixelFormatInfoSelector_BayerBG10 = 12, PixelFormatInfoSelector_BayerBG10p = 13, PixelFormatInfoSelector_BayerBG12 = 14, PixelFormatInfoSelector_BayerBG12p = 15, PixelFormatInfoSelector_BayerBG16 = 16, PixelFormatInfoSelector_BayerGB8 = 17, PixelFormatInfoSelector_BayerGB10 = 18, PixelFormatInfoSelector_BayerGB10p = 19, PixelFormatInfoSelector_BayerGB12 = 20, PixelFormatInfoSelector_BayerGB12p = 21, PixelFormatInfoSelector_BayerGB16 = 22, PixelFormatInfoSelector_BayerGR8 = 23, PixelFormatInfoSelector_BayerGR10 = 24, PixelFormatInfoSelector_BayerGR10p = 25, PixelFormatInfoSelector_BayerGR12 = 26, PixelFormatInfoSelector_BayerGR12p = 27, PixelFormatInfoSelector_BayerGR16 = 28, PixelFormatInfoSelector_BayerRG8 = 29, PixelFormatInfoSelector_BayerRG10 = 30, PixelFormatInfoSelector_BayerRG10p = 31, PixelFormatInfoSelector_BayerRG12 = 32, PixelFormatInfoSelector_BayerRG12p = 33, PixelFormatInfoSelector_BayerRG16 = 34, PixelFormatInfoSelector_RGBa8 = 35, PixelFormatInfoSelector_RGBa10 = 36, PixelFormatInfoSelector_RGBa10p = 37, PixelFormatInfoSelector_RGBa12 = 38, PixelFormatInfoSelector_RGBa12p = 39, PixelFormatInfoSelector_RGBa14 = 40, PixelFormatInfoSelector_RGBa16 = 41, PixelFormatInfoSelector_RGB8 = 42, PixelFormatInfoSelector_RGB8_Planar = 43, PixelFormatInfoSelector_RGB10 = 44, PixelFormatInfoSelector_RGB10_Planar = 45, PixelFormatInfoSelector_RGB10p = 46, PixelFormatInfoSelector_RGB10p32 = 47, PixelFormatInfoSelector_RGB12 = 48, PixelFormatInfoSelector_RGB12_Planar = 49, PixelFormatInfoSelector_RGB12p = 50, PixelFormatInfoSelector_RGB14 = 51, PixelFormatInfoSelector_RGB16 = 52, PixelFormatInfoSelector_RGB16_Planar = 53, PixelFormatInfoSelector_RGB565p = 54, PixelFormatInfoSelector_BGRa8 = 55, PixelFormatInfoSelector_BGRa10 = 56, PixelFormatInfoSelector_BGRa10p = 57, PixelFormatInfoSelector_BGRa12 = 58, PixelFormatInfoSelector_BGRa12p = 59, PixelFormatInfoSelector_BGRa14 = 60, PixelFormatInfoSelector_BGRa16 = 61, PixelFormatInfoSelector_BGR8 = 62, PixelFormatInfoSelector_BGR10 = 63, PixelFormatInfoSelector_BGR10p = 64, PixelFormatInfoSelector_BGR12 = 65, PixelFormatInfoSelector_BGR12p = 66, PixelFormatInfoSelector_BGR14 = 67, PixelFormatInfoSelector_BGR16 = 68, PixelFormatInfoSelector_BGR565p = 69, PixelFormatInfoSelector_R8 = 70, PixelFormatInfoSelector_R10 = 71, PixelFormatInfoSelector_R12 = 72, PixelFormatInfoSelector_R16 = 73, PixelFormatInfoSelector_G8 = 74, PixelFormatInfoSelector_G10 = 75, PixelFormatInfoSelector_G12 = 76, PixelFormatInfoSelector_G16 = 77, PixelFormatInfoSelector_B8 = 78, PixelFormatInfoSelector_B10 = 79, PixelFormatInfoSelector_B12 = 80, PixelFormatInfoSelector_B16 = 81, PixelFormatInfoSelector_Coord3D_ABC8 = 82, PixelFormatInfoSelector_Coord3D_ABC8_Planar = 83, PixelFormatInfoSelector_Coord3D_ABC10p = 84, PixelFormatInfoSelector_Coord3D_ABC10p_Planar = 85, PixelFormatInfoSelector_Coord3D_ABC12p = 86, PixelFormatInfoSelector_Coord3D_ABC12p_Planar = 87, PixelFormatInfoSelector_Coord3D_ABC16 = 88, PixelFormatInfoSelector_Coord3D_ABC16_Planar = 89, PixelFormatInfoSelector_Coord3D_ABC32f = 90, PixelFormatInfoSelector_Coord3D_ABC32f_Planar = 91, PixelFormatInfoSelector_Coord3D_AC8 = 92, PixelFormatInfoSelector_Coord3D_AC8_Planar = 93, PixelFormatInfoSelector_Coord3D_AC10p = 94, PixelFormatInfoSelector_Coord3D_AC10p_Planar = 95, PixelFormatInfoSelector_Coord3D_AC12p = 96, PixelFormatInfoSelector_Coord3D_AC12p_Planar = 97, PixelFormatInfoSelector_Coord3D_AC16 = 98, PixelFormatInfoSelector_Coord3D_AC16_Planar = 99, PixelFormatInfoSelector_Coord3D_AC32f = 100, PixelFormatInfoSelector_Coord3D_AC32f_Planar = 101, PixelFormatInfoSelector_Coord3D_A8 = 102, PixelFormatInfoSelector_Coord3D_A10p = 103, PixelFormatInfoSelector_Coord3D_A12p = 104, PixelFormatInfoSelector_Coord3D_A16 = 105, PixelFormatInfoSelector_Coord3D_A32f = 106, PixelFormatInfoSelector_Coord3D_B8 = 107, PixelFormatInfoSelector_Coord3D_B10p = 108, PixelFormatInfoSelector_Coord3D_B12p = 109, PixelFormatInfoSelector_Coord3D_B16 = 110, PixelFormatInfoSelector_Coord3D_B32f = 111, PixelFormatInfoSelector_Coord3D_C8 = 112, PixelFormatInfoSelector_Coord3D_C10p = 113, PixelFormatInfoSelector_Coord3D_C12p = 114, PixelFormatInfoSelector_Coord3D_C16 = 115, PixelFormatInfoSelector_Coord3D_C32f = 116, PixelFormatInfoSelector_Confidence1 = 117, PixelFormatInfoSelector_Confidence1p = 118, PixelFormatInfoSelector_Confidence8 = 119, PixelFormatInfoSelector_Confidence16 = 120, PixelFormatInfoSelector_Confidence32f = 121, PixelFormatInfoSelector_BiColorBGRG8 = 122, PixelFormatInfoSelector_BiColorBGRG10 = 123, PixelFormatInfoSelector_BiColorBGRG10p = 124, PixelFormatInfoSelector_BiColorBGRG12 = 125, PixelFormatInfoSelector_BiColorBGRG12p = 126, PixelFormatInfoSelector_BiColorRGBG8 = 127, PixelFormatInfoSelector_BiColorRGBG10 = 128, PixelFormatInfoSelector_BiColorRGBG10p = 129, PixelFormatInfoSelector_BiColorRGBG12 = 130, PixelFormatInfoSelector_BiColorRGBG12p = 131, PixelFormatInfoSelector_SCF1WBWG8 = 132, PixelFormatInfoSelector_SCF1WBWG10 = 133, PixelFormatInfoSelector_SCF1WBWG10p = 134, PixelFormatInfoSelector_SCF1WBWG12 = 135, PixelFormatInfoSelector_SCF1WBWG12p = 136, PixelFormatInfoSelector_SCF1WBWG14 = 137, PixelFormatInfoSelector_SCF1WBWG16 = 138, PixelFormatInfoSelector_SCF1WGWB8 = 139, PixelFormatInfoSelector_SCF1WGWB10 = 140, PixelFormatInfoSelector_SCF1WGWB10p = 141, PixelFormatInfoSelector_SCF1WGWB12 = 142, PixelFormatInfoSelector_SCF1WGWB12p = 143, PixelFormatInfoSelector_SCF1WGWB14 = 144, PixelFormatInfoSelector_SCF1WGWB16 = 145, PixelFormatInfoSelector_SCF1WGWR8 = 146, PixelFormatInfoSelector_SCF1WGWR10 = 147, PixelFormatInfoSelector_SCF1WGWR10p = 148, PixelFormatInfoSelector_SCF1WGWR12 = 149, PixelFormatInfoSelector_SCF1WGWR12p = 150, PixelFormatInfoSelector_SCF1WGWR14 = 151, PixelFormatInfoSelector_SCF1WGWR16 = 152, PixelFormatInfoSelector_SCF1WRWG8 = 153, PixelFormatInfoSelector_SCF1WRWG10 = 154, PixelFormatInfoSelector_SCF1WRWG10p = 155, PixelFormatInfoSelector_SCF1WRWG12 = 156, PixelFormatInfoSelector_SCF1WRWG12p = 157, PixelFormatInfoSelector_SCF1WRWG14 = 158, PixelFormatInfoSelector_SCF1WRWG16 = 159, PixelFormatInfoSelector_YCbCr8 = 160, PixelFormatInfoSelector_YCbCr8_CbYCr = 161, PixelFormatInfoSelector_YCbCr10_CbYCr = 162, PixelFormatInfoSelector_YCbCr10p_CbYCr = 163, PixelFormatInfoSelector_YCbCr12_CbYCr = 164, PixelFormatInfoSelector_YCbCr12p_CbYCr = 165, PixelFormatInfoSelector_YCbCr411_8 = 166, PixelFormatInfoSelector_YCbCr411_8_CbYYCrYY = 167, PixelFormatInfoSelector_YCbCr422_8 = 168, PixelFormatInfoSelector_YCbCr422_8_CbYCrY = 169, PixelFormatInfoSelector_YCbCr422_10 = 170, PixelFormatInfoSelector_YCbCr422_10_CbYCrY = 171, PixelFormatInfoSelector_YCbCr422_10p = 172, PixelFormatInfoSelector_YCbCr422_10p_CbYCrY = 173, PixelFormatInfoSelector_YCbCr422_12 = 174, PixelFormatInfoSelector_YCbCr422_12_CbYCrY = 175, PixelFormatInfoSelector_YCbCr422_12p = 176, PixelFormatInfoSelector_YCbCr422_12p_CbYCrY = 177, PixelFormatInfoSelector_YCbCr601_8_CbYCr = 178, PixelFormatInfoSelector_YCbCr601_10_CbYCr = 179, PixelFormatInfoSelector_YCbCr601_10p_CbYCr = 180, PixelFormatInfoSelector_YCbCr601_12_CbYCr = 181, PixelFormatInfoSelector_YCbCr601_12p_CbYCr = 182, PixelFormatInfoSelector_YCbCr601_411_8_CbYYCrYY = 183, PixelFormatInfoSelector_YCbCr601_422_8 = 184, PixelFormatInfoSelector_YCbCr601_422_8_CbYCrY = 185, PixelFormatInfoSelector_YCbCr601_422_10 = 186, PixelFormatInfoSelector_YCbCr601_422_10_CbYCrY = 187, PixelFormatInfoSelector_YCbCr601_422_10p = 188, PixelFormatInfoSelector_YCbCr601_422_10p_CbYCrY = 189, PixelFormatInfoSelector_YCbCr601_422_12 = 190, PixelFormatInfoSelector_YCbCr601_422_12_CbYCrY = 191, PixelFormatInfoSelector_YCbCr601_422_12p = 192, PixelFormatInfoSelector_YCbCr601_422_12p_CbYCrY = 193, PixelFormatInfoSelector_YCbCr709_8_CbYCr = 194, PixelFormatInfoSelector_YCbCr709_10_CbYCr = 195, PixelFormatInfoSelector_YCbCr709_10p_CbYCr = 196, PixelFormatInfoSelector_YCbCr709_12_CbYCr = 197, PixelFormatInfoSelector_YCbCr709_12p_CbYCr = 198, PixelFormatInfoSelector_YCbCr709_411_8_CbYYCrYY = 199, PixelFormatInfoSelector_YCbCr709_422_8 = 200, PixelFormatInfoSelector_YCbCr709_422_8_CbYCrY = 201, PixelFormatInfoSelector_YCbCr709_422_10 = 202, PixelFormatInfoSelector_YCbCr709_422_10_CbYCrY = 203, PixelFormatInfoSelector_YCbCr709_422_10p = 204, PixelFormatInfoSelector_YCbCr709_422_10p_CbYCrY = 205, PixelFormatInfoSelector_YCbCr709_422_12 = 206, PixelFormatInfoSelector_YCbCr709_422_12_CbYCrY = 207, PixelFormatInfoSelector_YCbCr709_422_12p = 208, PixelFormatInfoSelector_YCbCr709_422_12p_CbYCrY = 209, PixelFormatInfoSelector_YUV8_UYV = 210, PixelFormatInfoSelector_YUV411_8_UYYVYY = 211, PixelFormatInfoSelector_YUV422_8 = 212, PixelFormatInfoSelector_YUV422_8_UYVY = 213, PixelFormatInfoSelector_Polarized8 = 214, PixelFormatInfoSelector_Polarized10p = 215, PixelFormatInfoSelector_Polarized12p = 216, PixelFormatInfoSelector_Polarized16 = 217, PixelFormatInfoSelector_BayerRGPolarized8 = 218, PixelFormatInfoSelector_BayerRGPolarized10p = 219, PixelFormatInfoSelector_BayerRGPolarized12p = 220, PixelFormatInfoSelector_BayerRGPolarized16 = 221, NUM_PIXELFORMATINFOSELECTOR = 222, ) const spinPixelFormatInfoSelectorEnums = _spinPixelFormatInfoSelectorEnums @cenum(_spinDeinterlacingEnums, Deinterlacing_Off = 0, Deinterlacing_LineDuplication = 1, Deinterlacing_Weave = 2, NUM_DEINTERLACING = 3, ) const spinDeinterlacingEnums = _spinDeinterlacingEnums @cenum(_spinImageCompressionRateOptionEnums, ImageCompressionRateOption_FixBitrate = 0, ImageCompressionRateOption_FixQuality = 1, NUM_IMAGECOMPRESSIONRATEOPTION = 2, ) const spinImageCompressionRateOptionEnums = _spinImageCompressionRateOptionEnums @cenum(_spinImageCompressionJPEGFormatOptionEnums, ImageCompressionJPEGFormatOption_Lossless = 0, ImageCompressionJPEGFormatOption_BaselineStandard = 1, ImageCompressionJPEGFormatOption_BaselineOptimized = 2, ImageCompressionJPEGFormatOption_Progressive = 3, NUM_IMAGECOMPRESSIONJPEGFORMATOPTION = 4, ) const spinImageCompressionJPEGFormatOptionEnums = _spinImageCompressionJPEGFormatOptionEnums @cenum(_spinAcquisitionStatusSelectorEnums, AcquisitionStatusSelector_AcquisitionTriggerWait = 0, AcquisitionStatusSelector_AcquisitionActive = 1, AcquisitionStatusSelector_AcquisitionTransfer = 2, AcquisitionStatusSelector_FrameTriggerWait = 3, AcquisitionStatusSelector_FrameActive = 4, AcquisitionStatusSelector_ExposureActive = 5, NUM_ACQUISITIONSTATUSSELECTOR = 6, ) const spinAcquisitionStatusSelectorEnums = _spinAcquisitionStatusSelectorEnums @cenum(_spinExposureTimeModeEnums, ExposureTimeMode_Common = 0, ExposureTimeMode_Individual = 1, NUM_EXPOSURETIMEMODE = 2, ) const spinExposureTimeModeEnums = _spinExposureTimeModeEnums @cenum(_spinExposureTimeSelectorEnums, ExposureTimeSelector_Common = 0, ExposureTimeSelector_Red = 1, ExposureTimeSelector_Green = 2, ExposureTimeSelector_Blue = 3, ExposureTimeSelector_Cyan = 4, ExposureTimeSelector_Magenta = 5, ExposureTimeSelector_Yellow = 6, ExposureTimeSelector_Infrared = 7, ExposureTimeSelector_Ultraviolet = 8, ExposureTimeSelector_Stage1 = 9, ExposureTimeSelector_Stage2 = 10, NUM_EXPOSURETIMESELECTOR = 11, ) const spinExposureTimeSelectorEnums = _spinExposureTimeSelectorEnums @cenum(_spinGainAutoBalanceEnums, GainAutoBalance_Off = 0, GainAutoBalance_Once = 1, GainAutoBalance_Continuous = 2, NUM_GAINAUTOBALANCE = 3, ) const spinGainAutoBalanceEnums = _spinGainAutoBalanceEnums @cenum(_spinBlackLevelAutoEnums, BlackLevelAuto_Off = 0, BlackLevelAuto_Once = 1, BlackLevelAuto_Continuous = 2, NUM_BLACKLEVELAUTO = 3, ) const spinBlackLevelAutoEnums = _spinBlackLevelAutoEnums @cenum(_spinBlackLevelAutoBalanceEnums, BlackLevelAutoBalance_Off = 0, BlackLevelAutoBalance_Once = 1, BlackLevelAutoBalance_Continuous = 2, NUM_BLACKLEVELAUTOBALANCE = 3, ) const spinBlackLevelAutoBalanceEnums = _spinBlackLevelAutoBalanceEnums @cenum(_spinWhiteClipSelectorEnums, WhiteClipSelector_All = 0, WhiteClipSelector_Red = 1, WhiteClipSelector_Green = 2, WhiteClipSelector_Blue = 3, WhiteClipSelector_Y = 4, WhiteClipSelector_U = 5, WhiteClipSelector_V = 6, WhiteClipSelector_Tap1 = 7, WhiteClipSelector_Tap2 = 8, NUM_WHITECLIPSELECTOR = 9, ) const spinWhiteClipSelectorEnums = _spinWhiteClipSelectorEnums @cenum(_spinTimerSelectorEnums, TimerSelector_Timer0 = 0, TimerSelector_Timer1 = 1, TimerSelector_Timer2 = 2, NUM_TIMERSELECTOR = 3, ) const spinTimerSelectorEnums = _spinTimerSelectorEnums @cenum(_spinTimerStatusEnums, TimerStatus_TimerIdle = 0, TimerStatus_TimerTriggerWait = 1, TimerStatus_TimerActive = 2, TimerStatus_TimerCompleted = 3, NUM_TIMERSTATUS = 4, ) const spinTimerStatusEnums = _spinTimerStatusEnums @cenum(_spinTimerTriggerSourceEnums, TimerTriggerSource_Off = 0, TimerTriggerSource_AcquisitionTrigger = 1, TimerTriggerSource_AcquisitionStart = 2, TimerTriggerSource_AcquisitionEnd = 3, TimerTriggerSource_FrameTrigger = 4, TimerTriggerSource_FrameStart = 5, TimerTriggerSource_FrameEnd = 6, TimerTriggerSource_FrameBurstStart = 7, TimerTriggerSource_FrameBurstEnd = 8, TimerTriggerSource_LineTrigger = 9, TimerTriggerSource_LineStart = 10, TimerTriggerSource_LineEnd = 11, TimerTriggerSource_ExposureStart = 12, TimerTriggerSource_ExposureEnd = 13, TimerTriggerSource_Line0 = 14, TimerTriggerSource_Line1 = 15, TimerTriggerSource_Line2 = 16, TimerTriggerSource_UserOutput0 = 17, TimerTriggerSource_UserOutput1 = 18, TimerTriggerSource_UserOutput2 = 19, TimerTriggerSource_Counter0Start = 20, TimerTriggerSource_Counter1Start = 21, TimerTriggerSource_Counter2Start = 22, TimerTriggerSource_Counter0End = 23, TimerTriggerSource_Counter1End = 24, TimerTriggerSource_Counter2End = 25, TimerTriggerSource_Timer0Start = 26, TimerTriggerSource_Timer1Start = 27, TimerTriggerSource_Timer2Start = 28, TimerTriggerSource_Timer0End = 29, TimerTriggerSource_Timer1End = 30, TimerTriggerSource_Timer2End = 31, TimerTriggerSource_Encoder0 = 32, TimerTriggerSource_Encoder1 = 33, TimerTriggerSource_Encoder2 = 34, TimerTriggerSource_SoftwareSignal0 = 35, TimerTriggerSource_SoftwareSignal1 = 36, TimerTriggerSource_SoftwareSignal2 = 37, TimerTriggerSource_Action0 = 38, TimerTriggerSource_Action1 = 39, TimerTriggerSource_Action2 = 40, TimerTriggerSource_LinkTrigger0 = 41, TimerTriggerSource_LinkTrigger1 = 42, TimerTriggerSource_LinkTrigger2 = 43, NUM_TIMERTRIGGERSOURCE = 44, ) const spinTimerTriggerSourceEnums = _spinTimerTriggerSourceEnums @cenum(_spinTimerTriggerActivationEnums, TimerTriggerActivation_RisingEdge = 0, TimerTriggerActivation_FallingEdge = 1, TimerTriggerActivation_AnyEdge = 2, TimerTriggerActivation_LevelHigh = 3, TimerTriggerActivation_LevelLow = 4, NUM_TIMERTRIGGERACTIVATION = 5, ) const spinTimerTriggerActivationEnums = _spinTimerTriggerActivationEnums @cenum(_spinEncoderSelectorEnums, EncoderSelector_Encoder0 = 0, EncoderSelector_Encoder1 = 1, EncoderSelector_Encoder2 = 2, NUM_ENCODERSELECTOR = 3, ) const spinEncoderSelectorEnums = _spinEncoderSelectorEnums @cenum(_spinEncoderSourceAEnums, EncoderSourceA_Off = 0, EncoderSourceA_Line0 = 1, EncoderSourceA_Line1 = 2, EncoderSourceA_Line2 = 3, NUM_ENCODERSOURCEA = 4, ) const spinEncoderSourceAEnums = _spinEncoderSourceAEnums @cenum(_spinEncoderSourceBEnums, EncoderSourceB_Off = 0, EncoderSourceB_Line0 = 1, EncoderSourceB_Line1 = 2, EncoderSourceB_Line2 = 3, NUM_ENCODERSOURCEB = 4, ) const spinEncoderSourceBEnums = _spinEncoderSourceBEnums @cenum(_spinEncoderModeEnums, EncoderMode_FourPhase = 0, EncoderMode_HighResolution = 1, NUM_ENCODERMODE = 2, ) const spinEncoderModeEnums = _spinEncoderModeEnums @cenum(_spinEncoderOutputModeEnums, EncoderOutputMode_Off = 0, EncoderOutputMode_PositionUp = 1, EncoderOutputMode_PositionDown = 2, EncoderOutputMode_DirectionUp = 3, EncoderOutputMode_DirectionDown = 4, EncoderOutputMode_Motion = 5, NUM_ENCODEROUTPUTMODE = 6, ) const spinEncoderOutputModeEnums = _spinEncoderOutputModeEnums @cenum(_spinEncoderStatusEnums, EncoderStatus_EncoderUp = 0, EncoderStatus_EncoderDown = 1, EncoderStatus_EncoderIdle = 2, EncoderStatus_EncoderStatic = 3, NUM_ENCODERSTATUS = 4, ) const spinEncoderStatusEnums = _spinEncoderStatusEnums @cenum(_spinEncoderResetSourceEnums, EncoderResetSource_Off = 0, EncoderResetSource_AcquisitionTrigger = 1, EncoderResetSource_AcquisitionStart = 2, EncoderResetSource_AcquisitionEnd = 3, EncoderResetSource_FrameTrigger = 4, EncoderResetSource_FrameStart = 5, EncoderResetSource_FrameEnd = 6, EncoderResetSource_ExposureStart = 7, EncoderResetSource_ExposureEnd = 8, EncoderResetSource_Line0 = 9, EncoderResetSource_Line1 = 10, EncoderResetSource_Line2 = 11, EncoderResetSource_Counter0Start = 12, EncoderResetSource_Counter1Start = 13, EncoderResetSource_Counter2Start = 14, EncoderResetSource_Counter0End = 15, EncoderResetSource_Counter1End = 16, EncoderResetSource_Counter2End = 17, EncoderResetSource_Timer0Start = 18, EncoderResetSource_Timer1Start = 19, EncoderResetSource_Timer2Start = 20, EncoderResetSource_Timer0End = 21, EncoderResetSource_Timer1End = 22, EncoderResetSource_Timer2End = 23, EncoderResetSource_UserOutput0 = 24, EncoderResetSource_UserOutput1 = 25, EncoderResetSource_UserOutput2 = 26, EncoderResetSource_SoftwareSignal0 = 27, EncoderResetSource_SoftwareSignal1 = 28, EncoderResetSource_SoftwareSignal2 = 29, EncoderResetSource_Action0 = 30, EncoderResetSource_Action1 = 31, EncoderResetSource_Action2 = 32, EncoderResetSource_LinkTrigger0 = 33, EncoderResetSource_LinkTrigger1 = 34, EncoderResetSource_LinkTrigger2 = 35, NUM_ENCODERRESETSOURCE = 36, ) const spinEncoderResetSourceEnums = _spinEncoderResetSourceEnums @cenum(_spinEncoderResetActivationEnums, EncoderResetActivation_RisingEdge = 0, EncoderResetActivation_FallingEdge = 1, EncoderResetActivation_AnyEdge = 2, EncoderResetActivation_LevelHigh = 3, EncoderResetActivation_LevelLow = 4, NUM_ENCODERRESETACTIVATION = 5, ) const spinEncoderResetActivationEnums = _spinEncoderResetActivationEnums @cenum(_spinSoftwareSignalSelectorEnums, SoftwareSignalSelector_SoftwareSignal0 = 0, SoftwareSignalSelector_SoftwareSignal1 = 1, SoftwareSignalSelector_SoftwareSignal2 = 2, NUM_SOFTWARESIGNALSELECTOR = 3, ) const spinSoftwareSignalSelectorEnums = _spinSoftwareSignalSelectorEnums @cenum(_spinActionUnconditionalModeEnums, ActionUnconditionalMode_Off = 0, ActionUnconditionalMode_On = 1, NUM_ACTIONUNCONDITIONALMODE = 2, ) const spinActionUnconditionalModeEnums = _spinActionUnconditionalModeEnums @cenum(_spinSourceSelectorEnums, SourceSelector_Source0 = 0, SourceSelector_Source1 = 1, SourceSelector_Source2 = 2, SourceSelector_All = 3, NUM_SOURCESELECTOR = 4, ) const spinSourceSelectorEnums = _spinSourceSelectorEnums @cenum(_spinTransferSelectorEnums, TransferSelector_Stream0 = 0, TransferSelector_Stream1 = 1, TransferSelector_Stream2 = 2, TransferSelector_All = 3, NUM_TRANSFERSELECTOR = 4, ) const spinTransferSelectorEnums = _spinTransferSelectorEnums @cenum(_spinTransferTriggerSelectorEnums, TransferTriggerSelector_TransferStart = 0, TransferTriggerSelector_TransferStop = 1, TransferTriggerSelector_TransferAbort = 2, TransferTriggerSelector_TransferPause = 3, TransferTriggerSelector_TransferResume = 4, TransferTriggerSelector_TransferActive = 5, TransferTriggerSelector_TransferBurstStart = 6, TransferTriggerSelector_TransferBurstStop = 7, NUM_TRANSFERTRIGGERSELECTOR = 8, ) const spinTransferTriggerSelectorEnums = _spinTransferTriggerSelectorEnums @cenum(_spinTransferTriggerModeEnums, TransferTriggerMode_Off = 0, TransferTriggerMode_On = 1, NUM_TRANSFERTRIGGERMODE = 2, ) const spinTransferTriggerModeEnums = _spinTransferTriggerModeEnums @cenum(_spinTransferTriggerSourceEnums, TransferTriggerSource_Line0 = 0, TransferTriggerSource_Line1 = 1, TransferTriggerSource_Line2 = 2, TransferTriggerSource_Counter0Start = 3, TransferTriggerSource_Counter1Start = 4, TransferTriggerSource_Counter2Start = 5, TransferTriggerSource_Counter0End = 6, TransferTriggerSource_Counter1End = 7, TransferTriggerSource_Counter2End = 8, TransferTriggerSource_Timer0Start = 9, TransferTriggerSource_Timer1Start = 10, TransferTriggerSource_Timer2Start = 11, TransferTriggerSource_Timer0End = 12, TransferTriggerSource_Timer1End = 13, TransferTriggerSource_Timer2End = 14, TransferTriggerSource_SoftwareSignal0 = 15, TransferTriggerSource_SoftwareSignal1 = 16, TransferTriggerSource_SoftwareSignal2 = 17, TransferTriggerSource_Action0 = 18, TransferTriggerSource_Action1 = 19, TransferTriggerSource_Action2 = 20, NUM_TRANSFERTRIGGERSOURCE = 21, ) const spinTransferTriggerSourceEnums = _spinTransferTriggerSourceEnums @cenum(_spinTransferTriggerActivationEnums, TransferTriggerActivation_RisingEdge = 0, TransferTriggerActivation_FallingEdge = 1, TransferTriggerActivation_AnyEdge = 2, TransferTriggerActivation_LevelHigh = 3, TransferTriggerActivation_LevelLow = 4, NUM_TRANSFERTRIGGERACTIVATION = 5, ) const spinTransferTriggerActivationEnums = _spinTransferTriggerActivationEnums @cenum(_spinTransferStatusSelectorEnums, TransferStatusSelector_Streaming = 0, TransferStatusSelector_Paused = 1, TransferStatusSelector_Stopping = 2, TransferStatusSelector_Stopped = 3, TransferStatusSelector_QueueOverflow = 4, NUM_TRANSFERSTATUSSELECTOR = 5, ) const spinTransferStatusSelectorEnums = _spinTransferStatusSelectorEnums @cenum(_spinTransferComponentSelectorEnums, TransferComponentSelector_Red = 0, TransferComponentSelector_Green = 1, TransferComponentSelector_Blue = 2, TransferComponentSelector_All = 3, NUM_TRANSFERCOMPONENTSELECTOR = 4, ) const spinTransferComponentSelectorEnums = _spinTransferComponentSelectorEnums @cenum(_spinScan3dDistanceUnitEnums, Scan3dDistanceUnit_Millimeter = 0, Scan3dDistanceUnit_Inch = 1, NUM_SCAN3DDISTANCEUNIT = 2, ) const spinScan3dDistanceUnitEnums = _spinScan3dDistanceUnitEnums @cenum(_spinScan3dCoordinateSystemEnums, Scan3dCoordinateSystem_Cartesian = 0, Scan3dCoordinateSystem_Spherical = 1, Scan3dCoordinateSystem_Cylindrical = 2, NUM_SCAN3DCOORDINATESYSTEM = 3, ) const spinScan3dCoordinateSystemEnums = _spinScan3dCoordinateSystemEnums @cenum(_spinScan3dOutputModeEnums, Scan3dOutputMode_UncalibratedC = 0, Scan3dOutputMode_CalibratedABC_Grid = 1, Scan3dOutputMode_CalibratedABC_PointCloud = 2, Scan3dOutputMode_CalibratedAC = 3, Scan3dOutputMode_CalibratedAC_Linescan = 4, Scan3dOutputMode_CalibratedC = 5, Scan3dOutputMode_CalibratedC_Linescan = 6, Scan3dOutputMode_RectifiedC = 7, Scan3dOutputMode_RectifiedC_Linescan = 8, Scan3dOutputMode_DisparityC = 9, Scan3dOutputMode_DisparityC_Linescan = 10, NUM_SCAN3DOUTPUTMODE = 11, ) const spinScan3dOutputModeEnums = _spinScan3dOutputModeEnums @cenum(_spinScan3dCoordinateSystemReferenceEnums, Scan3dCoordinateSystemReference_Anchor = 0, Scan3dCoordinateSystemReference_Transformed = 1, NUM_SCAN3DCOORDINATESYSTEMREFERENCE = 2, ) const spinScan3dCoordinateSystemReferenceEnums = _spinScan3dCoordinateSystemReferenceEnums @cenum(_spinScan3dCoordinateSelectorEnums, Scan3dCoordinateSelector_CoordinateA = 0, Scan3dCoordinateSelector_CoordinateB = 1, Scan3dCoordinateSelector_CoordinateC = 2, NUM_SCAN3DCOORDINATESELECTOR = 3, ) const spinScan3dCoordinateSelectorEnums = _spinScan3dCoordinateSelectorEnums @cenum(_spinScan3dCoordinateTransformSelectorEnums, Scan3dCoordinateTransformSelector_RotationX = 0, Scan3dCoordinateTransformSelector_RotationY = 1, Scan3dCoordinateTransformSelector_RotationZ = 2, Scan3dCoordinateTransformSelector_TranslationX = 3, Scan3dCoordinateTransformSelector_TranslationY = 4, Scan3dCoordinateTransformSelector_TranslationZ = 5, NUM_SCAN3DCOORDINATETRANSFORMSELECTOR = 6, ) const spinScan3dCoordinateTransformSelectorEnums = _spinScan3dCoordinateTransformSelectorEnums @cenum(_spinScan3dCoordinateReferenceSelectorEnums, Scan3dCoordinateReferenceSelector_RotationX = 0, Scan3dCoordinateReferenceSelector_RotationY = 1, Scan3dCoordinateReferenceSelector_RotationZ = 2, Scan3dCoordinateReferenceSelector_TranslationX = 3, Scan3dCoordinateReferenceSelector_TranslationY = 4, Scan3dCoordinateReferenceSelector_TranslationZ = 5, NUM_SCAN3DCOORDINATEREFERENCESELECTOR = 6, ) const spinScan3dCoordinateReferenceSelectorEnums = _spinScan3dCoordinateReferenceSelectorEnums @cenum(_spinChunkImageComponentEnums, ChunkImageComponent_Intensity = 0, ChunkImageComponent_Color = 1, ChunkImageComponent_Infrared = 2, ChunkImageComponent_Ultraviolet = 3, ChunkImageComponent_Range = 4, ChunkImageComponent_Disparity = 5, ChunkImageComponent_Confidence = 6, ChunkImageComponent_Scatter = 7, NUM_CHUNKIMAGECOMPONENT = 8, ) const spinChunkImageComponentEnums = _spinChunkImageComponentEnums @cenum(_spinChunkCounterSelectorEnums, ChunkCounterSelector_Counter0 = 0, ChunkCounterSelector_Counter1 = 1, ChunkCounterSelector_Counter2 = 2, NUM_CHUNKCOUNTERSELECTOR = 3, ) const spinChunkCounterSelectorEnums = _spinChunkCounterSelectorEnums @cenum(_spinChunkTimerSelectorEnums, ChunkTimerSelector_Timer0 = 0, ChunkTimerSelector_Timer1 = 1, ChunkTimerSelector_Timer2 = 2, NUM_CHUNKTIMERSELECTOR = 3, ) const spinChunkTimerSelectorEnums = _spinChunkTimerSelectorEnums @cenum(_spinChunkEncoderSelectorEnums, ChunkEncoderSelector_Encoder0 = 0, ChunkEncoderSelector_Encoder1 = 1, ChunkEncoderSelector_Encoder2 = 2, NUM_CHUNKENCODERSELECTOR = 3, ) const spinChunkEncoderSelectorEnums = _spinChunkEncoderSelectorEnums @cenum(_spinChunkEncoderStatusEnums, ChunkEncoderStatus_EncoderUp = 0, ChunkEncoderStatus_EncoderDown = 1, ChunkEncoderStatus_EncoderIdle = 2, ChunkEncoderStatus_EncoderStatic = 3, NUM_CHUNKENCODERSTATUS = 4, ) const spinChunkEncoderStatusEnums = _spinChunkEncoderStatusEnums @cenum(_spinChunkExposureTimeSelectorEnums, ChunkExposureTimeSelector_Common = 0, ChunkExposureTimeSelector_Red = 1, ChunkExposureTimeSelector_Green = 2, ChunkExposureTimeSelector_Blue = 3, ChunkExposureTimeSelector_Cyan = 4, ChunkExposureTimeSelector_Magenta = 5, ChunkExposureTimeSelector_Yellow = 6, ChunkExposureTimeSelector_Infrared = 7, ChunkExposureTimeSelector_Ultraviolet = 8, ChunkExposureTimeSelector_Stage1 = 9, ChunkExposureTimeSelector_Stage2 = 10, NUM_CHUNKEXPOSURETIMESELECTOR = 11, ) const spinChunkExposureTimeSelectorEnums = _spinChunkExposureTimeSelectorEnums @cenum(_spinChunkSourceIDEnums, ChunkSourceID_Source0 = 0, ChunkSourceID_Source1 = 1, ChunkSourceID_Source2 = 2, NUM_CHUNKSOURCEID = 3, ) const spinChunkSourceIDEnums = _spinChunkSourceIDEnums @cenum(_spinChunkRegionIDEnums, ChunkRegionID_Region0 = 0, ChunkRegionID_Region1 = 1, ChunkRegionID_Region2 = 2, NUM_CHUNKREGIONID = 3, ) const spinChunkRegionIDEnums = _spinChunkRegionIDEnums @cenum(_spinChunkTransferStreamIDEnums, ChunkTransferStreamID_Stream0 = 0, ChunkTransferStreamID_Stream1 = 1, ChunkTransferStreamID_Stream2 = 2, ChunkTransferStreamID_Stream3 = 3, NUM_CHUNKTRANSFERSTREAMID = 4, ) const spinChunkTransferStreamIDEnums = _spinChunkTransferStreamIDEnums @cenum(_spinChunkScan3dDistanceUnitEnums, ChunkScan3dDistanceUnit_Millimeter = 0, ChunkScan3dDistanceUnit_Inch = 1, NUM_CHUNKSCAN3DDISTANCEUNIT = 2, ) const spinChunkScan3dDistanceUnitEnums = _spinChunkScan3dDistanceUnitEnums @cenum(_spinChunkScan3dOutputModeEnums, ChunkScan3dOutputMode_UncalibratedC = 0, ChunkScan3dOutputMode_CalibratedABC_Grid = 1, ChunkScan3dOutputMode_CalibratedABC_PointCloud = 2, ChunkScan3dOutputMode_CalibratedAC = 3, ChunkScan3dOutputMode_CalibratedAC_Linescan = 4, ChunkScan3dOutputMode_CalibratedC = 5, ChunkScan3dOutputMode_CalibratedC_Linescan = 6, ChunkScan3dOutputMode_RectifiedC = 7, ChunkScan3dOutputMode_RectifiedC_Linescan = 8, ChunkScan3dOutputMode_DisparityC = 9, ChunkScan3dOutputMode_DisparityC_Linescan = 10, NUM_CHUNKSCAN3DOUTPUTMODE = 11, ) const spinChunkScan3dOutputModeEnums = _spinChunkScan3dOutputModeEnums @cenum(_spinChunkScan3dCoordinateSystemEnums, ChunkScan3dCoordinateSystem_Cartesian = 0, ChunkScan3dCoordinateSystem_Spherical = 1, ChunkScan3dCoordinateSystem_Cylindrical = 2, NUM_CHUNKSCAN3DCOORDINATESYSTEM = 3, ) const spinChunkScan3dCoordinateSystemEnums = _spinChunkScan3dCoordinateSystemEnums @cenum(_spinChunkScan3dCoordinateSystemReferenceEnums, ChunkScan3dCoordinateSystemReference_Anchor = 0, ChunkScan3dCoordinateSystemReference_Transformed = 1, NUM_CHUNKSCAN3DCOORDINATESYSTEMREFERENCE = 2, ) const spinChunkScan3dCoordinateSystemReferenceEnums = _spinChunkScan3dCoordinateSystemReferenceEnums @cenum(_spinChunkScan3dCoordinateSelectorEnums, ChunkScan3dCoordinateSelector_CoordinateA = 0, ChunkScan3dCoordinateSelector_CoordinateB = 1, ChunkScan3dCoordinateSelector_CoordinateC = 2, NUM_CHUNKSCAN3DCOORDINATESELECTOR = 3, ) const spinChunkScan3dCoordinateSelectorEnums = _spinChunkScan3dCoordinateSelectorEnums @cenum(_spinChunkScan3dCoordinateTransformSelectorEnums, ChunkScan3dCoordinateTransformSelector_RotationX = 0, ChunkScan3dCoordinateTransformSelector_RotationY = 1, ChunkScan3dCoordinateTransformSelector_RotationZ = 2, ChunkScan3dCoordinateTransformSelector_TranslationX = 3, ChunkScan3dCoordinateTransformSelector_TranslationY = 4, ChunkScan3dCoordinateTransformSelector_TranslationZ = 5, NUM_CHUNKSCAN3DCOORDINATETRANSFORMSELECTOR = 6, ) const spinChunkScan3dCoordinateTransformSelectorEnums = _spinChunkScan3dCoordinateTransformSelectorEnums @cenum(_spinChunkScan3dCoordinateReferenceSelectorEnums, ChunkScan3dCoordinateReferenceSelector_RotationX = 0, ChunkScan3dCoordinateReferenceSelector_RotationY = 1, ChunkScan3dCoordinateReferenceSelector_RotationZ = 2, ChunkScan3dCoordinateReferenceSelector_TranslationX = 3, ChunkScan3dCoordinateReferenceSelector_TranslationY = 4, ChunkScan3dCoordinateReferenceSelector_TranslationZ = 5, NUM_CHUNKSCAN3DCOORDINATEREFERENCESELECTOR = 6, ) const spinChunkScan3dCoordinateReferenceSelectorEnums = _spinChunkScan3dCoordinateReferenceSelectorEnums @cenum(_spinDeviceTapGeometryEnums, DeviceTapGeometry_Geometry_1X_1Y = 0, DeviceTapGeometry_Geometry_1X2_1Y = 1, DeviceTapGeometry_Geometry_1X2_1Y2 = 2, DeviceTapGeometry_Geometry_2X_1Y = 3, DeviceTapGeometry_Geometry_2X_1Y2Geometry_2XE_1Y = 4, DeviceTapGeometry_Geometry_2XE_1Y2 = 5, DeviceTapGeometry_Geometry_2XM_1Y = 6, DeviceTapGeometry_Geometry_2XM_1Y2 = 7, DeviceTapGeometry_Geometry_1X_1Y2 = 8, DeviceTapGeometry_Geometry_1X_2YE = 9, DeviceTapGeometry_Geometry_1X3_1Y = 10, DeviceTapGeometry_Geometry_3X_1Y = 11, DeviceTapGeometry_Geometry_1X = 12, DeviceTapGeometry_Geometry_1X2 = 13, DeviceTapGeometry_Geometry_2X = 14, DeviceTapGeometry_Geometry_2XE = 15, DeviceTapGeometry_Geometry_2XM = 16, DeviceTapGeometry_Geometry_1X3 = 17, DeviceTapGeometry_Geometry_3X = 18, DeviceTapGeometry_Geometry_1X4_1Y = 19, DeviceTapGeometry_Geometry_4X_1Y = 20, DeviceTapGeometry_Geometry_2X2_1Y = 21, DeviceTapGeometry_Geometry_2X2E_1YGeometry_2X2M_1Y = 22, DeviceTapGeometry_Geometry_1X2_2YE = 23, DeviceTapGeometry_Geometry_2X_2YE = 24, DeviceTapGeometry_Geometry_2XE_2YE = 25, DeviceTapGeometry_Geometry_2XM_2YE = 26, DeviceTapGeometry_Geometry_1X4 = 27, DeviceTapGeometry_Geometry_4X = 28, DeviceTapGeometry_Geometry_2X2 = 29, DeviceTapGeometry_Geometry_2X2E = 30, DeviceTapGeometry_Geometry_2X2M = 31, DeviceTapGeometry_Geometry_1X8_1Y = 32, DeviceTapGeometry_Geometry_8X_1Y = 33, DeviceTapGeometry_Geometry_4X2_1Y = 34, DeviceTapGeometry_Geometry_2X2E_2YE = 35, DeviceTapGeometry_Geometry_1X8 = 36, DeviceTapGeometry_Geometry_8X = 37, DeviceTapGeometry_Geometry_4X2 = 38, DeviceTapGeometry_Geometry_4X2E = 39, DeviceTapGeometry_Geometry_4X2E_1Y = 40, DeviceTapGeometry_Geometry_1X10_1Y = 41, DeviceTapGeometry_Geometry_10X_1Y = 42, DeviceTapGeometry_Geometry_1X10 = 43, DeviceTapGeometry_Geometry_10X = 44, NUM_DEVICETAPGEOMETRY = 45, ) const spinDeviceTapGeometryEnums = _spinDeviceTapGeometryEnums @cenum(_spinGevPhysicalLinkConfigurationEnums, GevPhysicalLinkConfiguration_SingleLink = 0, GevPhysicalLinkConfiguration_MultiLink = 1, GevPhysicalLinkConfiguration_StaticLAG = 2, GevPhysicalLinkConfiguration_DynamicLAG = 3, NUM_GEVPHYSICALLINKCONFIGURATION = 4, ) const spinGevPhysicalLinkConfigurationEnums = _spinGevPhysicalLinkConfigurationEnums @cenum(_spinGevCurrentPhysicalLinkConfigurationEnums, GevCurrentPhysicalLinkConfiguration_SingleLink = 0, GevCurrentPhysicalLinkConfiguration_MultiLink = 1, GevCurrentPhysicalLinkConfiguration_StaticLAG = 2, GevCurrentPhysicalLinkConfiguration_DynamicLAG = 3, NUM_GEVCURRENTPHYSICALLINKCONFIGURATION = 4, ) const spinGevCurrentPhysicalLinkConfigurationEnums = _spinGevCurrentPhysicalLinkConfigurationEnums @cenum(_spinGevIPConfigurationStatusEnums, GevIPConfigurationStatus_None = 0, GevIPConfigurationStatus_PersistentIP = 1, GevIPConfigurationStatus_DHCP = 2, GevIPConfigurationStatus_LLA = 3, GevIPConfigurationStatus_ForceIP = 4, NUM_GEVIPCONFIGURATIONSTATUS = 5, ) const spinGevIPConfigurationStatusEnums = _spinGevIPConfigurationStatusEnums @cenum(_spinGevGVCPExtendedStatusCodesSelectorEnums, GevGVCPExtendedStatusCodesSelector_Version1_1 = 0, GevGVCPExtendedStatusCodesSelector_Version2_0 = 1, NUM_GEVGVCPEXTENDEDSTATUSCODESSELECTOR = 2, ) const spinGevGVCPExtendedStatusCodesSelectorEnums = _spinGevGVCPExtendedStatusCodesSelectorEnums @cenum(_spinGevGVSPExtendedIDModeEnums, GevGVSPExtendedIDMode_Off = 0, GevGVSPExtendedIDMode_On = 1, NUM_GEVGVSPEXTENDEDIDMODE = 2, ) const spinGevGVSPExtendedIDModeEnums = _spinGevGVSPExtendedIDModeEnums @cenum(_spinClConfigurationEnums, ClConfiguration_Base = 0, ClConfiguration_Medium = 1, ClConfiguration_Full = 2, ClConfiguration_DualBase = 3, ClConfiguration_EightyBit = 4, NUM_CLCONFIGURATION = 5, ) const spinClConfigurationEnums = _spinClConfigurationEnums @cenum(_spinClTimeSlotsCountEnums, ClTimeSlotsCount_One = 0, ClTimeSlotsCount_Two = 1, ClTimeSlotsCount_Three = 2, NUM_CLTIMESLOTSCOUNT = 3, ) const spinClTimeSlotsCountEnums = _spinClTimeSlotsCountEnums @cenum(_spinCxpLinkConfigurationStatusEnums, CxpLinkConfigurationStatus_None = 0, CxpLinkConfigurationStatus_Pending = 1, CxpLinkConfigurationStatus_CXP1_X1 = 2, CxpLinkConfigurationStatus_CXP2_X1 = 3, CxpLinkConfigurationStatus_CXP3_X1 = 4, CxpLinkConfigurationStatus_CXP5_X1 = 5, CxpLinkConfigurationStatus_CXP6_X1 = 6, CxpLinkConfigurationStatus_CXP1_X2 = 7, CxpLinkConfigurationStatus_CXP2_X2 = 8, CxpLinkConfigurationStatus_CXP3_X2 = 9, CxpLinkConfigurationStatus_CXP5_X2 = 10, CxpLinkConfigurationStatus_CXP6_X2 = 11, CxpLinkConfigurationStatus_CXP1_X3 = 12, CxpLinkConfigurationStatus_CXP2_X3 = 13, CxpLinkConfigurationStatus_CXP3_X3 = 14, CxpLinkConfigurationStatus_CXP5_X3 = 15, CxpLinkConfigurationStatus_CXP6_X3 = 16, CxpLinkConfigurationStatus_CXP1_X4 = 17, CxpLinkConfigurationStatus_CXP2_X4 = 18, CxpLinkConfigurationStatus_CXP3_X4 = 19, CxpLinkConfigurationStatus_CXP5_X4 = 20, CxpLinkConfigurationStatus_CXP6_X4 = 21, CxpLinkConfigurationStatus_CXP1_X5 = 22, CxpLinkConfigurationStatus_CXP2_X5 = 23, CxpLinkConfigurationStatus_CXP3_X5 = 24, CxpLinkConfigurationStatus_CXP5_X5 = 25, CxpLinkConfigurationStatus_CXP6_X5 = 26, CxpLinkConfigurationStatus_CXP1_X6 = 27, CxpLinkConfigurationStatus_CXP2_X6 = 28, CxpLinkConfigurationStatus_CXP3_X6 = 29, CxpLinkConfigurationStatus_CXP5_X6 = 30, CxpLinkConfigurationStatus_CXP6_X6 = 31, NUM_CXPLINKCONFIGURATIONSTATUS = 32, ) const spinCxpLinkConfigurationStatusEnums = _spinCxpLinkConfigurationStatusEnums @cenum(_spinCxpLinkConfigurationPreferredEnums, CxpLinkConfigurationPreferred_CXP1_X1 = 0, CxpLinkConfigurationPreferred_CXP2_X1 = 1, CxpLinkConfigurationPreferred_CXP3_X1 = 2, CxpLinkConfigurationPreferred_CXP5_X1 = 3, CxpLinkConfigurationPreferred_CXP6_X1 = 4, CxpLinkConfigurationPreferred_CXP1_X2 = 5, CxpLinkConfigurationPreferred_CXP2_X2 = 6, CxpLinkConfigurationPreferred_CXP3_X2 = 7, CxpLinkConfigurationPreferred_CXP5_X2 = 8, CxpLinkConfigurationPreferred_CXP6_X2 = 9, CxpLinkConfigurationPreferred_CXP1_X3 = 10, CxpLinkConfigurationPreferred_CXP2_X3 = 11, CxpLinkConfigurationPreferred_CXP3_X3 = 12, CxpLinkConfigurationPreferred_CXP5_X3 = 13, CxpLinkConfigurationPreferred_CXP6_X3 = 14, CxpLinkConfigurationPreferred_CXP1_X4 = 15, CxpLinkConfigurationPreferred_CXP2_X4 = 16, CxpLinkConfigurationPreferred_CXP3_X4 = 17, CxpLinkConfigurationPreferred_CXP5_X4 = 18, CxpLinkConfigurationPreferred_CXP6_X4 = 19, CxpLinkConfigurationPreferred_CXP1_X5 = 20, CxpLinkConfigurationPreferred_CXP2_X5 = 21, CxpLinkConfigurationPreferred_CXP3_X5 = 22, CxpLinkConfigurationPreferred_CXP5_X5 = 23, CxpLinkConfigurationPreferred_CXP6_X5 = 24, CxpLinkConfigurationPreferred_CXP1_X6 = 25, CxpLinkConfigurationPreferred_CXP2_X6 = 26, CxpLinkConfigurationPreferred_CXP3_X6 = 27, CxpLinkConfigurationPreferred_CXP5_X6 = 28, CxpLinkConfigurationPreferred_CXP6_X6 = 29, NUM_CXPLINKCONFIGURATIONPREFERRED = 30, ) const spinCxpLinkConfigurationPreferredEnums = _spinCxpLinkConfigurationPreferredEnums @cenum(_spinCxpLinkConfigurationEnums, CxpLinkConfiguration_Auto = 0, CxpLinkConfiguration_CXP1_X1 = 1, CxpLinkConfiguration_CXP2_X1 = 2, CxpLinkConfiguration_CXP3_X1 = 3, CxpLinkConfiguration_CXP5_X1 = 4, CxpLinkConfiguration_CXP6_X1 = 5, CxpLinkConfiguration_CXP1_X2 = 6, CxpLinkConfiguration_CXP2_X2 = 7, CxpLinkConfiguration_CXP3_X2 = 8, CxpLinkConfiguration_CXP5_X2 = 9, CxpLinkConfiguration_CXP6_X2 = 10, CxpLinkConfiguration_CXP1_X3 = 11, CxpLinkConfiguration_CXP2_X3 = 12, CxpLinkConfiguration_CXP3_X3 = 13, CxpLinkConfiguration_CXP5_X3 = 14, CxpLinkConfiguration_CXP6_X3 = 15, CxpLinkConfiguration_CXP1_X4 = 16, CxpLinkConfiguration_CXP2_X4 = 17, CxpLinkConfiguration_CXP3_X4 = 18, CxpLinkConfiguration_CXP5_X4 = 19, CxpLinkConfiguration_CXP6_X4 = 20, CxpLinkConfiguration_CXP1_X5 = 21, CxpLinkConfiguration_CXP2_X5 = 22, CxpLinkConfiguration_CXP3_X5 = 23, CxpLinkConfiguration_CXP5_X5 = 24, CxpLinkConfiguration_CXP6_X5 = 25, CxpLinkConfiguration_CXP1_X6 = 26, CxpLinkConfiguration_CXP2_X6 = 27, CxpLinkConfiguration_CXP3_X6 = 28, CxpLinkConfiguration_CXP5_X6 = 29, CxpLinkConfiguration_CXP6_X6 = 30, NUM_CXPLINKCONFIGURATION = 31, ) const spinCxpLinkConfigurationEnums = _spinCxpLinkConfigurationEnums @cenum(_spinCxpConnectionTestModeEnums, CxpConnectionTestMode_Off = 0, CxpConnectionTestMode_Mode1 = 1, NUM_CXPCONNECTIONTESTMODE = 2, ) const spinCxpConnectionTestModeEnums = _spinCxpConnectionTestModeEnums @cenum(_spinCxpPoCxpStatusEnums, CxpPoCxpStatus_Auto = 0, CxpPoCxpStatus_Off = 1, CxpPoCxpStatus_Tripped = 2, NUM_CXPPOCXPSTATUS = 3, ) const spinCxpPoCxpStatusEnums = _spinCxpPoCxpStatusEnums struct _spinChunkData m_blackLevel::Cdouble m_frameID::Int64 m_exposureTime::Cdouble m_timestamp::Int64 m_exposureEndLineStatusAll::Int64 m_width::Int64 m_image::Int64 m_height::Int64 m_gain::Cdouble m_sequencerSetActive::Int64 m_cRC::Int64 m_offsetX::Int64 m_offsetY::Int64 m_serialDataLength::Int64 m_partSelector::Int64 m_pixelDynamicRangeMin::Int64 m_pixelDynamicRangeMax::Int64 m_timestampLatchValue::Int64 m_lineStatusAll::Int64 m_counterValue::Int64 m_timerValue::Cdouble m_scanLineSelector::Int64 m_encoderValue::Int64 m_linePitch::Int64 m_transferBlockID::Int64 m_transferQueueCurrentBlockCount::Int64 m_streamChannelID::Int64 m_scan3dCoordinateScale::Cdouble m_scan3dCoordinateOffset::Cdouble m_scan3dInvalidDataValue::Cdouble m_scan3dAxisMin::Cdouble m_scan3dAxisMax::Cdouble m_scan3dTransformValue::Cdouble m_scan3dCoordinateReferenceValue::Cdouble m_inferenceResult::Int64 m_inferenceConfidence::Cdouble end const spinChunkData = _spinChunkData const spinNodeHandle = Ptr{Cvoid} const quickSpinStringNode = spinNodeHandle const quickSpinIntegerNode = spinNodeHandle const quickSpinFloatNode = spinNodeHandle const quickSpinBooleanNode = spinNodeHandle const quickSpinEnumerationNode = spinNodeHandle const quickSpinCommandNode = spinNodeHandle const quickSpinRegisterNode = spinNodeHandle struct _quickSpin LUTIndex::quickSpinIntegerNode LUTEnable::quickSpinBooleanNode LUTValue::quickSpinIntegerNode LUTSelector::quickSpinEnumerationNode ExposureTime::quickSpinFloatNode AcquisitionStop::quickSpinCommandNode AcquisitionResultingFrameRate::quickSpinFloatNode AcquisitionLineRate::quickSpinFloatNode AcquisitionStart::quickSpinCommandNode TriggerSoftware::quickSpinCommandNode ExposureMode::quickSpinEnumerationNode AcquisitionMode::quickSpinEnumerationNode AcquisitionFrameCount::quickSpinIntegerNode TriggerSource::quickSpinEnumerationNode TriggerActivation::quickSpinEnumerationNode SensorShutterMode::quickSpinEnumerationNode TriggerDelay::quickSpinFloatNode TriggerMode::quickSpinEnumerationNode AcquisitionFrameRate::quickSpinFloatNode TriggerOverlap::quickSpinEnumerationNode TriggerSelector::quickSpinEnumerationNode AcquisitionFrameRateEnable::quickSpinBooleanNode ExposureAuto::quickSpinEnumerationNode AcquisitionBurstFrameCount::quickSpinIntegerNode EventTest::quickSpinIntegerNode EventTestTimestamp::quickSpinIntegerNode EventExposureEndFrameID::quickSpinIntegerNode EventExposureEnd::quickSpinIntegerNode EventExposureEndTimestamp::quickSpinIntegerNode EventError::quickSpinIntegerNode EventErrorTimestamp::quickSpinIntegerNode EventErrorCode::quickSpinIntegerNode EventErrorFrameID::quickSpinIntegerNode EventSelector::quickSpinEnumerationNode EventSerialReceiveOverflow::quickSpinBooleanNode EventSerialPortReceive::quickSpinIntegerNode EventSerialPortReceiveTimestamp::quickSpinIntegerNode EventSerialData::quickSpinStringNode EventSerialDataLength::quickSpinIntegerNode EventNotification::quickSpinEnumerationNode LogicBlockLUTRowIndex::quickSpinIntegerNode LogicBlockSelector::quickSpinEnumerationNode LogicBlockLUTInputActivation::quickSpinEnumerationNode LogicBlockLUTInputSelector::quickSpinEnumerationNode LogicBlockLUTInputSource::quickSpinEnumerationNode LogicBlockLUTOutputValue::quickSpinBooleanNode LogicBlockLUTOutputValueAll::quickSpinIntegerNode LogicBlockLUTSelector::quickSpinEnumerationNode ColorTransformationValue::quickSpinFloatNode ColorTransformationEnable::quickSpinBooleanNode ColorTransformationSelector::quickSpinEnumerationNode RgbTransformLightSource::quickSpinEnumerationNode Saturation::quickSpinFloatNode SaturationEnable::quickSpinBooleanNode ColorTransformationValueSelector::quickSpinEnumerationNode TimestampLatchValue::quickSpinIntegerNode TimestampReset::quickSpinCommandNode DeviceUserID::quickSpinStringNode DeviceTemperature::quickSpinFloatNode MaxDeviceResetTime::quickSpinIntegerNode DeviceTLVersionMinor::quickSpinIntegerNode DeviceSerialNumber::quickSpinStringNode DeviceVendorName::quickSpinStringNode DeviceRegistersEndianness::quickSpinEnumerationNode DeviceManufacturerInfo::quickSpinStringNode DeviceLinkSpeed::quickSpinIntegerNode LinkUptime::quickSpinIntegerNode DeviceEventChannelCount::quickSpinIntegerNode TimestampLatch::quickSpinCommandNode DeviceScanType::quickSpinEnumerationNode DeviceReset::quickSpinCommandNode DeviceCharacterSet::quickSpinEnumerationNode DeviceLinkThroughputLimit::quickSpinIntegerNode DeviceFirmwareVersion::quickSpinStringNode DeviceStreamChannelCount::quickSpinIntegerNode DeviceTLType::quickSpinEnumerationNode DeviceVersion::quickSpinStringNode DevicePowerSupplySelector::quickSpinEnumerationNode SensorDescription::quickSpinStringNode DeviceModelName::quickSpinStringNode DeviceTLVersionMajor::quickSpinIntegerNode DeviceTemperatureSelector::quickSpinEnumerationNode EnumerationCount::quickSpinIntegerNode PowerSupplyCurrent::quickSpinFloatNode DeviceID::quickSpinStringNode DeviceUptime::quickSpinIntegerNode DeviceLinkCurrentThroughput::quickSpinIntegerNode DeviceMaxThroughput::quickSpinIntegerNode FactoryReset::quickSpinCommandNode PowerSupplyVoltage::quickSpinFloatNode DeviceIndicatorMode::quickSpinEnumerationNode DeviceLinkBandwidthReserve::quickSpinFloatNode AasRoiOffsetY::quickSpinIntegerNode AasRoiOffsetX::quickSpinIntegerNode AutoExposureControlPriority::quickSpinEnumerationNode BalanceWhiteAutoLowerLimit::quickSpinFloatNode BalanceWhiteAutoDamping::quickSpinFloatNode AasRoiHeight::quickSpinIntegerNode AutoExposureGreyValueUpperLimit::quickSpinFloatNode AutoExposureTargetGreyValue::quickSpinFloatNode AutoExposureGainLowerLimit::quickSpinFloatNode AutoExposureGreyValueLowerLimit::quickSpinFloatNode AutoExposureMeteringMode::quickSpinEnumerationNode AutoExposureExposureTimeUpperLimit::quickSpinFloatNode AutoExposureGainUpperLimit::quickSpinFloatNode AutoExposureControlLoopDamping::quickSpinFloatNode AutoExposureEVCompensation::quickSpinFloatNode AutoExposureExposureTimeLowerLimit::quickSpinFloatNode BalanceWhiteAutoProfile::quickSpinEnumerationNode AutoAlgorithmSelector::quickSpinEnumerationNode AutoExposureTargetGreyValueAuto::quickSpinEnumerationNode AasRoiEnable::quickSpinBooleanNode AutoExposureLightingMode::quickSpinEnumerationNode AasRoiWidth::quickSpinIntegerNode BalanceWhiteAutoUpperLimit::quickSpinFloatNode LinkErrorCount::quickSpinIntegerNode GevCurrentIPConfigurationDHCP::quickSpinBooleanNode GevInterfaceSelector::quickSpinIntegerNode GevSCPD::quickSpinIntegerNode GevTimestampTickFrequency::quickSpinIntegerNode GevSCPSPacketSize::quickSpinIntegerNode GevCurrentDefaultGateway::quickSpinIntegerNode GevSCCFGUnconditionalStreaming::quickSpinBooleanNode GevMCTT::quickSpinIntegerNode GevSCPSDoNotFragment::quickSpinBooleanNode GevCurrentSubnetMask::quickSpinIntegerNode GevStreamChannelSelector::quickSpinIntegerNode GevCurrentIPAddress::quickSpinIntegerNode GevMCSP::quickSpinIntegerNode GevGVCPPendingTimeout::quickSpinIntegerNode GevIEEE1588Status::quickSpinEnumerationNode GevFirstURL::quickSpinStringNode GevMACAddress::quickSpinIntegerNode GevPersistentSubnetMask::quickSpinIntegerNode GevMCPHostPort::quickSpinIntegerNode GevSCPHostPort::quickSpinIntegerNode GevGVCPPendingAck::quickSpinBooleanNode GevSCPInterfaceIndex::quickSpinIntegerNode GevSupportedOption::quickSpinBooleanNode GevIEEE1588Mode::quickSpinEnumerationNode GevCurrentIPConfigurationLLA::quickSpinBooleanNode GevSCSP::quickSpinIntegerNode GevIEEE1588::quickSpinBooleanNode GevSCCFGExtendedChunkData::quickSpinBooleanNode GevPersistentIPAddress::quickSpinIntegerNode GevCurrentIPConfigurationPersistentIP::quickSpinBooleanNode GevIEEE1588ClockAccuracy::quickSpinEnumerationNode GevHeartbeatTimeout::quickSpinIntegerNode GevPersistentDefaultGateway::quickSpinIntegerNode GevCCP::quickSpinEnumerationNode GevMCDA::quickSpinIntegerNode GevSCDA::quickSpinIntegerNode GevSCPDirection::quickSpinIntegerNode GevSCPSFireTestPacket::quickSpinBooleanNode GevSecondURL::quickSpinStringNode GevSupportedOptionSelector::quickSpinEnumerationNode GevGVCPHeartbeatDisable::quickSpinBooleanNode GevMCRC::quickSpinIntegerNode GevSCPSBigEndian::quickSpinBooleanNode GevNumberOfInterfaces::quickSpinIntegerNode TLParamsLocked::quickSpinIntegerNode PayloadSize::quickSpinIntegerNode PacketResendRequestCount::quickSpinIntegerNode SharpeningEnable::quickSpinBooleanNode BlackLevelSelector::quickSpinEnumerationNode GammaEnable::quickSpinBooleanNode SharpeningAuto::quickSpinBooleanNode BlackLevelClampingEnable::quickSpinBooleanNode BalanceRatio::quickSpinFloatNode BalanceWhiteAuto::quickSpinEnumerationNode SharpeningThreshold::quickSpinFloatNode GainAuto::quickSpinEnumerationNode Sharpening::quickSpinFloatNode Gain::quickSpinFloatNode BalanceRatioSelector::quickSpinEnumerationNode GainSelector::quickSpinEnumerationNode BlackLevel::quickSpinFloatNode BlackLevelRaw::quickSpinIntegerNode Gamma::quickSpinFloatNode DefectTableIndex::quickSpinIntegerNode DefectTableFactoryRestore::quickSpinCommandNode DefectTableCoordinateY::quickSpinIntegerNode DefectTableSave::quickSpinCommandNode DefectCorrectionMode::quickSpinEnumerationNode DefectTableCoordinateX::quickSpinIntegerNode DefectTablePixelCount::quickSpinIntegerNode DefectCorrectStaticEnable::quickSpinBooleanNode DefectTableApply::quickSpinCommandNode UserSetFeatureEnable::quickSpinBooleanNode UserSetSave::quickSpinCommandNode UserSetSelector::quickSpinEnumerationNode UserSetLoad::quickSpinCommandNode UserSetDefault::quickSpinEnumerationNode SerialPortBaudRate::quickSpinEnumerationNode SerialPortDataBits::quickSpinIntegerNode SerialPortParity::quickSpinEnumerationNode SerialTransmitQueueMaxCharacterCount::quickSpinIntegerNode SerialReceiveQueueCurrentCharacterCount::quickSpinIntegerNode SerialPortSelector::quickSpinEnumerationNode SerialPortStopBits::quickSpinEnumerationNode SerialReceiveQueueClear::quickSpinCommandNode SerialReceiveFramingErrorCount::quickSpinIntegerNode SerialTransmitQueueCurrentCharacterCount::quickSpinIntegerNode SerialReceiveParityErrorCount::quickSpinIntegerNode SerialPortSource::quickSpinEnumerationNode SerialReceiveQueueMaxCharacterCount::quickSpinIntegerNode SequencerSetStart::quickSpinIntegerNode SequencerMode::quickSpinEnumerationNode SequencerConfigurationValid::quickSpinEnumerationNode SequencerSetValid::quickSpinEnumerationNode SequencerSetSelector::quickSpinIntegerNode SequencerTriggerActivation::quickSpinEnumerationNode SequencerConfigurationMode::quickSpinEnumerationNode SequencerSetSave::quickSpinCommandNode SequencerTriggerSource::quickSpinEnumerationNode SequencerSetActive::quickSpinIntegerNode SequencerSetNext::quickSpinIntegerNode SequencerSetLoad::quickSpinCommandNode SequencerPathSelector::quickSpinIntegerNode SequencerFeatureEnable::quickSpinBooleanNode TransferBlockCount::quickSpinIntegerNode TransferStart::quickSpinCommandNode TransferQueueMaxBlockCount::quickSpinIntegerNode TransferQueueCurrentBlockCount::quickSpinIntegerNode TransferQueueMode::quickSpinEnumerationNode TransferOperationMode::quickSpinEnumerationNode TransferStop::quickSpinCommandNode TransferQueueOverflowCount::quickSpinIntegerNode TransferControlMode::quickSpinEnumerationNode ChunkBlackLevel::quickSpinFloatNode ChunkFrameID::quickSpinIntegerNode ChunkSerialData::quickSpinStringNode ChunkExposureTime::quickSpinFloatNode ChunkSerialReceiveOverflow::quickSpinBooleanNode ChunkTimestamp::quickSpinIntegerNode ChunkModeActive::quickSpinBooleanNode ChunkExposureEndLineStatusAll::quickSpinIntegerNode ChunkGainSelector::quickSpinEnumerationNode ChunkSelector::quickSpinEnumerationNode ChunkBlackLevelSelector::quickSpinEnumerationNode ChunkWidth::quickSpinIntegerNode ChunkImage::quickSpinIntegerNode ChunkHeight::quickSpinIntegerNode ChunkPixelFormat::quickSpinEnumerationNode ChunkGain::quickSpinFloatNode ChunkSequencerSetActive::quickSpinIntegerNode ChunkCRC::quickSpinIntegerNode ChunkOffsetX::quickSpinIntegerNode ChunkOffsetY::quickSpinIntegerNode ChunkEnable::quickSpinBooleanNode ChunkSerialDataLength::quickSpinIntegerNode FileAccessOffset::quickSpinIntegerNode FileAccessLength::quickSpinIntegerNode FileOperationStatus::quickSpinEnumerationNode FileOperationExecute::quickSpinCommandNode FileOpenMode::quickSpinEnumerationNode FileOperationResult::quickSpinIntegerNode FileOperationSelector::quickSpinEnumerationNode FileSelector::quickSpinEnumerationNode FileSize::quickSpinIntegerNode BinningSelector::quickSpinEnumerationNode PixelDynamicRangeMin::quickSpinIntegerNode PixelDynamicRangeMax::quickSpinIntegerNode OffsetY::quickSpinIntegerNode BinningHorizontal::quickSpinIntegerNode Width::quickSpinIntegerNode TestPatternGeneratorSelector::quickSpinEnumerationNode CompressionRatio::quickSpinFloatNode ReverseX::quickSpinBooleanNode ReverseY::quickSpinBooleanNode TestPattern::quickSpinEnumerationNode PixelColorFilter::quickSpinEnumerationNode WidthMax::quickSpinIntegerNode AdcBitDepth::quickSpinEnumerationNode BinningVertical::quickSpinIntegerNode DecimationHorizontalMode::quickSpinEnumerationNode BinningVerticalMode::quickSpinEnumerationNode OffsetX::quickSpinIntegerNode HeightMax::quickSpinIntegerNode DecimationHorizontal::quickSpinIntegerNode PixelSize::quickSpinEnumerationNode SensorHeight::quickSpinIntegerNode DecimationSelector::quickSpinEnumerationNode IspEnable::quickSpinBooleanNode AdaptiveCompressionEnable::quickSpinBooleanNode ImageCompressionMode::quickSpinEnumerationNode DecimationVertical::quickSpinIntegerNode Height::quickSpinIntegerNode BinningHorizontalMode::quickSpinEnumerationNode PixelFormat::quickSpinEnumerationNode SensorWidth::quickSpinIntegerNode DecimationVerticalMode::quickSpinEnumerationNode TestEventGenerate::quickSpinCommandNode TriggerEventTest::quickSpinCommandNode GuiXmlManifestAddress::quickSpinIntegerNode Test0001::quickSpinIntegerNode V3_3Enable::quickSpinBooleanNode LineMode::quickSpinEnumerationNode LineSource::quickSpinEnumerationNode LineInputFilterSelector::quickSpinEnumerationNode UserOutputValue::quickSpinBooleanNode UserOutputValueAll::quickSpinIntegerNode UserOutputSelector::quickSpinEnumerationNode LineStatus::quickSpinBooleanNode LineFormat::quickSpinEnumerationNode LineStatusAll::quickSpinIntegerNode LineSelector::quickSpinEnumerationNode ExposureActiveMode::quickSpinEnumerationNode LineInverter::quickSpinBooleanNode LineFilterWidth::quickSpinFloatNode CounterTriggerActivation::quickSpinEnumerationNode CounterValue::quickSpinIntegerNode CounterSelector::quickSpinEnumerationNode CounterValueAtReset::quickSpinIntegerNode CounterStatus::quickSpinEnumerationNode CounterTriggerSource::quickSpinEnumerationNode CounterDelay::quickSpinIntegerNode CounterResetSource::quickSpinEnumerationNode CounterEventSource::quickSpinEnumerationNode CounterEventActivation::quickSpinEnumerationNode CounterDuration::quickSpinIntegerNode CounterResetActivation::quickSpinEnumerationNode DeviceType::quickSpinEnumerationNode DeviceFamilyName::quickSpinStringNode DeviceSFNCVersionMajor::quickSpinIntegerNode DeviceSFNCVersionMinor::quickSpinIntegerNode DeviceSFNCVersionSubMinor::quickSpinIntegerNode DeviceManifestEntrySelector::quickSpinIntegerNode DeviceManifestXMLMajorVersion::quickSpinIntegerNode DeviceManifestXMLMinorVersion::quickSpinIntegerNode DeviceManifestXMLSubMinorVersion::quickSpinIntegerNode DeviceManifestSchemaMajorVersion::quickSpinIntegerNode DeviceManifestSchemaMinorVersion::quickSpinIntegerNode DeviceManifestPrimaryURL::quickSpinStringNode DeviceManifestSecondaryURL::quickSpinStringNode DeviceTLVersionSubMinor::quickSpinIntegerNode DeviceGenCPVersionMajor::quickSpinIntegerNode DeviceGenCPVersionMinor::quickSpinIntegerNode DeviceConnectionSelector::quickSpinIntegerNode DeviceConnectionSpeed::quickSpinIntegerNode DeviceConnectionStatus::quickSpinEnumerationNode DeviceLinkSelector::quickSpinIntegerNode DeviceLinkThroughputLimitMode::quickSpinEnumerationNode DeviceLinkConnectionCount::quickSpinIntegerNode DeviceLinkHeartbeatMode::quickSpinEnumerationNode DeviceLinkHeartbeatTimeout::quickSpinFloatNode DeviceLinkCommandTimeout::quickSpinFloatNode DeviceStreamChannelSelector::quickSpinIntegerNode DeviceStreamChannelType::quickSpinEnumerationNode DeviceStreamChannelLink::quickSpinIntegerNode DeviceStreamChannelEndianness::quickSpinEnumerationNode DeviceStreamChannelPacketSize::quickSpinIntegerNode DeviceFeaturePersistenceStart::quickSpinCommandNode DeviceFeaturePersistenceEnd::quickSpinCommandNode DeviceRegistersStreamingStart::quickSpinCommandNode DeviceRegistersStreamingEnd::quickSpinCommandNode DeviceRegistersCheck::quickSpinCommandNode DeviceRegistersValid::quickSpinBooleanNode DeviceClockSelector::quickSpinEnumerationNode DeviceClockFrequency::quickSpinFloatNode DeviceSerialPortSelector::quickSpinEnumerationNode DeviceSerialPortBaudRate::quickSpinEnumerationNode Timestamp::quickSpinIntegerNode SensorTaps::quickSpinEnumerationNode SensorDigitizationTaps::quickSpinEnumerationNode RegionSelector::quickSpinEnumerationNode RegionMode::quickSpinEnumerationNode RegionDestination::quickSpinEnumerationNode ImageComponentSelector::quickSpinEnumerationNode ImageComponentEnable::quickSpinBooleanNode LinePitch::quickSpinIntegerNode PixelFormatInfoSelector::quickSpinEnumerationNode PixelFormatInfoID::quickSpinIntegerNode Deinterlacing::quickSpinEnumerationNode ImageCompressionRateOption::quickSpinEnumerationNode ImageCompressionQuality::quickSpinIntegerNode ImageCompressionBitrate::quickSpinFloatNode ImageCompressionJPEGFormatOption::quickSpinEnumerationNode AcquisitionAbort::quickSpinCommandNode AcquisitionArm::quickSpinCommandNode AcquisitionStatusSelector::quickSpinEnumerationNode AcquisitionStatus::quickSpinBooleanNode TriggerDivider::quickSpinIntegerNode TriggerMultiplier::quickSpinIntegerNode ExposureTimeMode::quickSpinEnumerationNode ExposureTimeSelector::quickSpinEnumerationNode GainAutoBalance::quickSpinEnumerationNode BlackLevelAuto::quickSpinEnumerationNode BlackLevelAutoBalance::quickSpinEnumerationNode WhiteClipSelector::quickSpinEnumerationNode WhiteClip::quickSpinFloatNode LUTValueAll::quickSpinRegisterNode UserOutputValueAllMask::quickSpinIntegerNode CounterReset::quickSpinCommandNode TimerSelector::quickSpinEnumerationNode TimerDuration::quickSpinFloatNode TimerDelay::quickSpinFloatNode TimerReset::quickSpinCommandNode TimerValue::quickSpinFloatNode TimerStatus::quickSpinEnumerationNode TimerTriggerSource::quickSpinEnumerationNode TimerTriggerActivation::quickSpinEnumerationNode EncoderSelector::quickSpinEnumerationNode EncoderSourceA::quickSpinEnumerationNode EncoderSourceB::quickSpinEnumerationNode EncoderMode::quickSpinEnumerationNode EncoderDivider::quickSpinIntegerNode EncoderOutputMode::quickSpinEnumerationNode EncoderStatus::quickSpinEnumerationNode EncoderTimeout::quickSpinFloatNode EncoderResetSource::quickSpinEnumerationNode EncoderResetActivation::quickSpinEnumerationNode EncoderReset::quickSpinCommandNode EncoderValue::quickSpinIntegerNode EncoderValueAtReset::quickSpinIntegerNode SoftwareSignalSelector::quickSpinEnumerationNode SoftwareSignalPulse::quickSpinCommandNode ActionUnconditionalMode::quickSpinEnumerationNode ActionDeviceKey::quickSpinIntegerNode ActionQueueSize::quickSpinIntegerNode ActionSelector::quickSpinIntegerNode ActionGroupMask::quickSpinIntegerNode ActionGroupKey::quickSpinIntegerNode EventAcquisitionTrigger::quickSpinIntegerNode EventAcquisitionTriggerTimestamp::quickSpinIntegerNode EventAcquisitionTriggerFrameID::quickSpinIntegerNode EventAcquisitionStart::quickSpinIntegerNode EventAcquisitionStartTimestamp::quickSpinIntegerNode EventAcquisitionStartFrameID::quickSpinIntegerNode EventAcquisitionEnd::quickSpinIntegerNode EventAcquisitionEndTimestamp::quickSpinIntegerNode EventAcquisitionEndFrameID::quickSpinIntegerNode EventAcquisitionTransferStart::quickSpinIntegerNode EventAcquisitionTransferStartTimestamp::quickSpinIntegerNode EventAcquisitionTransferStartFrameID::quickSpinIntegerNode EventAcquisitionTransferEnd::quickSpinIntegerNode EventAcquisitionTransferEndTimestamp::quickSpinIntegerNode EventAcquisitionTransferEndFrameID::quickSpinIntegerNode EventAcquisitionError::quickSpinIntegerNode EventAcquisitionErrorTimestamp::quickSpinIntegerNode EventAcquisitionErrorFrameID::quickSpinIntegerNode EventFrameTrigger::quickSpinIntegerNode EventFrameTriggerTimestamp::quickSpinIntegerNode EventFrameTriggerFrameID::quickSpinIntegerNode EventFrameStart::quickSpinIntegerNode EventFrameStartTimestamp::quickSpinIntegerNode EventFrameStartFrameID::quickSpinIntegerNode EventFrameEnd::quickSpinIntegerNode EventFrameEndTimestamp::quickSpinIntegerNode EventFrameEndFrameID::quickSpinIntegerNode EventFrameBurstStart::quickSpinIntegerNode EventFrameBurstStartTimestamp::quickSpinIntegerNode EventFrameBurstStartFrameID::quickSpinIntegerNode EventFrameBurstEnd::quickSpinIntegerNode EventFrameBurstEndTimestamp::quickSpinIntegerNode EventFrameBurstEndFrameID::quickSpinIntegerNode EventFrameTransferStart::quickSpinIntegerNode EventFrameTransferStartTimestamp::quickSpinIntegerNode EventFrameTransferStartFrameID::quickSpinIntegerNode EventFrameTransferEnd::quickSpinIntegerNode EventFrameTransferEndTimestamp::quickSpinIntegerNode EventFrameTransferEndFrameID::quickSpinIntegerNode EventExposureStart::quickSpinIntegerNode EventExposureStartTimestamp::quickSpinIntegerNode EventExposureStartFrameID::quickSpinIntegerNode EventStream0TransferStart::quickSpinIntegerNode EventStream0TransferStartTimestamp::quickSpinIntegerNode EventStream0TransferStartFrameID::quickSpinIntegerNode EventStream0TransferEnd::quickSpinIntegerNode EventStream0TransferEndTimestamp::quickSpinIntegerNode EventStream0TransferEndFrameID::quickSpinIntegerNode EventStream0TransferPause::quickSpinIntegerNode EventStream0TransferPauseTimestamp::quickSpinIntegerNode EventStream0TransferPauseFrameID::quickSpinIntegerNode EventStream0TransferResume::quickSpinIntegerNode EventStream0TransferResumeTimestamp::quickSpinIntegerNode EventStream0TransferResumeFrameID::quickSpinIntegerNode EventStream0TransferBlockStart::quickSpinIntegerNode EventStream0TransferBlockStartTimestamp::quickSpinIntegerNode EventStream0TransferBlockStartFrameID::quickSpinIntegerNode EventStream0TransferBlockEnd::quickSpinIntegerNode EventStream0TransferBlockEndTimestamp::quickSpinIntegerNode EventStream0TransferBlockEndFrameID::quickSpinIntegerNode EventStream0TransferBlockTrigger::quickSpinIntegerNode EventStream0TransferBlockTriggerTimestamp::quickSpinIntegerNode EventStream0TransferBlockTriggerFrameID::quickSpinIntegerNode EventStream0TransferBurstStart::quickSpinIntegerNode EventStream0TransferBurstStartTimestamp::quickSpinIntegerNode EventStream0TransferBurstStartFrameID::quickSpinIntegerNode EventStream0TransferBurstEnd::quickSpinIntegerNode EventStream0TransferBurstEndTimestamp::quickSpinIntegerNode EventStream0TransferBurstEndFrameID::quickSpinIntegerNode EventStream0TransferOverflow::quickSpinIntegerNode EventStream0TransferOverflowTimestamp::quickSpinIntegerNode EventStream0TransferOverflowFrameID::quickSpinIntegerNode EventSequencerSetChange::quickSpinIntegerNode EventSequencerSetChangeTimestamp::quickSpinIntegerNode EventSequencerSetChangeFrameID::quickSpinIntegerNode EventCounter0Start::quickSpinIntegerNode EventCounter0StartTimestamp::quickSpinIntegerNode EventCounter0StartFrameID::quickSpinIntegerNode EventCounter1Start::quickSpinIntegerNode EventCounter1StartTimestamp::quickSpinIntegerNode EventCounter1StartFrameID::quickSpinIntegerNode EventCounter0End::quickSpinIntegerNode EventCounter0EndTimestamp::quickSpinIntegerNode EventCounter0EndFrameID::quickSpinIntegerNode EventCounter1End::quickSpinIntegerNode EventCounter1EndTimestamp::quickSpinIntegerNode EventCounter1EndFrameID::quickSpinIntegerNode EventTimer0Start::quickSpinIntegerNode EventTimer0StartTimestamp::quickSpinIntegerNode EventTimer0StartFrameID::quickSpinIntegerNode EventTimer1Start::quickSpinIntegerNode EventTimer1StartTimestamp::quickSpinIntegerNode EventTimer1StartFrameID::quickSpinIntegerNode EventTimer0End::quickSpinIntegerNode EventTimer0EndTimestamp::quickSpinIntegerNode EventTimer0EndFrameID::quickSpinIntegerNode EventTimer1End::quickSpinIntegerNode EventTimer1EndTimestamp::quickSpinIntegerNode EventTimer1EndFrameID::quickSpinIntegerNode EventEncoder0Stopped::quickSpinIntegerNode EventEncoder0StoppedTimestamp::quickSpinIntegerNode EventEncoder0StoppedFrameID::quickSpinIntegerNode EventEncoder1Stopped::quickSpinIntegerNode EventEncoder1StoppedTimestamp::quickSpinIntegerNode EventEncoder1StoppedFrameID::quickSpinIntegerNode EventEncoder0Restarted::quickSpinIntegerNode EventEncoder0RestartedTimestamp::quickSpinIntegerNode EventEncoder0RestartedFrameID::quickSpinIntegerNode EventEncoder1Restarted::quickSpinIntegerNode EventEncoder1RestartedTimestamp::quickSpinIntegerNode EventEncoder1RestartedFrameID::quickSpinIntegerNode EventLine0RisingEdge::quickSpinIntegerNode EventLine0RisingEdgeTimestamp::quickSpinIntegerNode EventLine0RisingEdgeFrameID::quickSpinIntegerNode EventLine1RisingEdge::quickSpinIntegerNode EventLine1RisingEdgeTimestamp::quickSpinIntegerNode EventLine1RisingEdgeFrameID::quickSpinIntegerNode EventLine0FallingEdge::quickSpinIntegerNode EventLine0FallingEdgeTimestamp::quickSpinIntegerNode EventLine0FallingEdgeFrameID::quickSpinIntegerNode EventLine1FallingEdge::quickSpinIntegerNode EventLine1FallingEdgeTimestamp::quickSpinIntegerNode EventLine1FallingEdgeFrameID::quickSpinIntegerNode EventLine0AnyEdge::quickSpinIntegerNode EventLine0AnyEdgeTimestamp::quickSpinIntegerNode EventLine0AnyEdgeFrameID::quickSpinIntegerNode EventLine1AnyEdge::quickSpinIntegerNode EventLine1AnyEdgeTimestamp::quickSpinIntegerNode EventLine1AnyEdgeFrameID::quickSpinIntegerNode EventLinkTrigger0::quickSpinIntegerNode EventLinkTrigger0Timestamp::quickSpinIntegerNode EventLinkTrigger0FrameID::quickSpinIntegerNode EventLinkTrigger1::quickSpinIntegerNode EventLinkTrigger1Timestamp::quickSpinIntegerNode EventLinkTrigger1FrameID::quickSpinIntegerNode EventActionLate::quickSpinIntegerNode EventActionLateTimestamp::quickSpinIntegerNode EventActionLateFrameID::quickSpinIntegerNode EventLinkSpeedChange::quickSpinIntegerNode EventLinkSpeedChangeTimestamp::quickSpinIntegerNode EventLinkSpeedChangeFrameID::quickSpinIntegerNode FileAccessBuffer::quickSpinRegisterNode SourceCount::quickSpinIntegerNode SourceSelector::quickSpinEnumerationNode TransferSelector::quickSpinEnumerationNode TransferBurstCount::quickSpinIntegerNode TransferAbort::quickSpinCommandNode TransferPause::quickSpinCommandNode TransferResume::quickSpinCommandNode TransferTriggerSelector::quickSpinEnumerationNode TransferTriggerMode::quickSpinEnumerationNode TransferTriggerSource::quickSpinEnumerationNode TransferTriggerActivation::quickSpinEnumerationNode TransferStatusSelector::quickSpinEnumerationNode TransferStatus::quickSpinBooleanNode TransferComponentSelector::quickSpinEnumerationNode TransferStreamChannel::quickSpinIntegerNode Scan3dDistanceUnit::quickSpinEnumerationNode Scan3dCoordinateSystem::quickSpinEnumerationNode Scan3dOutputMode::quickSpinEnumerationNode Scan3dCoordinateSystemReference::quickSpinEnumerationNode Scan3dCoordinateSelector::quickSpinEnumerationNode Scan3dCoordinateScale::quickSpinFloatNode Scan3dCoordinateOffset::quickSpinFloatNode Scan3dInvalidDataFlag::quickSpinBooleanNode Scan3dInvalidDataValue::quickSpinFloatNode Scan3dAxisMin::quickSpinFloatNode Scan3dAxisMax::quickSpinFloatNode Scan3dCoordinateTransformSelector::quickSpinEnumerationNode Scan3dTransformValue::quickSpinFloatNode Scan3dCoordinateReferenceSelector::quickSpinEnumerationNode Scan3dCoordinateReferenceValue::quickSpinFloatNode ChunkPartSelector::quickSpinIntegerNode ChunkImageComponent::quickSpinEnumerationNode ChunkPixelDynamicRangeMin::quickSpinIntegerNode ChunkPixelDynamicRangeMax::quickSpinIntegerNode ChunkTimestampLatchValue::quickSpinIntegerNode ChunkLineStatusAll::quickSpinIntegerNode ChunkCounterSelector::quickSpinEnumerationNode ChunkCounterValue::quickSpinIntegerNode ChunkTimerSelector::quickSpinEnumerationNode ChunkTimerValue::quickSpinFloatNode ChunkEncoderSelector::quickSpinEnumerationNode ChunkScanLineSelector::quickSpinIntegerNode ChunkEncoderValue::quickSpinIntegerNode ChunkEncoderStatus::quickSpinEnumerationNode ChunkExposureTimeSelector::quickSpinEnumerationNode ChunkLinePitch::quickSpinIntegerNode ChunkSourceID::quickSpinEnumerationNode ChunkRegionID::quickSpinEnumerationNode ChunkTransferBlockID::quickSpinIntegerNode ChunkTransferStreamID::quickSpinEnumerationNode ChunkTransferQueueCurrentBlockCount::quickSpinIntegerNode ChunkStreamChannelID::quickSpinIntegerNode ChunkScan3dDistanceUnit::quickSpinEnumerationNode ChunkScan3dOutputMode::quickSpinEnumerationNode ChunkScan3dCoordinateSystem::quickSpinEnumerationNode ChunkScan3dCoordinateSystemReference::quickSpinEnumerationNode ChunkScan3dCoordinateSelector::quickSpinEnumerationNode ChunkScan3dCoordinateScale::quickSpinFloatNode ChunkScan3dCoordinateOffset::quickSpinFloatNode ChunkScan3dInvalidDataFlag::quickSpinBooleanNode ChunkScan3dInvalidDataValue::quickSpinFloatNode ChunkScan3dAxisMin::quickSpinFloatNode ChunkScan3dAxisMax::quickSpinFloatNode ChunkScan3dCoordinateTransformSelector::quickSpinEnumerationNode ChunkScan3dTransformValue::quickSpinFloatNode ChunkScan3dCoordinateReferenceSelector::quickSpinEnumerationNode ChunkScan3dCoordinateReferenceValue::quickSpinFloatNode TestPendingAck::quickSpinIntegerNode DeviceTapGeometry::quickSpinEnumerationNode GevPhysicalLinkConfiguration::quickSpinEnumerationNode GevCurrentPhysicalLinkConfiguration::quickSpinEnumerationNode GevActiveLinkCount::quickSpinIntegerNode GevPAUSEFrameReception::quickSpinBooleanNode GevPAUSEFrameTransmission::quickSpinBooleanNode GevIPConfigurationStatus::quickSpinEnumerationNode GevDiscoveryAckDelay::quickSpinIntegerNode GevGVCPExtendedStatusCodesSelector::quickSpinEnumerationNode GevGVCPExtendedStatusCodes::quickSpinBooleanNode GevPrimaryApplicationSwitchoverKey::quickSpinIntegerNode GevGVSPExtendedIDMode::quickSpinEnumerationNode GevPrimaryApplicationSocket::quickSpinIntegerNode GevPrimaryApplicationIPAddress::quickSpinIntegerNode GevSCCFGPacketResendDestination::quickSpinBooleanNode GevSCCFGAllInTransmission::quickSpinBooleanNode GevSCZoneCount::quickSpinIntegerNode GevSCZoneDirectionAll::quickSpinIntegerNode GevSCZoneConfigurationLock::quickSpinBooleanNode aPAUSEMACCtrlFramesTransmitted::quickSpinIntegerNode aPAUSEMACCtrlFramesReceived::quickSpinIntegerNode ClConfiguration::quickSpinEnumerationNode ClTimeSlotsCount::quickSpinEnumerationNode CxpLinkConfigurationStatus::quickSpinEnumerationNode CxpLinkConfigurationPreferred::quickSpinEnumerationNode CxpLinkConfiguration::quickSpinEnumerationNode CxpConnectionSelector::quickSpinIntegerNode CxpConnectionTestMode::quickSpinEnumerationNode CxpConnectionTestErrorCount::quickSpinIntegerNode CxpConnectionTestPacketCount::quickSpinIntegerNode CxpPoCxpAuto::quickSpinCommandNode CxpPoCxpTurnOff::quickSpinCommandNode CxpPoCxpTripReset::quickSpinCommandNode CxpPoCxpStatus::quickSpinEnumerationNode ChunkInferenceResult::quickSpinIntegerNode ChunkInferenceConfidence::quickSpinFloatNode end const quickSpin = _quickSpin const bool8_t = UInt8 const spinSystem = Ptr{Cvoid} const spinInterfaceList = Ptr{Cvoid} const spinInterface = Ptr{Cvoid} const spinCameraList = Ptr{Cvoid} const spinCamera = Ptr{Cvoid} const spinImage = Ptr{Cvoid} const spinImageStatistics = Ptr{Cvoid} const spinDeviceEvent = Ptr{Cvoid} const spinImageEvent = Ptr{Cvoid} const spinArrivalEvent = Ptr{Cvoid} const spinRemovalEvent = Ptr{Cvoid} const spinInterfaceEvent = Ptr{Cvoid} const spinLogEvent = Ptr{Cvoid} const spinLogEventData = Ptr{Cvoid} const spinDeviceEventData = Ptr{Cvoid} const spinAVIRecorder = Ptr{Cvoid} const spinVideo = Ptr{Cvoid} const spinDeviceEventFunction = Ptr{Cvoid} const spinImageEventFunction = Ptr{Cvoid} const spinArrivalEventFunction = Ptr{Cvoid} const spinRemovalEventFunction = Ptr{Cvoid} const spinLogEventFunction = Ptr{Cvoid} @cenum(_spinError{Int32}, SPINNAKER_ERR_SUCCESS = 0, SPINNAKER_ERR_ERROR = -1001, SPINNAKER_ERR_NOT_INITIALIZED = -1002, SPINNAKER_ERR_NOT_IMPLEMENTED = -1003, SPINNAKER_ERR_RESOURCE_IN_USE = -1004, SPINNAKER_ERR_ACCESS_DENIED = -1005, SPINNAKER_ERR_INVALID_HANDLE = -1006, SPINNAKER_ERR_INVALID_ID = -1007, SPINNAKER_ERR_NO_DATA = -1008, SPINNAKER_ERR_INVALID_PARAMETER = -1009, SPINNAKER_ERR_IO = -1010, SPINNAKER_ERR_TIMEOUT = -1011, SPINNAKER_ERR_ABORT = -1012, SPINNAKER_ERR_INVALID_BUFFER = -1013, SPINNAKER_ERR_NOT_AVAILABLE = -1014, SPINNAKER_ERR_INVALID_ADDRESS = -1015, SPINNAKER_ERR_BUFFER_TOO_SMALL = -1016, SPINNAKER_ERR_INVALID_INDEX = -1017, SPINNAKER_ERR_PARSING_CHUNK_DATA = -1018, SPINNAKER_ERR_INVALID_VALUE = -1019, SPINNAKER_ERR_RESOURCE_EXHAUSTED = -1020, SPINNAKER_ERR_OUT_OF_MEMORY = -1021, SPINNAKER_ERR_BUSY = -1022, GENICAM_ERR_INVALID_ARGUMENT = -2001, GENICAM_ERR_OUT_OF_RANGE = -2002, GENICAM_ERR_PROPERTY = -2003, GENICAM_ERR_RUN_TIME = -2004, GENICAM_ERR_LOGICAL = -2005, GENICAM_ERR_ACCESS = -2006, GENICAM_ERR_TIMEOUT = -2007, GENICAM_ERR_DYNAMIC_CAST = -2008, GENICAM_ERR_GENERIC = -2009, GENICAM_ERR_BAD_ALLOCATION = -2010, SPINNAKER_ERR_IM_CONVERT = -3001, SPINNAKER_ERR_IM_COPY = -3002, SPINNAKER_ERR_IM_MALLOC = -3003, SPINNAKER_ERR_IM_NOT_SUPPORTED = -3004, SPINNAKER_ERR_IM_HISTOGRAM_RANGE = -3005, SPINNAKER_ERR_IM_HISTOGRAM_MEAN = -3006, SPINNAKER_ERR_IM_MIN_MAX = -3007, SPINNAKER_ERR_IM_COLOR_CONVERSION = -3008, SPINNAKER_ERR_CUSTOM_ID = -10000, ) const spinError = _spinError @cenum(_spinColorProcessingAlgorithm, DEFAULT = 0, NO_COLOR_PROCESSING = 1, NEAREST_NEIGHBOR = 2, EDGE_SENSING = 3, HQ_LINEAR = 4, RIGOROUS = 5, IPP = 6, DIRECTIONAL_FILTER = 7, WEIGHTED_DIRECTIONAL_FILTER = 8, ) const spinColorProcessingAlgorithm = _spinColorProcessingAlgorithm @cenum(_spinStatisticsChannel, GREY = 0, RED = 1, GREEN = 2, BLUE = 3, HUE = 4, SATURATION = 5, LIGHTNESS = 6, NUM_STATISTICS_CHANNELS = 7, ) const spinStatisticsChannel = _spinStatisticsChannel @cenum(_spinImageFileFormat{Int32}, FROM_FILE_EXT = -1, PGM = 0, PPM = 1, BMP = 2, JPEG = 3, JPEG2000 = 4, TIFF = 5, PNG = 6, RAW = 7, IMAGE_FILE_FORMAT_FORCE_32BITS = 2147483647, ) const spinImageFileFormat = _spinImageFileFormat @cenum(_spinPixelFormatNamespaceID, SPINNAKER_PIXELFORMAT_NAMESPACE_UNKNOWN = 0, SPINNAKER_PIXELFORMAT_NAMESPACE_GEV = 1, SPINNAKER_PIXELFORMAT_NAMESPACE_IIDC = 2, SPINNAKER_PIXELFORMAT_NAMESPACE_PFNC_16BIT = 3, SPINNAKER_PIXELFORMAT_NAMESPACE_PFNC_32BIT = 4, SPINNAKER_PIXELFORMAT_NAMESPACE_CUSTOM_ID = 1000, ) const spinPixelFormatNamespaceID = _spinPixelFormatNamespaceID @cenum(_spinImageStatus{Int32}, IMAGE_UNKNOWN_ERROR = -1, IMAGE_NO_ERROR = 0, IMAGE_CRC_CHECK_FAILED = 1, IMAGE_DATA_OVERFLOW = 2, IMAGE_MISSING_PACKETS = 3, IMAGE_LEADER_BUFFER_SIZE_INCONSISTENT = 4, IMAGE_TRAILER_BUFFER_SIZE_INCONSISTENT = 5, IMAGE_PACKETID_INCONSISTENT = 6, IMAGE_MISSING_LEADER = 7, IMAGE_MISSING_TRAILER = 8, IMAGE_DATA_INCOMPLETE = 9, IMAGE_INFO_INCONSISTENT = 10, IMAGE_CHUNK_DATA_INVALID = 11, IMAGE_NO_SYSTEM_RESOURCES = 12, ) const spinImageStatus = _spinImageStatus @cenum(_spinLogLevel{Int32}, LOG_LEVEL_OFF = -1, LOG_LEVEL_FATAL = 0, LOG_LEVEL_ALERT = 100, LOG_LEVEL_CRIT = 200, LOG_LEVEL_ERROR = 300, LOG_LEVEL_WARN = 400, LOG_LEVEL_NOTICE = 500, LOG_LEVEL_INFO = 600, LOG_LEVEL_DEBUG = 700, LOG_LEVEL_NOTSET = 800, ) const spinnakerLogLevel = _spinLogLevel @cenum(_spinPayloadTypeInfoIDs, PAYLOAD_TYPE_UNKNOWN = 0, PAYLOAD_TYPE_IMAGE = 1, PAYLOAD_TYPE_RAW_DATA = 2, PAYLOAD_TYPE_FILE = 3, PAYLOAD_TYPE_CHUNK_DATA = 4, PAYLOAD_TYPE_JPEG = 5, PAYLOAD_TYPE_JPEG2000 = 6, PAYLOAD_TYPE_H264 = 7, PAYLOAD_TYPE_CHUNK_ONLY = 8, PAYLOAD_TYPE_DEVICE_SPECIFIC = 9, PAYLOAD_TYPE_MULTI_PART = 10, PAYLOAD_TYPE_CUSTOM_ID = 1000, PAYLOAD_TYPE_EXTENDED_CHUNK = 1001, ) const spinPayloadTypeInfoIDs = _spinPayloadTypeInfoIDs struct _spinPNGOption interlaced::bool8_t compressionLevel::UInt32 reserved::NTuple{16, UInt32} end const spinPNGOption = _spinPNGOption struct _spinPPMOption binaryFile::bool8_t reserved::NTuple{16, UInt32} end const spinPPMOption = _spinPPMOption struct _spinPGMOption binaryFile::bool8_t reserved::NTuple{16, UInt32} end const spinPGMOption = _spinPGMOption @cenum(CompressionMethod, NONE = 1, PACKBITS = 2, DEFLATE = 3, ADOBE_DEFLATE = 4, CCITTFAX3 = 5, CCITTFAX4 = 6, LZW = 7, JPG = 8, ) const spinCompressionMethod = CompressionMethod struct _spinTIFFOption compression::spinCompressionMethod reserved::NTuple{16, UInt32} end const spinTIFFOption = _spinTIFFOption struct _spinJPEGOption progressive::bool8_t quality::UInt32 reserved::NTuple{16, UInt32} end const spinJPEGOption = _spinJPEGOption struct _spinJPG2Option quality::UInt32 reserved::NTuple{16, UInt32} end const spinJPG2Option = _spinJPG2Option struct _spinBMPOption indexedColor_8bit::bool8_t reserved::NTuple{16, UInt32} end const spinBMPOption = _spinBMPOption struct _spinMJPGOption frameRate::Cfloat quality::UInt32 reserved::NTuple{256, UInt32} end const spinMJPGOption = _spinMJPGOption struct _spinH264Option frameRate::Cfloat width::UInt32 height::UInt32 bitrate::UInt32 reserved::NTuple{256, UInt32} end const spinH264Option = _spinH264Option struct _spinAVIOption frameRate::Cfloat reserved::NTuple{256, UInt32} end const spinAVIOption = _spinAVIOption struct _spinLibraryVersion major::UInt32 minor::UInt32 type::UInt32 build::UInt32 end const spinLibraryVersion = _spinLibraryVersion @cenum(_actionCommandStatus, ACTION_COMMAND_STATUS_OK = 0, ACTION_COMMAND_STATUS_NO_REF_TIME = 32787, ACTION_COMMAND_STATUS_OVERFLOW = 32789, ACTION_COMMAND_STATUS_ACTION_LATE = 32790, ACTION_COMMAND_STATUS_ERROR = 36863, ) const actionCommandStatus = _actionCommandStatus struct _actionCommandResult DeviceAddress::UInt32 Status::actionCommandStatus end const actionCommandResult = _actionCommandResult const spinNodeMapHandle = Ptr{Cvoid} const spinNodeCallbackHandle = Ptr{Cvoid} const spinNodeCallbackFunction = Ptr{Cvoid} @cenum(_spinNodeType{Int32}, ValueNode = 0, BaseNode = 1, IntegerNode = 2, BooleanNode = 3, FloatNode = 4, CommandNode = 5, StringNode = 6, RegisterNode = 7, EnumerationNode = 8, EnumEntryNode = 9, CategoryNode = 10, PortNode = 11, UnknownNode = -1, ) const spinNodeType = _spinNodeType @cenum(_spinSign, Signed = 0, Unsigned = 1, _UndefinedSign = 2, ) const spinSign = _spinSign @cenum(_spinAccessMode, NI = 0, NA = 1, WO = 2, RO = 3, RW = 4, _UndefinedAccesMode = 5, _CycleDetectAccesMode = 6, ) const spinAccessMode = _spinAccessMode @cenum(_spinVisibility, Beginner = 0, Expert = 1, Guru = 2, Invisible = 3, _UndefinedVisibility = 99, ) const spinVisibility = _spinVisibility @cenum(_spinCachingMode, NoCache = 0, WriteThrough = 1, WriteAround = 2, _UndefinedCachingMode = 3, ) const spinCachingMode = _spinCachingMode @cenum(_spinRepresentation, Linear = 0, Logarithmic = 1, Boolean = 2, PureNumber = 3, HexNumber = 4, IPV4Address = 5, MACAddress = 6, _UndefinedRepresentation = 7, ) const spinRepresentation = _spinRepresentation @cenum(_spinEndianess, BigEndian = 0, LittleEndian = 1, _UndefinedEndian = 2, ) const spinEndianess = _spinEndianess @cenum(_spinNameSpace, Custom = 0, Standard = 1, _UndefinedNameSpace = 2, ) const spinNameSpace = _spinNameSpace @cenum(_spinStandardNameSpace, None = 0, GEV = 1, IIDC = 2, CL = 3, USB = 4, _UndefinedStandardNameSpace = 5, ) const spinStandardNameSpace = _spinStandardNameSpace @cenum(_spinYesNo, Yes = 1, No = 0, _UndefinedYesNo = 2, ) const spinYesNo = _spinYesNo @cenum(_spinSlope, Increasing = 0, Decreasing = 1, Varying = 2, Automatic = 3, _UndefinedESlope = 4, ) const spinSlope = _spinSlope @cenum(_spinXMLValidation, xvLoad = 1, xvCycles = 2, xvSFNC = 4, xvDefault = 0, xvAll = 4294967295, _UndefinedEXMLValidation = 134217728, ) const spinXMLValidation = _spinXMLValidation @cenum(_spinDisplayNotation, fnAutomatic = 0, fnFixed = 1, fnScientific = 2, _UndefinedEDisplayNotation = 3, ) const spinDisplayNotation = _spinDisplayNotation @cenum(_spinInterfaceType, intfIValue = 0, intfIBase = 1, intfIInteger = 2, intfIBoolean = 3, intfICommand = 4, intfIFloat = 5, intfIString = 6, intfIRegister = 7, intfICategory = 8, intfIEnumeration = 9, intfIEnumEntry = 10, intfIPort = 11, ) const spinInterfaceType = _spinInterfaceType @cenum(_spinLinkType, ctAllDependingNodes = 0, ctAllTerminalNodes = 1, ctInvalidators = 2, ctReadingChildren = 3, ctWritingChildren = 4, ctDependingChildren = 5, ) const spinLinkType = _spinLinkType @cenum(_spinIncMode, noIncrement = 0, fixedIncrement = 1, listIncrement = 2, ) const spinIncMode = _spinIncMode @cenum(_spinInputDirection, idFrom = 0, idTo = 1, idNone = 2, ) const spinInputDirection = _spinInputDirection # Skipping MacroDefinition: SPINC_IMPORT_EXPORT __attribute__ ( ( visibility ( "default" ) ) ) # Skipping MacroDefinition: EXTERN_C extern "C" # Skipping MacroDefinition: SPINNAKERC_API_DEPRECATED ( msg , func ) SPINC_IMPORT_EXPORT spinError SPINC_CALLTYPE func __attribute__ ( ( deprecated ( msg ) ) ) # Skipping MacroDefinition: SPINNAKERC_API SPINC_IMPORT_EXPORT spinError SPINC_CALLTYPE @cenum(_spinTLStreamTypeEnums, StreamType_Mixed = 0, StreamType_Custom = 1, StreamType_GEV = 2, StreamType_CL = 3, StreamType_IIDC = 4, StreamType_UVC = 5, StreamType_CXP = 6, StreamType_CLHS = 7, StreamType_U3V = 8, StreamType_ETHERNET = 9, StreamType_PCI = 10, NUMSTREAMTYPE = 11, ) const spinTLStreamTypeEnums = _spinTLStreamTypeEnums @cenum(_spinTLStreamDefaultBufferCountModeEnums, StreamDefaultBufferCountMode_Manual = 0, StreamDefaultBufferCountMode_Auto = 1, NUMSTREAMDEFAULTBUFFERCOUNTMODE = 2, ) const spinTLStreamDefaultBufferCountModeEnums = _spinTLStreamDefaultBufferCountModeEnums @cenum(_spinTLStreamBufferCountModeEnums, StreamBufferCountMode_Manual = 0, StreamBufferCountMode_Auto = 1, NUMSTREAMBUFFERCOUNTMODE = 2, ) const spinTLStreamBufferCountModeEnums = _spinTLStreamBufferCountModeEnums @cenum(_spinTLStreamBufferHandlingModeEnums, StreamBufferHandlingMode_OldestFirst = 0, StreamBufferHandlingMode_OldestFirstOverwrite = 1, StreamBufferHandlingMode_NewestFirst = 2, StreamBufferHandlingMode_NewestFirstOverwrite = 3, StreamBufferHandlingMode_NewestOnly = 4, NUMSTREAMBUFFERHANDLINGMODE = 5, ) const spinTLStreamBufferHandlingModeEnums = _spinTLStreamBufferHandlingModeEnums @cenum(_spinTLDeviceTypeEnums, DeviceType_Mixed = 0, DeviceType_Custom = 1, DeviceType_GEV = 2, DeviceType_CL = 3, DeviceType_IIDC = 4, DeviceType_UVC = 5, DeviceType_CXP = 6, DeviceType_CLHS = 7, DeviceType_U3V = 8, DeviceType_ETHERNET = 9, DeviceType_PCI = 10, NUMDEVICETYPE = 11, ) const spinTLDeviceTypeEnums = _spinTLDeviceTypeEnums @cenum(_spinTLDeviceAccessStatusEnums, DeviceAccessStatus_Unknown = 0, DeviceAccessStatus_ReadWrite = 1, DeviceAccessStatus_ReadOnly = 2, DeviceAccessStatus_NoAccess = 3, NUMDEVICEACCESSSTATUS = 4, ) const spinTLDeviceAccessStatusEnums = _spinTLDeviceAccessStatusEnums @cenum(_spinTLGevCCPEnums, GevCCP_EnumEntry_GevCCP_OpenAccess = 0, GevCCP_EnumEntry_GevCCP_ExclusiveAccess = 1, GevCCP_EnumEntry_GevCCP_ControlAccess = 2, NUMGEVCCP = 3, ) const spinTLGevCCPEnums = _spinTLGevCCPEnums @cenum(_spinTLGUIXMLLocationEnums, GUIXMLLocation_Device = 0, GUIXMLLocation_Host = 1, NUMGUIXMLLOCATION = 2, ) const spinTLGUIXMLLocationEnums = _spinTLGUIXMLLocationEnums @cenum(_spinTLGenICamXMLLocationEnums, GenICamXMLLocation_Device = 0, GenICamXMLLocation_Host = 1, NUMGENICAMXMLLOCATION = 2, ) const spinTLGenICamXMLLocationEnums = _spinTLGenICamXMLLocationEnums @cenum(_spinTLDeviceEndianessMechanismEnums, DeviceEndianessMechanism_Legacy = 0, DeviceEndianessMechanism_Standard = 1, NUMDEVICEENDIANESSMECHANISM = 2, ) const spinTLDeviceEndianessMechanismEnums = _spinTLDeviceEndianessMechanismEnums @cenum(_spinTLDeviceCurrentSpeedEnums, DeviceCurrentSpeed_UnknownSpeed = 0, DeviceCurrentSpeed_LowSpeed = 1, DeviceCurrentSpeed_FullSpeed = 2, DeviceCurrentSpeed_HighSpeed = 3, DeviceCurrentSpeed_SuperSpeed = 4, NUMDEVICECURRENTSPEED = 5, ) const spinTLDeviceCurrentSpeedEnums = _spinTLDeviceCurrentSpeedEnums @cenum(_spinTLPOEStatusEnums, POEStatus_NotSupported = 0, POEStatus_PowerOff = 1, POEStatus_PowerOn = 2, NUMPOESTATUS = 3, ) const spinTLPOEStatusEnums = _spinTLPOEStatusEnums struct _quickSpinTLDevice DeviceID::quickSpinStringNode DeviceSerialNumber::quickSpinStringNode DeviceVendorName::quickSpinStringNode DeviceModelName::quickSpinStringNode DeviceType::quickSpinEnumerationNode DeviceDisplayName::quickSpinStringNode DeviceAccessStatus::quickSpinEnumerationNode DeviceVersion::quickSpinStringNode DeviceUserID::quickSpinStringNode DeviceDriverVersion::quickSpinStringNode DeviceIsUpdater::quickSpinBooleanNode GevCCP::quickSpinEnumerationNode GUIXMLLocation::quickSpinEnumerationNode GUIXMLPath::quickSpinStringNode GenICamXMLLocation::quickSpinEnumerationNode GenICamXMLPath::quickSpinStringNode GevDeviceIPAddress::quickSpinIntegerNode GevDeviceSubnetMask::quickSpinIntegerNode GevDeviceMACAddress::quickSpinIntegerNode GevDeviceGateway::quickSpinIntegerNode DeviceLinkSpeed::quickSpinIntegerNode GevVersionMajor::quickSpinIntegerNode GevVersionMinor::quickSpinIntegerNode GevDeviceModeIsBigEndian::quickSpinBooleanNode GevDeviceReadAndWriteTimeout::quickSpinIntegerNode GevDeviceMaximumRetryCount::quickSpinIntegerNode GevDevicePort::quickSpinIntegerNode GevDeviceDiscoverMaximumPacketSize::quickSpinCommandNode GevDeviceMaximumPacketSize::quickSpinIntegerNode GevDeviceIsWrongSubnet::quickSpinBooleanNode DeviceMulticastMonitorMode::quickSpinBooleanNode DeviceEndianessMechanism::quickSpinEnumerationNode DeviceInstanceId::quickSpinStringNode DeviceCurrentSpeed::quickSpinEnumerationNode DeviceU3VProtocol::quickSpinBooleanNode end const quickSpinTLDevice = _quickSpinTLDevice struct _quickSpinTLInterface InterfaceID::quickSpinStringNode InterfaceDisplayName::quickSpinStringNode InterfaceType::quickSpinStringNode GevInterfaceGateway::quickSpinIntegerNode GevInterfaceMACAddress::quickSpinIntegerNode GevInterfaceIPAddress::quickSpinIntegerNode GevInterfaceSubnetMask::quickSpinIntegerNode POEStatus::quickSpinEnumerationNode GevActionDeviceKey::quickSpinIntegerNode GevActionGroupKey::quickSpinIntegerNode GevActionGroupMask::quickSpinIntegerNode GevActionTime::quickSpinIntegerNode ActionCommand::quickSpinCommandNode DeviceUnlock::quickSpinStringNode DeviceUpdateList::quickSpinCommandNode DeviceCount::quickSpinIntegerNode DeviceSelector::quickSpinIntegerNode DeviceID::quickSpinStringNode DeviceVendorName::quickSpinStringNode DeviceModelName::quickSpinStringNode DeviceAccessStatus::quickSpinEnumerationNode GevDeviceIPAddress::quickSpinIntegerNode GevDeviceSubnetMask::quickSpinIntegerNode GevDeviceMACAddress::quickSpinIntegerNode AutoForceIP::quickSpinCommandNode IncompatibleDeviceCount::quickSpinIntegerNode IncompatibleDeviceSelector::quickSpinIntegerNode IncompatibleDeviceID::quickSpinStringNode IncompatibleDeviceVendorName::quickSpinStringNode IncompatibleDeviceModelName::quickSpinStringNode IncompatibleGevDeviceIPAddress::quickSpinIntegerNode IncompatibleGevDeviceSubnetMask::quickSpinIntegerNode IncompatibleGevDeviceMACAddress::quickSpinIntegerNode HostAdapterName::quickSpinStringNode HostAdapterVendor::quickSpinStringNode HostAdapterDriverVersion::quickSpinStringNode end const quickSpinTLInterface = _quickSpinTLInterface struct _quickSpinTLStream StreamID::quickSpinStringNode StreamType::quickSpinEnumerationNode StreamTotalBufferCount::quickSpinIntegerNode StreamDefaultBufferCount::quickSpinIntegerNode StreamDefaultBufferCountMax::quickSpinIntegerNode StreamDefaultBufferCountMode::quickSpinEnumerationNode StreamBufferCountManual::quickSpinIntegerNode StreamBufferCountResult::quickSpinIntegerNode StreamBufferCountMax::quickSpinIntegerNode StreamBufferCountMode::quickSpinEnumerationNode StreamBufferHandlingMode::quickSpinEnumerationNode StreamCRCCheckEnable::quickSpinBooleanNode GevPacketResendMode::quickSpinBooleanNode GevMaximumNumberResendRequests::quickSpinIntegerNode GevPacketResendTimeout::quickSpinIntegerNode GevMaximumNumberResendBuffers::quickSpinIntegerNode GevTotalPacketCount::quickSpinIntegerNode GevFailedPacketCount::quickSpinIntegerNode GevResendPacketCount::quickSpinIntegerNode StreamFailedBufferCount::quickSpinIntegerNode StreamBufferUnderrunCount::quickSpinIntegerNode GevResendRequestCount::quickSpinIntegerNode StreamBlockTransferSize::quickSpinIntegerNode end const quickSpinTLStream = _quickSpinTLStream
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
code
3149
using Test, ImageCore function is_ci() get(ENV, "TRAVIS", "") == "true" || get(ENV, "APPVEYOR", "") in ("true", "True") || get(ENV, "CI", "") in ("true", "True") end using Spinnaker if is_ci() @info "CI testing is disabled due to the need for a Spinnaker-compatible camera during tests." else camlist = CameraList() if length(camlist) < 1 error("""Spinnaker could not find a compatible camera. Tests require that a Spinnaker-compatible camera is connected and discoverable. If such a camera is connected, check that it is discoverable in SpinView""") else @testset "Camera Interaction" begin cam = camlist[0] @test typeof(cam) == Spinnaker.Camera @testset "Set continuous mode" begin triggermode!(cam, "Off") @test triggermode(cam) == "Off" acquisitionmode!(cam, "Continuous") @test acquisitionmode(cam) == "Continuous" max_framerate = framerate_limits(cam)[end] framerate!(cam, max_framerate) @test isapprox(framerate(cam), max_framerate) end @testset "Set exposure" begin exposure!(cam, 4000) exp, mode = exposure(cam) @test isapprox(exp, 4000, rtol=0.1) @test mode == "Off" exposure!(cam) exp, mode = exposure(cam) @test mode == "Continuous" end @testset "Read image" begin @testset "Mono8" begin pixelformat!(cam, "Mono8") @assert pixelformat(cam) == "Mono8" start!(cam) img = getimage(cam, Gray{N0f8}, normalize=true) @test all(size(img) .> 0) stop!(cam) end end @testset "Digital IO" begin line_inverter!(cam, true) @test line_inverter(cam) line_inverter!(cam, false) @test !line_inverter(cam) line_mode!(cam, "Input") @test line_mode(cam) == "Input" line_mode!(cam, "Output") @test line_mode(cam) == "Output" v3_3_enable!(cam, true) @test v3_3_enable(cam) v3_3_enable!(cam, false) @test !v3_3_enable(cam) @testset "deprecated" begin @test_deprecated line_mode(cam, "Input") @test line_mode(cam) == "Input" @test_deprecated line_mode(cam, "Output") @test line_mode(cam) == "Output" @test_deprecated v3_3_enable(cam, true) @test v3_3_enable(cam) @test_deprecated v3_3_enable(cam, false) @test !v3_3_enable(cam) end end end @testset "#90: duplicate initialization crash" begin CameraList() CameraList() GC.gc(true) end end end
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
1.2.0
8bee45836b07ed6e6e7a70edcf9b70d5082a270b
docs
13027
# Spinnaker.jl A Julia interface to the FLIR/PointGrey [Spinnaker SDK](https://www.ptgrey.com/spinnaker-sdk). ## Overview This package provides a complete wrapper of the Spinnaker SDK C API. All functions and enumerations prefixed by `spin` are exported from the package and can be called according to the API documentation. See `examples/wrapper/` for examples. The package also provides a high-level interface for common camera functions which allows control from Julia with a relatively terse syntax, and for the retrieval of images as native Julia arrays. The high-level interface is work-in-progress, and may be subject to change. ## Installation Ensure that the Spinnaker SDK is installed, then use the Julia package manage to install and build the package. ```Julia ]add Spinnaker ``` NOTE: The official Julia 1.4.0 MacOS binaries appear to have an issue with notarization which causes a failure to load the dynamic libraries. Whilst this is being resolved, either use a previous version, or the fix detailed [here](https://github.com/samuelpowell/Spinnaker.jl/pull/63#issuecomment-602821121). ## Graphical user interface [SpinnakerGUI.jl](https://github.com/ianshmean/SpinnakerGUI.jl) by @ianshmean uses @Gnimuc's [CImGui.jl](https://github.com/Gnimuc/CImGui.jl) package to implement an experimental GUI for image capture and recording, driven by this package. ## High-level Interface The high-level interface provides convenience functions for more typical camera operations, in addition to utility functions which allow the setting of camera nodes directly. Camera settings which take a numeric value, e.g., gain or exposure time, can be provided with any number type, and this will be _clamped_ to the acceptable range, the actual value set on the camera being returned. Settings which are boolean in nature accept Julia `bool` types. Enumeration settings require the user to provide a member of the enumeration in string format, e.g., selecting a 12-bit ADC bit depth requires the parameter `"Bit12"`, these values can be found in the technical reference manual for the particular camera. All types and references are managed by the Julia GC - there is no need to explicitly release resources (with the sole exception of `BufferImages`). ### Enumeration Get a list of cameras by constructing a `CameraList` object: ```julia julia> camlist = CameraList() CameraList with 1 enumerated devices: ID Serial No. Description 0 XXXXXXX FLIR Blackfly S BFS-U3-16S2M ``` Acquire a camera by indexing a `CameraList` by ID: ```julia julia> cam = camlist[0] FLIR Blackfly S BFS-U3-16S2M (XXXXXXXX): stopped ``` ### Acquisition controls Change the exposure time to 0.1s: ```julia julia> exposure!(cam, 0.1e6) 100001.0 ``` Change the framerate for continuous mode to 60 fps: ```julia julia> framerate!(cam, 60) 60.0 ``` Start an acquisition, and trigger it (if set to trigger mode): ```julia start!(cam) trigger!(cam) # do something stop!(cam) ``` See `triggermode(!)`, `triggersource(!)`, `exposure(!)`. ### Analog controls Set the gain to 12dB: ```julia julia> gain!(cam, 12) 12.0 ``` ### Image format Set the ADC to 12-bit mode: ```julia julia> adcbits!(cam, "Bit12") "Bit12" ``` Set the image size and offset: ```julia julia> imagedims!(cam, (1024, 1024)) (1024, 1024) julia> offsetdims!(cam, (0,10)) (0, 10) ``` See `gammaenable(!)`, `pixelformat(!)`, `adcbits(!)`, `sensordims`, `imagedims(!)`, `offsetdims(!)`. ### Retrieving images All of the following functions are blocking by default, and execution will halt until an image is available. Use the keyword argument 'timeout' to specify a timeout in ms, after which an error is thrown. For each function the keyword argument `release=true` is supported which by default will release the buffer for further use. If you choose `release=false` then the buffer will not be released, allowing one to inspect the image without removing it from the stream buffer (e.g the next call to the function will return the same image). Images can be retrieved in three formats: - CameraImage, an abstract array interface of arbitrary type, which stores metadata about the image; - Array, a raw Julia array of arbitrary type, with metadata returned as additional return values; - SpinImage, an internal Spinnaker library image type, which can be queried for metadata. **The native camera format for images is row-major**, to avoid performing a transposition this means that the resulting Julia matrices are of dimensions (width x height), which is transposed compared to the normal (height x width) arrangement in a column-major language such as Julia or MATLAB. Perform a transposition if this is problematic. #### CameraImage If the pixel format from the camera is _unpacked_ Images can be retrieved to a `CameraImage` type which provides an `AbstractArray` interface to the underlying data, in addition to storing metadata available when the image is acquired. One can acquire an image in this way by specifying the desired data format: ```julia julia> getimage(cam, Gray{N0f8}, normalize=true); julia> getimage(cam, Float64, normalize=false) 1440×1080 CameraImage{Float64,2}: 84.0 85.0 90.0 90.0 87.0 94.0 89.0 92.0 … 88.0 79.0 76.0 87.0 78.0 ``` By specifying `normalize=true` the image data from the camera is intepreted as a fixed point number in the range [0,1]. By combining this with a fixed point Colorant type `Gray{N0f8}`, this provides direct compatibilty with the Julia images stack. Alterantively, without normalisation the unsigned integer data returned from the camera will be supplied in its natural range, e.g., a Mono8 pixel format will result in values in the range [0, 255]. Mutating versions are available, where the type is determined from the input, the metadata will be updated and the underlying data array reused. ```julia julia> getimage!(cam, cameraimage); 1440×1080 CameraImage{Float64,2}: 84.0 85.0 90.0 90.0 87.0 94.0 89.0 92.0 … 88.0 79.0 76.0 87.0 78.0 ``` Metadata such as the id, timestamp, and exposure can be returned from the CameraImage: ```julia julia> id(getimage(camera, Float64)) 391050 julia> id(getimage(camera, Float64)) 391051 ``` #### Array A raw Julia array can be passed to the mutating form `getimage!`, which operates in the same way as the method which accepts the CameraImage format, however the metadata will be returned by the function: ```julia julia> imid, imtimestamp, imexposure = getimage!(camera, Array{Float64}(undef, 1440, 1080)) (391055, 20685632735104, 14996.0) ``` #### SpinImage Alternatively, a `SpinImage` type can be retrieved from the camera, which supports all possible pixel formats, including packed data. To copy the image from the camera buffer, and release the buffer for acquisition: ```julia julia> image = getimage(cam) Spinnaker Image, (1440, 1080), 16bpp, PixelFormat_Mono16(1) ``` The resulting `SpinImage` type contains a handle to a Spinnaker image object. These types can queried for metadata, converted to alternative pixel formats, saved to disc, etc., by the Spinnaker SDK (see `src/SpinImage.jl` for details). For example, the timestamp of the image in nanoseconds since the last reset of the camera clock (i.e. at camera boot) may be read: ```julia timestamp(image) 2166531583413 ``` If you havean existing `SpinImage` and wish to overwrite it in-place, ```julia julia> getimage!(cam, image) Spinnaker Image, (1440, 1080), 16bpp, PixelFormat_Mono16(1) ``` Alternatively, It is possible to convert a `SpinImage` to a `CameraImage` using the `CameraImage` constructor: ``` julia> CameraImage(spinimage, Float64, normalize=true) ``` One may directly save an acquired image to disc: ```julia saveimage(cam, "output.png", Spinnaker.PNG) ``` ### Stream (buffer) handling To set the current buffer mode, ```julia julia> buffermode!(cam, "NewestFirst") "NewestFirst" ``` To set the number of buffers, and move to manual buffer count mode: ```julia julia> buffercount!(cam, 12) (12, Manual) ``` To return to automatic buffer count, ```julia julia> buffercount!(cam) ``` To check for buffer underruns, or invalid buffer frames: ```julia julia> bufferunderrun(camera) 0 julia> bufferfailed(camera) 0 ``` Please note the [specifics](https://www.ptgrey.com/tan/11174) of buffer handling to understand the expected behaviour of the various buffer modes. ### Demo ```julia julia> using Spinnaker julia> camlist = CameraList() CameraList with 1 enumerated devices: ID Serial No. Description 0 17458441 FLIR Blackfly S BFS-U3-16S2M julia> cam = camlist[0] FLIR Blackfly S BFS-U3-16S2M (XXXXXXXX) julia> triggersource!(cam, "Software") "Software" julia> triggermode!(cam, "On") "On" julia> start!(cam) FLIR Blackfly S BFS-U3-16S2M (XXXXXXXX) julia> trigger!(cam) julia> saveimage(cam, joinpath(@__DIR__, "test.png"), spinImageFileFormat(6)) julia> stop!(cam) FLIR Blackfly S BFS-U3-16S2M (XXXXXXXX) ``` ## Low-level Interface The operation of this package revolves around the manipulation of [nodes](https://www.ptgrey.com/tan/11153) defined by a camera specification. Nodes exist as part of a node map, of which there are several: the camera node map controls camera features; the stream node map controls image buffers; and the transport node map controls the specific transport layer of the device. Nodes may be integer valued, floating point valued, an enumeration, etc. In Spinnaker.jl, node access functions are provided which allow manipulation through their textual names (rather than integer identifiers). For example, a nodes can be written to using the `set!`function: ```julia julia> Spinnaker.set!(Spinnaker.SpinEnumNode(cam, "TriggerSelector"), "FrameStart") "FrameStart" ``` This command creates a reference to an enumeration valued node with name `TriggerSelector`, and sets the value to the named enumeration element `FrameStart`. By default, nodes refer to the _camera_ node map. To access a different node map, pass the appropriate singleton type to the node constructor: ```julia julia> get(SpinEnumNode(cam, "StreamBufferHandlingMode", CameraTLStreamNodeMap())) "NewestFirst" ``` This command creates a reference to the enumeration valued node with the name `StreamBufferHandlingMode` in the _transport steram node map_, and returns the current enuemration selection by its string representation. The available node maps are `CameraNodeMap`, `CameraTLStreamNodeMap`, and `CameraTLDeviceNodeMap`. Node types are defined for enumerations (`SpinEnumNode`), floating point values (`SpinFloatNode`), booleans (`SpinBoolNode`), and integers (`SpinIntegerNode`). Set operations on numeric node types are clamped to the range of the node, and a warning is printed if the desired setting is out of range. The majority of the high level interface is defined by convenience functions which safely or logically manipualte camera nodes. If you frequently require access to specific nodes, consider creating a high level convenience function for this action, and submitting a PR. ## Troubleshooting ### Spinnaker.jl Cannot Load If running `using Spinnaker` results in an error similar to this one: ```julia ┌ Error: Spinnaker SDK loaded but Spinnaker.jl failed to initialize └ @ Spinnaker ~/.julia/packages/Spinnaker/4E5ov/src/Spinnaker.jl:99 Spinnaker SDK error: SPINNAKER_ERR_ABORT(-1012) Stacktrace: [1] checkerror @ ~/.julia/packages/Spinnaker/4E5ov/src/Spinnaker.jl:31 [inlined] [2] spinSystemGetInstance @ ~/.julia/packages/Spinnaker/4E5ov/src/wrapper/spin_api.jl:97 [inlined] [3] Spinnaker.System() @ Spinnaker ~/.julia/packages/Spinnaker/4E5ov/src/System.jl:16 [4] __init__() @ Spinnaker ~/.julia/packages/Spinnaker/4E5ov/src/Spinnaker.jl:96 [5] _include_from_serialized(path::String, depmods::Vector{Any}) @ Base ./loading.jl:768 [6] _require_search_from_serialized(pkg::Base.PkgId, sourcepath::String) @ Base ./loading.jl:854 [7] _require(pkg::Base.PkgId) @ Base ./loading.jl:1097 [8] require(uuidkey::Base.PkgId) @ Base ./loading.jl:1013 [9] require(into::Module, mod::Symbol) @ Base ./loading.jl:997 [10] eval @ ./boot.jl:373 [inlined] [11] exec_options(opts::Base.JLOptions) @ Base ./client.jl:268 [12] _start() @ Base ./client.jl:495 ``` Check that you have the environment variable `FLIR_GENTL64_CTI` set to the path to `FLIR_GenTL.cti` (e.g. `/opt/spinnaker/lib/flir-gentl/FLIR_GenTL.cti`). ### Loading Spinnaker causes binary dependency (i.e. JLL) errors in other packages From v1.1.1 Spinnaker.jl initializes the Spinnaker SDK during first usage of `CameraList()`. If you need to call any of the SDK's native functions before using `CameraList()`, then call `Spinnaker.init()` manually. Prior to v1.1.1, Spinnaker.jl initializes the SDK inside its `__init__()` function, called on Julia load. You can delay this by setting `ENV["JULIA_SPINNAKER_MANUAL_INIT"]="true"` and loading Julia packages before calling `Spinnaker.init()` manually.
Spinnaker
https://github.com/samuelpowell/Spinnaker.jl.git
[ "MIT" ]
0.2.1
69f24ad09c1501d0795f518d9355168a262e2dc0
code
1996
module MeanSquaredDisplacement using Autocorrelations using AxisArrays using LinearAlgebra: dot using OffsetArrays using Statistics: mean export emsd, imsd, unfold, unfold! #== Ensemble MSD ==# """ emsd(x::AbstractVector) Return the ensemble average of the mean squared displacement of each vector in `x`. `x` can contain timeseries of different lengths. """ function emsd(x::AbstractVector{T}) where {T<:AbstractVector} individual_msds = imsd.(x) tmax = maximum(length.(x)) S = eltype(first(individual_msds)) out = zeros(S, tmax) counter = zeros(Int, tmax) for i in eachindex(x) for t in eachindex(x[i]) out[t] += individual_msds[i][t] counter[t] += 1 end end for t in eachindex(out) out[t] /= counter[t] end return out end """ emsd(x::AbstractMatrix, [lags]) Return the ensemble average of the mean squared displacement of each column of `x` at lag times `lags`. If not specified `lags` defaults to `0:size(x,1)-1`. """ function emsd(x::AbstractMatrix, lags=0:size(x,1)-1) vec(mean(imsd(x, lags), dims=2)) end #== Individual MSD ==# """ imsd(x::AbstractMatrix, [lags]) Return the mean squared displacement of each column of `x` at lag times `lags`. If not specified `lags` defaults to `0:size(x,1)-1`. """ function imsd(x::AbstractMatrix, lags=0:size(x,1)-1) mapslices(y -> imsd(y, lags), x, dims=1) end """ imsd(x::AbstractVector, [lags]) Return the mean squared displacement of `x` at lag times `lags`. If not specified `lags` defaults to `0:size(x,1)-1`. """ function imsd(x::AbstractVector, lags=0:size(x,1)-1) l = length(x) S₂ = acf(x, lags) D = OffsetArray([0.0; dot.(x,x); 0.0], -1:l) Q = 2*sum(D) S₁ = AxisArray(similar(S₂), lags) for k in 0:lags[end] Q -= (D[k-1] + D[l-k]) if k ∈ lags S₁[atvalue(k)] = Q / (l-k) end end @. S₁ - 2S₂ end include("unfold.jl") end # module MeanSquaredDisplacement
MeanSquaredDisplacement
https://github.com/mastrof/MeanSquaredDisplacement.jl.git
[ "MIT" ]
0.2.1
69f24ad09c1501d0795f518d9355168a262e2dc0
code
1728
""" unfold(x::AbstractVector, P) Unfold timeseries `x` from a periodic domain extending from `0` to `P`. """ function unfold(x::AbstractVector, P) y = deepcopy(x) unfold!(y, P) return y end """ unfold!(x::AbstractVector, P) Unfold timeseries `x` from a periodic domain extending from `0` to `P`. The periodicity `P` can be either a real number (for a cubic domain) or a collection (`AbstractVector` or `NTuple`) with one value for each dimension. """ function unfold!(x::AbstractVector, P) indices = eachindex(x) ind_prev = @view indices[1:end-1] ind_next = @view indices[2:end] for (i,j) in zip(ind_prev, ind_next) x0 = x[i] x1 = x[j] x[j] = unfold(x1, x0, P) end return x end NTupleOrVec = Union{NTuple{D,<:Real},AbstractVector{<:Real}} where D function unfold(x1::AbstractVector, x0::AbstractVector, P::Real) @assert length(x1) == length(x0) map(i -> unfold(x1[i], x0[i], P), eachindex(x1)) end function unfold(x1::NTuple{D}, x0::NTuple{D}, P::Real) where D ntuple(i -> unfold(x1[i], x0[i], P), D) end function unfold(x1::AbstractVector, x0::AbstractVector, P::NTupleOrVec) @assert length(x1) == length(x0) == length(P) map(i -> unfold(x1[i], x0[i], P[i]), eachindex(x1)) end function unfold(x1::NTuple{D}, x0::NTuple{D}, P::NTupleOrVec) where D @assert D == length(P) ntuple(i -> unfold(x1[i], x0[i], P[i]), D) end """ unfold(x1::Real, x0::Real, P::Real) Unfold the value of `x1` with respect to `x0` from a domain of periodicity `P`. """ function unfold(x1::Real, x0::Real, P::Real) dx = x1 - x0 a = round(abs(dx / P)) if abs(dx) > P/2 return x1 - a*P*sign(dx) else return x1 end end
MeanSquaredDisplacement
https://github.com/mastrof/MeanSquaredDisplacement.jl.git
[ "MIT" ]
0.2.1
69f24ad09c1501d0795f518d9355168a262e2dc0
code
1846
using MeanSquaredDisplacement using Test @testset "MeanSquaredDisplacement.jl" begin # ballistic trajectory x = collect(1:10) m = imsd(x) @test length(m) == length(x) @test m ≈ (eachindex(x) .-1 ).^2 lags = 2:2:6 mlags = imsd(x, lags) @test mlags ≈ m[lags.+1] x = collect(1:10_000) @test imsd(x) ≈ (eachindex(x) .- 1).^2 # non-scalar msd is the sum of each dimension's msd x = [(i,0) for i in 1:10] m2 = imsd(x) @test m2 ≈ m x = [(i,i) for i in 1:10] m3 = imsd(x) @test m3 ≈ 2m # imsd over matrix is hcat of each column's imsd x = cumsum(randn(100,3), dims=1) m = imsd(x) m2 = hcat([imsd(x[:,i]) for i in axes(x,2)]...) @test m ≈ m2 # emsd is the average of imsds using Statistics: mean @test emsd(x) ≈ vec(mean(m2, dims=2)) x = [collect(1:10), collect(1:10)] @test emsd(x) ≈ imsd(x[1]) na, nb = 10, 5 a = randn(na) b = randn(nb) x = [a, b] m = emsd(x) ma = imsd(a) mb = [imsd(b); repeat([0.0], na-nb)] divisor = [repeat([2], nb); repeat([1], na-nb)] @test m ≈ (ma .+ mb) ./ divisor @testset "Unfolding" begin function wrap(x,L) s = x while !(0 ≤ s < L) δ = s < 0 ? +L : s > L ? -L : 0 s += δ end return s end x = cumsum(rand(1000)) # wrap trajectory between 0 and L L = 10 y = wrap.(x, L) z = copy(y) unfold!(y, L) @test y ≈ x y2 = unfold(x, L) @test y2 == y Lx, Ly = 8.6, 13.0 x = (1:100) .% Lx y = (1:100) .% Ly traj = Tuple.(zip(x,y)) utraj = copy(traj) unfold!(utraj, (Lx, Ly)) @test first.(utraj) == (1:100) @test last.(utraj) == (1:100) end end
MeanSquaredDisplacement
https://github.com/mastrof/MeanSquaredDisplacement.jl.git
[ "MIT" ]
0.2.1
69f24ad09c1501d0795f518d9355168a262e2dc0
docs
1498
# MeanSquaredDisplacement [![Build Status](https://github.com/mastrof/MeanSquaredDisplacement.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/mastrof/MeanSquaredDisplacement.jl/actions/workflows/CI.yml?query=branch%3Amain) MeanSquaredDisplacement.jl provides Julia functions (`imsd` and `emsd`) to compute the mean squared displacement (MSD) of timeseries. `imsd` is used to evaluate the MSD of individual timeseries, while `emsd` evaluates ensemble averages. MeanSquaredDisplacement.jl relies on [Autocorrelations.jl](https://github.com/mastrof/Autocorrelations.jl) to compute MSDs, which uses a plain correlation algorithm (O(N^2)) for short timeseries and a FFT-based algorithm (O(NlogN)) for larger ones, ensuring good performance for all sample sizes. The MSD of non-scalar timeseries can also be evaluated (equivalent to summing the MSD of each scalar element), but it's not yet optimized. ## MSD of a single timeseries ```julia using MeanSquaredDisplacement x = cumsum(randn(10000)) imsd(x) ``` ## Individual MSD of multiple timeseries ```julia using MeanSquaredDisplacement x = cumsum(randn(10000, 100)) imsd(x) # evaluates MSD along columns ``` ## MSD of uneven timeseries ```julia using MeanSquaredDisplacement N = 100 Tmin, Tmax = 100, 2000 # trajectories of random length between Tmin and Tmax x = [cumsum(randn(rand(Tmin:Tmax))) for _ in 1:N] iM = imsd.(x) eM = emsd(x) ``` ![Individual and ensemble MSD for brownian motions of random lengths](msd.svg)
MeanSquaredDisplacement
https://github.com/mastrof/MeanSquaredDisplacement.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
221
ENV["PYTHON"] = "" using Pkg Pkg.build("PyCall") using Conda pipcmd = joinpath(Conda.PYTHONDIR,"pip") run(`$pipcmd install pyneid`) #= env = Conda.ROOTENV Conda.pip_interop(true, env) Conda.pip("install", "pyneid") =#
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
616
using NeidArchive using Documenter DocMeta.setdocmeta!(NeidArchive, :DocTestSetup, :(using NeidArchive); recursive=true) makedocs(; modules=[NeidArchive], authors="Eric Ford", repo="https://github.com/RvSpectML/NeidArchive.jl/blob/{commit}{path}#{line}", sitename="NeidArchive.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://RvSpectML.github.io/NeidArchive.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/RvSpectML/NeidArchive.jl", devbranch="main", )
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
1048
using NeidArchive using Dates include("password.jl") # Needs to set user_nexsci and passwd_nexsci cookie_nexsci = "./neidadmincookie.txt" query_result_file = "./criteria1.csv" NeidArchive.login(userid=user_nexsci, password=passwd_nexsci, cookiepath=cookie_nexsci) param = Dict{String,String}() param["datalevel"] = "solarl1" param["piname"] = "Mahadevan" param["object"] = "Sun" param["datetime"] = NeidArchive.datetime_one_day_solar(Date(2021,1,13)) #param["datetime"] = NeidArchive.datetime_range(Date(2021,1,13,00,0,0),Date(2021,1,15)) NeidArchive.query(param, cookiepath=cookie_nexsci, outpath=query_result_file) num_lines = countlines(query_result_file) - 1 println("# Query resulted in file with ", num_lines, " entries.") NeidArchive.download(query_result_file, param["datalevel"], cookiepath=cookie_nexsci, start_row=1, end_row=3) #= If you want to parse the file using CSV, DataFrames if (@isdefined CSV) && (@isdefined DataFrames) df = CSV.read(query_result_file, DataFrame) nfiles = size(df,1) @assert nfiles >= 1 end =#
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
907
using NeidArchive using Dates last_day_retreived_solar_data = Date(2021,3,19) include("password.jl") # Needs to set user_nexsci and passwd_nexsci cookie_nexsci = "./neidadmincookie.txt" query_result_file = "./criteria.csv" NeidArchive.login(userid=user_nexsci, password=passwd_nexsci, cookiepath=cookie_nexsci) param = Dict{String,String}() param["datalevel"] = "solarl1" param["piname"] = "Mahadevan" param["object"] = "Sun" param["datetime"] = NeidArchive.datetime_range_after(last_day_retreived_solar_data) NeidArchive.query(param, cookiepath=cookie_nexsci, outpath=query_result_file) num_lines = countlines(query_result_file) - 1 println("# Query resulted in file with ", num_lines, " entries.") #= If you want to parse the file using CSV, DataFrames if (@isdefined CSV) && (@isdefined DataFrames) df = CSV.read(query_result_file, DataFrame) nfiles = size(df,1) @assert nfiles >= 1 end =#
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
5057
""" Julia interface to the PyNeid API for accessing the NEID archive at NExScI """ #__precompile__() module NeidArchive using PyCall using Dates #using CSV, DataFrames const PyNeid = PyNULL() const archive = PyNULL() const valid_datalevel = [ "l0", "l1", "l2", "eng", "solarl0", "solarl1", "solarl2", "solareng"] const valid_format = [ "ipac", "votable", "csv", "tsv"] const default_format = "csv" const datefmt = DateFormat("yyyy-mm-dd HH:MM:SS") function __init__() copy!(PyNeid, pyimport("pyneid.neid")) copy!(archive, PyNeid.Neid) end #= Broken: Code doesn't get an updated token. function login(;userid::String, password::String, token::String) neid.login(userid=userid, password=password, token=token) return token end =# """ login(;userid, password, cookiepath) Login to the NEID archive at NExScI. All three named arguments are required. Login credentials stored in cookiepath. """ function login(;userid::String="", password::String="", cookiepath::String) if length(userid)>=1 && length(password)>=1 archive.login(userid=userid, password=password, cookiepath=cookiepath) #, debugfile="./archive.debug") else archive.login(cookiepath=cookiepath) end end """ query_criteria(param::Dict{String,String}; cookiepath, [outpath] ) Query the NEID archive using constraints in param. Named argument cookiepath is required. """ function query_criteria(param::Dict{String,String}; cookiepath::String, outpath::String=".", format::String = default_format) archive.query_criteria(param, cookiepath=cookiepath, format=format, outpath=outpath) end """ query(param::Dict{String,String}; cookiepath, [outpath] ) Shorthaned for query_criteria """ query = query_criteria # TODO: Implement query_adql, query_datetime, query_object, query_piname, query_program, query_qobject """ download(filename, datalevel; cookiepath, [format, outdir, start_row, end_row] ) Download files returned from a query of the NEID archive. Named argument cookiepath is required. """ function download(filename::String, datalevel::String; format::String = default_format, outdir::String=".", cookiepath::String = "", start_row::Integer=0, end_row::Integer=1000) @assert datalevel ∈ valid_datalevel @assert format ∈ valid_format @assert 0 <= start_row <= end_row @assert end_row-start_row <= 10000 if length(cookiepath) >= 1 if start_row==0 && end_row==1000 println("# Calling pyNEID archive.download without start_row or end_row") archive.download(filename, datalevel, format, outdir, cookiepath=cookiepath) else println("# Calling pyNEID archive.download with start_row=",start_row," end_row=",end_row) archive.download(filename, datalevel, format, outdir, cookiepath=cookiepath, start_row=start_row, end_row=end_row) end else if start_row==0 && end_row==1000 println("# Calling pyNEID archive.download without start_row or end_row") archive.download(filename, datalevel, format, outdir) else println("# Calling pyNEID archive.download with start_row=",start_row," end_row=",end_row) archive.download(filename, datalevel, format, outdir, start_row=start_row, end_row=end_row) end end end #= # TODO: See if there's a clever way to pass all extra optional args to pyneid. Maybe something like function download(filename::String, datalevel::String; format::String = default_format, outdir::String="."), kwargs...) archive.download(filename, datalevel, format, outdir, kwargs...) end =# """ Create a date range string in PyNeid format from start to stop.""" function datetime_range(start::DateTime, stop::DateTime) Dates.format(start,datefmt) * "/" * Dates.format(stop,datefmt) end function datetime_range(start::Date, stop::Date) datetime_range(DateTime(start), DateTime(year(stop),month(stop),day(stop),23,59,59)) end """ Create a date range string in PyNeid format for one day.""" function datetime_one_day(day::Date) datetime_range(day, day) end """ Create a date range string in PyNeid format for 24 hours starting at given DateTime.""" function datetime_one_day(start::DateTime) datetime_range(start, start+Dates.Day(1)) end """ Create a date range string in PyNeid format for 24 hours starting at 12:00 on given Date.""" function datetime_one_day_solar(start::Date) datetime_one_day(DateTime(start)+Dates.Hour(12)) end """ Create a date range string in PyNeid format starting at 00:00:00 on start date.""" function datetime_range_after(start::DateTime ) Dates.format(start,datefmt) * "/" end function datetime_range_after(start::Date ) datetime_range_after(DateTime(start)) end """ Create a date range string in PyNeid format ending at 23:59:59 on stop date.""" function datetime_range_before(stop::DateTime) datetime_range_before(DateTime(year(stop),month(stop),day(stop),23,59,59)) end end
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
code
929
using NeidArchive using Test using Dates @testset "NeidArchive.jl" begin user_nexsci = "pyneidprop" passwd_nexsci = "pielemonquietyellow" cookie_nexsci = "./neidadmincookie.txt" query_result_file = "./criteria.csv" @testset "login" begin NeidArchive.login(userid=user_nexsci, password=passwd_nexsci, cookiepath=cookie_nexsci) end @testset "Query" begin param = Dict{String,String}() param["datalevel"] = "l0" param["piname"] = "Logsdon" param["datetime"] = NeidArchive.datetime_one_day(Date(2021,1,31)) NeidArchive.query(param, cookiepath=cookie_nexsci, outpath=query_result_file) num_lines = countlines(query_result_file) - 1 #println("# Query resulted in file with ", num_lines, " entries.") # #df = CSV.read(query_result_file, DataFrame) #num_files = size(df, 1) @test num_lines == 238 end end
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
docs
1072
# NeidArchive [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://RvSpectML.github.io/NeidArchive.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://RvSpectML.github.io/NeidArchive.jl/dev) [![Build Status](https://github.com/RvSpectML/NeidArchive.jl/workflows/CI/badge.svg)](https://github.com/RvSpectML/NeidArchive.jl/actions) [![Coverage](https://codecov.io/gh/RvSpectML/NeidArchive.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/RvSpectML/NeidArchive.jl) NeidArchive.jl is a Julia wrapper for [pyNEID](https://pyneid.readthedocs.io/en/latest/). It provides a convenient, simple API for querying and downloading data files from the [NEID archive](neid.ipac.caltech.edu) and [NEID Solar archive](https://neid.ipac.caltech.edu/search_solar.php) hosted by the [NASA Exoplanet Science Institute (NExScI)](https://nexsci.caltech.edu/). Currently, NeidArchive.jl has limited features (i.e., what the developer needs). Please feel free to submit PRs to increase the completeness of NeidArchive.jl relative to pyNEID.
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.1.3
3235c6e1ca9f14e97766c24efcd5d88488113adc
docs
113
```@meta CurrentModule = NeidArchive ``` # NeidArchive ```@index ``` ```@autodocs Modules = [NeidArchive] ```
NeidArchive
https://github.com/RvSpectML/NeidArchive.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
855
using Documenter using DocumenterVitepress using CairoMakie using JetReconstruction push!(LOAD_PATH, "../ext/") include(joinpath(@__DIR__, "..", "ext", "JetVisualisation.jl")) makedocs(sitename = "JetReconstruction.jl", format = MarkdownVitepress(repo = "github.com/JuliaHEP/JetReconstruction.jl"), pages = [ "Home" => "index.md", "Examples" => "examples.md", "Reference" => Any["Public API" => "lib/public.md", "Internal API" => "lib/internal.md", "Visualisation API" => "lib/visualisation.md"] ]) deploydocs(repo = "github.com/JuliaHEP/JetReconstruction.jl.git", devbranch = "main", devurl = "dev", versions = ["stable" => "v^", "v#.#", "dev" => "dev"], push_preview = true)
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
2546
#! /usr/bin/env julia """Use the visualisation tools to produce an animation of the jet reconstruction""" using ArgParse using Logging using CairoMakie using JetReconstruction # Parsing for algorithm and strategy enums include(joinpath(@__DIR__, "parse-options.jl")) function main() s = ArgParseSettings(autofix_names = true) @add_arg_table s begin "--event", "-e" help = "Event in file to visualise" arg_type = Int default = 1 "--distance", "-R" help = "Distance parameter for jet merging" arg_type = Float64 default = 0.4 "--algorithm", "-A" help = """Algorithm to use for jet reconstruction: $(join(JetReconstruction.AllJetRecoAlgorithms, ", "))""" arg_type = JetAlgorithm.Algorithm "--power", "-p" help = """Power value for jet reconstruction""" arg_type = Float64 "--strategy", "-S" help = """Strategy for the algorithm, valid values: $(join(JetReconstruction.AllJetRecoStrategies, ", "))""" arg_type = RecoStrategy.Strategy default = RecoStrategy.Best "file" help = "HepMC3 event file in HepMC3 to read" required = true "output" help = "File for output animation" default = "jetreco.mp4" end args = parse_args(ARGS, s; as_symbols = true) logger = ConsoleLogger(stdout, Logging.Info) global_logger(logger) events::Vector{Vector{PseudoJet}} = read_final_state_particles(args[:file], maxevents = args[:event], skipevents = args[:event]) if isnothing(args[:algorithm]) && isnothing(args[:power]) @warn "Neither algorithm nor power specified, defaulting to AntiKt" args[:algorithm] = JetAlgorithm.AntiKt end # Set consistent algorithm and power (p, algorithm) = JetReconstruction.get_algorithm_power_consistency(p = args[:power], algorithm = args[:algorithm]) cs = jet_reconstruct(events[1], R = args[:distance], p = p, algorithm = algorithm, strategy = args[:strategy]) animatereco(cs, args[:output]; azimuth = (1.8, 3.0), elevation = 0.5, perspective = 0.5, framerate = 20, ancestors = true, barsize_phi = 0.1, barsize_y = 0.3) @info "Saved jet reconstruction animation to $(args[:output])" end main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
11375
#! /usr/bin/env julia """ Example of running jet reconstruction on a HepMC3 file, which also produces timing measurements. Options are available to profile the code (flamegraphs and allocations). """ using FlameGraphs: FlameGraphs using ProfileSVG: ProfileSVG using ArgParse using Profile using Colors using StatProfilerHTML using Logging using JSON using LorentzVectorHEP using JetReconstruction # Parsing for algorithm and strategy enums include(joinpath(@__DIR__, "parse-options.jl")) function profile_code(profile, jet_reconstruction, events, niters; R = 0.4, p = -1, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.AntiKt, strategy = RecoStrategy.N2Tiled) Profile.init(n = 5 * 10^6, delay = 0.00001) function profile_events(events) for evt in events jet_reconstruction(evt, R = R, p = p, algorithm = algorithm, strategy = strategy) end end profile_events(events[1:1]) @profile for i in 1:niters profile_events(events) end profile_path = joinpath("profile", profile, "profsvg.svg") mkpath(dirname(profile_path)) statprofilehtml(path = dirname(profile_path)) fcolor = FlameGraphs.FlameColors(reverse(colormap("Blues", 15))[1:5], colorant"slategray4", colorant"gray95", reverse(colormap("Reds", 15))[1:5], reverse(sequential_palette(39, 10; s = 38, b = 2))[1:5]) ProfileSVG.save(fcolor, profile_path, combine = true, timeunit = :ms, font = "Arial, Helvetica, sans-serif") println("Flame graph from ProfileSVG.jl at file://", abspath(profile_path), "\n", """ \tRed tint: Runtime dispatch \tBrown/yellow tint: Garbage collection \tBlue tint: OK """) end """ Top level call funtion for demonstrating the use of jet reconstruction This uses the "jet_reconstruct" wrapper, so algorithm switching happens inside the JetReconstruction package itself. Some other ustilities are also supported here, such as profiling and serialising the reconstructed jet outputs. """ function jet_process(events::Vector{Vector{PseudoJet}}; distance::Real = 0.4, algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing, p::Union{Real, Nothing} = nothing, ptmin::Real = 5.0, dcut = nothing, njets = nothing, strategy::RecoStrategy.Strategy, nsamples::Integer = 1, gcoff::Bool = false, profile = nothing, alloc::Bool = false, dump::Union{String, Nothing} = nothing, dump_cs = false) # If we are dumping the results, setup the JSON structure if !isnothing(dump) jet_collection = FinalJets[] end # Set consistent algorithm and power (p, algorithm) = JetReconstruction.get_algorithm_power_consistency(p = p, algorithm = algorithm) @info "Jet reconstruction will use $(algorithm) with power $(p)" # Warmup code if we are doing a multi-sample timing run if nsamples > 1 || !isnothing(profile) @info "Doing initial warm-up run" for event in events _ = inclusive_jets(jet_reconstruct(event, R = distance, p = p, algorithm = algorithm, strategy = strategy); ptmin = ptmin) end end if !isnothing(profile) profile_code(profile, jet_reconstruct, events, nsamples, algorithm = algorithm, R = distance, p = p, strategy = strategy) return nothing end if alloc println("Memory allocation statistics:") @timev for event in events _ = inclusive_jets(jet_reconstruct(event, R = distance, p = p, algorithm = algorithm, strategy = strategy), ptmin = ptmin) end return nothing end # Now setup timers and run the loop GC.gc() cummulative_time = 0.0 cummulative_time2 = 0.0 lowest_time = typemax(Float64) for irun in 1:nsamples gcoff && GC.enable(false) t_start = time_ns() for (ievt, event) in enumerate(events) cs = jet_reconstruct(event, R = distance, p = p, algorithm = algorithm, strategy = strategy) if !isnothing(njets) finaljets = exclusive_jets(cs; njets = njets) elseif !isnothing(dcut) finaljets = exclusive_jets(cs; dcut = dcut) else finaljets = inclusive_jets(cs; ptmin = ptmin) end # Only print the jet content once if irun == 1 @info begin jet_output = "Event $(ievt)\n" sort!(finaljets, by = x -> pt(x), rev = true) for (ijet, jet) in enumerate(finaljets) jet_output *= " $(ijet) - $(jet)\n" end "$(jet_output)" end if !isnothing(dump) push!(jet_collection, FinalJets(ievt, finaljets)) end if dump_cs println("Cluster sequence for event $(ievt)") for (ijet, jet) in enumerate(cs.jets) println(" $(ijet) - $(jet)") end for (ihistory, history) in enumerate(cs.history) println(" $(ihistory) - $(history)") end end end end t_stop = time_ns() gcoff && GC.enable(true) dt_μs = convert(Float64, t_stop - t_start) * 1.e-3 if nsamples > 1 @info "$(irun)/$(nsamples) $(dt_μs)" end cummulative_time += dt_μs cummulative_time2 += dt_μs^2 lowest_time = dt_μs < lowest_time ? dt_μs : lowest_time end mean = cummulative_time / nsamples cummulative_time2 /= nsamples if nsamples > 1 sigma = sqrt(nsamples / (nsamples - 1) * (cummulative_time2 - mean^2)) else sigma = 0.0 end mean /= length(events) sigma /= length(events) lowest_time /= length(events) # Why also record the lowest time? # # The argument is that on a "busy" machine, the run time of an application is # always TrueRunTime+Overheads, where Overheads is a nuisance parameter that # adds jitter, depending on the other things the machine is doing. Therefore # the minimum value is (a) more stable and (b) reflects better the intrinsic # code performance. println("Processed $(length(events)) events $(nsamples) times") println("Average time per event $(mean) ± $(sigma) μs") println("Lowest time per event $lowest_time μs") if !isnothing(dump) open(dump, "w") do io JSON.print(io, jet_collection, 2) end end end function parse_command_line(args) s = ArgParseSettings(autofix_names = true) @add_arg_table! s begin "--maxevents", "-n" help = "Maximum number of events to read. -1 to read all events from the file." arg_type = Int default = -1 "--skip", "-s" help = "Number of events to skip at beginning of the file." arg_type = Int default = 0 "--ptmin" help = "Minimum p_t for final inclusive jets (energy unit is the same as the input clusters, usually GeV)" arg_type = Float64 default = 5.0 "--exclusive-dcut" help = "Return all exclusive jets where further merging would have d>d_cut" arg_type = Float64 "--exclusive-njets" help = "Return all exclusive jets once clusterisation has produced n jets" arg_type = Int "--distance", "-R" help = "Distance parameter for jet merging" arg_type = Float64 default = 0.4 "--algorithm", "-A" help = """Algorithm to use for jet reconstruction: $(join(JetReconstruction.AllJetRecoAlgorithms, ", "))""" arg_type = JetAlgorithm.Algorithm "--power", "-p" help = """Power value for jet reconstruction""" arg_type = Float64 "--strategy", "-S" help = """Strategy for the algorithm, valid values: $(join(JetReconstruction.AllJetRecoStrategies, ", "))""" arg_type = RecoStrategy.Strategy default = RecoStrategy.Best "--nsamples", "-m" help = "Number of measurement points to acquire." arg_type = Int default = 1 "--dump-clusterseq" help = "Dump the cluster sequence for each event" action = :store_true "--gcoff" help = "Turn off Julia garbage collector during each time measurement." action = :store_true "--profile" help = """Profile code and generate a flame graph; the results will be stored in 'profile/PROFILE' subdirectory, where PROFILE is the value given to this option)""" "--alloc" help = "Provide memory allocation statistics." action = :store_true "--dump" help = "Write list of reconstructed jets to a JSON formatted file" "--info" help = "Print info level log messages" action = :store_true "--debug" help = "Print debug level log messages" action = :store_true "file" help = "HepMC3 event file in HepMC3 to read." required = true end return parse_args(args, s; as_symbols = true) end function main() args = parse_command_line(ARGS) if args[:debug] logger = ConsoleLogger(stdout, Logging.Debug) elseif args[:info] logger = ConsoleLogger(stdout, Logging.Info) else logger = ConsoleLogger(stdout, Logging.Warn) end global_logger(logger) events::Vector{Vector{PseudoJet}} = read_final_state_particles(args[:file], maxevents = args[:maxevents], skipevents = args[:skip]) if isnothing(args[:algorithm]) && isnothing(args[:power]) @warn "Neither algorithm nor power specified, defaulting to AntiKt" args[:algorithm] = JetAlgorithm.AntiKt end jet_process(events, distance = args[:distance], algorithm = args[:algorithm], p = args[:power], strategy = args[:strategy], ptmin = args[:ptmin], dcut = args[:exclusive_dcut], njets = args[:exclusive_njets], nsamples = args[:nsamples], gcoff = args[:gcoff], profile = args[:profile], alloc = args[:alloc], dump = args[:dump], dump_cs = args[:dump_clusterseq]) nothing end main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
2516
### A Pluto.jl notebook ### # v0.19.45 using Markdown using InteractiveUtils # ╔═╡ f3a6edec-9d40-4044-89bc-4ff1656f634f using Pkg # ╔═╡ cd974dcf-ab96-4ff2-b76a-e18032343581 Pkg.activate(".") # ╔═╡ d25974b4-6531-408f-a0f7-ae7ae4a731d4 using Revise # ╔═╡ 32b48d85-40cb-42c8-b3ad-ab613081da38 using JetReconstruction # ╔═╡ dff6a188-2cbe-11ef-32d0-73c4c05efad2 md"""# Jet Reconstruction Constituents Example Perform a simple reconstruction example and show how to retrieve constituent jets.""" # ╔═╡ b16f99a0-31ec-4e8f-99c6-7a6fcb16cbee md"As this is running in development, use `Pkg` to activate the local development version of the package and use `Revise` to track code changes. (Currently you must use the `jet-constituents` branch of `JetReconstruction`.) " # ╔═╡ 79f24ec1-a63e-4e96-bd67-49661125be66 input_file = joinpath(dirname(pathof(JetReconstruction)), "..", "test", "data", "events.hepmc3.gz") # ╔═╡ 7d7a8b11-19b3-4b83-a0b1-8201b74b588e events = read_final_state_particles(input_file) # ╔═╡ fe05d243-6d19-47cc-814b-0f44e5424233 md"Event to pick" # ╔═╡ 6bbf7e6a-30a2-4917-bc36-e0da4f2cd098 event_no = 1 # ╔═╡ 2a899d67-71f3-4fe0-8104-7633a44a06a8 cluster_seq = jet_reconstruct(events[event_no], p = 1, R = 1.0) # ╔═╡ 043cc484-e537-409c-8aa2-e4904b5dc283 md"Retrieve the exclusive pj_jets, but as `PseudoJet` types" # ╔═╡ 0d8d4664-915f-4f28-9d5a-6e03cb8d7d8b pj_jets = inclusive_jets(cluster_seq; ptmin = 5.0, T = PseudoJet) # ╔═╡ 0bd764f9-d427-43fc-8342-603b6759ec8f md"Get the constituents of the first jet" # ╔═╡ 46a64c6f-51d7-4083-a953-ecc76882f21e my_constituents = JetReconstruction.constituents(pj_jets[1], cluster_seq) # ╔═╡ 300879ca-b53d-40b3-864a-1d46f2094123 begin println("Constituents of jet number $(event_no):") for c in my_constituents println(" $c") end end # ╔═╡ Cell order: # ╟─dff6a188-2cbe-11ef-32d0-73c4c05efad2 # ╟─b16f99a0-31ec-4e8f-99c6-7a6fcb16cbee # ╠═f3a6edec-9d40-4044-89bc-4ff1656f634f # ╠═cd974dcf-ab96-4ff2-b76a-e18032343581 # ╠═d25974b4-6531-408f-a0f7-ae7ae4a731d4 # ╠═32b48d85-40cb-42c8-b3ad-ab613081da38 # ╠═79f24ec1-a63e-4e96-bd67-49661125be66 # ╠═7d7a8b11-19b3-4b83-a0b1-8201b74b588e # ╟─fe05d243-6d19-47cc-814b-0f44e5424233 # ╠═6bbf7e6a-30a2-4917-bc36-e0da4f2cd098 # ╠═2a899d67-71f3-4fe0-8104-7633a44a06a8 # ╟─043cc484-e537-409c-8aa2-e4904b5dc283 # ╠═0d8d4664-915f-4f28-9d5a-6e03cb8d7d8b # ╟─0bd764f9-d427-43fc-8342-603b6759ec8f # ╠═46a64c6f-51d7-4083-a953-ecc76882f21e # ╠═300879ca-b53d-40b3-864a-1d46f2094123
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
1248
# # Jet Reconstruction Constituents Example # # Perform a simple reconstruction example and show how to retrieve constituent jets. # # N.B. currently you must use the `jet-constituents` branch of `JetReconstruction`. using JetReconstruction using LorentzVectorHEP using Logging logger = ConsoleLogger(stdout, Logging.Info) global_logger(logger) input_file = joinpath(dirname(pathof(JetReconstruction)), "..", "test", "data", "events.hepmc3.gz") events = read_final_state_particles(input_file) # Event to pick event_no = 1 cluster_seq = jet_reconstruct(events[event_no], p = 1, R = 1.0) # Retrieve the exclusive pj_jets, but as `PseudoJet` types pj_jets = inclusive_jets(cluster_seq; ptmin = 5.0, T = PseudoJet) # Get the constituents of the first jet my_constituents = JetReconstruction.constituents(pj_jets[1], cluster_seq) println("Constituents of jet number $(event_no):") for c in my_constituents println(" $c") end # Now show how to convert to LorentzVectorCyl: println("\nConstituents of jet number $(event_no) as LorentzVectorCyl:") for c in my_constituents println(" $(LorentzVectorCyl(JetReconstruction.pt(c), JetReconstruction.rapidity(c), JetReconstruction.phi(c), JetReconstruction.mass(c)))") end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
5525
#! /usr/bin/env julia """ Simple example of a jet reconstruction code that reads in a text HepMC3 file and performs standard jet reconstruction on the final state particles. """ using ArgParse using Profile using Logging using JSON using LorentzVectorHEP using JetReconstruction # Parsing for algorithm and strategy enums include(joinpath(@__DIR__, "parse-options.jl")) """ Top level call funtion for demonstrating the use of jet reconstruction This uses the "jet_reconstruct" wrapper, so algorithm switching happens inside the JetReconstruction package itself. Final jets can be serialised if the "dump" option is given """ function jet_process(events::Vector{Vector{PseudoJet}}; distance::Real = 0.4, algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing, p::Union{Real, Nothing} = nothing, ptmin::Real = 5.0, dcut = nothing, njets = nothing, strategy::RecoStrategy.Strategy, dump::Union{String, Nothing} = nothing) # Set consistent algorithm and power (p, algorithm) = JetReconstruction.get_algorithm_power_consistency(p = p, algorithm = algorithm) @info "Jet reconstruction will use $(algorithm) with power $(p)" # A friendly label for the algorithm and final jet selection if !isnothing(njets) @info "Will produce exclusive jets with n_jets = $(njets)" elseif !isnothing(dcut) @info "Will produce exclusive jets with dcut = $(dcut)" else @info "Will produce inclusive jets with ptmin = $(ptmin)" end # Now run over each event for (ievt, event) in enumerate(events) # Run the jet reconstruction cluster_seq = jet_reconstruct(event, R = distance, p = p, algorithm = algorithm, strategy = strategy) # Now select jets, with inclusive or exclusive parameters if !isnothing(njets) finaljets = exclusive_jets(cluster_seq; njets = njets) elseif !isnothing(dcut) finaljets = exclusive_jets(cluster_seq; dcut = dcut) else finaljets = inclusive_jets(cluster_seq; ptmin = ptmin) end @info begin jet_output = "Event $(ievt)\n" sort!(finaljets, by = x -> pt(x), rev = true) for (ijet, jet) in enumerate(finaljets) jet_output *= " $(ijet) - $(jet)\n" end "$(jet_output)" end if !isnothing(dump) push!(jet_collection, FinalJets(ievt, finaljets)) end end if !isnothing(dump) open(dump, "w") do io JSON.print(io, jet_collection, 2) end end end function parse_command_line(args) s = ArgParseSettings(autofix_names = true) @add_arg_table! s begin "--maxevents", "-n" help = "Maximum number of events to read. -1 to read all events from the file." arg_type = Int default = -1 "--skip", "-s" help = "Number of events to skip at beginning of the file." arg_type = Int default = 0 "--ptmin" help = "Minimum p_t for final inclusive jets (energy unit is the same as the input clusters, usually GeV)" arg_type = Float64 default = 5.0 "--exclusive-dcut" help = "Return all exclusive jets where further merging would have d>d_cut" arg_type = Float64 "--exclusive-njets" help = "Return all exclusive jets once clusterisation has produced n jets" arg_type = Int "--distance", "-R" help = "Distance parameter for jet merging" arg_type = Float64 default = 0.4 "--algorithm", "-A" help = """Algorithm to use for jet reconstruction: $(join(JetReconstruction.AllJetRecoAlgorithms, ", "))""" arg_type = JetAlgorithm.Algorithm "--power", "-p" help = """Power value for jet reconstruction""" arg_type = Float64 "--strategy", "-S" help = """Strategy for the algorithm, valid values: $(join(JetReconstruction.AllJetRecoStrategies, ", "))""" arg_type = RecoStrategy.Strategy default = RecoStrategy.Best "--dump" help = "Write list of reconstructed jets to a JSON formatted file" "file" help = "HepMC3 event file in HepMC3 to read." required = true end return parse_args(args, s; as_symbols = true) end function main() args = parse_command_line(ARGS) logger = ConsoleLogger(stdout, Logging.Info) global_logger(logger) events::Vector{Vector{PseudoJet}} = read_final_state_particles(args[:file], maxevents = args[:maxevents], skipevents = args[:skip]) if isnothing(args[:algorithm]) && isnothing(args[:power]) @warn "Neither algorithm nor power specified, defaulting to AntiKt" args[:algorithm] = JetAlgorithm.AntiKt end jet_process(events, distance = args[:distance], algorithm = args[:algorithm], p = args[:power], strategy = args[:strategy], ptmin = args[:ptmin], dcut = args[:exclusive_dcut], njets = args[:exclusive_njets], dump = args[:dump]) nothing end main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
587
""" Add `parse_item` code for interpeting `JetAlgorithm.Algorithm` and `RecoStrategy.Strategy` types from the command line. """ function ArgParse.parse_item(::Type{RecoStrategy.Strategy}, x::AbstractString) s = tryparse(RecoStrategy.Strategy, x) if s === nothing throw(ErrorException("Invalid value for strategy: $(x)")) end s end function ArgParse.parse_item(::Type{JetAlgorithm.Algorithm}, x::AbstractString) s = tryparse(JetAlgorithm.Algorithm, x) if s === nothing throw(ErrorException("Invalid value for algorithm: $(x)")) end s end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
3302
### A Pluto.jl notebook ### # v0.19.45 using Markdown using InteractiveUtils # This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error). macro bind(def, element) quote local iv = try Base.loaded_modules[Base.PkgId(Base.UUID("6e696c72-6542-2067-7265-42206c756150"), "AbstractPlutoDingetjes")].Bonds.initial_value catch b -> missing end local el = $(esc(element)) global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : iv(el) el end end # ╔═╡ cf88f2f9-bf19-47e2-ae04-b4476eb26efb import Pkg # ╔═╡ 24dd666c-49be-4c44-9b9d-d27128c1ffbb Pkg.activate(".") # ╔═╡ 0a1a8211-507b-4dc0-9060-0d18a5a695a4 using GLMakie # ╔═╡ f7ec7400-bbb2-4f28-9f13-881dea775f41 using PlutoUI # ╔═╡ 32b48d85-40cb-42c8-b3ad-ab613081da38 using JetReconstruction # ╔═╡ dff6a188-2cbe-11ef-32d0-73c4c05efad2 md"""# Jet Reconstruction Visualisation This Pluto script visualises the result of a jet reconstruction process. Use the sliders below to change the reconstructed event, the algorithm and the jet radius parameter.""" # ╔═╡ 4e569f74-570b-4b30-9ea7-9cbc420f50f8 md"Event number:" # ╔═╡ 83030910-8d00-4949-b69e-fa492b61db6b @bind event_no PlutoUI.Slider(1:100, show_value = true) # ╔═╡ 306f6e66-788c-4a95-a9df-3ac4c37cf776 md"``k_T`` algorithm power (-1=Anti-``k_T``, 0 = Cambridge/Aachen, 1=Inclusive kT)" # ╔═╡ 864d7a31-b634-4edc-b6c4-0835fee53304 @bind power PlutoUI.Slider(-1:1, show_value = true) # ╔═╡ 9f7988a5-041e-4a83-9da9-d48db34cea98 md"Jet radius parameter" # ╔═╡ 187315d4-ac3c-4847-ae00-e7da1b27d63f @bind radius PlutoUI.Slider(range(start = 0.4, stop = 2.0, step = 0.1), show_value = true) # ╔═╡ 79f24ec1-a63e-4e96-bd67-49661125be66 input_file = joinpath(dirname(pathof(JetReconstruction)), "..", "test", "data", "events.hepmc3.gz") # ╔═╡ 7d7a8b11-19b3-4b83-a0b1-8201b74b588e events::Vector{Vector{PseudoJet}} = read_final_state_particles(input_file, maxevents = event_no, skipevents = event_no); # ╔═╡ 2a899d67-71f3-4fe0-8104-7633a44a06a8 cs = jet_reconstruct(events[1], p = power, R = radius) # ╔═╡ b5fd4e96-d073-4e5f-8de1-41addaa0dc3d jetreco_vis = jetsplot(events[1], cs; Module = GLMakie) # ╔═╡ 81b14eba-6981-4943-92fe-529c53b0ac35 display(jetreco_vis); # ╔═╡ Cell order: # ╟─dff6a188-2cbe-11ef-32d0-73c4c05efad2 # ╠═cf88f2f9-bf19-47e2-ae04-b4476eb26efb # ╠═24dd666c-49be-4c44-9b9d-d27128c1ffbb # ╠═0a1a8211-507b-4dc0-9060-0d18a5a695a4 # ╠═f7ec7400-bbb2-4f28-9f13-881dea775f41 # ╠═32b48d85-40cb-42c8-b3ad-ab613081da38 # ╟─4e569f74-570b-4b30-9ea7-9cbc420f50f8 # ╟─83030910-8d00-4949-b69e-fa492b61db6b # ╟─306f6e66-788c-4a95-a9df-3ac4c37cf776 # ╟─864d7a31-b634-4edc-b6c4-0835fee53304 # ╟─9f7988a5-041e-4a83-9da9-d48db34cea98 # ╟─187315d4-ac3c-4847-ae00-e7da1b27d63f # ╟─79f24ec1-a63e-4e96-bd67-49661125be66 # ╠═7d7a8b11-19b3-4b83-a0b1-8201b74b588e # ╠═2a899d67-71f3-4fe0-8104-7633a44a06a8 # ╠═b5fd4e96-d073-4e5f-8de1-41addaa0dc3d # ╠═81b14eba-6981-4943-92fe-529c53b0ac35
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
2624
#! /usr/bin/env julia """Use the visualisation tools to plot the reconstructed jets""" using ArgParse using Logging using CairoMakie using JetReconstruction # Parsing for algorithm and strategy enums include(joinpath(@__DIR__, "parse-options.jl")) function main() s = ArgParseSettings(autofix_names = true) @add_arg_table s begin "--event", "-e" help = "Event in file to visualise" arg_type = Int default = 1 "--ptmin" help = "Minimum p_t for final inclusive jets (energy unit is the same as the input clusters, usually GeV)" arg_type = Float64 default = 5.0 "--exclusive-dcut" help = "Return all exclusive jets where further merging would have d>d_cut" arg_type = Float64 "--exclusive-njets" help = "Return all exclusive jets once clusterisation has produced n jets" arg_type = Int "--distance", "-R" help = "Distance parameter for jet merging" arg_type = Float64 default = 0.4 "--algorithm", "-A" help = """Algorithm to use for jet reconstruction: $(join(JetReconstruction.AllJetRecoAlgorithms, ", "))""" arg_type = JetAlgorithm.Algorithm "--power", "-p" help = """Power value for jet reconstruction""" arg_type = Float64 "--strategy", "-S" help = """Strategy for the algorithm, valid values: $(join(JetReconstruction.AllJetRecoStrategies, ", "))""" arg_type = RecoStrategy.Strategy default = RecoStrategy.Best "file" help = "HepMC3 event file in HepMC3 to read" required = true "output" help = "File for output image" default = "jetvis.png" end args = parse_args(ARGS, s; as_symbols = true) logger = ConsoleLogger(stdout, Logging.Info) global_logger(logger) events::Vector{Vector{PseudoJet}} = read_final_state_particles(args[:file], maxevents = args[:event], skipevents = args[:event]) (p, algorithm) = JetReconstruction.get_algorithm_power_consistency(p = args[:power], algorithm = args[:algorithm]) cs = jet_reconstruct(events[1], R = args[:distance], p = p, algorithm = algorithm, strategy = args[:strategy]) plt = jetsplot(events[1], cs; Module = CairoMakie) save(args[:output], plt) @info "Saved jet visualisation to $(args[:output])" end main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
14499
## Jet visualisation module JetVisualisation using JetReconstruction using Makie # Set font size generally (as opposed to xlabelsize=20, etc.) const jetreco_theme = Theme(fontsize = 24) """ jetsplot(objects, cs::ClusterSequence; barsize_phi=0.1, barsize_eta=0.1, colormap=:glasbey_hv_n256, Module=Main) Plots a 3d bar chart that represents jets. Takes `objects`, an array of objects to display (should be the same array you have passed to `jet_reconstruct` to get the `cs::ClusterSequence`), and the `cs::ClusterSequence` itself as arguments. Optional arguments: `barsize_phi::Real` — width of a bar along the ϕ axis; `barsize_eta::Real` — width of a bar along the η axis; `colormap::Symbol` — Makie colour map; `Module` — the module where you have your Makie (see below); ``` # example using CairoMakie # use any other Makie that you have here jetsplot([object1, object2, object3], cluster_sequence_I_got_from_jet_reconstruct; Module=CairoMakie) ``` This function needs `Makie.jl` to work. You should install and import/use a specific backend yourself. `jetsplot` works with `CairoMakie`, `WGLMakie`, `GLMakie`, etc. Additionally, you can specify the module where you have your `Makie` explicitly: ``` import CairoMakie jetsplot(my_objects, cs, Module=CairoMakie) import GLMakie jetsplot(my_objects, cs, Module=GLMakie) using WGLMakie jetsplot(my_objects, cs, Module=Main) #default ``` """ function JetReconstruction.jetsplot(objects, cs::ClusterSequence; barsize_phi = 0.1, barsize_eta = 0.1, colormap = :glasbey_hv_n256, Module = Makie) idx_arrays = Vector{Int}[] for elt in cs.history elt.parent2 == JetReconstruction.BeamJet || continue push!(idx_arrays, JetReconstruction.get_all_ancestors(elt.parent1, cs)) end jetsplot(objects, idx_arrays; barsize_phi, barsize_eta, colormap, Module) end """ `jetsplot(objects, idx_arrays; barsize_phi=0.1, barsize_eta=0.1, colormap=:glasbey_hv_n256, Module=Main)` Plots a 3d bar chart that represents jets. Takes an `objects` array of objects to display and `idx_arrays`, an array of arrays with indeces, where `idx_arrays[i]` gives indeces of `objects` that form the jet number `i`. This function's signature might not be the most practical for the current version of the JetReconstruction.jl package, as it has been written during the early stage of development. There is now an overload of it that takes a `ClusterSequence` object as its argument. Optional arguments: `barsize_phi::Real` — width of a bar along the ϕ axis; `barsize_eta::Real` — width of a bar along the η axis; `colormap::Symbol` — Makie colour map; `Module` — the module where you have your Makie (see below); ``` # example using CairoMakie # use any other Makie that you have here jetsplot([object1, object2, object3], [[1], [2, 3]]) ``` The example above plots `object1` as a separate jet in one colour and `object2` and `object3` together in another colour. This function needs `Makie.jl` to work. You should install and import/use a specific backend yourself. `jetsplot` works with `CairoMakie`, `WGLMakie`, `GLMakie`, etc. Additionally, you can specify the module where you have your `Makie` explicitly: ``` import CairoMakie jetsplot(my_objects, my_colour_arrays, Module=CairoMakie) import GLMakie jetsplot(my_objects, my_colour_arrays, Module=GLMakie) using WGLMakie jetsplot(my_objects, my_colour_arrays, Module=Main) #default ``` """ function JetReconstruction.jetsplot(objects, idx_arrays; barsize_phi = 0.1, barsize_eta = 0.1, colormap = :glasbey_hv_n256, Module = Main) cs = fill(0, length(objects)) # colours for i in 1:length(idx_arrays), j in idx_arrays[i] cs[j] = i end pts = sqrt.(JetReconstruction.pt2.(objects)) set_theme!(jetreco_theme) Module.meshscatter(Module.Point3f.(JetReconstruction.phi.(objects), JetReconstruction.rapidity.(objects), 0pts); color = cs, markersize = Module.Vec3f.(barsize_phi, barsize_eta, pts), colormap = colormap, marker = Module.Rect3f(Module.Vec3f(0), Module.Vec3f(1)), figure = (size = (700, 600),), axis = (type = Module.Axis3, perspectiveness = 0.5, azimuth = 2.6, elevation = 0.5, xlabel = L"\phi", ylabel = L"y", zlabel = L"p_T", limits = (nothing, nothing, nothing, nothing, 0, findmax(pts)[1] + 10)), shading = NoShading) end function JetReconstruction.jetsplot(cs::ClusterSequence, reco_state::Dict{Int, JetReconstruction.JetWithAncestors}; barsize_phi = 0.1, barsize_y = 0.1, colormap = :glasbey_category10_n256, Module = Makie) # Setup the marker as a square object jet_plot_marker = Rect3f(Vec3f(0), Vec3f(1)) # Get the jet variables to plot phis = [JetReconstruction.phi(x.self) for x in values(reco_state)] ys = [JetReconstruction.rapidity(x.self) for x in values(reco_state)] pts = [JetReconstruction.pt(x.self) for x in values(reco_state)] # The core points to plot are on the pt=0 axis, with the marker size # scaled up to the p_T of the jet jet_plot_points = Point3f.(phis .- (barsize_phi / 2), ys .- (barsize_y / 2), 0pts) jet_plot_marker_size = Vec3f.(barsize_phi, barsize_y, pts) # Colours are defined from the rank of the ancestor jets jet_plot_colours = [x.jet_rank for x in values(reco_state)] # Limits for rapidity and p_T are set to the maximum values in the data # (For ϕ the limits are (0, 2π)) min_rap = max_rap = max_pt = 0.0 for jet in cs.jets min_rap = min(min_rap, JetReconstruction.rapidity(jet)) max_rap = max(max_rap, JetReconstruction.rapidity(jet)) max_pt = max(max_pt, JetReconstruction.pt(jet)) end set_theme!(jetreco_theme) fig, ax, plt_obj = Module.meshscatter(jet_plot_points; markersize = jet_plot_marker_size, marker = jet_plot_marker, colormap = colormap, color = jet_plot_colours, colorrange = (1, 256), figure = (size = (700, 600),), axis = (type = Axis3, perspectiveness = 0.5, azimuth = 2.7, elevation = 0.5, xlabel = L"\phi", ylabel = L"y", zlabel = L"p_T", limits = (0, 2π, min_rap - 0.5, max_rap + 0.5, 0, max_pt + 10)), shading = NoShading) fig, ax, plt_obj end """ animatereco(cs::ClusterSequence, filename; barsize_phi = 0.1, barsize_y = 0.1, colormap = :glasbey_category10_n256, perspective = 0.5, azimuth = 2.7, elevation = 0.5, framerate = 5, ancestors = false, Module = Makie) Animate the jet reconstruction process and save it as a video file. # Arguments - `cs::ClusterSequence`: The cluster sequence object containing the jets. - `filename`: The name of the output video file. # Optional Arguments - `barsize_phi=0.1`: The size of the bars in the phi direction. - `barsize_y=0.1`: The size of the bars in the y direction. - `colormap=:glasbey_category10_n256`: The colormap to use for coloring the jets. - `perspective=0.5`: The perspective of the plot. - `azimuth=2.7`: The azimuth angle of the plot. - `elevation=0.5`: The elevation angle of the plot. - `framerate=5`: The framerate of the output video. - `end_frames=0`: The number of static frames to show at the end of the animation. This can be useful to show the final state of the jets for a longer time. - `title=nothing`: The title to add to the plot. - `ancestors=false`: Whether to include ancestors of the jets in the animation. When `true` the ancestors of the jets will be plotted as well, as height zero bars, with the same colour as the jet they are ancestors of. - `Module`: The plotting module to use. Default is `Makie`. For `perspective`, `azimuth`, and `elevation`, a single value can be passed for a fixed viewpoint, or a tuple of two values for a changing viewpoint. The viewpoint will then change linearly between the two values over the course of the animation. # Returns - `fig`: The figure object representing the final frame. """ function JetReconstruction.animatereco(cs::ClusterSequence, filename; barsize_phi = 0.1, barsize_y = 0.1, colormap = :glasbey_category10_n256, perspective::Union{Real, Tuple{Real, Real}} = 0.5, azimuth::Union{Real, Tuple{Real, Real}} = 2.7, elevation::Union{Real, Tuple{Real, Real}} = 0.5, framerate = 5, end_frames = 0, ancestors = false, title = nothing, Module = Makie) # Setup the marker as a square object jet_plot_marker = Rect3f(Vec3f(0), Vec3f(1)) # Get the number of meaningful reconstruction steps and rank the initial # particles by p_T merge_steps = JetReconstruction.merge_steps(cs) jet_ranks = JetReconstruction.jet_ranks(cs) # End point of the catagorical color map # (How to get this programmatically from the CM Symbol?) colormap_end = 256 # Keep plot limits constant min_rap = max_rap = max_pt = 0.0 for jet in cs.jets min_rap = min(min_rap, JetReconstruction.rapidity(jet)) max_rap = max(max_rap, JetReconstruction.rapidity(jet)) max_pt = max(max_pt, JetReconstruction.pt(jet)) end # Get the reconstruction state at each meaningful iteration # And calculate the plot parameters all_jet_plot_points = Vector{Vector{Point3f}}() all_jet_plot_marker_size = Vector{Vector{Vec3f}}() all_jet_plot_colours = Vector{Vector{Int}}() for step in 0:merge_steps reco_state = JetReconstruction.reco_state(cs, jet_ranks; iteration = step) phis = [JetReconstruction.phi(x.self) for x in values(reco_state)] ys = [JetReconstruction.rapidity(x.self) for x in values(reco_state)] pts = [JetReconstruction.pt(x.self) for x in values(reco_state)] push!(all_jet_plot_points, Point3f.(phis .- (barsize_phi / 2), ys .- (barsize_y / 2), 0pts)) push!(all_jet_plot_marker_size, Vec3f.(barsize_phi, barsize_y, pts)) push!(all_jet_plot_colours, [mod1(x.jet_rank, colormap_end) for x in values(reco_state)]) if ancestors for jet_entry in values(reco_state) for ancestor in jet_entry.ancestors ancestor_jet = cs.jets[ancestor] push!(all_jet_plot_points[end], Point3f(JetReconstruction.phi(ancestor_jet) - (barsize_phi / 2), JetReconstruction.rapidity(ancestor_jet) - (barsize_y / 2), 0.0)) push!(all_jet_plot_marker_size[end], Vec3f(barsize_phi, barsize_y, 0.001max_pt)) push!(all_jet_plot_colours[end], mod1(jet_entry.jet_rank, colormap_end)) end end end end # Keep plot limits constant min_rap = max_rap = max_pt = 0.0 for jet in cs.jets min_rap = min(min_rap, JetReconstruction.rapidity(jet)) max_rap = max(max_rap, JetReconstruction.rapidity(jet)) max_pt = max(max_pt, JetReconstruction.pt(jet)) end # Setup an observable for the iteration number it_obs = Observable(0) jet_plot_points_obs = @lift all_jet_plot_points[$it_obs + 1] jet_plot_marker_size_obs = @lift all_jet_plot_marker_size[$it_obs + 1] jet_plot_colours_obs = @lift all_jet_plot_colours[$it_obs + 1] # We may want to have a shifting viewpoint azimuth_axis = typeof(azimuth) <: Tuple ? @lift(azimuth[1]+$it_obs / merge_steps * (azimuth[2] - azimuth[1])) : azimuth elevation_axis = typeof(elevation) <: Tuple ? @lift(elevation[1]+$it_obs / merge_steps * (elevation[2] - elevation[1])) : elevation perspective_axis = typeof(perspective) <: Tuple ? @lift(perspective[1]+$it_obs / merge_steps * (perspective[2] - perspective[1])) : perspective set_theme!(jetreco_theme) ax = (type = Axis3, title = isnothing(title) ? "" : title, xlabel = L"\phi", ylabel = L"y", zlabel = L"p_T", limits = (0, 2π, min_rap - 0.5, max_rap + 0.5, 0, max_pt + 10), perspectiveness = perspective_axis, azimuth = azimuth_axis, elevation = elevation_axis) fig = Module.meshscatter(jet_plot_points_obs; markersize = jet_plot_marker_size_obs, marker = jet_plot_marker, colormap = colormap, color = jet_plot_colours_obs, colorrange = (1, colormap_end), figure = (size = (800, 600),), axis = ax, shading = NoShading) record(fig, filename, 0:(merge_steps + end_frames); framerate = framerate) do iteration it_obs[] = min(iteration, merge_steps) end fig end end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
5359
# EnumX provides scoped enums, which are nicer using EnumX """ enum RecoStrategy Scoped enumeration (using EnumX) representing the different strategies for jet reconstruction. ## Fields - `Best`: The best strategy. - `N2Plain`: The plain N2 strategy. - `N2Tiled`: The tiled N2 strategy. """ @enumx T=Strategy RecoStrategy Best N2Plain N2Tiled const AllJetRecoStrategies = [String(Symbol(x)) for x in instances(RecoStrategy.Strategy)] """ enum T Scoped enumeration (using EnumX) representing different jet algorithms used in the JetReconstruction module. ## Fields - `AntiKt`: The Anti-Kt algorithm. - `CA`: The Cambridge/Aachen algorithm. - `Kt`: The Inclusive-Kt algorithm. - `GenKt`: The Generalised Kt algorithm (with arbitrary power). - `EEKt`: The Generalised e+e- kt algorithm. - `Durham`: The e+e- kt algorithm, aka Durham. """ @enumx T=Algorithm JetAlgorithm AntiKt CA Kt GenKt EEKt Durham const AllJetRecoAlgorithms = [String(Symbol(x)) for x in instances(JetAlgorithm.Algorithm)] """ const varpower_algorithms A constant array that contains the jet algorithms for which power is variable. """ const varpower_algorithms = [JetAlgorithm.GenKt, JetAlgorithm.EEKt] """ power2algorithm A dictionary that maps power values to corresponding jet algorithm used for pp jet reconstruction, where these are fixed. """ const power2algorithm = Dict(-1 => JetAlgorithm.AntiKt, 0 => JetAlgorithm.CA, 1 => JetAlgorithm.Kt) """ algorithm2power A dictionary that maps pp algorithm names to their corresponding power values. The dictionary is created by iterating over the `power2algorithm` dictionary and swapping the keys and values. """ const algorithm2power = Dict((i.second, i.first) for i in power2algorithm) """ Base.tryparse(E::Type{<:Enum}, str::String) Parser that converts a string to an enum value if it exists, otherwise returns nothing. """ Base.tryparse(E::Type{<:Enum}, str::String) = let insts = instances(E), p = findfirst(==(Symbol(str)) ∘ Symbol, insts) p !== nothing ? insts[p] : nothing end """ get_algorithm_power_consistency(; p::Union{Real, Nothing}, algorithm::Union{JetAlgorithm, Nothing}) Get the algorithm and power consistency correct This function checks the consistency between the algorithm and power parameters. If the algorithm is specified, it checks if the power parameter is consistent with the algorithm's known power. If the power parameter is not specified, it sets the power parameter based on the algorithm. If neither the algorithm nor the power parameter is specified, it throws an `ArgumentError`. # Arguments - `p::Union{Real, Nothing}`: The power value. - `algorithm::Union{JetAlgorithm, Nothing}`: The algorithm. # Returns A named tuple of the consistent power and algorithm values. # Throws - `ArgumentError`: If the algorithm and power are inconsistent or if neither the algorithm nor the power is specified. """ function get_algorithm_power_consistency(; p::Union{Real, Nothing}, algorithm::Union{JetAlgorithm.Algorithm, Nothing}) # For the case where an algorithm has a variable power value # we need to check that the power value and algorithm are both specified if algorithm in varpower_algorithms if isnothing(p) throw(ArgumentError("Power must be specified for algorithm $algorithm")) end # And then we just return what these are... return (p = p, algorithm = algorithm) end # Some algorithms have fixed power values if algorithm == JetAlgorithm.Durham return (p = 1, algorithm = algorithm) end # Otherwise we check the consistency between the algorithm and power if !isnothing(algorithm) power_from_alg = algorithm2power[algorithm] if !isnothing(p) && p != power_from_alg throw(ArgumentError("Algorithm and power are inconsistent")) end return (p = power_from_alg, algorithm = algorithm) else if isnothing(p) throw(ArgumentError("Either algorithm or power must be specified")) end # Set the algorithm from the power algorithm_from_power = power2algorithm[p] return (p = p, algorithm = algorithm_from_power) end end """Allow a check for algorithm and power consistency""" function check_algorithm_power_consistency(; p::Union{Real, Nothing}, algorithm::Union{JetAlgorithm.Algorithm, Nothing}) get_algorithm_power_consistency(p = p, algorithm = algorithm) return true end """ is_pp(algorithm::JetAlgorithm.Algorithm) Check if the algorithm is a pp reconstruction algorithm. # Returns `true` if the algorithm is a pp reconstruction algorithm, `false` otherwise. """ function is_pp(algorithm::JetAlgorithm.Algorithm) return algorithm in [JetAlgorithm.AntiKt, JetAlgorithm.CA, JetAlgorithm.Kt] end """ is_ee(algorithm::JetAlgorithm.Algorithm) Check if the algorithm is a e+e- reconstruction algorithm. # Returns `true` if the algorithm is a e+e- reconstruction algorithm, `false` otherwise. """ function is_ee(algorithm::JetAlgorithm.Algorithm) return algorithm in [JetAlgorithm.EEKt, JetAlgorithm.Durham] end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
22197
# Structure definitions for the Tiled algorithm, with linked list # and TiledJets (a la FastJet) # # Original Julia implementation by Philippe Gras, # ported to this package by Graeme Stewart using Accessors using Logging # Constant values for "magic numbers" that represent special states # in the history. These are negative integers, but as this is # not runtime critical, so could consider a Union{Int,Emum} "Invalid child for this jet, meaning it did not recombine further" const Invalid = -3 "Original cluster so it has no parent" const NonexistentParent = -2 "Cluster recombined with beam" const BeamJet = -1 """ struct HistoryElement A struct holding a record of jet mergers and finalisations Fields: - `parent1`: Index in history where first parent of this jet was created (NonexistentParent if this jet is an original particle) - `parent2`: Index in history where second parent of this jet was created (NonexistentParent if this jet is an original particle); BeamJet if this history entry just labels the fact that the jet has recombined with the beam) - `child`: Index in history where the current jet is recombined with another jet to form its child. It is Invalid if this jet does not further recombine. - `jetp_index`: Index in the jets vector where we will find the PseudoJet object corresponding to this jet (i.e. the jet created at this entry of the history). NB: if this element of the history corresponds to a beam recombination, then `jetp_index=Invalid`. - `dij`: The distance corresponding to the recombination at this stage of the clustering. - `max_dij_so_far`: The largest recombination distance seen so far in the clustering history. """ struct HistoryElement parent1::Int parent2::Int child::Int jetp_index::Int dij::Float64 max_dij_so_far::Float64 end """ HistoryElement(jetp_index) Constructs a `HistoryElement` object with the given `jetp_index`, used for initialising the history with original particles. # Arguments - `jetp_index`: The index of the jetp. # Returns A `HistoryElement` object. """ HistoryElement(jetp_index) = HistoryElement(NonexistentParent, NonexistentParent, Invalid, jetp_index, 0.0, 0.0) """ initial_history(particles) Create an initial history for the given particles. # Arguments - `particles`: The initial vector of stable particles. # Returns - `history`: An array of `HistoryElement` objects. - `Qtot`: The total energy in the event. """ function initial_history(particles) # reserve sufficient space for everything history = Vector{HistoryElement}(undef, length(particles)) sizehint!(history, 2 * length(particles)) Qtot::Float64 = 0 for i in eachindex(particles) history[i] = HistoryElement(i) # get cross-referencing right from the Jets particles[i]._cluster_hist_index = i # determine the total energy in the event Qtot += particles[i].E end history, Qtot end """ struct ClusterSequence A struct holding the full history of a jet clustering sequence, including the final jets. # Fields - `algorithm::JetAlgorithm.Algorithm`: The algorithm used for clustering. - `strategy::RecoStrategy.Strategy`: The strategy used for clustering. - `power::Float64`: The power value used for the clustering algorithm (not that this value is always stored as a Float64 to be type stable) - `R::Float64`: The R parameter used for the clustering algorithm. - `jets::Vector{PseudoJet}`: The physical PseudoJets in the cluster sequence. Each PseudoJet corresponds to a position in the history. - `n_initial_jets::Int`: The initial number of particles used for exclusive jets. - `history::Vector{HistoryElement}`: The branching history of the cluster sequence. Each stage in the history indicates where to look in the jets vector to get the physical PseudoJet. - `Qtot::Any`: The total energy of the event. """ struct ClusterSequence algorithm::JetAlgorithm.Algorithm power::Float64 R::Float64 strategy::RecoStrategy.Strategy jets::Vector{FourMomentum} n_initial_jets::Int history::Vector{HistoryElement} Qtot::Any end """ ClusterSequence(algorithm::JetAlgorithm.Algorithm, p::Real, R::Float64, strategy::RecoStrategy.Strategy, jets, history, Qtot) Construct a `ClusterSequence` object. # Arguments - `algorithm::JetAlgorithm.Algorithm`: The algorithm used for clustering. - `p::Real`: The power value used for the clustering algorithm. - `R::Float64`: The R parameter used for the clustering algorithm. - `strategy::RecoStrategy.Strategy`: The strategy used for clustering. - `jets::Vector{PseudoJet}`: The physical PseudoJets in the cluster sequence. - `history::Vector{HistoryElement}`: The branching history of the cluster sequence. - `Qtot::Any`: The total energy of the event. """ ClusterSequence(algorithm::JetAlgorithm.Algorithm, p::Real, R::Float64, strategy::RecoStrategy.Strategy, jets, history, Qtot) = begin ClusterSequence(algorithm, Float64(p), R, strategy, jets, length(jets), history, Qtot) end """ add_step_to_history!(clusterseq::ClusterSequence, parent1, parent2, jetp_index, dij) Add a new jet's history into the recombination sequence. Arguments: - `clusterseq::ClusterSequence`: The cluster sequence object. - `parent1`: The index of the first parent. - `parent2`: The index of the second parent. - `jetp_index`: The index of the jet. - `dij`: The dij value. This function adds a new `HistoryElement` to the `history` vector of the `clusterseq` object. The `HistoryElement` contains information about the parents, child, jet index, dij value, and the maximum dij value so far. It also updates the child index of the parent elements. If the `parent1` or `parent2` have already been recombined, an `InternalError` is thrown. The `jetp_index` is used to update the `_cluster_hist_index` of the corresponding `PseudoJet` object. """ add_step_to_history!(clusterseq::ClusterSequence, parent1, parent2, jetp_index, dij) = begin max_dij_so_far = max(dij, clusterseq.history[end].max_dij_so_far) push!(clusterseq.history, HistoryElement(parent1, parent2, Invalid, jetp_index, dij, max_dij_so_far)) local_step = length(clusterseq.history) # println("Adding step $local_step: parent1=$parent1, parent2=$parent2, jetp_index=$jetp_index, dij=$dij") # Sanity check: make sure the particles have not already been recombined # # Note that good practice would make this an assert (since this is # a serious internal issue). However, we decided to throw an # InternalError so that the end user can decide to catch it and # retry the clustering with a different strategy. @assert parent1 >= 1 if clusterseq.history[parent1].child != Invalid error("Internal error. Trying to recombine an object that has previsously been recombined. Parent " * string(parent1) * "'s child index " * string(clusterseq.history[parent1].child) * ". Parent jet index: " * string(clusterseq.history[parent1].jetp_index) * ".") end hist_elem = clusterseq.history[parent1] clusterseq.history[parent1] = @set hist_elem.child = local_step if parent2 >= 1 clusterseq.history[parent2].child == Invalid || error("Internal error. Trying to recombine an object that has previsously been recombined. Parent " * string(parent2) * "'s child index " * string(clusterseq.history[parent1].child) * ". Parent jet index: " * string(clusterseq.history[parent2].jetp_index) * ".") hist_elem = clusterseq.history[parent2] clusterseq.history[parent2] = @set hist_elem.child = local_step end # Get cross-referencing right from PseudoJets if jetp_index != Invalid @assert jetp_index >= 1 clusterseq.jets[jetp_index]._cluster_hist_index = local_step end end """ inclusive_jets(clusterseq::ClusterSequence; ptmin = 0.0, T = LorentzVectorCyl) Return all inclusive jets of a ClusterSequence with pt > ptmin. # Arguments - `clusterseq::ClusterSequence`: The `ClusterSequence` object containing the clustering history and jets. - `ptmin::Float64 = 0.0`: The minimum transverse momentum (pt) threshold for the inclusive jets. - `T = LorentzVectorCyl`: The return type used for the selected jets. # Returns An array of `T` objects representing the inclusive jets. # Description This function computes the inclusive jets from a given `ClusterSequence` object. It iterates over the clustering history and checks the transverse momentum of each parent jet. If the transverse momentum is greater than or equal to `ptmin`, the jet is added to the array of inclusive jets. Valid return types are `LorentzVectorCyl` and `PseudoJet` (N.B. this will evolve in the future to be any subtype of `FourMomemntumBase`; currently unrecognised types will return `LorentzVectorCyl`). # Example ```julia inclusive_jets(clusterseq; ptmin = 10.0) ``` """ function inclusive_jets(clusterseq::ClusterSequence; ptmin = 0.0, T = LorentzVectorCyl) pt2min = ptmin * ptmin jets_local = T[] # sizehint!(jets_local, length(clusterseq.jets)) # For inclusive jets with a plugin algorithm, we make no # assumptions about anything (relation of dij to momenta, # ordering of the dij, etc.) # for elt in Iterators.reverse(clusterseq.history) for elt in clusterseq.history elt.parent2 == BeamJet || continue iparent_jet = clusterseq.history[elt.parent1].jetp_index jet = clusterseq.jets[iparent_jet] if pt2(jet) >= pt2min @debug "Added inclusive jet index $iparent_jet" if T == PseudoJet push!(jets_local, jet) else push!(jets_local, LorentzVectorCyl(pt(jet), rapidity(jet), phi(jet), mass(jet))) end end end jets_local end """ exclusive_jets(clusterseq::ClusterSequence; dcut = nothing, njets = nothing, T = LorentzVectorCyl) Return all exclusive jets of a ClusterSequence, with either a specific number of jets or a cut on the maximum distance parameter. # Arguments - `clusterseq::ClusterSequence`: The `ClusterSequence` object containing the clustering history and jets. - `dcut::Union{Nothing, Real}`: The distance parameter used to define the exclusive jets. If `dcut` is provided, the number of exclusive jets will be calculated based on this parameter. - `njets::Union{Nothing, Integer}`: The number of exclusive jets to be calculated. If `njets` is provided, the distance parameter `dcut` will be calculated based on this number. - `T = LorentzVectorCyl`: The return type used for the selected jets. **Note**: Either `dcut` or `njets` must be provided (but not both). # Returns - An array of `T` objects representing the exclusive jets. Valid return types are `LorentzVectorCyl` and `PseudoJet` (N.B. this will evolve in the future to be any subtype of `FourMomemntumBase`; currently unrecognised types will return `LorentzVectorCyl`) # Exceptions - `ArgumentError`: If neither `dcut` nor `njets` is provided. - `ArgumentError`: If the algorithm used in the `ClusterSequence` object is not suitable for exclusive jets. - `ErrorException`: If the cluster sequence is incomplete and exclusive jets are unavailable. # Examples ```julia exclusive_jets(clusterseq, dcut = 20.0) exclusive_jets(clusterseq, njets = 3, T = PseudoJet) ``` """ function exclusive_jets(clusterseq::ClusterSequence; dcut = nothing, njets = nothing, T = LorentzVectorCyl) if isnothing(dcut) && isnothing(njets) throw(ArgumentError("Must pass either a dcut or an njets value")) end if !isnothing(dcut) njets = n_exclusive_jets(clusterseq, dcut = dcut) end # Check that an algorithm was used that makes sense for exclusive jets if !(clusterseq.algorithm ∈ (JetAlgorithm.CA, JetAlgorithm.Kt, JetAlgorithm.EEKt, JetAlgorithm.Durham)) throw(ArgumentError("Algorithm used is not suitable for exclusive jets ($(clusterseq.algorithm))")) end # njets search stop_point = 2 * clusterseq.n_initial_jets - njets + 1 # Sanity check - never return more jets than initial particles if stop_point < clusterseq.n_initial_jets stop_point = clusterseq.n_initial_jets end # Sanity check - ensure that reconstruction proceeded to the end if 2 * clusterseq.n_initial_jets != length(clusterseq.history) throw(ErrorException("Cluster sequence is incomplete, exclusive jets unavailable")) end excl_jets = T[] for j in stop_point:length(clusterseq.history) @debug "Search $j ($(clusterseq.history[j].parent1) + $(clusterseq.history[j].parent2))" for parent in (clusterseq.history[j].parent1, clusterseq.history[j].parent2) if (parent < stop_point && parent > 0) @debug "Added exclusive jet index $(clusterseq.history[parent].jetp_index)" jet = clusterseq.jets[clusterseq.history[parent].jetp_index] if T == PseudoJet push!(excl_jets, jet) else push!(excl_jets, LorentzVectorCyl(pt(jet), rapidity(jet), phi(jet), mass(jet))) end end end end excl_jets end """ n_exclusive_jets(clusterseq::ClusterSequence; dcut::AbstractFloat) Return the number of exclusive jets of a ClusterSequence that are above a certain dcut value. # Arguments - `clusterseq::ClusterSequence`: The `ClusterSequence` object containing the clustering history. - `dcut::AbstractFloat`: The maximum calue for the distance parameter in the reconstruction. # Returns The number of exclusive jets in the `ClusterSequence` object. # Example ```julia n_exclusive_jets(clusterseq, dcut = 20.0) ``` """ function n_exclusive_jets(clusterseq::ClusterSequence; dcut::AbstractFloat) # Check that an algorithm was used that makes sense for exclusive jets if !(clusterseq.algorithm ∈ (JetAlgorithm.CA, JetAlgorithm.Kt, JetAlgorithm.EEKt, JetAlgorithm.Durham)) throw(ArgumentError("Algorithm used is not suitable for exclusive jets ($(clusterseq.algorithm))")) end # Locate the point where clustering would have stopped (i.e. the # first time max_dij_so_far > dcut) i_dcut = length(clusterseq.history) for i_history in length(clusterseq.history):-1:1 @debug "Examining $i_history, max_dij=$(clusterseq.history[i_history].max_dij_so_far)" if clusterseq.history[i_history].max_dij_so_far <= dcut i_dcut = i_history break end end # The number of jets is then given by this formula length(clusterseq.history) - i_dcut end """ get_all_ancestors(idx, cs::ClusterSequence) Recursively finds all ancestors of a given index in a `ClusterSequence` object. # Arguments - `idx`: The index of the jet for which to find ancestors. - `cs`: The `ClusterSequence` object containing the jet history. # Returns An array of indices representing the ancestors of the given jet. """ function get_all_ancestors(idx, cs::ClusterSequence) if cs.history[idx].parent1 == JetReconstruction.NonexistentParent return [cs.history[idx].jetp_index] else branch1 = get_all_ancestors(cs.history[idx].parent1, cs) cs.history[idx].parent2 == JetReconstruction.BeamJet && return branch1 branch2 = get_all_ancestors(cs.history[idx].parent2, cs) return [branch1; branch2] end end """ merge_steps(clusterseq::ClusterSequence) Compute the number of jet-jet merge steps in a cluster sequence. This is useful to give the number of meaningful recombination steps in a jet reconstruction sequence (beam merge steps are not counted). # Arguments - `clusterseq::ClusterSequence`: The cluster sequence object. # Returns - `merge_steps::Int`: The number of merge steps. """ function merge_steps(clusterseq::ClusterSequence) merge_steps = 0 for step in clusterseq.history[(clusterseq.n_initial_jets + 1):end] step.parent2 == BeamJet && continue merge_steps += 1 end merge_steps end """ jet_ranks(clusterseq::ClusterSequence; compare_fn = JetReconstruction.pt) Compute the ranks of jets in a given `ClusterSequence` object based on a specified comparison function. ## Arguments - `clusterseq::ClusterSequence`: The `ClusterSequence` object containing the jets to rank. - `compare_fn = JetReconstruction.pt`: The comparison function used to determine the order of the jets. Defaults to `JetReconstruction.pt`, which compares jets based on their transverse momentum. ## Returns A dictionary mapping each jet index to its rank. ## Note This is a utility function that can be used to rank initial clusters based on a specified jet property. It can be used to assign a consistent "rank" to each reconstructed jet in the cluster sequence, which is useful for stable plotting of jet outputs. """ function jet_ranks(clusterseq::ClusterSequence; compare_fn = JetReconstruction.pt) initial_jet_list = collect(1:(clusterseq.n_initial_jets)) sort!(initial_jet_list, by = i -> compare_fn(clusterseq.jets[i]), rev = true) jet_ranks = Dict{Int, Int}() for (rank, jetp_index) in enumerate(initial_jet_list) jet_ranks[jetp_index] = rank end jet_ranks end """ struct JetWithAncestors A struct representing a jet with its origin ancestors. # Fields - `self::PseudoJet`: The PseudoJet object for this jet. - `jetp_index::Int`: The index of the jet in the corresponding cluster sequence. - `ancestors::Set{Int}`: A set of indices representing the jetp_indexes of ancestors of the jet (in the cluster sequence). - `jet_rank::Int`: The rank of the jet based on a comparison of all of the jet's ancestors # Note This structure needs its associated cluster sequence origin to be useful. """ struct JetWithAncestors self::PseudoJet jetp_index::Int ancestors::Set{Int} jet_rank::Int end """ reco_state(cs::ClusterSequence, pt_ranks; iteration=0) This function returns the reconstruction state of a `ClusterSequence` object based on a given iteration number in the reconstruction. # Arguments - `cs::ClusterSequence`: The `ClusterSequence` object to update. - `ranks`: The ranks of the original clusters, that are inherited by peudojets during the reconstruction process. - `iteration=0`: The iteration number to consider for updating the reconstruction state (0 represents the initial state). - `ignore_beam_merge=true`: Ignore beam merging steps in the reconstruction (which produce no change in status). # Returns A dictionary representing a snapshot of the reconstruction state. # Details The function starts by initializing the reconstruction state with the initial particles. Then, it walks over the iteration sequence and updates the reconstruction state based on the history of recombination and finalization/beam merger steps. """ function reco_state(cs::ClusterSequence, ranks; iteration = 0, ignore_beam_merge = true) # Get the initial particles reco_state = Dict{Int, JetWithAncestors}() for jet_index in 1:(cs.n_initial_jets) reco_state[jet_index] = JetWithAncestors(cs.jets[cs.history[jet_index].jetp_index], jet_index, Set([]), ranks[jet_index]) end # Now update the reconstruction state by walking over the iteration sequence iterations_done = 0 for h_step in (cs.n_initial_jets + 1):length(cs.history) h_entry = cs.history[h_step] if h_entry.parent2 > 0 # This is a recombination iterations_done += 1 # We store all of the original particle ancestors (but only the # original ones, not intermediate merges) my_ancestors = union(reco_state[cs.history[h_entry.parent1].jetp_index].ancestors, reco_state[cs.history[h_entry.parent2].jetp_index].ancestors) cs.history[h_entry.parent1].parent1 == JetReconstruction.NonexistentParent && push!(my_ancestors, h_entry.parent1) cs.history[h_entry.parent2].parent1 == JetReconstruction.NonexistentParent && push!(my_ancestors, h_entry.parent2) # Now find the ancestor with the highest p_T value pt_rank = cs.n_initial_jets for ancestor in my_ancestors (ranks[ancestor] < pt_rank) && (pt_rank = ranks[ancestor]) end reco_state[h_entry.jetp_index] = JetWithAncestors(cs.jets[h_entry.jetp_index], h_entry.jetp_index, my_ancestors, pt_rank) delete!(reco_state, cs.history[h_entry.parent1].jetp_index) delete!(reco_state, cs.history[h_entry.parent2].jetp_index) else # This is a finalisation / beam merger, so here we do nothing if ignore_beam_merge != true iterations_done += 1 end end # Abort when we have done the required number of iterations if iterations_done == iteration break end end reco_state end """ constituents(j::PseudoJet, cs::ClusterSequence) Get the constituents of a given jet in a cluster sequence. # Arguments - `cs::ClusterSequence`: The cluster sequence object. - `j::PseudoJet`: The jet for which to retrieve the constituents. # Returns An array of `PseudoJet` objects representing the constituents of the given jet. (That is, the original clusters that were recombined to form this jet.) """ function constituents(j::PseudoJet, cs::ClusterSequence) constituent_indexes = get_all_ancestors(cs.history[j._cluster_hist_index].jetp_index, cs) constituents = Vector{PseudoJet}() for idx in constituent_indexes push!(constituents, cs.jets[idx]) end constituents end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
14433
# Use these constants whenever we need to set a large value for the distance or # metric distance const large_distance = 16.0 # = 4^2 const large_dij = 1.0e6 """ angular_distance(eereco, i, j) -> Float64 Calculate the angular distance between two jets `i` and `j` using the formula ``1 - cos(θ_{ij})``. # Arguments - `eereco`: The array of `EERecoJet` objects. - `i`: The first jet. - `j`: The second jet. # Returns - `Float64`: The angular distance between `i` and `j`, which is ``1 - cos\theta``. """ @inline function angular_distance(eereco, i, j) @inbounds @muladd 1.0 - eereco[i].nx * eereco[j].nx - eereco[i].ny * eereco[j].ny - eereco[i].nz * eereco[j].nz end """ dij_dist(eereco, i, j, dij_factor) Calculate the dij distance between two ``e^+e^-``jets. # Arguments - `eereco`: The array of `EERecoJet` objects. - `i`: The first jet. - `j`: The second jet. - `dij_factor`: The scaling factor to multiply the dij distance by. # Returns - The dij distance between `i` and `j`. """ @inline function dij_dist(eereco, i, j, dij_factor) # Calculate the dij distance for jet i from jet j j == 0 && return large_dij @inbounds min(eereco[i].E2p, eereco[j].E2p) * dij_factor * eereco[i].nndist end function get_angular_nearest_neighbours!(eereco, algorithm, dij_factor) # Get the initial nearest neighbours for each jet N = length(eereco) # this_dist_vector = Vector{Float64}(undef, N) # Nearest neighbour geometric distance @inbounds for i in 1:N # TODO: Replace the 'j' loop with a vectorised operation over the appropriate array elements? # this_dist_vector .= 1.0 .- eereco.nx[i:N] .* eereco[i + 1:end].nx .- # eereco[i].ny .* eereco[i + 1:end].ny .- eereco[i].nz .* eereco[i + 1:end].nz # The problem here will be avoiding allocations for the array outputs, which would easily # kill performance @inbounds for j in (i + 1):N this_nndist = angular_distance(eereco, i, j) # Using these ternary operators is faster than the if-else block better_nndist_i = this_nndist < eereco[i].nndist eereco.nndist[i] = better_nndist_i ? this_nndist : eereco.nndist[i] eereco.nni[i] = better_nndist_i ? j : eereco.nni[i] better_nndist_j = this_nndist < eereco[j].nndist eereco.nndist[j] = better_nndist_j ? this_nndist : eereco.nndist[j] eereco.nni[j] = better_nndist_j ? i : eereco.nni[j] end end # Nearest neighbour dij distance for i in 1:N eereco.dijdist[i] = dij_dist(eereco, i, eereco[i].nni, dij_factor) end # For the EEKt algorithm, we need to check the beam distance as well # (This is structured to only check for EEKt once) if algorithm == JetAlgorithm.EEKt @inbounds for i in 1:N beam_closer = eereco[i].E2p < eereco[i].dijdist eereco.dijdist[i] = beam_closer ? eereco[i].E2p : eereco.dijdist[i] eereco.nni[i] = beam_closer ? 0 : eereco.nni[i] end end end # Update the nearest neighbour for jet i, w.r.t. all other active jets function update_nn_no_cross!(eereco, i, N, algorithm, dij_factor) eereco.nndist[i] = large_distance eereco.nni[i] = i @inbounds for j in 1:N if j != i this_nndist = angular_distance(eereco, i, j) better_nndist_i = this_nndist < eereco[i].nndist eereco.nndist[i] = better_nndist_i ? this_nndist : eereco.nndist[i] eereco.nni[i] = better_nndist_i ? j : eereco.nni[i] end end eereco.dijdist[i] = dij_dist(eereco, i, eereco[i].nni, dij_factor) if algorithm == JetAlgorithm.EEKt beam_close = eereco[i].E2p < eereco[i].dijdist eereco.dijdist[i] = beam_close ? eereco[i].E2p : eereco.dijdist[i] eereco.nni[i] = beam_close ? 0 : eereco.nni[i] end end function update_nn_cross!(eereco, i, N, algorithm, dij_factor) # Update the nearest neighbour for jet i, w.r.t. all other active jets # also doing the cross check for the other jet eereco.nndist[i] = large_distance eereco.nni[i] = i @inbounds for j in 1:N if j != i this_nndist = angular_distance(eereco, i, j) better_nndist_i = this_nndist < eereco[i].nndist eereco.nndist[i] = better_nndist_i ? this_nndist : eereco.nndist[i] eereco.nni[i] = better_nndist_i ? j : eereco.nni[i] if this_nndist < eereco[j].nndist eereco.nndist[j] = this_nndist eereco.nni[j] = i # j will not be revisited, so update metric distance here eereco.dijdist[j] = dij_dist(eereco, j, i, dij_factor) if algorithm == JetAlgorithm.EEKt if eereco[j].E2p < eereco[j].dijdist eereco.dijdist[j] = eereco[j].E2p eereco.nni[j] = 0 end end end end end eereco.dijdist[i] = dij_dist(eereco, i, eereco[i].nni, dij_factor) if algorithm == JetAlgorithm.EEKt beam_close = eereco[i].E2p < eereco[i].dijdist eereco.dijdist[i] = beam_close ? eereco[i].E2p : eereco.dijdist[i] eereco.nni[i] = beam_close ? 0 : eereco.nni[i] end end function ee_check_consistency(clusterseq, eereco, N) # Check the consistency of the reconstruction state for i in 1:N if eereco[i].nni > N @error "Jet $i has invalid nearest neighbour $(eereco[i].nni)" end for i in 1:N jet = clusterseq.jets[eereco[i].index] jet_hist = clusterseq.history[jet._cluster_hist_index] if jet_hist.child != Invalid @error "Jet $i has invalid child $(jet_hist.child)" end end end @debug "Consistency check passed at $msg" end """ ee_genkt_algorithm(particles::Vector{T}; p = -1, R = 4.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.Durham, recombine = +) where {T} Run an e+e- reconstruction algorithm on a set of initial particles. # Arguments - `particles::Vector{T}`: A vector of particles to be clustered. - `p = 1`: The power parameter for the algorithm. Not required / ignored for the Durham algorithm when it is set to 1. - `R = 4.0`: The jet radius parameter. Not required / ignored for the Durham algorithm. - `algorithm::JetAlgorithm.Algorithm = JetAlgorithm.Durham`: The specific jet algorithm to use. - `recombine`: The recombination scheme to use. Defaults to `+`. # Returns - The result of the jet clustering as a `ClusterSequence` object. # Notes This is the public interface to the e+e- jet clustering algorithm. The function will check for consistency between the algorithm and the power parameter as needed. It will then prepare the internal EDM particles for the clustering itself, and call the actual reconstruction method `_ee_genkt_algorithm`. If the algorithm is Durham, `p` is set to 1 and `R` is nominally set to 4. Note that unlike `pp` reconstruction the algorithm has to be specified explicitly. """ function ee_genkt_algorithm(particles::Vector{T}; p = 1, R = 4.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.Durham, recombine = +) where {T} # Check for consistency between algorithm and power (p, algorithm) = get_algorithm_power_consistency(p = p, algorithm = algorithm) # Integer p if possible p = (round(p) == p) ? Int(p) : p # For the Durham algorithm, p=1 and R is not used, but nominally set to 4 if algorithm == JetAlgorithm.Durham R = 4.0 end if T == EEjet # recombination_particles will become part of the cluster sequence, so size it for # the starting particles and all N recombinations recombination_particles = copy(particles) sizehint!(recombination_particles, length(particles) * 2) else recombination_particles = EEjet[] sizehint!(recombination_particles, length(particles) * 2) for i in eachindex(particles) push!(recombination_particles, EEjet(px(particles[i]), py(particles[i]), pz(particles[i]), energy(particles[i]))) end end # Now call the actual reconstruction method, tuned for our internal EDM _ee_genkt_algorithm(particles = recombination_particles, p = p, R = R, algorithm = algorithm, recombine = recombine) end """ _ee_genkt_algorithm(; particles::Vector{EEjet}, p = 1, R = 4.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.Durham, recombine = +) This function is the actual implementation of the e+e- jet clustering algorithm. """ function _ee_genkt_algorithm(; particles::Vector{EEjet}, p = 1, R = 4.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.Durham, recombine = +) # Bounds N::Int = length(particles) # R squared R2 = R^2 # Constant factor for the dij metric and the beam distance function if algorithm == JetAlgorithm.Durham dij_factor = 2.0 elseif algorithm == JetAlgorithm.EEKt if R < π dij_factor = 1 / (1 - cos(R)) else dij_factor = 1 / (3 + cos(R)) end else throw(ArgumentError("Algorithm $algorithm not supported for e+e-")) end # For optimised reconstruction generate an SoA containing the necessary # jet information and populate it accordingly # We need N slots for this array eereco = StructArray{EERecoJet}(undef, N) for i in eachindex(particles) eereco.index[i] = i eereco.nni[i] = 0 eereco.nndist[i] = R2 # eereco[i].dijdist = UNDEF # Not needed eereco.nx[i] = nx(particles[i]) eereco.ny[i] = ny(particles[i]) eereco.nz[i] = nz(particles[i]) eereco.E2p[i] = energy(particles[i])^(2p) end # Setup the initial history and get the total energy history, Qtot = initial_history(particles) clusterseq = ClusterSequence(algorithm, p, R, RecoStrategy.N2Plain, particles, history, Qtot) # Run over initial pairs of jets to find nearest neighbours get_angular_nearest_neighbours!(eereco, algorithm, dij_factor) # Only for debugging purposes... # ee_check_consistency(clusterseq, clusterseq_index, N, nndist, nndij, nni, "Start") # Now we can start the main loop iter = 0 while N != 0 iter += 1 dij_min, ijetA = fast_findmin(eereco.dijdist, N) ijetB = eereco[ijetA].nni # Now we check if there is a "beam" merge possibility if ijetB == 0 # We have an EEKt beam merge ijetB = ijetA add_step_to_history!(clusterseq, clusterseq.jets[eereco[ijetA].index]._cluster_hist_index, BeamJet, Invalid, dij_min) elseif N == 1 # We have a single jet left ijetB = ijetA add_step_to_history!(clusterseq, clusterseq.jets[eereco[ijetA].index]._cluster_hist_index, BeamJet, Invalid, dij_min) else # Jet-jet merge if ijetB < ijetA ijetA, ijetB = ijetB, ijetA end # Source "history" for merge hist_jetA = clusterseq.jets[eereco[ijetA].index]._cluster_hist_index hist_jetB = clusterseq.jets[eereco[ijetB].index]._cluster_hist_index # Recombine jetA and jetB into the next jet merged_jet = recombine(clusterseq.jets[eereco[ijetA].index], clusterseq.jets[eereco[ijetB].index]) merged_jet._cluster_hist_index = length(clusterseq.history) + 1 # Now add the jet to the sequence, and update the history push!(clusterseq.jets, merged_jet) newjet_k = length(clusterseq.jets) add_step_to_history!(clusterseq, minmax(hist_jetA, hist_jetB)..., newjet_k, dij_min) # Update the compact arrays, reusing the JetA slot eereco.index[ijetA] = newjet_k eereco.nni[ijetA] = 0 eereco.nndist[ijetA] = R2 eereco.nx[ijetA] = nx(merged_jet) eereco.ny[ijetA] = ny(merged_jet) eereco.nz[ijetA] = nz(merged_jet) eereco.E2p[ijetA] = energy(merged_jet)^(2p) end # Squash step - copy the final jet's compact data into the jetB slot # unless we are at the end of the array, in which case do nothing if ijetB != N eereco.index[ijetB] = eereco.index[N] eereco.nni[ijetB] = eereco.nni[N] eereco.nndist[ijetB] = eereco.nndist[N] eereco.dijdist[ijetB] = eereco.dijdist[N] eereco.nx[ijetB] = eereco.nx[N] eereco.ny[ijetB] = eereco.ny[N] eereco.nz[ijetB] = eereco.nz[N] eereco.E2p[ijetB] = eereco.E2p[N] end # Now number of active jets is decreased by one N -= 1 # Update nearest neighbours step for i in 1:N # First, if any jet's NN was the old index N, it's now ijetB if (ijetB != N + 1) && (eereco[i].nni == N + 1) eereco.nni[i] = ijetB else # Otherwise, if the jet had ijetA or ijetB as their NN, we need to update them # plus "belt and braces" check for an invalid NN (>N) if (eereco[i].nni == ijetA) || (eereco[i].nni == ijetB) || (eereco[i].nni > N) update_nn_no_cross!(eereco, i, N, algorithm, dij_factor) end end end # Finally, we need to update the nearest neighbours for the new jet, checking both ways # (But only if there was a new jet!) if ijetA != ijetB update_nn_cross!(eereco, ijetA, N, algorithm, dij_factor) end # Only for debugging purposes... # ee_check_consistency(clusterseq, eereco, N) end # Return the final cluster sequence structure clusterseq end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
3035
""" struct EEjet The `EEjet` struct is a 4-momentum object used for the e+e jet reconstruction routines. # Fields - `px::Float64`: The x-component of the jet momentum. - `py::Float64`: The y-component of the jet momentum. - `pz::Float64`: The z-component of the jet momentum. - `E::Float64`: The energy of the jet. - `_cluster_hist_index::Int`: The index of the cluster histogram. - `_p2::Float64`: The squared momentum of the jet. - `_inv_p::Float64`: The inverse momentum of the jet. """ mutable struct EEjet <: FourMomentum px::Float64 py::Float64 pz::Float64 E::Float64 _p2::Float64 _inv_p::Float64 _cluster_hist_index::Int end function EEjet(px::Float64, py::Float64, pz::Float64, E::Float64, _cluster_hist_index::Int) @muladd p2 = px * px + py * py + pz * pz inv_p = @fastmath 1.0 / sqrt(p2) EEjet(px, py, pz, E, p2, inv_p, _cluster_hist_index) end EEjet(px::Float64, py::Float64, pz::Float64, E::Float64) = EEjet(px, py, pz, E, 0) EEjet(pj::PseudoJet) = EEjet(px(pj), py(pj), pz(pj), energy(pj), cluster_hist_index(pj)) p2(eej::EEjet) = eej._p2 pt2(eej::EEjet) = eej.px^2 + eej.py^2 const kt2 = pt2 pt(eej::EEjet) = sqrt(pt2(eej)) energy(eej::EEjet) = eej.E px(eej::EEjet) = eej.px py(eej::EEjet) = eej.py pz(eej::EEjet) = eej.pz nx(eej::EEjet) = eej.px * eej._inv_p ny(eej::EEjet) = eej.py * eej._inv_p nz(eej::EEjet) = eej.pz * eej._inv_p cluster_hist_index(eej::EEjet) = eej._cluster_hist_index phi(eej::EEjet) = begin phi = pt2(eej) == 0.0 ? 0.0 : atan(eej.py, eej.px) if phi < 0.0 phi += 2π elseif phi >= 2π phi -= 2π # can happen if phi=-|eps<1e-15|? end phi end m2(eej::EEjet) = energy(eej)^2 - p2(eej) mass(eej::EEjet) = m2(eej) < 0.0 ? -sqrt(-m2(eej)) : sqrt(m2(eej)) function rapidity(eej::EEjet) if energy(eej) == abs(pz(eej)) && iszero(pt2(eej)) MaxRapHere = _MaxRap + abs(pz(eej)) rap = (pz(eej) >= 0.0) ? MaxRapHere : -MaxRapHere else # get the rapidity in a way that's modestly insensitive to roundoff # error when things pz,E are large (actually the best we can do without # explicit knowledge of mass) effective_m2 = max(0.0, m2(eej)) # force non tachyonic mass E_plus_pz = energy(eej) + abs(pz(eej)) # the safer of p+, p- rapidity = 0.5 * log((pt2(eej) + effective_m2) / (E_plus_pz * E_plus_pz)) if pz(eej) > 0 rapidity = -rapidity end end rapidity end import Base.+; function +(jet1::EEjet, jet2::EEjet) EEjet(jet1.px + jet2.px, jet1.py + jet2.py, jet1.pz + jet2.pz, jet1.E + jet2.E) end import Base.show function show(io::IO, eej::EEjet) print(io, "EEjet(px: ", eej.px, " py: ", eej.py, " pz: ", eej.pz, " E: ", eej.E, " cluster_hist_index: ", eej._cluster_hist_index, ")") end # Optimised reconstruction struct for e+e jets mutable struct EERecoJet index::Int nni::Int nndist::Float64 dijdist::Float64 nx::Float64 ny::Float64 nz::Float64 E2p::Float64 end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
3665
""" jet_reconstruct(particles; p = -1, algorithm = nothing, R = 1.0, recombine = +, strategy = RecoStrategy.Best) Reconstructs jets from a collection of particles using a specified algorithm and strategy # Arguments - `particles`: A collection of particles used for jet reconstruction. - `p::Union{Real, Nothing} = -1`: The power value used for the distance measure for generalised k_T, which maps to a particular reconstruction algorithm (-1 = AntiKt, 0 = Cambridge/Aachen, 1 = Kt). - `algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing`: The algorithm to use for jet reconstruction. - `R=1.0`: The jet radius parameter. - `recombine=+`: The recombination scheme used for combining particles. - `strategy=RecoStrategy.Best`: The jet reconstruction strategy to use. `RecoStrategy.Best` makes a dynamic decision based on the number of starting particles. # Returns A cluster sequence object containing the reconstructed jets and the merging history. # Details ## `particles` argument Any type that supplies the methods `pt2()`, `phi()`, `rapidity()`, `px()`, `py()`, `pz()`, `energy()` (in the `JetReconstruction` namespace) can be used. This includes `LorentzVector`, `LorentzVectorCyl`, and `PseudoJet`, for which these methods are already predefined in the `JetReconstruction` namespace. ## `recombine` argument The `recombine` argument is the function used to merge pairs of particles. The default is simply `+(jet1,jet2)`, i.e. 4-momenta addition or the *E*-scheme. ## Consitency of `p`, `algorithm` and `R` arguments If an algorithm is explicitly specified the `p` value should be consistent with it or `nothing`. If the algorithm is one where `p` can vary, then it has to be given, along with the algorithm.`` If the `p` parameter is passed and `algorithm=nothing`, then pp-type reconstruction is implied (i.e., AntiKt, CA, Kt or GenKt will be used, depending on the value of `p`). When an algorithm has no `R` dependence the `R` parameter is ignored. # Example ```julia jet_reconstruct(particles; p = -1, R = 0.4) jet_reconstruct(particles; algorithm = JetAlgorithm.Kt, R = 1.0) jet_reconstruct(particles; algorithm = JetAlgorithm.Durham) jet_reconstruct(particles; algorithm = JetAlgorithm.GenKt, p = 0.5, R = 1.0) ``` """ function jet_reconstruct(particles; p::Union{Real, Nothing} = -1, R = 1.0, algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing, recombine = +, strategy = RecoStrategy.Best) # Either map to the fixed algorithm corresponding to the strategy # or to an optimal choice based on the density of initial particles if (algorithm === nothing) && (p === nothing) throw(ArgumentError("Please specify either an algorithm or a power value (power only for pp-type reconstruction)")) end if (algorithm === nothing) || is_pp(algorithm) # We assume a pp reconstruction if strategy == RecoStrategy.Best # The breakpoint of ~80 is determined empirically on e+e- -> H and 0.5TeV pp -> 5GeV jets alg = length(particles) > 80 ? tiled_jet_reconstruct : plain_jet_reconstruct elseif strategy == RecoStrategy.N2Plain alg = plain_jet_reconstruct elseif strategy == RecoStrategy.N2Tiled alg = tiled_jet_reconstruct else throw(ErrorException("Invalid strategy: $(strategy)")) end elseif is_ee(algorithm) alg = ee_genkt_algorithm end # Now call the chosen algorithm, passing through the other parameters alg(particles; p = p, algorithm = algorithm, R = R, recombine = recombine) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
5165
""" Module providing a minimal support to read HepMC3 ascii files. This module contains functions and types for reading HepMC3 ASCII files. It provides a `Particle` struct to represent particles in the event, and a `read_events` function to read events from a file. ## Types - `Particle{T}`: A struct representing a particle in the event. It contains fields for momentum, status, PDG ID, barcode, and vertex. - `T`: The type parameter for the `Particle` struct, specifying the precision of the momentum components. ## Functions - `read_events(f, fin; maxevents=-1, skipevents=0)`: Reads events from a HepMC3 ascii file. Each event is passed to the provided function `f` as a vector of `Particle`s. The `maxevents` parameter specifies the maximum number of events to read (-1 to read all available events), and the `skipevents` parameter specifies the number of events to skip at the beginning of the file. Example usage: ```julia function process_event(particles) # Process the event end file = open("events.hepmc", "r") read_events(process_event, file, maxevents=10, skipevents=2) close(file) ``` - `f`: The function to be called for each event. It should take a single argument of type `Vector{Particle}`. - `fin`: The input file stream to read from. - `maxevents`: The maximum number of events to read. Default is -1, which reads all available events. - `skipevents`: The number of events to skip at the beginning of the file. Default is 0. ## References - [HepMC3](https://doi.org/10.1016/j.cpc.2020.107310): The HepMC3 software package. """ module HepMC3 using LorentzVectors """ struct Particle{T} A struct representing a particle in the HepMC3 library. # Fields - `momentum::LorentzVector{T}`: The momentum of the particle. - `status::Integer`: The status code of the particle. - `pdgid::Integer`: The PDG ID of the particle. - `barcode::Integer`: The barcode of the particle. - `vertex::Integer`: The vertex ID of the particle. """ struct Particle{T} momentum::LorentzVector{T} status::Integer pdgid::Integer barcode::Integer vertex::Integer end Particle{T}() where {T} = Particle(LorentzVector{T}(0.0, 0.0, 0.0, 0.0), 0, 0, 0, 0) """ Read a [HepMC3](https://doi.org/10.1016/j.cpc.2020.107310) ascii file. Each event is passed to the provided function f as a vector of Particles. A maximum number of events to read (value -1 to read all availble events) and a number of events to skip at the beginning of the file can be provided. """ """ read_events(f, fin; maxevents=-1, skipevents=0) Reads events from a file and processes them. ## Arguments - `f`: A function that takes an array of `Particle{T}` as input and processes it. - `fin`: The input file object. - `maxevents`: The maximum number of events to read. Default is -1, which means all events will be read. - `skipevents`: The number of events to skip before processing. Default is 0. ## Description This function reads events from a file and processes them using the provided function `f`. Each event is represented by a series of lines in the file, where each line corresponds to a particle. The function parses the lines and creates `Particle{T}` objects, which are then passed to the processing function `f`. The function `f` can perform any desired operations on the particles. ## Example ```julia f = open(fname) events = Vector{PseudoJet}[] HepMC3.read_events(f, maxevents = maxevents, skipevents = skipevents) do parts input_particles = PseudoJet[] for p in parts if p.status == 1 push!( input_particles, PseudoJet(p.momentum.x, p.momentum.y, p.momentum.z, p.momentum.t), ) end end push!(events, input_particles) end close(f) ``` """ function read_events(f, fin; maxevents = -1, skipevents = 0) T = Float64 particles = Particle{T}[] ievent = 0 ipart = 0 toskip = skipevents for (il, l) in enumerate(eachline(fin)) if occursin(r"HepMC::.*-END_EVENT_LISTING", l) break end tok = split(l) if tok[1] == "E" ievent += 1 (maxevents >= 0 && ievent > maxevents) && break if ievent > 1 && toskip == 0 f(particles) end if toskip > 0 toskip -= 1 end resize!(particles, 0) ipart = 0 elseif tok[1] == "P" && toskip == 0 ipart += 1 if ipart > length(particles) push!(particles, Particle{T}()) end barcode = parse(Int, tok[2]) vertex = parse(Int, tok[3]) pdgid = parse(Int, tok[4]) px = parse(T, tok[5]) py = parse(T, tok[6]) pz = parse(T, tok[7]) e = parse(T, tok[8]) status = parse(Int, tok[10]) push!(particles, Particle{T}(LorentzVector(e, px, py, pz), status, pdgid, barcode, vertex)) end end #processing the last event: ievent > 0 && f(particles) end end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
658
""" struct FinalJet A struct representing the final properties of a jet, used for JSON serialisation. # Fields - `rap::Float64`: The rapidity of the jet. - `phi::Float64`: The azimuthal angle of the jet. - `pt::Float64`: The transverse momentum of the jet. """ struct FinalJet rap::Float64 phi::Float64 pt::Float64 end """ struct FinalJets A struct with the vector of all jets for a certain jet identifier, used for JSON serialisation. # Fields - `jetid::Int64`: The ID of the jet. - `jets::Vector{FinalJet}`: A vector of `FinalJet` objects representing the jets. """ struct FinalJets jetid::Int64 jets::Vector{FinalJet} end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
2852
""" Module for jet reconstruction algorithms and utilities. This module provides various algorithms and utilities for jet reconstruction in high-energy physics (HEP) experiments. It includes functions for performing jet clustering with different algorithms and strategies. Utility functions are also provided for reading input from HepMC3 files, saving and loading jet objects, and visualizing jets. # Usage To use this module, include it in your Julia code and call the desired functions or use the exported types. See the documentation for each function and the examples in this package for more information. """ module JetReconstruction using LorentzVectorHEP using MuladdMacro using StructArrays # Import from LorentzVectorHEP methods for those 4-vector types pt2(p::LorentzVector) = LorentzVectorHEP.pt2(p) phi(p::LorentzVector) = LorentzVectorHEP.phi(p) rapidity(p::LorentzVector) = LorentzVectorHEP.rapidity(p) px(p::LorentzVector) = LorentzVectorHEP.px(p) py(p::LorentzVector) = LorentzVectorHEP.py(p) pz(p::LorentzVector) = LorentzVectorHEP.pz(p) energy(p::LorentzVector) = LorentzVectorHEP.energy(p) pt2(p::LorentzVectorCyl) = LorentzVectorHEP.pt2(p) phi(p::LorentzVectorCyl) = LorentzVectorHEP.phi(p) rapidity(p::LorentzVectorCyl) = LorentzVectorHEP.rapidity(p) px(p::LorentzVectorCyl) = LorentzVectorHEP.px(p) py(p::LorentzVectorCyl) = LorentzVectorHEP.py(p) pz(p::LorentzVectorCyl) = LorentzVectorHEP.pz(p) energy(p::LorentzVectorCyl) = LorentzVectorHEP.energy(p) # Pseudojet and EEjet types include("Pseudojet.jl") include("EEjet.jl") export PseudoJet, EEjet # Jet reconstruction strategies and algorithms (enums!) include("AlgorithmStrategyEnums.jl") export RecoStrategy, JetAlgorithm # ClusterSequence type include("ClusterSequence.jl") export ClusterSequence, inclusive_jets, exclusive_jets, n_exclusive_jets, constituents ## N2Plain algorithm # Algorithmic part for simple sequential implementation include("PlainAlgo.jl") export plain_jet_reconstruct ## N2Tiled algorithm # Common pieces include("TiledAlgoUtils.jl") # Algorithmic part, tiled reconstruction strategy with linked list jet objects include("TiledAlgoLL.jl") export tiled_jet_reconstruct ## E+E- algorithms include("EEAlgorithm.jl") export ee_genkt_algorithm ## Generic algorithm, which can switch strategy dynamically include("GenericAlgo.jl") export jet_reconstruct # Simple HepMC3 reader include("HepMC3.jl") # jet serialisation (saving to file) include("Serialize.jl") export savejets, loadjets!, loadjets # utility functions, useful for different primary scripts include("Utils.jl") export read_final_state_particles, final_jets # Jet visualisation is an extension, see ext/JetVisualisation.jl function jetsplot() end function animatereco() end export jetsplot, animatereco # JSON results include("JSONresults.jl") export FinalJet, FinalJets end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
15772
using LoopVectorization """ dist(i, j, rapidity_array, phi_array) Compute the distance between points in a 2D space defined by rapidity and phi coordinates. # Arguments - `i::Int`: Index of the first point to consider (indexes into `rapidity_array` and `phi_array`). - `j::Int`: Index of the second point to consider (indexes into `rapidity_array` and `phi_array`). - `rapidity_array::Vector{Float64}`: Array of rapidity coordinates. - `phi_array::Vector{Float64}`: Array of phi coordinates. # Returns - `distance::Float64`: The distance between the two points. """ Base.@propagate_inbounds function dist(i, j, rapidity_array, phi_array) drapidity = rapidity_array[i] - rapidity_array[j] dphi = abs(phi_array[i] - phi_array[j]) dphi = ifelse(dphi > pi, 2pi - dphi, dphi) @muladd drapidity * drapidity + dphi * dphi end """ dij(i, kt2_array, nn, nndist) Compute the dij value for a given index `i` to its nearest neighbor. The nearest neighbor is determined from `nn[i]`, and the metric distance to the nearest neighbor is given by the distance `nndist[i]` applying the lower of the `kt2_array` values for the two particles.ßß # Arguments - `i`: The index of the element. - `kt2_array`: An array of kt2 values. - `nn`: An array of nearest neighbors. - `nndist`: An array of nearest neighbor distances. # Returns - The computed dij value. """ Base.@propagate_inbounds function dij(i, kt2_array, nn, nndist) j = nn[i] d = nndist[i] d * min(kt2_array[i], kt2_array[j]) end """ upd_nn_crosscheck!(i, from, to, rapidity_array, phi_array, R2, nndist, nn) Update the nearest neighbor information for a given particle index `i` against all particles in the range indexes `from` to `to`. The function updates the `nndist` and `nn` arrays with the nearest neighbor distance and index respectively, both for particle `i` and the checked particles `[from:to]` (hence *crosscheck*). # Arguments - `i::Int`: The index of the particle to update and check against. - `from::Int`: The starting index of the range of particles to check against. - `to::Int`: The ending index of the range of particles to check against. - `rapidity_array`: An array containing the rapidity values of all particles. - `phi_array`: An array containing the phi values of the all particles. - `R2`: The squared jet distance threshold for considering a particle as a neighbour. - `nndist`: The array that stores the nearest neighbor distances. - `nn`: The array that stores the nearest neighbor indices. """ Base.@propagate_inbounds function upd_nn_crosscheck!(i::Int, from::Int, to::Int, rapidity_array, phi_array, R2, nndist, nn) nndist_min = R2 nn_min = i @inbounds @simd for j in from:to Δ2 = dist(i, j, rapidity_array, phi_array) if Δ2 < nndist_min nn_min = j nndist_min = Δ2 end if Δ2 < nndist[j] nndist[j] = Δ2 nn[j] = i end end nndist[i] = nndist_min nn[i] = nn_min end # finds new nn for i """ upd_nn_nocross!(i, from, to, rapidity_array, phi_array, R2, nndist, nn) Update the nearest neighbor information for a given particle index `i` against all particles in the range indexes `from` to `to`. The function updates the `nndist` and `nn` arrays with the nearest neighbor distance and index respectively, only for particle `i` (hence *nocross*). # Arguments - `i::Int`: The index of the particle to update and check against. - `from::Int`: The starting index of the range of particles to check against. - `to::Int`: The ending index of the range of particles to check against. - `rapidity_array`: An array containing the rapidity values of all particles. - `phi_array`: An array containing the phi values of the all particles. - `R2`: The squared jet distance threshold for considering a particle as a neighbour. - `nndist`: The array that stores the nearest neighbor distances. - `nn`: The array that stores the nearest neighbor indices. """ Base.@propagate_inbounds function upd_nn_nocross!(i::Int, from::Int, to::Int, rapidity_array, phi_array, R2, nndist, nn) nndist_min = R2 nn_min = i @inbounds @simd for j in from:(i - 1) Δ2 = dist(i, j, rapidity_array, phi_array) if Δ2 <= nndist_min nn_min = j nndist_min = Δ2 end end @inbounds @simd for j in (i + 1):to Δ2 = dist(i, j, rapidity_array, phi_array) f = Δ2 <= nndist_min nn_min = ifelse(f, j, nn_min) nndist_min = ifelse(f, Δ2, nndist_min) end nndist[i] = nndist_min nn[i] = nn_min end """ upd_nn_step!(i, j, k, N, Nn, kt2_array, rapidity_array, phi_array, R2, nndist, nn, nndij) Update the nearest neighbor information after a jet merge step. Arguments: - `i`: Index of the first particle in the last merge step. - `j`: Index of the second particle in the last merge step. - `k`: Index of the current particle for which the nearest neighbour will be updated. - `N`: Total number of particles (currently vaild array indexes are `[1:N]`). - `Nn`: Number of nearest neighbors to consider. - `kt2_array`: Array of transverse momentum squared values. - `rapidity_array`: Array of rapidity values. - `phi_array`: Array of azimuthal angle values. - `R2`: Distance threshold squared for nearest neighbors. - `nndist`: Array of nearest neighbor geometric distances. - `nn`: Array of nearest neighbor indices. - `nndij`: Array of metric distances between particles. This function updates the nearest neighbor information for the current particle `k` by considering the distances to particles `i` and `j`. It checks if the distance between `k` and `i` is smaller than the current nearest neighbor distance for `k`, and updates the nearest neighbor information accordingly. It also updates the nearest neighbor information for `i` if the distance between `k` and `i` is smaller than the current nearest neighbor distance for `i`. Finally, it checks if the nearest neighbor of `k` is the total number of particles `Nn` and updates it to `j` if necessary. """ Base.@propagate_inbounds function upd_nn_step!(i, j, k, N, Nn, kt2_array, rapidity_array, phi_array, R2, nndist, nn, nndij) nnk = nn[k] # Nearest neighbour of k if nnk == i || nnk == j # Our old nearest neighbour is one of the merged particles upd_nn_nocross!(k, 1, N, rapidity_array, phi_array, R2, nndist, nn) # Update dist and nn nndij[k] = dij(k, kt2_array, nn, nndist) nnk = nn[k] end if j != i && k != i # Update particle's nearest neighbour if it's not i and the merge step was not a beam merge Δ2 = dist(i, k, rapidity_array, phi_array) if Δ2 < nndist[k] nndist[k] = Δ2 nnk = nn[k] = i nndij[k] = dij(k, kt2_array, nn, nndist) end cond = Δ2 < nndist[i] nndist[i], nn[i] = ifelse(cond, (Δ2, k), (nndist[i], nn[i])) end # If the previous nearest neighbour was the final jet in the array before # the merge that was just done, this jet has now been moved in the array to # position k (to compactify the array), so we need to update the nearest # neighbour nnk == Nn && (nn[k] = j) end """ plain_jet_reconstruct(particles::Vector{T}; p = -1, R = 1.0, recombine = +) where T Perform pp jet reconstruction using the plain algorithm. # Arguments - `particles::Vector{T}`: A vector of particles used for jet reconstruction, any array of particles, which supports suitable 4-vector methods, viz. pt2(), phi(), rapidity(), px(), py(), pz(), energy(), can be used. for each element. - `algorithm::Union{JetAlgorithm, Nothing} = nothing`: The explicit jet algorithm to use. - `p::Int=-1`: The integer value used for jet reconstruction. - `R::Float64=1.0`: The radius parameter used for jet reconstruction. - `recombine::Function=+`: The recombination function used for jet reconstruction. **Note** for the `particles` argument, the 4-vector methods need to exist in the JetReconstruction package namespace. This code will use the `k_t` algorithm types, operating in `(rapidity, φ)` space. It is not necessary to specify both the `algorithm` and the `p` (power) value. If both are given they must be consistent or an exception is thrown. # Returns - `Vector{PseudoJet}`: A vector of reconstructed jets. # Example ```julia jets = plain_jet_reconstruct(particles; p = -1, R = 0.4) jets = plain_jet_reconstruct(particles; algorithm = JetAlgorithm.Kt, R = 1.0) ``` """ function plain_jet_reconstruct(particles::Vector{T}; p::Union{Real, Nothing} = -1, R = 1.0, algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing, recombine = +) where {T} # Check for consistency between algorithm and power (p, algorithm) = get_algorithm_power_consistency(p = p, algorithm = algorithm) # Integer p if possible p = (round(p) == p) ? Int(p) : p if T == PseudoJet # recombination_particles will become part of the cluster sequence, so size it for # the starting particles and all N recombinations recombination_particles = copy(particles) sizehint!(recombination_particles, length(particles) * 2) else recombination_particles = PseudoJet[] sizehint!(recombination_particles, length(particles) * 2) for i in eachindex(particles) push!(recombination_particles, PseudoJet(px(particles[i]), py(particles[i]), pz(particles[i]), energy(particles[i]))) end end # Now call the actual reconstruction method, tuned for our internal EDM _plain_jet_reconstruct(particles = recombination_particles, p = p, R = R, algorithm = algorithm, recombine = recombine) end """ _plain_jet_reconstruct(; particles::Vector{PseudoJet}, p = -1, R = 1.0, recombine = +) This is the internal implementation of jet reconstruction using the plain algorithm. It takes a vector of `particles` representing the input particles and reconstructs jets based on the specified parameters. Here the particles must be of type `PseudoJet`. Users of the package should use the `plain_jet_reconstruct` function as their entry point to this jet reconstruction. The power value maps to specific pp jet reconstruction algorithms: -1 = AntiKt, 0 = Cambridge/Aachen, 1 = Inclusive Kt. Floating point values are allowed for generalised k_t algorithm. # Arguments - `particles`: A vector of `PseudoJet` objects representing the input particles. - `p=-1`: The power to which the transverse momentum (`pt`) of each particle is raised. - `R=1.0`: The jet radius parameter. - `recombine`: The recombination function used to merge two jets. Default is `+` (additive recombination). # Returns - `clusterseq`: The resulting `ClusterSequence` object representing the reconstructed jets. """ function _plain_jet_reconstruct(; particles::Vector{PseudoJet}, p = -1, R = 1.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.AntiKt, recombine = +) # Bounds N::Int = length(particles) # Parameters R2 = R^2 # Optimised compact arrays for determining the next merge step # We make sure these arrays are type stable - have seen issues where, depending on the values # returned by the methods, they can become unstable and performance degrades kt2_array::Vector{Float64} = pt2.(particles) .^ p phi_array::Vector{Float64} = phi.(particles) rapidity_array::Vector{Float64} = rapidity.(particles) nn::Vector{Int} = Vector(1:N) # nearest neighbours nndist::Vector{Float64} = fill(float(R2), N) # geometric distances to the nearest neighbour nndij::Vector{Float64} = zeros(N) # dij metric distance # Maps index from the compact array to the clusterseq jet vector clusterseq_index::Vector{Int} = collect(1:N) # Setup the initial history and get the total energy history, Qtot = initial_history(particles) # Current implementation mutates the particles vector, so need to copy it # for the cluster sequence (there is too much copying happening, so this # needs to be rethought and reoptimised) clusterseq = ClusterSequence(algorithm, p, R, RecoStrategy.N2Plain, particles, history, Qtot) # Initialize nearest neighbours @simd for i in 1:N upd_nn_crosscheck!(i, 1, i - 1, rapidity_array, phi_array, R2, nndist, nn) end # diJ table * R2 @inbounds @simd for i in 1:N nndij[i] = dij(i, kt2_array, nn, nndist) end iteration::Int = 1 while N != 0 # Extremely odd - having these @debug statements present causes a performance # degradation of ~140μs per event on my M2 mac (20%!), even when no debugging is used # so they need to be completely commented out... #@debug "Beginning iteration $iteration" # Findmin and add back renormalisation to distance dij_min, i = fast_findmin(nndij, N) @fastmath dij_min /= R2 j::Int = nn[i] #@debug "Closest compact jets are $i ($(clusterseq_index[i])) and $j ($(clusterseq_index[j]))" if i != j # Merge jets i and j # swap if needed if j < i i, j = j, i end # Source "history" for merge hist_i = clusterseq.jets[clusterseq_index[i]]._cluster_hist_index hist_j = clusterseq.jets[clusterseq_index[j]]._cluster_hist_index # Recombine i and j into the next jet push!(clusterseq.jets, recombine(clusterseq.jets[clusterseq_index[i]], clusterseq.jets[clusterseq_index[j]])) # Get its index and the history index newjet_k = length(clusterseq.jets) newstep_k = length(clusterseq.history) + 1 clusterseq.jets[newjet_k]._cluster_hist_index = newstep_k # Update history add_step_to_history!(clusterseq, minmax(hist_i, hist_j)..., newjet_k, dij_min) # Update the compact arrays, reusing the i-th slot kt2_array[i] = pt2(clusterseq.jets[newjet_k])^p rapidity_array[i] = rapidity(clusterseq.jets[newjet_k]) phi_array[i] = phi(clusterseq.jets[newjet_k]) clusterseq_index[i] = newjet_k nndist[i] = R2 nn[i] = i else # i == j, this is a final jet ("merged with beam") add_step_to_history!(clusterseq, clusterseq.jets[clusterseq_index[i]]._cluster_hist_index, BeamJet, Invalid, dij_min) end # Squash step - copy the final jet's compact data into the j-th slot if j != N phi_array[j] = phi_array[N] rapidity_array[j] = rapidity_array[N] kt2_array[j] = kt2_array[N] nndist[j] = nndist[N] nn[j] = nn[N] nndij[j] = nndij[N] clusterseq_index[j] = clusterseq_index[N] end Nn::Int = N N -= 1 iteration += 1 # Update nearest neighbours step @inbounds @simd for k in 1:N upd_nn_step!(i, j, k, N, Nn, kt2_array, rapidity_array, phi_array, R2, nndist, nn, nndij) end nndij[i] = dij(i, kt2_array, nn, nndist) end # Return the final cluster sequence structure clusterseq end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
11579
# Inspired by the PseudoJet class of c++ code of Fastjet (https://fastjet.fr, # hep-ph/0512210, arXiv:1111.6097) # # Some of the implementation is taken from LorentzVectorHEP.jl, by Jerry Ling """Interface for composite types that includes fields px, py, py, and E that represents the components of a four-momentum vector.""" abstract type FourMomentum end """Used to protect against parton-level events where pt can be zero for some partons, giving rapidity=infinity. KtJet fails in those cases.""" const _MaxRap = 1e5 """Used to signal that the phi value has not yet been computed.""" const _invalid_phi = -100.0 """Used to signal that the rapidity value has not yet been computed.""" const _invalid_rap = -1.e200 """ mutable struct PseudoJet <: FourMomentum The `PseudoJet` struct represents a pseudojet, a four-momentum object used in jet reconstruction algorithms. Additonal information for the link back into the history of the clustering is stored in the `_cluster_hist_index` field. There is caching of the more expensive calculations for rapidity and azimuthal angle. # Fields - `px::Float64`: The x-component of the momentum. - `py::Float64`: The y-component of the momentum. - `pz::Float64`: The z-component of the momentum. - `E::Float64`: The energy component of the momentum. - `_cluster_hist_index::Int`: The index of the cluster history. - `_pt2::Float64`: The squared transverse momentum. - `_inv_pt2::Float64`: The inverse squared transverse momentum. - `_rap::Float64`: The rapidity. - `_phi::Float64`: The azimuthal angle. """ mutable struct PseudoJet <: FourMomentum px::Float64 py::Float64 pz::Float64 E::Float64 _cluster_hist_index::Int _pt2::Float64 _inv_pt2::Float64 _rap::Float64 _phi::Float64 end """ PseudoJet(px::Float64, py::Float64, pz::Float64, E::Float64, _cluster_hist_index::Int, pt2::Float64) Constructs a PseudoJet object with the given momentum components and energy and history index. # Arguments - `px::Float64`: The x-component of the momentum. - `py::Float64`: The y-component of the momentum. - `pz::Float64`: The z-component of the momentum. - `E::Float64`: The energy. - `_cluster_hist_index::Int`: The cluster history index. - `pt2::Float64`: The transverse momentum squared. # Returns A `PseudoJet` object. """ PseudoJet(px::Float64, py::Float64, pz::Float64, E::Float64, _cluster_hist_index::Int, pt2::Float64) = PseudoJet(px, py, pz, E, _cluster_hist_index, pt2, 1.0 / pt2, _invalid_rap, _invalid_phi) """ PseudoJet(px::Float64, py::Float64, pz::Float64, E::Float64) Constructs a PseudoJet object with the given momentum components and energy. # Arguments - `px::Float64`: The x-component of the momentum. - `py::Float64`: The y-component of the momentum. - `pz::Float64`: The z-component of the momentum. - `E::Float64`: The energy. # Returns A PseudoJet object. """ PseudoJet(px::Float64, py::Float64, pz::Float64, E::Float64) = PseudoJet(px, py, pz, E, 0, px^2 + py^2) import Base.show """ show(io::IO, jet::PseudoJet) Print a `PseudoJet` object to the specified IO stream. # Arguments - `io::IO`: The IO stream to which the information will be printed. - `jet::PseudoJet`: The `PseudoJet` object whose information will be printed. """ show(io::IO, jet::PseudoJet) = begin print(io, "Pseudojet(px: ", jet.px, " py: ", jet.py, " pz: ", jet.pz, " E: ", jet.E, "; ", "pt: ", sqrt(jet._pt2), " rapidity: ", rapidity(jet), " phi: ", phi(jet), ", m: ", m(jet), ")") end """ set_momentum!(j::PseudoJet, px, py, pz, E) Set the momentum components and energy of a `PseudoJet` object. # Arguments - `j::PseudoJet`: The `PseudoJet` object to set the momentum for. - `px`: The x-component of the momentum. - `py`: The y-component of the momentum. - `pz`: The z-component of the momentum. - `E`: The energy of the particle. """ set_momentum!(j::PseudoJet, px, py, pz, E) = begin j.px = px j.py = py j.pz = pz j.E = E j._pt2 = px^2 + py^2 j._inv_pt2 = 1.0 / j._pt2 j._rap = _invalid_rap j._phi = _invalid_phi end """ _ensure_valid_rap_phi(p::PseudoJet) Ensure that the rapidity and azimuthal angle of the PseudoJet `p` are valid. If the azimuthal angle is invalid (used as a proxy for both variables), they are set to a valid value using `_set_rap_phi!`. # Arguments - `p::PseudoJet`: The PseudoJet object to ensure valid rapidity and azimuthal angle for. """ _ensure_valid_rap_phi(p::PseudoJet) = p._phi == _invalid_phi && _set_rap_phi!(p) """ _set_rap_phi!(p::PseudoJet) Set the rapidity and azimuthal angle of the PseudoJet `p`. # Arguments - `p::PseudoJet`: The PseudoJet object for which to set the rapidity and azimuthal angle. # Description This function calculates and sets the rapidity and azimuthal angle of the PseudoJet `p` based on its momentum components. The rapidity is calculated in a way that is insensitive to roundoff errors when the momentum components are large. If the PseudoJet represents a point with infinite rapidity, a large number is assigned to the rapidity in order to lift the degeneracy between different zero-pt momenta. Note - the ϕ angle is calculated in the range [0, 2π). """ _set_rap_phi!(p::PseudoJet) = begin p._phi = p._pt2 == 0.0 ? 0.0 : atan(p.py, p.px) if p._phi < 0.0 p._phi += 2π elseif p._phi >= 2π p._phi -= 2π # can happen if phi=-|eps<1e-15|? end if p.E == abs(p.pz) && iszero(p._pt2) # Point has infinite rapidity -- convert that into a very large # number, but in such a way that different 0-pt momenta will have # different rapidities (so as to lift the degeneracy between # them) [this can be relevant at parton-level] MaxRapHere = _MaxRap + abs(p.pz) p._rap = p.pz >= 0.0 ? MaxRapHere : -MaxRapHere else # get the rapidity in a way that's modestly insensitive to roundoff # error when things pz,E are large (actually the best we can do without # explicit knowledge of mass) effective_m2 = max(0.0, m2(p)) # force non tachyonic mass E_plus_pz = p.E + abs(p.pz) # the safer of p+, p- p._rap = 0.5 * log((p._pt2 + effective_m2) / (E_plus_pz * E_plus_pz)) if p.pz > 0 p._rap = -p._rap end end nothing end """ phi(p::PseudoJet) Compute the ϕ angle of a `PseudoJet` object `p`. Note this function is a wrapper for `phi_02pi(p)`. # Arguments - `p::PseudoJet`: The `PseudoJet` object for which to compute the azimuthal angle. # Returns - The azimuthal angle of `p` in the range [0, 2π). """ phi(p::PseudoJet) = phi_02pi(p) """ phi_02pi(p::PseudoJet) Compute the azimuthal angle of a `PseudoJet` object `p` in the range [0, 2π). # Arguments - `p::PseudoJet`: The `PseudoJet` object for which to compute the azimuthal angle. # Returns - The azimuthal angle of `p` in the range [0, 2π). """ phi_02pi(p::PseudoJet) = begin _ensure_valid_rap_phi(p) return p._phi end """ rapidity(p::PseudoJet) Compute the rapidity of a `PseudoJet` object. # Arguments - `p::PseudoJet`: The `PseudoJet` object for which to compute the rapidity. # Returns The rapidity of the `PseudoJet` object. """ rapidity(p::PseudoJet) = begin _ensure_valid_rap_phi(p) return p._rap end """ pt2(p::PseudoJet) Get the squared transverse momentum of a PseudoJet. # Arguments - `p::PseudoJet`: The PseudoJet object. # Returns - The squared transverse momentum of the PseudoJet. """ pt2(p::PseudoJet) = p._pt2 """ pt(p::PseudoJet) Compute the scalar transverse momentum (pt) of a PseudoJet. # Arguments - `p::PseudoJet`: The PseudoJet object for which to compute the transverse momentum. # Returns - The transverse momentum (pt) of the PseudoJet. """ pt(p::PseudoJet) = sqrt(p._pt2) """ m2(p::PseudoJet) Calculate the invariant mass squared (m^2) of a PseudoJet. # Arguments - `p::PseudoJet`: The PseudoJet object for which to calculate the invariant mass squared. # Returns - The invariant mass squared (m^2) of the PseudoJet. """ m2(p::PseudoJet) = (p.E + p.pz) * (p.E - p.pz) - p._pt2 """ mag(p::PseudoJet) Return the magnitude of the momentum of a `PseudoJet`, `|p|`. # Arguments - `p::PseudoJet`: The `PseudoJet` object for which to compute the magnitude. # Returns The magnitude of the `PseudoJet` object. """ mag(p::PseudoJet) = sqrt(muladd(p.px, p.px, p.py^2) + p.pz^2) """ CosTheta(p::PseudoJet) Compute the cosine of the angle between the momentum vector `p` and the z-axis. # Arguments - `p::PseudoJet`: The PseudoJet object representing the momentum vector. # Returns - The cosine of the angle between `p` and the z-axis. """ @inline function CosTheta(p::PseudoJet) fZ = p.pz ptot = mag(p) return ifelse(ptot == 0.0, 1.0, fZ / ptot) end """ eta(p::PseudoJet) Compute the pseudorapidity (η) of a PseudoJet. # Arguments - `p::PseudoJet`: The PseudoJet object for which to compute the pseudorapidity. # Returns - The pseudorapidity (η) of the PseudoJet. """ function eta(p::PseudoJet) cosTheta = CosTheta(p) (cosTheta^2 < 1.0) && return -0.5 * log((1.0 - cosTheta) / (1.0 + cosTheta)) fZ = p.pz iszero(fZ) && return 0.0 # Warning("PseudoRapidity","transverse momentum = 0! return +/- 10e10"); fZ > 0.0 && return 10e10 return -10e10 end """ const η = eta Alias for the pseudorapidity function, `eta`. """ const η = eta """ m(p::PseudoJet) Compute the invariant mass of a `PseudoJet` object. By convention if m^2 < 0, then -sqrt{(-m^2)} is returned. # Arguments - `p::PseudoJet`: The `PseudoJet` object for which to compute the invariant mass. # Returns The invariant mass of the `PseudoJet` object. """ m(p::PseudoJet) = begin x = m2(p) x < 0.0 ? -sqrt(-x) : sqrt(x) end """ mass(p::PseudoJet) Compute the invariant mass (alias for `m(p)`). # Arguments - `p::PseudoJet`: The PseudoJet object for which to compute the mass. # Returns - The mass of the PseudoJet. """ mass(p::PseudoJet) = m(p) """Alias for `m2` function""" const mass2 = m2 """ px(p::PseudoJet) Return the x-component of the momentum of a `PseudoJet`. # Arguments - `p::PseudoJet`: The `PseudoJet` object. # Returns - The x-component of the momentum of the `PseudoJet`. """ px(p::PseudoJet) = p.px """ py(p::PseudoJet) Return the y-component of the momentum of a `PseudoJet`. # Arguments - `p::PseudoJet`: The `PseudoJet` object. # Returns - The y-component of the momentum of the `PseudoJet`. """ py(p::PseudoJet) = p.py """ pz(p::PseudoJet) Return the z-component of the momentum of a `PseudoJet`. # Arguments - `p::PseudoJet`: The `PseudoJet` object. # Returns - The z-component of the momentum of the `PseudoJet`. """ pz(p::PseudoJet) = p.pz """ energy(p::PseudoJet) Return the energy of a `PseudoJet`. # Arguments - `p::PseudoJet`: The `PseudoJet` object. # Returns - The energy of the `PseudoJet`. """ energy(p::PseudoJet) = p.E cluster_hist_index(p::PseudoJet) = p._cluster_hist_index import Base.+; """ +(j1::PseudoJet, j2::PseudoJet) Addition operator for `PseudoJet` objects. # Arguments - `j1::PseudoJet`: The first `PseudoJet` object. - `j2::PseudoJet`: The second `PseudoJet` object. # Returns A new `PseudoJet` object with the sum of the momenta and energy of `j1` and `j2`. """ +(j1::PseudoJet, j2::PseudoJet) = begin PseudoJet(j1.px + j2.px, j1.py + j2.py, j1.pz + j2.pz, j1.E + j2.E) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
4339
""" savejets(filename, jets; format="px py pz E") Save jet data to a file. # Arguments - `filename`: The name of the file to save the jet data to. - `jets`: An array of jet objects to save. - `format="px py pz E"`: (optional) A string specifying the format of the jet data to save. The default format is "px py pz E". # Details This function saves jet data to a file in a specific format. Each line in the file represents a jet and contains the information about the jet in the specified format. The format string can include the following placeholders: - "E" or "energy": Jet energy - "px": Momentum along the x-axis - "py": Momentum along the y-axis - "pz": Momentum along the z-axis - "pt2": Square of the transverse momentum - "phi": Azimuth angle - "rapidity": Rapidity Lines starting with '#' are treated as comments and are ignored. It is strongly NOT recommended to put something other than values and (possibly custom) separators in the `format` string. """ function savejets(filename, jets; format = "px py pz E") symbols = Dict("E" => JetReconstruction.energy, "energy" => JetReconstruction.energy, "px" => JetReconstruction.px, "py" => JetReconstruction.py, "pz" => JetReconstruction.pz, "pt2" => JetReconstruction.pt2, "phi" => JetReconstruction.phi, "rapidity" => JetReconstruction.rapidity) for pair in symbols if !occursin(pair[1], format) pop!(symbols, pair[1]) end end open(filename, "w") do file write(file, "# this file contains jet data.\n# each line that does not start with '#' contains the information about a jet in the following format:\n# " * "$(format)" * "\n# where E is energy, px is momentum along x, py is momentum along y, pz is momentum along z, pt2 is pt^2, phi is azimuth, and rapidity is rapidity\n") for j in jets line = format for pair in symbols line = replace(line, pair[1] => "$(pair[2](j))") end write(file, line * '\n') end write(file, "#END") end nothing end """ loadjets!(filename, jets; splitby=isspace, constructor=(px,py,pz,E)->LorentzVectorHEP(E,px,py,pz), dtype=Float64) Loads the `jets` from a file. Ignores lines that start with `'#'`. Each line gets processed in the following way: the line is split using `split(line, splitby)` or simply `split(line)` by default. Every value in this line is then converted to the `dtype` (which is `Float64` by default). These values are then used as arguments for the `constructor` function which should produce individual jets. By default, the `constructor` constructs Lorentz vectors. Everything that was already in `jets` is not affected as we only use `push!` on it. # Example ```julia # Load jets from two files into one array jets = [] loadjets!("myjets1.dat", jets) loadjets!("myjets2.dat", jets) ``` """ function loadjets!(filename, jets; splitby = isspace, constructor = (px, py, pz, E) -> LorentzVectorHEP(E, px, py, pz), dtype = Float64) open(filename, "r") do file for line in eachline(file) if line[1] != '#' jet = constructor((parse(dtype, x) for x in split(line, splitby) if x != "")...) push!(jets, jet) end end end jets end """ loadjets(filename; splitby=isspace, constructor=(px,py,pz,E)->LorentzVectorHEP(E,px,py,pz), VT=LorentzVector) Load jets from a file. # Arguments - `filename`: The name of the file to load jets from. - `splitby`: The delimiter used to split the data in the file. Default is `isspace`. - `constructor`: A function that constructs a `VT` object from the jet data. Default is `(px,py,pz,E)->LorentzVector(E,px,py,pz)`. - `VT`: The type of the vector used to store the jet data. Default is `LorentzVector`. # Returns - A vector of `VT` objects representing the loaded jets. """ function loadjets(filename; splitby = isspace, constructor = (px, py, pz, E) -> LorentzVectorHEP(E, px, py, pz), VT = LorentzVector) loadjets!(filename, VT[], splitby = splitby, constructor = constructor) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
22218
# Implementation of Tiled Algorithm, using linked list # This is very similar to FastJet's N2Tiled algorithm # Original Julia implementation by Philippe Gras, # ported to this package by Graeme Stewart using Logging using Accessors using LoopVectorization # Include struct definitions and basic operations include("TiledAlgoLLStructs.jl") """ _tj_dist(jetA, jetB) Compute the geometric distance in the (y, ϕ)-plane between two jets in the TiledAlgoLL module. # Arguments - `jetA`: The first jet. - `jetB`: The second jet. # Returns The squared distance between `jetA` and `jetB`. # Examples """ _tj_dist(jetA, jetB) = begin dphi = π - abs(π - abs(jetA.phi - jetB.phi)) deta = jetA.eta - jetB.eta @muladd dphi * dphi + deta * deta end """ _tj_diJ(jet) Compute the dij metric value for a given jet. # Arguments - `jet`: The input jet. # Returns - The dij value for the jet. # Example """ _tj_diJ(jet) = begin kt2 = jet.kt2 if isvalid(jet.NN) && jet.NN.kt2 < kt2 kt2 = jet.NN.kt2 end return jet.NN_dist * kt2 end """ tile_index(tiling_setup, eta::Float64, phi::Float64) Compute the tile index for a given (eta, phi) coordinate. # Arguments - `tiling_setup`: The tiling setup object containing the tile size and number of tiles. - `eta::Float64`: The eta coordinate. - `phi::Float64`: The phi coordinate. # Returns The tile index corresponding to the (eta, phi) coordinate. """ tile_index(tiling_setup, eta::Float64, phi::Float64) = begin # Use clamp() to restrict to the correct ranges # - eta can be out of range by construction (open ended bins) # - phi is protection against bad rounding ieta = clamp(1 + unsafe_trunc(Int, (eta - tiling_setup._tiles_eta_min) / tiling_setup._tile_size_eta), 1, tiling_setup._n_tiles_eta) iphi = clamp(unsafe_trunc(Int, phi / tiling_setup._tile_size_phi), 0, tiling_setup._n_tiles_phi) return iphi * tiling_setup._n_tiles_eta + ieta end """ tiledjet_set_jetinfo!(jet::TiledJet, clusterseq::ClusterSequence, tiling::Tiling, jets_index, R2, p) Initialise a tiled jet from a PseudoJet (using an index into our ClusterSequence) Arguments: - `jet::TiledJet`: The TiledJet object to set the information for. - `clusterseq::ClusterSequence`: The ClusterSequence object containing the jets. - `tiling::Tiling`: The Tiling object containing the tile information. - `jets_index`: The index of the jet in the ClusterSequence. - `R2`: The jet radius parameter squared. - `p`: The power to raise the pt2 value to. This function sets the eta, phi, kt2, jets_index, NN_dist, NN, tile_index, previous, and next fields of the TiledJet object. Returns: - `nothing` """ tiledjet_set_jetinfo!(jet::TiledJet, clusterseq::ClusterSequence, tiling::Tiling, jets_index, R2, p) = begin @inbounds jet.eta = rapidity(clusterseq.jets[jets_index]) @inbounds jet.phi = phi_02pi(clusterseq.jets[jets_index]) @inbounds jet.kt2 = pt2(clusterseq.jets[jets_index]) > 1.e-300 ? pt2(clusterseq.jets[jets_index])^p : 1.e300 jet.jets_index = jets_index # Initialise NN info as well jet.NN_dist = R2 jet.NN = noTiledJet # Find out which tile it belonds to jet.tile_index = tile_index(tiling.setup, jet.eta, jet.phi) # Insert it into the tile's linked list of jets (at the beginning) jet.previous = noTiledJet @inbounds jet.next = tiling.tiles[jet.tile_index] if isvalid(jet.next) jet.next.previous = jet end @inbounds tiling.tiles[jet.tile_index] = jet nothing end """Full scan for nearest neighbours""" """ set_nearest_neighbours!(clusterseq::ClusterSequence, tiling::Tiling, tiledjets::Vector{TiledJet}) This function sets the nearest neighbor information for all jets in the `tiledjets` vector. # Arguments - `clusterseq::ClusterSequence`: The cluster sequence object. - `tiling::Tiling`: The tiling object. - `tiledjets::Vector{TiledJet}`: The vector of tiled jets. # Returns - `NNs::Vector{TiledJet}`: The vector of nearest neighbor jets. - `diJ::Vector{Float64}`: The vector of diJ values. The function iterates over each tile in the `tiling` and sets the nearest neighbor information for each jet in the tile. It then looks for neighbor jets in the neighboring tiles and updates the nearest neighbor information accordingly. Finally, it creates the diJ table and returns the vectors of nearest neighbor jets and diJ values. Note: The diJ values are calculated as the kt distance multiplied by R^2. """ function set_nearest_neighbours!(clusterseq::ClusterSequence, tiling::Tiling, tiledjets::Vector{TiledJet}) # Setup the initial nearest neighbour information for tile in tiling.tiles isvalid(tile) || continue for jetA in tile for jetB in tile if jetB == jetA break end dist = _tj_dist(jetA, jetB) if (dist < jetA.NN_dist) jetA.NN_dist = dist jetA.NN = jetB end if dist < jetB.NN_dist jetB.NN_dist = dist jetB.NN = jetA end end end # Look for neighbour jets n the neighbour tiles for rtile_index in rightneighbours(tile.tile_index, tiling) for jetA in tile for jetB in @inbounds tiling.tiles[rtile_index] dist = _tj_dist(jetA, jetB) if (dist < jetA.NN_dist) jetA.NN_dist = dist jetA.NN = jetB end if dist < jetB.NN_dist jetB.NN_dist = dist jetB.NN = jetA end end end # No need to do it for LH tiles, since they are implicitly done # when we set NN for both jetA and jetB on the RH tiles. end end # Now create the diJ (where J is i's NN) table - remember that # we differ from standard normalisation here by a factor of R2 # (corrected for at the end). diJ = similar(clusterseq.jets, Float64) NNs = similar(clusterseq.jets, TiledJet) for i in eachindex(diJ) jetA = tiledjets[i] diJ[i] = _tj_diJ(jetA) # kt distance * R^2 # Our compact diJ table will not be in one-to-one corresp. with non-compact jets, # so set up bi-directional correspondence here. @inbounds NNs[i] = jetA jetA.dij_posn = i end NNs, diJ end """ do_ij_recombination_step!(clusterseq::ClusterSequence, jet_i, jet_j, dij, recombine=+) Perform the bookkeeping associated with the step of recombining jet_i and jet_j (assuming a distance dij). # Arguments - `clusterseq::ClusterSequence`: The cluster sequence object. - `jet_i`: The index of the first jet to be recombined. - `jet_j`: The index of the second jet to be recombined. - `dij`: The distance between the two jets. - `recombine=+`: The recombination function to be used. Default is addition. # Returns - `newjet_k`: The index of the newly created jet. # Description This function performs the i-j recombination step in the cluster sequence. It creates a new jet by recombining the first two jets using the specified recombination function. The new jet is then added to the cluster sequence. The function also updates the indices and history information of the new jet and sorts out the history. """ do_ij_recombination_step!(clusterseq::ClusterSequence, jet_i, jet_j, dij, recombine = +) = begin # Create the new jet by recombining the first two with # the E-scheme push!(clusterseq.jets, recombine(clusterseq.jets[jet_i], clusterseq.jets[jet_j])) # Get its index and the history index newjet_k = length(clusterseq.jets) newstep_k = length(clusterseq.history) + 1 # And provide jet with this info clusterseq.jets[newjet_k]._cluster_hist_index = newstep_k # Finally sort out the history hist_i = clusterseq.jets[jet_i]._cluster_hist_index hist_j = clusterseq.jets[jet_j]._cluster_hist_index add_step_to_history!(clusterseq, minmax(hist_i, hist_j)..., newjet_k, dij) newjet_k end """ do_iB_recombination_step!(clusterseq::ClusterSequence, jet_i, diB) Bookkeeping for recombining a jet with the beam (i.e., finalising the jet) by adding a step to the history of the cluster sequence. # Arguments - `clusterseq::ClusterSequence`: The cluster sequence object. - `jet_i`: The index of the jet. - `diB`: The diB value. """ do_iB_recombination_step!(clusterseq::ClusterSequence, jet_i, diB) = begin # Recombine the jet with the beam add_step_to_history!(clusterseq, clusterseq.jets[jet_i]._cluster_hist_index, BeamJet, Invalid, diB) end """ add_untagged_neighbours_to_tile_union(center_index, tile_union, n_near_tiles, tiling) Adds to the vector tile_union the tiles that are in the neighbourhood of the specified center_index, including itself and whose tagged status are false - start adding from position n_near_tiles-1, and increase n_near_tiles. When a neighbour is added its tagged status is set to true. # Arguments - `center_index`: The index of the center tile. - `tile_union`: An array to store the indices of neighbouring tiles. - `n_near_tiles`: The number of neighbouring tiles. - `tiling`: The tiling object containing the tile tags. # Returns The updated number of near tiles. """ function add_untagged_neighbours_to_tile_union(center_index, tile_union, n_near_tiles, tiling) for tile_index in surrounding(center_index, tiling) @inbounds if !tiling.tags[tile_index] n_near_tiles += 1 tile_union[n_near_tiles] = tile_index tiling.tags[tile_index] = true else end end n_near_tiles end """ find_tile_neighbours!(tile_union, jetA, jetB, oldB, tiling) Find the union of neighbouring tiles of `jetA`, `jetB`, and `oldB` and add them to the `tile_union`. This established the set of tiles over which searches for updated and new nearest-neighbours must be run # Arguments - `tile_union`: The tile union to which the neighbouring tiles will be added. - `jetA`: The first jet. - `jetB`: The second jet. - `oldB`: The old second jet. - `tiling`: The tiling information. # Returns The number of neighbouring tiles added to the `tile_union`. """ function find_tile_neighbours!(tile_union, jetA, jetB, oldB, tiling) n_near_tiles = add_untagged_neighbours_to_tile_union(jetA.tile_index, tile_union, 0, tiling) if isvalid(jetB) if jetB.tile_index != jetA.tile_index n_near_tiles = add_untagged_neighbours_to_tile_union(jetB.tile_index, tile_union, n_near_tiles, tiling) end if oldB.tile_index != jetA.tile_index && oldB.tile_index != jetB.tile_index n_near_tiles = add_untagged_neighbours_to_tile_union(oldB.tile_index, tile_union, n_near_tiles, tiling) end end n_near_tiles end """ tiled_jet_reconstruct(particles::Vector{T}; p = -1, R = 1.0, recombine = +) where {T} Main jet reconstruction algorithm entry point for reconstructing jets using the tiled stragegy for generic jet type T. **Note** - if a non-standard recombination is used, it must be defined for JetReconstruction.PseudoJet, as this struct is used internally. This code will use the `k_t` algorithm types, operating in `(rapidity, φ)` space. It is not necessary to specify both the `algorithm` and the `p` (power) value. If both are given they must be consistent or an exception is thrown. ## Arguments - `particles::Vector{T}`: A vector of particles used as input for jet reconstruction. T must support methods px, py, pz and energy (defined in the JetReconstruction namespace) - `p::Union{Real, Nothing} = -1`: The power parameter for the jet reconstruction algorithm, thus swiching between different algorithms. - `algorithm::Union{JetAlgorithm, Nothing} = nothing`: The explicit jet algorithm to use. - `R::Float64 = 1.0`: The jet radius parameter for the jet reconstruction algorithm. - `recombine::Function = +`: The recombination function used for combining pseudojets. ## Returns - `Vector{PseudoJet}`: A vector of reconstructed jets. ## Example ```julia tiled_jet_reconstruct(particles::Vector{LorentzVectorHEP}; p = -1, R = 0.4, recombine = +) ``` """ function tiled_jet_reconstruct(particles::Vector{T}; p::Union{Real, Nothing} = -1, R = 1.0, algorithm::Union{JetAlgorithm.Algorithm, Nothing} = nothing, recombine = +) where {T} # Check for consistency between algorithm and power (p, algorithm) = get_algorithm_power_consistency(p = p, algorithm = algorithm) # If we have PseudoJets, we can just call the main algorithm... if T == PseudoJet # recombination_particles will become part of the cluster sequence, so size it for # the starting particles and all N recombinations recombination_particles = copy(particles) sizehint!(recombination_particles, length(particles) * 2) else recombination_particles = PseudoJet[] sizehint!(recombination_particles, length(particles) * 2) for i in eachindex(particles) push!(recombination_particles, PseudoJet(px(particles[i]), py(particles[i]), pz(particles[i]), energy(particles[i]))) end end _tiled_jet_reconstruct(recombination_particles; p = p, R = R, algorithm = algorithm, recombine = recombine) end """ Main jet reconstruction algorithm, using PseudoJet objects """ """ _tiled_jet_reconstruct(particles::Vector{PseudoJet}; p = -1, R = 1.0, recombine = +) where {T} Main jet reconstruction algorithm entry point for reconstructing jets once preprocessing of data types are done. ## Arguments - `particles::Vector{PseudoJet}`: A vector of `PseudoJet` particles used as input for jet reconstruction. - `p::Int = -1`: The power parameter for the jet reconstruction algorithm, thus swiching between different algorithms. - `R::Float64 = 1.0`: The jet radius parameter for the jet reconstruction algorithm. - `recombine::Function = +`: The recombination function used for combining pseudojets. ## Returns - `Vector{PseudoJet}`: A vector of reconstructed jets. ## Example ```julia tiled_jet_reconstruct(particles::Vector{PseudoJet}; p = 1, R = 1.0, recombine = +) ``` """ function _tiled_jet_reconstruct(particles::Vector{PseudoJet}; p::Real = -1, R = 1.0, algorithm::JetAlgorithm.Algorithm = JetAlgorithm.AntiKt, recombine = +) # Bounds N::Int = length(particles) # Extremely odd - having these @debug statements present causes a performance # degradation of ~20μs per event on my M2 mac (12%!), even when no debugging is used # so they need to be completely commented out... # # There are a few reports of this in, e.g., https://github.com/JuliaLang/julia/issues/28147 # It does seem to have improved, but it's far from perfect! # @debug "Initial particles: $(N)" # Algorithm parameters R2::Float64 = R * R p = (round(p) == p) ? Int(p) : p # integer p if possible # This will be used quite deep inside loops, so declare it here so that # memory (de)allocation gets done only once tile_union = Vector{Int}(undef, 3 * _n_tile_neighbours) # Container for pseudojets, sized for all initial particles, plus all of the # merged jets that can be created during reconstruction jets = PseudoJet[] sizehint!(jets, N * 2) resize!(jets, N) # Copy input data into the jets container copyto!(jets, particles) # Setup the initial history and get the total energy history, Qtot = initial_history(jets) # Now get the tiling setup _eta = Vector{Float64}(undef, length(particles)) for ijet in 1:length(particles) _eta[ijet] = rapidity(particles[ijet]) end tiling = Tiling(setup_tiling(_eta, R)) # ClusterSequence is the struct that holds the state of the reconstruction clusterseq = ClusterSequence(algorithm, p, R, RecoStrategy.N2Tiled, jets, history, Qtot) # Tiled jets is a structure that has additional variables for tracking which tile a jet is in tiledjets = similar(clusterseq.jets, TiledJet) for ijet in eachindex(tiledjets) tiledjets[ijet] = TiledJet(ijet) tiledjet_set_jetinfo!(tiledjets[ijet], clusterseq, tiling, ijet, R2, p) end # Now initalise all of the nearest neighbour tiles NNs, dij = set_nearest_neighbours!(clusterseq, tiling, tiledjets) # Main loop of the reconstruction # Each iteration we either merge 2→1 or finalise a jet, so it takes N iterations # to complete the reconstruction for iteration in 1:N # Last slot holds the index of the final valid entry in the # compact NNs and dij arrays ilast = N - (iteration - 1) # Search for the lowest value of min_dij_ijet dij_min, ibest = fast_findmin(dij, ilast) @inbounds jetA = NNs[ibest] jetB = jetA.NN # Normalisation @fastmath dij_min /= R2 # @debug "Iteration $(iteration): dij_min $(dij_min); jetA $(jetA.id), jetB $(jetB.id)" if isvalid(jetB) # Jet-jet recombination # If necessary relabel A & B to ensure jetB < jetA, that way if # the larger of them == newtail then that ends up being jetA and # the new jet that is added as jetB is inserted in a position that # has a future! if jetA.id < jetB.id jetA, jetB = jetB, jetA end # Recombine jetA and jetB and retrieves the new index, nn nn = do_ij_recombination_step!(clusterseq, jetA.jets_index, jetB.jets_index, dij_min, recombine) tiledjet_remove_from_tiles!(tiling, jetA) oldB = copy(jetB) # take a copy because we will need it... tiledjet_remove_from_tiles!(tiling, jetB) tiledjet_set_jetinfo!(jetB, clusterseq, tiling, nn, R2, p) # cause jetB to become _jets[nn] # (in addition, registers the jet in the tiling) else # Jet-beam recombination do_iB_recombination_step!(clusterseq, jetA.jets_index, dij_min) tiledjet_remove_from_tiles!(tiling, jetA) oldB = jetB end # Find all the neighbour tiles that hold candidate jets for Updates n_near_tiles = find_tile_neighbours!(tile_union, jetA, jetB, oldB, tiling) # Firstly compactify the diJ by taking the last of the diJ and copying # it to the position occupied by the diJ for jetA @inbounds NNs[ilast].dij_posn = jetA.dij_posn @inbounds dij[jetA.dij_posn] = dij[ilast] @inbounds NNs[jetA.dij_posn] = NNs[ilast] # Initialise jetB's NN distance as well as updating it for # other particles. # Run over all tiles in our union for itile in 1:n_near_tiles @inbounds tile = tiling.tiles[@inbounds tile_union[itile]] #TAKES 5μs @inbounds tiling.tags[tile_union[itile]] = false # reset tag, since we're done with unions isvalid(tile) || continue #Probably not required # run over all jets in the current tile for jetI in tile # see if jetI had jetA or jetB as a NN -- if so recalculate the NN if jetI.NN == jetA || (jetI.NN == jetB && isvalid(jetB)) jetI.NN_dist = R2 jetI.NN = noTiledJet # now go over tiles that are neighbours of I (include own tile) for near_tile_index in surrounding(tile.tile_index, tiling) # and then over the contents of that tile for jetJ in @inbounds tiling.tiles[near_tile_index] # Sometimes jetJ comes out as invalid...? dist = _tj_dist(jetI, jetJ) if dist < jetI.NN_dist && jetJ != jetI jetI.NN_dist = dist jetI.NN = jetJ end end # next jetJ end # next near_tile dij[jetI.dij_posn] = _tj_diJ(jetI) # update diJ kt-dist end #jetI.NN == jetA || (jetI.NN == jetB && !isnothing(jetB)) # check whether new jetB is closer than jetI's current NN and # if jetI is closer than jetB's current (evolving) nearest # neighbour. Where relevant update things. if isvalid(jetB) dist = _tj_dist(jetI, jetB) if dist < jetI.NN_dist if jetI != jetB jetI.NN_dist = dist jetI.NN = jetB dij[jetI.dij_posn] = _tj_diJ(jetI) # update diJ... end end if dist < jetB.NN_dist && jetI != jetB jetB.NN_dist = dist jetB.NN = jetI end end # isvalid(jetB) end #next jetI end #next itile # finally, register the updated kt distance for B if isvalid(jetB) @inbounds dij[jetB.dij_posn] = _tj_diJ(jetB) end end clusterseq end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
10722
# Structures used internally by the tiled algorithm """Structure analogous to PseudoJet, but with the extra information needed for dealing with tiles for the tiled stragegy""" """ struct TiledJet TiledJet represents a jet in a tiled algorithm for jet reconstruction, with additional information to track the jet's position in the tiled structures. # Fields - `id::Int`: The ID of the jet. - `eta::Float64`: The rapidity of the jet. - `phi::Float64`: The azimuthal angle of the jet. - `kt2::Float64`: The transverse momentum squared of the jet. - `NN_dist::Float64`: The distance to the nearest neighbor. - `jets_index::Int`: The index of the jet in the jet array. - `tile_index::Int`: The index of the tile in the tile array. - `dij_posn::Int`: The position of this jet in the dij compact array. - `NN::TiledJet`: The nearest neighbor. - `previous::TiledJet`: The previous jet. - `next::TiledJet`: The next jet. """ mutable struct TiledJet id::Int eta::Float64 phi::Float64 kt2::Float64 NN_dist::Float64 jets_index::Int tile_index::Int dij_posn::Int "Nearest neighbour" NN::TiledJet previous::TiledJet next::TiledJet TiledJet(::Type{Nothing}) = begin t = new(-1, 0.0, 0.0, 0.0, 0.0, -1, 0, 0) t.NN = t.previous = t.next = t t end """ TiledJet constructor with all fields. """ function TiledJet(id, eta, phi, kt2, NN_dist, jet_index, tile_index, dij_posn, NN, previous, next) new(id, eta, phi, kt2, NN_dist, jet_index, tile_index, dij_posn, NN, previous, next) end end """ const noTiledJet::TiledJet = TiledJet(Nothing) A constant variable representing a "blank" `TiledJet` object with invalid values. """ const noTiledJet::TiledJet = TiledJet(Nothing) """ isvalid(t::TiledJet) Check if a `TiledJet` is valid, by seeing if it is not the `noTiledJet` object. # Arguments - `t::TiledJet`: The `TiledJet` object to check. # Returns - `Bool`: `true` if the `TiledJet` object is valid, `false` otherwise. """ isvalid(t::TiledJet) = !(t === noTiledJet) """ TiledJet(id) Constructs a `TiledJet` object with the given `id` and initializes its properties to zero. # Arguments - `id`: The ID of the `TiledJet` object. # Returns A `TiledJet` object with the specified `id` and values set to zero or noTiledJet. """ TiledJet(id) = TiledJet(id, 0.0, 0.0, 0.0, 0.0, 0, 0, 0, noTiledJet, noTiledJet, noTiledJet) """ insert!(nextjet::TiledJet, jettomove::TiledJet) Inserts a `TiledJet` object into the linked list of `TiledJet` objects, before the `nextjet` object. The jet to move can be an isolated jet, a jet from another list or a jet from the same list # Arguments - `nextjet::TiledJet`: The `TiledJet` object after which `jettomove` should be inserted. - `jettomove::TiledJet`: The `TiledJet` object to be inserted. # Example """ insert!(nextjet::TiledJet, jettomove::TiledJet) = begin if !isnothing(nextjet) nextjet.previous = jettomove end jettomove.next = nextjet jettomove.previous = nextjet.previous nextjet = jettomove end """ detach!(jet::TiledJet) Detach a `TiledJet` from its linked list by updating the `previous` and `next` pointers. # Arguments - `jet::TiledJet`: The `TiledJet` object to detach. """ detach!(jet::TiledJet) = begin if !isnothing(jet.previous) jet.previous.next = jet.next end if !isnothing(jet.next) jet.next.previous = jet.previous end jet.next = jet.previous = noTiledJet end import Base.copy """ copy(j::TiledJet) Create a copy of a `TiledJet` object. # Arguments - `j::TiledJet`: The `TiledJet` object to be copied. # Returns A new `TiledJet` object with the same attributes as the input object. """ copy(j::TiledJet) = TiledJet(j.id, j.eta, j.phi, j.kt2, j.NN_dist, j.jets_index, j.tile_index, j.dij_posn, j.NN, j.previous, j.next) # Iterator over a TiledJet walks along the chain of linked jets # until we reach a "noTiledJet" (which is !isvalid) """ Base.iterate(tj::TiledJet) Iterate over a `TiledJet` object's linked list, walking over all jets until the end (then the next jet is invalid). # Arguments - `tj::TiledJet`: The `TiledJet` object to start to iterate over. """ Base.iterate(tj::TiledJet) = begin isvalid(tj) ? (tj, tj) : nothing end function Base.iterate(tj::TiledJet, state::TiledJet) isvalid(state.next) ? (state.next::TiledJet, state.next::TiledJet) : nothing end """ struct Tiling The `Tiling` struct represents a tiling configuration for jet reconstruction. # Fields - `setup::TilingDef`: The tiling definition used for the configuration. - `tiles::Matrix{TiledJet}`: A matrix of tiled jets, containing the first jet in each tile (then the linked list of the first jet is followed to get access to all jets in this tile). - `positions::Matrix{Int}`: Used to track tiles that are on the edge of ϕ array, where neighbours need to be wrapped around. - `tags::Matrix{Bool}`: The matrix of tags indicating whether a tile is valid or not (set to `false` initially, then `true` when the tile has been setup properly). """ struct Tiling setup::TilingDef tiles::Matrix{TiledJet} positions::Matrix{Int} tags::Matrix{Bool} end """ Tiling(setup::TilingDef) Constructs a intial `Tiling` object based on the provided `setup` parameters. # Arguments - `setup::TilingDef`: The setup parameters for the tiling. # Returns A `Tiling` object. """ Tiling(setup::TilingDef) = begin t = Tiling(setup, fill(noTiledJet, (setup._n_tiles_eta, setup._n_tiles_phi)), fill(0, (setup._n_tiles_eta, setup._n_tiles_phi)), fill(false, (setup._n_tiles_eta, setup._n_tiles_phi))) @inbounds for iphi in 1:(setup._n_tiles_phi) # The order of the following two statements is important # to have position = tile_right in case n_tiles_eta = 1 t.positions[1, iphi] = tile_left t.positions[setup._n_tiles_eta, iphi] = tile_right end t end "Signal that a tile is on the left hand side of the tiling array in ϕ" const tile_left = -1 "Signal that a tile is central for the tiling array in ϕ" const tile_central = 0 "Signal that a tile is on the right hand side of the tiling array in ϕ" const tile_right = 1 "Number of neighbours for a tile in the tiling array (including itself)" const _n_tile_neighbours = 9 """ struct Surrounding{N} Structure used for iterating over neighbour tiles. # Fields - `indices::NTuple{N, Int}`: A tuple of `N` integers representing the indices. """ struct Surrounding{N} indices::NTuple{N, Int} end import Base.iterate Base.iterate(x::T) where {T <: Surrounding} = (x.indices[1], 2) Base.iterate(x::Surrounding{0}) = nothing Base.iterate(x::Surrounding{1}, state) = nothing Base.iterate(x::Surrounding{2}, state) = nothing Base.iterate(x::Surrounding{3}, state) = state > 3 ? nothing : (x.indices[state], state + 1) Base.iterate(x::Surrounding{4}, state) = state > 4 ? nothing : (x.indices[state], state + 1) Base.iterate(x::Surrounding{6}, state) = state > 6 ? nothing : (x.indices[state], state + 1) Base.iterate(x::Surrounding{9}, state) = state > 9 ? nothing : (x.indices[state], state + 1) import Base.length length(x::Surrounding{N}) where {N} = N """ surrounding(center::Int, tiling::Tiling) Compute the surrounding indices of a given center index in a tiling. # Arguments - `center::Int`: The center index. - `tiling::Tiling`: The tiling object. # Returns - `Surrounding`: An object containing the surrounding indices. """ surrounding(center::Int, tiling::Tiling) = begin # 4|6|9 # 3|1|8 # 2|5|7 # -> η iphip = mod1(center + tiling.setup._n_tiles_eta, tiling.setup._n_tiles) iphim = mod1(center - tiling.setup._n_tiles_eta, tiling.setup._n_tiles) if tiling.setup._n_tiles_eta == 1 return Surrounding{3}((center, iphim, iphip)) elseif tiling.positions[center] == tile_right return Surrounding{6}((center, iphim, iphip, iphim - 1, center - 1, iphip - 1)) elseif tiling.positions[center] == tile_central return Surrounding{9}((center, iphim - 1, center - 1, iphip - 1, iphim, iphip, iphim + 1, center + 1, iphip + 1)) else #tile_left return Surrounding{6}((center, iphim, iphip, iphim + 1, center + 1, iphip + 1)) end end """ rightneighbours(center::Int, tiling::Tiling) Compute the indices of the right neighbors of a given center index in a tiling. This is used in the inital sweep to calculate the nearest neighbors, where the search between jets for the nearest neighbour is bi-directional, thus when a tile is considered only the right neighbours are needed to compare jet distances as the left-hand tiles have been done from that tile already. # Arguments - `center::Int`: The center index. - `tiling::Tiling`: The tiling object. # Returns - `Surrounding`: An object containing the indices of the right neighbors. """ rightneighbours(center::Int, tiling::Tiling) = begin # |1|4 # | |3 # | |2 # -> η iphip = mod1(center + tiling.setup._n_tiles_eta, tiling.setup._n_tiles) iphim = mod1(center - tiling.setup._n_tiles_eta, tiling.setup._n_tiles) if tiling.positions[center] == tile_right return Surrounding{1}((iphip,)) else return Surrounding{4}((iphip, iphim + 1, center + 1, iphip + 1)) end end """ tiledjet_remove_from_tiles!(tiling, jet) Remove a jet from the given tiling structure. # Arguments - `tiling`: The tiling structure from which the jet will be removed. - `jet`: The jet to be removed from the tiling structure. # Description This function removes a jet from the tiling structure. It adjusts the linked list to be consistent with the removal of the jet. """ tiledjet_remove_from_tiles!(tiling, jet) = begin if !isvalid(jet.previous) # We are at head of the tile, so reset it. # If this was the only jet on the tile then tile->head will now be NULL tiling.tiles[jet.tile_index] = jet.next else # Adjust link from previous jet in this tile jet.previous.next = jet.next end if isvalid(jet.next) # Adjust backwards-link from next jet in this tile jet.next.previous = jet.previous end jet.next = jet.previous = noTiledJet # To be clean, but not mandatory end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
13050
# Common functions and structures for Tiled reconstruction algorithms """ struct TilingDef A struct representing the definition of a spcific tiling scheme. # Fields - `_tiles_eta_min::Float64`: The minimum rapidity of the tiles. - `_tiles_eta_max::Float64`: The maximum rapidity of the tiles. - `_tile_size_eta::Float64`: The size of a tile in rapidity (usually R^2). - `_tile_size_phi::Float64`: The size of a tile in phi (usually a bit more than R^2). - `_n_tiles_eta::Int`: The number of tiles across rapidity. - `_n_tiles_phi::Int`: The number of tiles across phi. - `_n_tiles::Int`: The total number of tiles. - `_tiles_ieta_min::Int`: The minimum rapidity tile index. - `_tiles_ieta_max::Int`: The maximum rapidity tile index. # Constructor TilingDef(_tiles_eta_min, _tiles_eta_max, _tile_size_eta, _tile_size_phi, _n_tiles_eta, _n_tiles_phi, _tiles_ieta_min, _tiles_ieta_max) Constructs a `TilingDef` object with the given parameters. """ struct TilingDef _tiles_eta_min::Float64 _tiles_eta_max::Float64 _tile_size_eta::Float64 _tile_size_phi::Float64 _n_tiles_eta::Int _n_tiles_phi::Int _n_tiles::Int _tiles_ieta_min::Int _tiles_ieta_max::Int function TilingDef(_tiles_eta_min, _tiles_eta_max, _tile_size_eta, _tile_size_phi, _n_tiles_eta, _n_tiles_phi, _tiles_ieta_min, _tiles_ieta_max) new(_tiles_eta_min, _tiles_eta_max, _tile_size_eta, _tile_size_phi, _n_tiles_eta, _n_tiles_phi, _n_tiles_eta * _n_tiles_phi, _tiles_ieta_min, _tiles_ieta_max) end end """ determine_rapidity_extent(eta::Vector{T}) where T <: AbstractFloat Calculate the minimum and maximum rapidities based on the input vector `eta`. The function determines the rapidity extent by binning the multiplicities as a function of rapidity and finding the minimum and maximum rapidities such that the edge bins contain a certain fraction (~1/4) of the busiest bin and a minimum number of particles. This is the heuristic which is used by FastJet (inline comments are from FastJet). ## Arguments - `eta::Vector{T}`: A vector of rapidity values. ## Returns - `minrap::T`: The minimum rapidity value. - `maxrap::T`: The maximum rapidity value. """ function determine_rapidity_extent(eta::Vector{T}) where {T <: AbstractFloat} length(eta) == 0 && return 0.0, 0.0 nrap = 20 nbins = 2 * nrap counts = zeros(Int, nbins) # Get the minimum and maximum rapidities and at the same time bin # the multiplicities as a function of rapidity to help decide how # far out it is worth going minrap = maxrap = eta[1] ibin = 0 for y in eta minrap = min(minrap, y) maxrap = max(maxrap, y) # Bin in rapidity to decide how far to go with the tiling. # The bins go from ibin=1 (rap=-infinity..-19) # to ibin = nbins (rap=19..infinity for nrap=20) ibin = clamp(1 + unsafe_trunc(Int, y + nrap), 1, nbins) @inbounds counts[ibin] += 1 end # Get the busiest bin max_in_bin = maximum(counts) # Now find minrap, maxrap such that edge bin never contains more # than some fraction of busiest, and at least a few particles; first do # it from left. NB: the thresholds chosen here are largely # guesstimates as to what might work. # # 2014-07-17: in some tests at high multiplicity (100k) and particles going up to # about 7.3, anti-kt R=0.4, we found that 0.25 gave 20% better run times # than the original value of 0.5. allowed_max_fraction = 0.25 # The edge bins should also contain at least min_multiplicity particles min_multiplicity = 4 # now calculate how much we can accumulate into an edge bin allowed_max_cumul = floor(max(max_in_bin * allowed_max_fraction, min_multiplicity)) # make sure we don't require more particles in a bin than max_in_bin allowed_max_cumul = min(max_in_bin, allowed_max_cumul) # start scan over rapidity bins from the "left", to find out minimum rapidity of tiling cumul_lo = 0.0 ibin_lo = 1 while ibin_lo <= nbins @inbounds cumul_lo += counts[ibin_lo] if cumul_lo >= allowed_max_cumul minrap = max(minrap, ibin_lo - nrap - 1) break end ibin_lo += 1 end @assert ibin_lo != nbins # internal consistency check that you found a bin # then do it from "right", to find out maximum rapidity of tiling cumul_hi = 0.0 ibin_hi = nbins while ibin_hi >= 1 @inbounds cumul_hi += counts[ibin_hi] if cumul_hi >= allowed_max_cumul maxrap = min(maxrap, ibin_hi - nrap) break end ibin_hi -= 1 end @assert ibin_hi >= 1 # internal consistency check that you found a bin # consistency check @assert ibin_hi >= ibin_lo minrap, maxrap end """ setup_tiling(eta::Vector{T}, Rparam::AbstractFloat) where T <: AbstractFloat This function sets up the tiling parameters for a reconstruction given a vector of rapidities `eta` and a radius parameter `Rparam`. # Arguments - `eta::Vector{T}`: A vector of rapidities. - `Rparam::AbstractFloat`: The jet radius parameter. # Returns - `tiling_setup`: A `TilingDef` object containing the tiling setup parameters. # Description The function first decides the tile sizes based on the `Rparam` value. It then determines the number of tiles in the phi direction (`n_tiles_phi`) based on the tile size. Next, it determines the rapidity extent of the input `eta` vector and adjusts the values accordingly. Finally, it creates a `TilingDef` object with the calculated tiling parameters and returns it. """ function setup_tiling(eta::Vector{T}, Rparam::AbstractFloat) where {T <: AbstractFloat} # First decide tile sizes (with a lower bound to avoid huge memory use with # very small R) tile_size_eta = max(0.1, Rparam) # It makes no sense to go below 3 tiles in phi -- 3 tiles is # sufficient to make sure all pair-wise combinations up to pi in # phi are possible n_tiles_phi = max(3, floor(Int, 2π / tile_size_eta)) tile_size_phi = 2π / n_tiles_phi # >= Rparam and fits in 2pi tiles_eta_min, tiles_eta_max = determine_rapidity_extent(eta) # now adjust the values tiles_ieta_min = floor(Int, tiles_eta_min / tile_size_eta) tiles_ieta_max = floor(Int, tiles_eta_max / tile_size_eta) #FIXME shouldn't it be ceil ? tiles_eta_min = tiles_ieta_min * tile_size_eta tiles_eta_max = tiles_ieta_max * tile_size_eta n_tiles_eta = tiles_ieta_max - tiles_ieta_min + 1 tiling_setup = TilingDef(tiles_eta_min, tiles_eta_max, tile_size_eta, tile_size_phi, n_tiles_eta, n_tiles_phi, tiles_ieta_min, tiles_ieta_max) tiling_setup end """ geometric_distance(eta1::AbstractFloat, phi1::AbstractFloat, eta2::AbstractFloat, phi2::AbstractFloat) Compute the geometric distance between two points in the rap-phi plane. # Arguments - `eta1::AbstractFloat`: The eta coordinate of the first point. - `phi1::AbstractFloat`: The phi coordinate of the first point. - `eta2::AbstractFloat`: The eta coordinate of the second point. - `phi2::AbstractFloat`: The phi coordinate of the second point. # Returns - `distance::Float64`: The geometric distance between the two points. """ geometric_distance(eta1::AbstractFloat, phi1::AbstractFloat, eta2::AbstractFloat, phi2::AbstractFloat) = begin δeta = eta2 - eta1 δphi = π - abs(π - abs(phi1 - phi2)) return δeta * δeta + δphi * δphi end """ get_dij_dist(nn_dist, kt2_1, kt2_2, R2) Compute the dij metric distance between two jets. # Arguments - `nn_dist`: The nearest-neighbor distance between two jets. - `kt2_1`: The squared momentum metric value of the first jet. - `kt2_2`: The squared momentum metric value of the second jet. - `R2`: The jet radius parameter squared. # Returns The distance between the two jets. If `kt2_2` is equal to 0.0, then the first jet doesn't actually have a valid neighbour, so it's treated as a single jet adjecent to the beam. """ get_dij_dist(nn_dist, kt2_1, kt2_2, R2) = begin if kt2_2 == 0.0 return kt2_1 * R2 end return nn_dist * min(kt2_1, kt2_2) end """ get_tile(tiling_setup::TilingDef, eta::AbstractFloat, phi::AbstractFloat) Given a `tiling_setup` object, `eta` and `phi` values, this function calculates the tile indices for the given `eta` and `phi` values. # Arguments - `tiling_setup`: A `TilingDef` object that contains the tiling setup parameters. - `eta`: The eta value for which to calculate the tile index. - `phi`: The phi value for which to calculate the tile index. # Returns - `ieta`: The tile index along the eta direction. - `iphi`: The tile index along the phi direction. """ get_tile(tiling_setup::TilingDef, eta::AbstractFloat, phi::AbstractFloat) = begin # The eta clamp is necessary as the extreme bins catch overflows for high abs(eta) ieta = clamp(floor(Int, (eta - tiling_setup._tiles_eta_min) / tiling_setup._tile_size_eta), 1, tiling_setup._n_tiles_eta) # The phi clamp should not really be necessary, as long as phi values are [0,2π) iphi = clamp(floor(Int, 1 + (phi / 2π) * tiling_setup._n_tiles_phi), 1, tiling_setup._n_tiles_phi) ieta, iphi end """ get_tile_linear_index(tiling_setup::TilingDef, i_η::Int, i_ϕ::Int) Compute the linear index of a tile in a tiled setup. This is much faster in this function than using the LinearIndices construct (like x100, which is bonkers, but there you go...) # Arguments - `tiling_setup::TilingDef`: The tiling setup defining the number of tiles in each dimension. - `i_η::Int`: The index of the tile in the η dimension. - `i_ϕ::Int`: The index of the tile in the ϕ dimension. # Returns - The linear index of the tile. """ get_tile_cartesian_indices(tiling_setup::TilingDef, index::Int) = begin return (rem(index - 1, tiling_setup._n_tiles_eta) + 1, div(index - 1, tiling_setup._n_tiles_eta) + 1) end """ Iterator for the indexes of rightmost tiles for a given Cartesian tile index - These are the tiles above and to the right of the given tile (X=yes, O=no) XXX O.X OOO - rapidity coordinate must be in range, ϕ coordinate wraps """ """ struct rightmost_tiles A struct for iterating over rightmost tiles for a given Cartesian tile index. These are the tiles above and to the right of the given tile (X=included, O=not included): XXX O.X OOO Note, rapidity coordinate must be in range, ϕ coordinate wraps # Fields - `n_η::Int`: Number of η tiles - `n_ϕ::Int`: Number of ϕ tiles - `start_η::Int`: Centre η tile coordinate - `start_ϕ::Int`: Centre ϕ tile coordinate """ struct rightmost_tiles n_η::Int# Number of η tiles n_ϕ::Int# Number of ϕ tiles start_η::Int# Centre η tile coordinate start_ϕ::Int# Centre ϕ tile coordinate end """ Base.iterate(t::rightmost_tiles, state=1) Iterate over the `rightmost_tiles` object, returning all the rightmost tiles for a given Cartesian tile index. """ function Base.iterate(t::rightmost_tiles, state = 1) mapping = ((-1, -1), (-1, 0), (-1, 1), (0, 1)) if t.start_η == 1 && state == 1 state = 4 end while state <= 4 η = t.start_η + mapping[state][1] ϕ = t.start_ϕ + mapping[state][2] if ϕ > t.n_ϕ ϕ = 1 elseif ϕ < 1 ϕ = t.n_ϕ end return (η, ϕ), state + 1 end return nothing end """ struct neighbour_tiles A struct representing the neighbouring tiles. A struct for iterating over all neighbour tiles for a given Cartesian tile index. These are the tiles above and to the right of the given tile (X=included, O=not included): XXX X.X XXX Note, rapidity coordinate must be in range, ϕ coordinate wraps # Fields - `n_η::Int`: Number of η tiles - `n_ϕ::Int`: Number of ϕ tiles - `start_η::Int`: Centre η tile coordinate - `start_ϕ::Int`: Centre ϕ tile coordinate """ struct neighbour_tiles n_η::Int# Number of η tiles n_ϕ::Int# Number of ϕ tiles start_η::Int# Centre η tile coordinate start_ϕ::Int# Centre ϕ tile coordinate end """ Base.iterate(t::neighbour_tiles, state=1) Iterate over the `neighbour_tiles` object, returning all the neighbour tiles for a given Cartesian tile index. """ function Base.iterate(t::neighbour_tiles, state = 1) mapping = ((-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)) # Skip for top row in η if t.start_η == 1 && state == 1 state = 4 end # Skip for bottom row in η if t.start_η == t.n_η && state == 6 state = 9 end while state <= 8 η = t.start_η + mapping[state][1] ϕ = t.start_ϕ + mapping[state][2] if ϕ > t.n_ϕ ϕ = 1 elseif ϕ < 1 ϕ = t.n_ϕ end return (η, ϕ), state + 1 end return nothing end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
4798
# Utility functions, which can be used by different top level scripts using CodecZlib """ read_final_state_particles(fname; maxevents = -1, skipevents = 0, T=PseudoJet) Reads final state particles from a file and returns them as a vector of type T. # Arguments - `fname`: The name of the HepMC3 ASCII file to read particles from. If the file is gzipped, the function will automatically decompress it. - `maxevents=-1`: The maximum number of events to read. -1 means all events will be read. - `skipevents=0`: The number of events to skip before an event is included. - `T=PseudoJet`: The type of object to contruct and return. # Returns A vector of vectors of T objects, where each inner vector represents all the particles of a particular event. In particular T can be `PseudoJet` or a `LorentzVector` type. Note, if T is not `PseudoJet`, the order of the arguments in the constructor must be `(t, x, y, z)`. """ function read_final_state_particles(fname; maxevents = -1, skipevents = 0, T = PseudoJet) f = open(fname) if endswith(fname, ".gz") @debug "Reading gzipped file $fname" f = GzipDecompressorStream(f) end events = Vector{T}[] ipart = 1 HepMC3.read_events(f, maxevents = maxevents, skipevents = skipevents) do parts input_particles = T[] for p in parts if p.status == 1 # Annoyingly PseudoJet and LorentzVector constructors # disagree on the order of arguments... if T == PseudoJet particle = T(p.momentum.x, p.momentum.y, p.momentum.z, p.momentum.t) else particle = T(p.momentum.t, p.momentum.x, p.momentum.y, p.momentum.z) end push!(input_particles, particle) end end push!(events, input_particles) ipart += 1 end close(f) @info "Total Events: $(length(events))" @debug events events end """ final_jets(jets::Vector{PseudoJet}, ptmin::AbstractFloat=0.0) This function takes a vector of `PseudoJet` objects and a minimum transverse momentum `ptmin` as input. It returns a vector of `FinalJet` objects that satisfy the transverse momentum condition. # Arguments - `jets::Vector{PseudoJet}`: A vector of `PseudoJet` objects representing the input jets. - `ptmin::AbstractFloat=0.0`: The minimum transverse momentum required for a jet to be included in the final jets vector. # Returns A vector of `FinalJet` objects that satisfy the transverse momentum condition. """ function final_jets(jets::Vector{PseudoJet}, ptmin::AbstractFloat = 0.0) count = 0 final_jets = Vector{FinalJet}() sizehint!(final_jets, 6) for jet in jets dcut = ptmin^2 if pt2(jet) > dcut count += 1 push!(final_jets, FinalJet(rapidity(jet), phi(jet), sqrt(pt2(jet)))) end end final_jets end """Specialisation for final jets from LorentzVectors (TODO: merge into more general function)""" function final_jets(jets::Vector{LorentzVector}, ptmin::AbstractFloat = 0.0) count = 0 final_jets = Vector{FinalJet}() sizehint!(final_jets, 6) dcut = ptmin^2 for jet in jets if LorentzVectorHEP.pt(jet)^2 > dcut count += 1 push!(final_jets, FinalJet(LorentzVectorHEP.rapidity(jet), LorentzVectorHEP.phi(jet), LorentzVectorHEP.pt(jet))) end end final_jets end """Specialisation for final jets from LorentzVectorCyl (TODO: merge into more general function)""" function final_jets(jets::Vector{LorentzVectorCyl}, ptmin::AbstractFloat = 0.0) count = 0 final_jets = Vector{FinalJet}() sizehint!(final_jets, 6) dcut = ptmin^2 for jet in jets if LorentzVectorHEP.pt(jet)^2 > dcut count += 1 push!(final_jets, FinalJet(LorentzVectorHEP.eta(jet), LorentzVectorHEP.phi(jet), LorentzVectorHEP.pt(jet))) end end final_jets end """ fast_findmin(dij, n) Find the minimum value and its index in the first `n` elements of the `dij` array. The use of `@turbo` macro gives a significiant performance boost. # Arguments - `dij`: An array of values. - `n`: The number of elements to consider in the `dij` array. # Returns - `dij_min`: The minimum value in the first `n` elements of the `dij` array. - `best`: The index of the minimum value in the `dij` array. """ fast_findmin(dij, n) = begin # findmin(@inbounds @view dij[1:n]) best = 1 @inbounds dij_min = dij[1] @turbo for here in 2:n newmin = dij[here] < dij_min best = newmin ? here : best dij_min = newmin ? dij[here] : dij_min end dij_min, best end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
5121
# Put here common parameters for the jet reconstruction tests # This allows different test scripts to be run standalone, but # to easily share common parameters. # Set this variable for use by the include guard wrapper const JETRECO_TEST_COMMON = true using JetReconstruction using Logging using LorentzVectorHEP using JSON using Test using CodecZlib logger = ConsoleLogger(stdout, Logging.Warn) global_logger(logger) const events_file_pp = joinpath(@__DIR__, "data", "events.pp13TeV.hepmc3.gz") const events_file_ee = joinpath(@__DIR__, "data", "events.eeH.hepmc3.gz") const pp_algorithms = Dict(-1 => "Anti-kt", 0 => "Cambridge/Achen", 1 => "Inclusive-kt", 1.5 => "Generalised-kt") """ struct ComparisonTest Test parameters for the comparison of jet reconstruction against known FastJet results. # Fields - `events_file::AbstractString`: The file containing the event data. - `fastjet_outputs::AbstractString`: The file containing the FastJet outputs in JSON format (N.B. can be gzipped) - `algorithm::JetAlgorithm.Algorithm`: The algorithm used for jet reconstruction. - `power::Real`: The power parameter for the jet reconstruction algorithm. - `R::Real`: The radius parameter for the jet reconstruction algorithm. - `selector`: The selector used for final jet outputs. `selector` should be a closure that takes a `ClusterSequence` object and returns a vector of `FinalJet` objects, e.g., ```julia selector = (cs) -> exclusive_jets(cs; njets = 2) ``` """ struct ComparisonTest events_file::AbstractString fastjet_outputs::AbstractString algorithm::JetAlgorithm.Algorithm strategy::RecoStrategy.Strategy power::Real R::Real selector::Any selector_name::AbstractString end """Constructor where there is no selector_name given""" function ComparisonTest(events_file, fastjet_outputs, algorithm, strategy, power, R, selector) selector_name = "" ComparisonTest(events_file, fastjet_outputs, algorithm, strategy, power, R, selector, selector_name) end """Read JSON file with fastjet jets in it""" function read_fastjet_outputs(fname) f = open(fname) if endswith(fname, ".gz") @debug "Reading gzipped file $fname" f = GzipDecompressorStream(f) end JSON.parse(f) end """Sort jet outputs by pt of final jets""" function sort_jets!(event_jet_array) jet_pt(jet) = jet["pt"] for e in event_jet_array sort!(e["jets"], by = jet_pt, rev = true) end end function sort_jets!(jet_array::Vector{FinalJet}) jet_pt(jet) = jet.pt sort!(jet_array, by = jet_pt, rev = true) end function sort_jets!(jet_array::Vector{LorentzVectorCyl}) jet_pt(jet) = jet.pt sort!(jet_array, by = jet_pt, rev = true) end function run_reco_test(test::ComparisonTest; testname = nothing) # Read the input events events = JetReconstruction.read_final_state_particles(test.events_file) # Read the fastjet results fastjet_jets = read_fastjet_outputs(test.fastjet_outputs) sort_jets!(fastjet_jets) # Run the jet reconstruction jet_collection = Vector{FinalJets}() for (ievent, event) in enumerate(events) cluster_seq = JetReconstruction.jet_reconstruct(event; R = test.R, p = test.power, algorithm = test.algorithm, strategy = test.strategy) finaljets = final_jets(test.selector(cluster_seq)) sort_jets!(finaljets) push!(jet_collection, FinalJets(ievent, finaljets)) end if isnothing(testname) testname = "FastJet comparison: alg=$(test.algorithm), p=$(test.power), R=$(test.R), strategy=$(test.strategy)" if test.selector_name != "" testname *= ", $(test.selector_name)" end end @testset "$testname" begin # Test each event in turn... for (ievt, event) in enumerate(jet_collection) @testset "Event $(ievt)" begin @test size(event.jets) == size(fastjet_jets[ievt]["jets"]) # Test each jet in turn for (ijet, jet) in enumerate(event.jets) if ijet <= size(fastjet_jets[ievt]["jets"])[1] # Approximate test - note that @test macro passes the # tolerance into the isapprox() function # Use atol for position as this is absolute, but rtol for # the momentum # Sometimes phi could be in the range [-π, π], but FastJet always is [0, 2π] normalised_phi = jet.phi < 0.0 ? jet.phi + 2π : jet.phi @test jet.rap≈fastjet_jets[ievt]["jets"][ijet]["rap"] atol=1e-7 @test normalised_phi≈fastjet_jets[ievt]["jets"][ijet]["phi"] atol=1e-7 @test jet.pt≈fastjet_jets[ievt]["jets"][ijet]["pt"] rtol=1e-6 end end end end end end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
1002
# Bootstrap script to setup this local version of the JetReconstruction package # for running the examples println("Starting example boostrap script") # if isfile(joinpath(@__DIR__, "..", "examples", "Manifest.toml")) # println("Exisiting Manifest.toml found - assuming environment is already setup") # exit(0) # end local_pkg_path = joinpath(@__DIR__, "..", "..", "JetReconstruction") if !isdir(local_pkg_path) # Try a symlink to the current checkout local_checkout_path = realpath(joinpath(@__DIR__, "..", "..")) println("Creating symlink from $local_pkg_path to $local_checkout_path") symlink(local_checkout_path, local_pkg_path) else println(realpath(local_pkg_path)) println(readdir(local_pkg_path)) end println("Setting up examples project") using Pkg Pkg.instantiate() Pkg.resolve() println(("Seting JetReconstruction development package path: $local_pkg_path")) Pkg.develop(path = local_pkg_path) Pkg.status() println("Finished examples boostrap script")
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
305
# This is a wrapper file that checks that we did not # already include _common.jl. # # This is needed to allow sub-test scripts to be run # independently, but to also allow the main test script # to avoid double-including the common file. if !@isdefined JETRECO_TEST_COMMON include("_common.jl") end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
8843
#! /usr/bin/env julia using JetReconstruction using Test using JSON using LorentzVectorHEP using Logging include("common.jl") function main() # A few unit tests @testset "Algorithm/power consistency" begin @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.AntiKt, p = -1) @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.CA, p = 0) @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.Kt, p = 1) @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.AntiKt, p = nothing) @test JetReconstruction.check_algorithm_power_consistency(algorithm = nothing, p = -1) @test_throws ArgumentError JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.AntiKt, p = 0) @test_throws ArgumentError JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.Kt, p = 1.5) @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.GenKt, p = 1.5) @test JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.GenKt, p = -0.5) @test_throws ArgumentError JetReconstruction.check_algorithm_power_consistency(algorithm = JetAlgorithm.GenKt, p = nothing) end # New test structure, factorised tests for pp and e+e- include("test-pp-reconstruction.jl") include("test-ee-reconstruction.jl") # Compare inputing data in PseudoJet with using a LorentzVector do_test_compare_types(RecoStrategy.N2Plain, algname = pp_algorithms[-1], power = -1) do_test_compare_types(RecoStrategy.N2Tiled, algname = pp_algorithms[-1], power = -1) # Suppress these tests for now, as the examples Project.toml is rather heavy # because of the GLMakie dependency, plus on a CI there is no GL subsystem, # so things fail. The examples should be restructured to have a cleaner set # of examples that are good to run in the CI. # # Now run a few tests with our examples # include("tests_examples.jl") end """ Run the jet test dijmax -> apply inclusive dijmax cut njets -> apply inclusive njets cut If dijmax and njets are nothing, test inclusive jets with pt >= ptmin """ function do_test_compare_to_fastjet(strategy::RecoStrategy.Strategy, fastjet_jets; algname = "Unknown", selection = "Inclusive", ptmin::Float64 = 5.0, distance::Float64 = 0.4, power::Real = -1, dijmax = nothing, njets = nothing) # Strategy if (strategy == RecoStrategy.N2Plain) jet_reconstruction = plain_jet_reconstruct strategy_name = "N2Plain" elseif (strategy == RecoStrategy.N2Tiled) jet_reconstruction = tiled_jet_reconstruct strategy_name = "N2Tiled" elseif (strategy == RecoStrategy.Best) jet_reconstruction = jet_reconstruct strategy_name = "Best" else throw(ErrorException("Strategy not yet implemented")) end # Now run our jet reconstruction... # From PseudoJets events::Vector{Vector{PseudoJet}} = read_final_state_particles(events_file_pp) jet_collection = FinalJets[] for (ievt, event) in enumerate(events) # First run the reconstruction if power == 1.5 cluster_seq = jet_reconstruction(event, R = distance, algorithm = JetAlgorithm.GenKt, p = power) else cluster_seq = jet_reconstruction(event, R = distance, p = power) end # Now make the requested selection if !isnothing(dijmax) selected_jets = exclusive_jets(cluster_seq; dcut = dijmax) elseif !isnothing(njets) selected_jets = exclusive_jets(cluster_seq; njets = njets) else selected_jets = inclusive_jets(cluster_seq; ptmin = ptmin) end # And extact in out final_jets format finaljets = final_jets(selected_jets) sort_jets!(finaljets) push!(jet_collection, FinalJets(ievt, finaljets)) end @testset "Jet Reconstruction compare to FastJet: Strategy $strategy_name, Algorithm $algname, Selection $selection" begin # Test each event in turn... for (ievt, event) in enumerate(jet_collection) @testset "Event $(ievt)" begin @test size(event.jets) == size(fastjet_jets[ievt]["jets"]) # Test each jet in turn for (ijet, jet) in enumerate(event.jets) if ijet <= size(fastjet_jets[ievt]["jets"])[1] # Approximate test - note that @test macro passes the # tolerance into the isapprox() function # Use atol for position as this is absolute, but rtol for # the momentum # Sometimes phi could be in the range [-π, π], but FastJet always is [0, 2π] normalised_phi = jet.phi < 0.0 ? jet.phi + 2π : jet.phi @test jet.rap≈fastjet_jets[ievt]["jets"][ijet]["rap"] atol=1e-7 @test normalised_phi≈fastjet_jets[ievt]["jets"][ijet]["phi"] atol=1e-7 @test jet.pt≈fastjet_jets[ievt]["jets"][ijet]["pt"] rtol=1e-6 end end end end end end function do_test_compare_types(strategy::RecoStrategy.Strategy; algname = "Unknown", ptmin::Float64 = 5.0, distance::Float64 = 0.4, power::Integer = -1) # Strategy if (strategy == RecoStrategy.N2Plain) jet_reconstruction = plain_jet_reconstruct strategy_name = "N2Plain" elseif (strategy == RecoStrategy.N2Tiled) jet_reconstruction = tiled_jet_reconstruct strategy_name = "N2Tiled" else throw(ErrorException("Strategy not yet implemented")) end # Now run our jet reconstruction... # From PseudoJets events::Vector{Vector{PseudoJet}} = read_final_state_particles(events_file_pp) jet_collection = FinalJets[] for (ievt, event) in enumerate(events) finaljets = final_jets(inclusive_jets(jet_reconstruction(event, R = distance, p = power), ptmin = ptmin)) sort_jets!(finaljets) push!(jet_collection, FinalJets(ievt, finaljets)) end # From LorentzVector events_lv::Vector{Vector{LorentzVector}} = read_final_state_particles(events_file_pp; T = LorentzVector) jet_collection_lv = FinalJets[] for (ievt, event) in enumerate(events_lv) finaljets = final_jets(inclusive_jets(jet_reconstruction(event, R = distance, p = power), ptmin = ptmin)) sort_jets!(finaljets) push!(jet_collection_lv, FinalJets(ievt, finaljets)) end @testset "Jet Reconstruction Compare PseudoJet and LorentzVector, Strategy $strategy_name, Algorithm $algname" begin # Here we test that inputing LorentzVector gave the same results as PseudoJets for (ievt, (event, event_lv)) in enumerate(zip(jet_collection, jet_collection_lv)) @testset "Event $(ievt)" begin @test size(event.jets) == size(event_lv.jets) # Test each jet in turn for (jet, jet_lv) in zip(event.jets, event_lv.jets) @test jet.rap≈jet_lv.rap atol=1e-7 @test jet.phi≈jet_lv.phi atol=1e-7 @test jet.pt≈jet_lv.pt rtol=1e-6 end end end end end logger = ConsoleLogger(stdout, Logging.Warn) global_logger(logger) main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
1302
# Tests of e+e- reconstruction algorithms include("common.jl") durham_njets3 = ComparisonTest(events_file_ee, joinpath(@__DIR__, "data", "jet-collections-fastjet-njets3-Durham-eeH.json.gz"), JetAlgorithm.Durham, RecoStrategy.N2Plain, 1, 4.0, (cs) -> exclusive_jets(cs; njets = 3), "exclusive njets") run_reco_test(durham_njets3) eekt_inclusive = ComparisonTest(events_file_ee, joinpath(@__DIR__, "data", "jet-collections-fastjet-inclusive-EEKt-p-1-R1.0.json.gz"), JetAlgorithm.EEKt, RecoStrategy.N2Plain, -1, 1.0, (cs) -> inclusive_jets(cs; ptmin = 5.0), "inclusive") run_reco_test(eekt_inclusive) for r in [2.0, 4.0] eekt_njets = ComparisonTest(events_file_ee, joinpath(@__DIR__, "data", "jet-collections-fastjet-njets4-EEKt-p1-R$(r).json.gz"), JetAlgorithm.EEKt, RecoStrategy.N2Plain, 1, r, (cs) -> exclusive_jets(cs; njets = 4), "exclusive njets") run_reco_test(eekt_njets) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
1816
# Tests of pp reconstruction algorithms # Contains all common functions and necessary imports include("common.jl") # Test inclusive jets for each algorithm and strategy for alg in [JetAlgorithm.AntiKt, JetAlgorithm.CA, JetAlgorithm.Kt], stg in [RecoStrategy.N2Plain, RecoStrategy.N2Tiled] fastjet_file = joinpath(@__DIR__, "data", "jet-collections-fastjet-inclusive-$(alg).json.gz") test = ComparisonTest(events_file_pp, fastjet_file, alg, stg, JetReconstruction.algorithm2power[alg], 0.4, (cs) -> inclusive_jets(cs; ptmin = 5.0), "inclusive") run_reco_test(test) end # Test exclusive njet selections for CA and Kt algorithms for alg in [JetAlgorithm.CA, JetAlgorithm.Kt] fastjet_file = joinpath(@__DIR__, "data", "jet-collections-fastjet-njets4-$(alg).json.gz") test = ComparisonTest(events_file_pp, fastjet_file, alg, RecoStrategy.Best, JetReconstruction.algorithm2power[alg], 0.4, (cs) -> exclusive_jets(cs; njets = 4), "exclusive njets") run_reco_test(test) end # Test exclusive dij selections for CA and Kt algorithms for (alg, dij_max) in zip([JetAlgorithm.CA, JetAlgorithm.Kt], ["0.99", "20.0"]) fastjet_file = joinpath(@__DIR__, "data", "jet-collections-fastjet-dij$(dij_max)-$(alg).json.gz") test = ComparisonTest(events_file_pp, fastjet_file, alg, RecoStrategy.Best, JetReconstruction.algorithm2power[alg], 0.4, (cs) -> exclusive_jets(cs; dcut = tryparse(Float64, dij_max)), "exclusive dcut") run_reco_test(test) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
1756
#! /usr/bin/env julia using Test const example_dir = joinpath(pkgdir(JetReconstruction), "examples") const test_dir = joinpath(pkgdir(JetReconstruction), "test") # Need to ensure examples is properly instatiated run(`julia --project=$example_dir $test_dir/bootstrap_examples.jl`) # Now run a few tests with our examples @testset "Jet Reconstruction Examples" begin @test success(run(pipeline(`julia --project=$example_dir $example_dir/jetreco.jl -S N2Plain -A AntiKt -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/jetreco.jl -S N2Tiled -p 1 -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/jetreco.jl -p 1.5 -A GenKt -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/instrumented-jetreco.jl -S N2Plain -A AntiKt -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/instrumented-jetreco.jl -S N2Tiled -p 1 -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/instrumented-jetreco.jl -p 1.5 -A GenKt -R 1.0 $events_file`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/jetreco-constituents.jl`, devnull))) @test success(run(pipeline(`julia --project=$example_dir $example_dir/visualise-jets.jl -A AntiKt --event 5 -R 2.0 $events_file $example_dir/jetvis.png`, devnull))) end
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
code
3730
#! /usr/bin/env julia using ArgParse using LorentzVectorHEP using Statistics using UnicodePlots struct Particle{T} momentum::LorentzVector{T} status::Integer pdgid::Integer barcode::Integer vertex::Integer end Particle{T}() where {T} = Particle(LorentzVector{T}(0.0, 0.0, 0.0, 0.0), 0, 0, 0, 0) """ Read a [HepMC3](https://doi.org/10.1016/j.cpc.2020.107310) ascii file. Each event is passed to the provided function f as a vector of Particles. A maximum number of events to read (value -1 to read all availble events) and a number of events to skip at the beginning of the file can be provided. """ function read_events(f, fin; maxevents = -1, skipevents = 0) T = Float64 particles = Particle{T}[] ievent = 0 ipart = 0 toskip = skipevents for (il, l) in enumerate(eachline(fin)) if occursin(r"HepMC::.*-END_EVENT_LISTING", l) break end tok = split(l) if tok[1] == "E" ievent += 1 (maxevents >= 0 && ievent > maxevents) && break if ievent > 1 && toskip == 0 f(particles) end if toskip > 0 toskip -= 1 end resize!(particles, 0) ipart = 0 elseif tok[1] == "P" && toskip == 0 ipart += 1 if ipart > length(particles) push!(particles, Particle{T}()) end barcode = parse(Int, tok[2]) vertex = parse(Int, tok[3]) pdgid = parse(Int, tok[4]) px = parse(T, tok[5]) py = parse(T, tok[6]) pz = parse(T, tok[7]) e = parse(T, tok[8]) status = parse(Int, tok[10]) push!(particles, Particle{T}(LorentzVector(e, px, py, pz), status, pdgid, barcode, vertex)) end end #processing the last event: ievent > 0 && f(particles) end function read_events(fname, maxevents = -1, skipevents = 0) f = open(fname) events = Vector{LorentzVector}[] read_events(f, maxevents = maxevents, skipevents = skipevents) do parts input_particles = LorentzVector[] for p in parts if p.status == 1 push!(input_particles, p.momentum) end end push!(events, input_particles) end events end function parse_command_line(args) s = ArgParseSettings(autofix_names = true) @add_arg_table! s begin "--summary" help = "Print only summary information, filename and average density" action = :store_true "--maxevents", "-n" help = "Maximum number of events to read. -1 to read all events from the file." arg_type = Int default = -1 "--skip", "-s" help = "Number of events to skip at beginning of the file." arg_type = Int default = 0 "files" help = "The HepMC3 event files to read." required = true nargs = '+' end return parse_args(args, s; as_symbols = true) end function main() args = parse_command_line(ARGS) for file in args[:files] events = read_events(file, args[:maxevents], args[:skip]) n_events = length(events) n_particles = Int[] for e in events push!(n_particles, length(e)) end average_n = mean(n_particles) if args[:summary] println("$file,$average_n") else println("File $file") println(" Number of events: $n_events") println(" Average number of particles: ", mean(n_particles)) println(histogram(n_particles)) end end end main()
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
7279
# JetReconstruction.jl [![Build Status](https://github.com/JuliaHEP/JetReconstruction.jl/actions/workflows/CI.yml/badge.svg?branch=main)](https://github.com/JuliaHEP/JetReconstruction.jl/actions/workflows/CI.yml?query=branch%3Amain) [![DOI](https://zenodo.org/badge/507671522.svg)](https://zenodo.org/doi/10.5281/zenodo.12671414) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://juliahep.github.io/JetReconstruction.jl/stable) [![](https://img.shields.io/badge/docs-dev-blue.svg)](https://juliahep.github.io/JetReconstruction.jl/dev) ## This package implements sequential Jet Reconstruction (clustering) ### Algorithms Algorithms used are based on the C++ FastJet package (<https://fastjet.fr>, [hep-ph/0512210](https://arxiv.org/abs/hep-ph/0512210), [arXiv:1111.6097](https://arxiv.org/abs/1111.6097)), reimplemented natively in Julia. The algorithms include anti-$`{k}_\text{T}`$, Cambridge/Aachen, inclusive $`k_\text{T}`$, generalised $`k_\text{T}`$ for $`pp`$ events; and the Durham algorithm and generalised $`k_\text{T}`$ for $`e^+e^-`$. ### Interface The simplest interface is to call: ```julia cs = jet_reconstruct(particles::Vector{T}; algorithm = JetAlgorithm.AntiKt, R = 1.0, [p = -1,] [recombine = +,] [strategy = RecoStrategy.Best]) ``` - `particles` - a vector of input particles for the clustering - Any type that supplies the methods `pt2()`, `phi()`, `rapidity()`, `px()`, `py()`, `pz()`, `energy()` can be used - These methods have to be defined in the namespace of this package, i.e., `JetReconstruction.pt2(::T)` - The `PseudoJet` type from this package, or a 4-vector from `LorentzVectorHEP` are suitable (and have the appropriate definitions) - `algorithm` is the name of the jet algorithm to be used (from the `JetAlgorithm` enum) - `JetAlgorithm.AntiKt` anti-$`{k}_\text{T}`$ clustering (default) - `JetAlgorithm.CA` Cambridge/Aachen clustering - `JetAlgorithm.Kt` inclusive $k_\text{T}$ - `JetAlgorithm.GenKt` generalised $k_\text{T}$ (which also requires specification of `p`) - `JetAlgorithm.Durham` the $e^+e-$ $k_\text{T}$ algorithm, also known as the Durham algorithm - `JetAlgorithm.EEKt` the $e^+e-$ generalised $k_\text{T}$ algorithm - `R` - the cone size parameter; no particles more geometrically distance than `R` will be merged (default 1.0; note this parameter is ignored for the Durham algorithm) - `recombine` - the function used to merge two pseudojets (default is a simple 4-vector addition of $`(E, \mathbf{p})`$) - `strategy` - the algorithm strategy to adopt, as described below (default `RecoStrategy.Best`) The object returned is a `ClusterSequence`, which internally tracks all merge steps. Alternatively, *for pp reconstruction*, one can swap the `algorithm=...` parameter for the value of `p`, the transverse momentum power used in the $d_{ij}$ metric for deciding on closest jets, as $k^{2p}_\text{T}$. Different values of $p$ then correspond to different reconstruction algorithms: - `-1` gives anti-$`{k}_\text{T}`$ clustering (default) - `0` gives Cambridge/Aachen - `1` gives inclusive $k_\text{T}$ Note, for the `GenKt` and `EEKt` algorithms the `p` value *must* also be given to specify the algorithm fully. To obtain the final inclusive jets, use the `inclusive_jets` method: ```julia final_jets = inclusive_jets(cs::ClusterSequence; ptmin=0.0) ``` Only jets passing the cut $p_T > p_{Tmin}$ will be returned. The result is returned as a `Vector{LorentzVectorHEP}`. #### Sorting As sorting vectors is trivial in Julia, no special sorting methods are provided. As an example, to sort exclusive jets of $>5.0$ (usually GeV, depending on your EDM) from highest energy to lowest: ```julia sorted_jets = sort!(inclusive_jets(cs::ClusterSequence; ptmin=5.0), by=JetReconstruction.energy, rev=true) ``` #### Strategy Three strategies are available for the different algorithms: | Strategy Name | Notes | Interface | |---|---|---| | `RecoStrategy.Best` | Dynamically switch strategy based on input particle density | `jet_reconstruct` | | `RecoStrategy.N2Plain` | Global matching of particles at each interation (works well for low $N$) | `plain_jet_reconstruct` | | `RecoStrategy.N2Tiled` | Use tiles of radius $R$ to limit search space (works well for higher $N$) | `tiled_jet_reconstruct` | Generally one can use the `jet_reconstruct` interface, shown above, as the *Best* strategy safely as the overhead is extremely low. That interface supports a `strategy` option to switch to a different option. Another option, if one wishes to use a specific strategy, is to call that strategy's interface directly, e.g., ```julia # For N2Plain strategy called directly plain_jet_reconstruct(particles::Vector{T}; algorithm = JetAlgorithm.AntiKt, R = 1.0, recombine = +) ``` Note that there is no `strategy` option in these interfaces. ### Examples In the examples directory there are a number of example scripts. See the `jetreco.jl` script for an example of how to call jet reconstruction. ```sh julia --project=examples examples/jetreco.jl --algorithm=AntiKt test/data/events.pp13TeV.hepmc3.gz ... julia --project=examples examples/jetreco.jl --algorithm=Durham test/data/events.eeH.hepmc3.gz ... julia --project=examples examples/jetreco.jl --maxevents=10 --strategy=N2Plain --algorithm=Kt --exclusive-njets=3 test/data/events.pp13TeV.hepmc3.gz ... ``` There are options to explicitly set the algorithm (use `--help` to see these). The example also shows how to use `JetReconstruction.HepMC3` to read HepMC3 ASCII files (via the `read_final_state_particles()` wrapper). Further examples, which show visualisation, timing measurements, profiling, etc. are given - see the `README.md` file in the examples directory. Note that due to additional dependencies the `Project.toml` file for the examples is different from the package itself. ### Plotting ![illustration](docs/src/assets/jetvis.png) To visualise the clustered jets as a 3d bar plot (see illustration above) we now use `Makie.jl`. See the `jetsplot` function in `ext/JetVisualisation.jl` and its documentation for more. There are two worked examples in the `examples` directory. The plotting code is a package extension and will load if the one of the `Makie` modules is loaded in the environment. ### Serialisation The package also provides methods such as `loadjets`, `loadjets!`, and `savejets` that one can use to save and load objects on/from disk easily in a very flexible format. See documentation for more. ## Reference Although it has been developed further since the CHEP2023 conference, the CHEP conference proceedings, [arXiv:2309.17309](https://arxiv.org/abs/2309.17309), should be cited if you use this package: ```bibtex @misc{stewart2023polyglot, title={Polyglot Jet Finding}, author={Graeme Andrew Stewart and Philippe Gras and Benedikt Hegner and Atell Krasnopolski}, year={2023}, eprint={2309.17309}, archivePrefix={arXiv}, primaryClass={hep-ex} } ``` ## Authors and Copyright Code in this package is authored by: - Atell Krasnopolski <[email protected]> - Graeme A Stewart <[email protected]> - Philippe Gras <[email protected]> and is Copyright 2022-2024 The Authors, CERN. The code is under the MIT License.
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
2062
# Jet Reconstruction Examples The Jet Reconstruction package has a number of example files that show how to usage. *Note:* because of extra dependencies in these scripts, one must use the `Project.toml` file in the `examples` directory. ## `jetreco.jl` This is a basic jet reconstruction example that shows how to call the package to perform a jet reconstruction, with different algorithms and (optionally) strategy, producing exclusive and inclusive jet selections. ```sh julia --project=examples examples/jetreco.jl --algorithm=AntiKt test/data/events.pp13TeV.hepmc3.gz ... julia --project=examples examples/jetreco.jl --algorithm=Durham test/data/events.eeH.hepmc3.gz ... julia --project=examples examples/jetreco.jl --maxevents=10 --strategy=N2Plain --algorithm=Kt --exclusive-njets=3 test/data/events.pp13TeV.hepmc3.gz ... ``` There are options to explicitly set the algorithm (use `--help` to see these). ## `instrumented-jetreco.jl` This is a more sophisticated example that allows performance measurements to be made of the reconstruction, as well as profiling (flamegraphs and memory profiling). Use the `--help` option to see usage. e.g., to extract timing performance for the AntiKt algorithm using the tiled strategy: ```sh julia --project instrumented-jetreco.jl -S N2Tiled -A AntiKt --nsamples 100 ../test/data/events.hepmc3 ``` ## `visualise-jets.jl` This script will produce a PNG/PDF showing the results of a jet reconstruction. This is a 3D plot where all the initial energy deposits are visualised, with colours that indicate in which final cluster the deposit ended up in. ## `visualise-jets.ipynb` Similar to `visualise-jets.jl` this notebook will produce a visualisation of jet reconstruction in the browser. This is a 3D plot where all the initial energy deposits are visualised, with colours that indicate in which final cluster the deposit ended up in. ## `animate-reconstruction.jl` Performs jet reconstruction and then produces and animation of the process, showing how the jets merge from their different constituents.
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
6590
```@raw html --- layout: home hero: name: "JetReconstruction.jl" tagline: "Jet reconstruction (reclustering) with Julia" image: src: /logo.png alt: DocumenterVitepress actions: - theme: brand text: Examples link: /examples - theme: alt text: Public APIs link: /lib/public --- ``` # Jet Reconstruction This package implements sequential Jet Reconstruction (clustering) algorithms, which are used in high-energy physics as part of event reconstruction for $pp$ and $e^+e^-$ colliders. ## Algorithms Algorithms used are based on the C++ FastJet package (<https://fastjet.fr>, [hep-ph/0512210](https://arxiv.org/abs/hep-ph/0512210), [arXiv:1111.6097](https://arxiv.org/abs/1111.6097)), reimplemented natively in Julia. The algorithms include anti-``{k}_\text{T}``, Cambridge/Aachen, inclusive ``k_\text{T}``, generalised ``k_\text{T}`` for ``pp`` events; and the Durham algorithm and generalised ``k_\text{T}`` for ``e^+e^-``. ## Reconstruction Interface The main interface for reconstruction is [`jet_reconstruct`](@ref), called as, e.g., ```julia jet_reconstruct(particles; algorithm = JetAlgorithm.AntiKt, R = 1.0) ``` or with some of the optional arguments, ```julia jet_reconstruct(particles; algorithm = JetAlgorithm.GenKt, R = 0.4, p = 0.5, recombine = +, strategy = RecoStrategy.Best) ``` Where `particles` is a collection of 4-vector objects to reconstruct and the algorithm is either given explicitly or implied by the power value. For the case of generalised ``k_T`` (for ``pp`` and ``e^+e^-``) both the algorithm (`JetAlgorithm.GenKt`) and `p` are needed. For the case of the Durham algorithm the `R` value is ignored. The object returned is a [`ClusterSequence`](@ref), which internally tracks all merge steps. ### Algorithm Types Each known algorithm is referenced using a `JetAlgorithm` scoped enum value. | Algorithm | Type name | Notes | |-----------|-----------|-------| | anti-``{k}_\text{T}`` | `JetAlgorithm.AntiKt` | Implies `p=-1` | | Cambridge/Aachen | `JetAlgorithm.CA` | Implies `p=0` | | inclusive ``k_\text{T}`` | `JetAlgorithm.Kt` | Implies `p=1` | | generalised ``k_\text{T}`` | `JetAlgorithm.GenKt` | For $pp$, value of `p` must also be specified | | ``e^+e-`` ``k_\text{T}`` / Durham | `JetAlgorithm.Durham` | `R` value ignored and can be omitted | | generalised ``e^+e-`` ``k_\text{T}`` | `JetAlgorithm.EEKt` | For ``e^+e^-``, value of `p` must also be specified | ### ``pp`` Algorithms For the three ``pp`` algorithms with fixed `p` values, the `p` value can be given instead of the algorithm name. However, this should be considered *deprecated* and will be removed in a future release. ## Strategy Three strategies are available for the different algorithms, which can be specified by passing the named argument `strategy=...`. | Strategy Name | Notes | Interface | |---|---|---| | `RecoStrategy.Best` | Dynamically switch strategy based on input particle density | `jet_reconstruct` | | `RecoStrategy.N2Plain` | Global matching of particles at each interation (works well for low $N$) | `plain_jet_reconstruct` | | `RecoStrategy.N2Tiled` | Use tiles of radius $R$ to limit search space (works well for higher $N$) | `tiled_jet_reconstruct` | Generally one can use the `jet_reconstruct` interface, shown above, as the *Best* strategy safely as the overhead is extremely low. That interface supports a `strategy` option to switch to a different option. Another option, if one wishes to use a specific strategy, is to call that strategy's interface directly, e.g., ```julia # For N2Plain strategy called directly plain_jet_reconstruct(particles::Vector{T}; algorithm = JetAlgorithm.AntiKt, R = 1.0, recombine = +) ``` (There is no `strategy` option in these interfaces.) ## Inclusive and Exclusive Selections To obtain final jets both inclusive (``p_T`` cut) and exclusive (``n_{jets}`` or ``d_{ij}`` cut) selections are supported: - [inclusive_jets(clusterseq::ClusterSequence, ptmin = 0.0)](@ref) - [exclusive_jets(clusterseq::ClusterSequence; dcut = nothing, njets = nothing)](@ref) ### Sorting Sorting vectors is trivial in Julia, no special sorting methods are provided. As an example, to sort exclusive jets of ``>5.0`` (usually GeV, depending on your EDM) from highest energy to lowest: ```julia sorted_jets = sort!(inclusive_jets(cs::ClusterSequence; ptmin=5.0), by=JetReconstruction.energy, rev=true) ``` ## Plotting and Animation ![illustration](assets/jetvis.png) To visualise the clustered jets as a 3d bar plot (see illustration above) we now use `Makie.jl`. See the `jetsplot` function in `ext/JetVisualisation.jl` and its documentation for more. There are two worked examples in the `examples` directory. The plotting code is a package extension and will load if the one of the `Makie` modules is loaded in the environment. The [`animatereco`](@ref) function will animate the reconstruction sequence, given a `ClusterSequence` object. See the function documentation for the many options that can be customised. ## Serialisation The package also provides methods such as `loadjets`, `loadjets!`, and `savejets` that one can use to save and load objects on/from disk easily in a very flexible format. See documentation for more. ## Reference Although it has been developed further since the CHEP2023 conference, the CHEP conference proceedings, [10.1051/epjconf/202429505017](https://doi.org/10.1051/epjconf/202429505017), should be cited if you use this package: ```bibtex @article{refId0, author = {{Stewart, Graeme Andrew} and {Gras, Philippe} and {Hegner, Benedikt} and {Krasnopolski, Atell}}, doi = {10.1051/epjconf/202429505017}, journal = {EPJ Web of Conf.}, pages = {05017}, title = {Polyglot Jet Finding}, url = {https://doi.org/10.1051/epjconf/202429505017}, volume = 295, year = 2024, eprint={2309.17309}, archivePrefix={arXiv}, primaryClass={hep-ex} } ``` The original paper on [arXiv](https://arxiv.org/abs/2309.17309) is: ```bibtex @misc{stewart2023polyglot, title={Polyglot Jet Finding}, author={Graeme Andrew Stewart and Philippe Gras and Benedikt Hegner and Atell Krasnopolski}, year={2023}, eprint={2309.17309}, archivePrefix={arXiv}, primaryClass={hep-ex} } ``` ## Authors and Copyright Code in this package is authored by: - Atell Krasnopolski <[email protected]> - Graeme A Stewart <[email protected]> - Philippe Gras <[email protected]> and is Copyright 2022-2024 The Authors, CERN. The code is under the MIT License.
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
387
# Jet Reconstruction Internal Documentation Documentation for `JetReconstruction.jl`'s internal methods and types. N.B. no guarantee is made of stability of these interfaces or types. ```@meta CollapsedDocStrings = true ``` ## Index ```@index Pages = ["internal.md"] ``` ## Public Interface ```@autodocs Modules = [JetReconstruction] Public = false Order = [:function, :type] ```
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
272
# Jet Reconstruction Public Documentation Documentation for `JetReconstruction.jl`'s public interfaces. ## Index ```@index Pages = ["public.md"] ``` ## Public Methods and Types ```@autodocs Modules = [JetReconstruction] Private = false Order = [:function, :type] ```
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
257
# Jet Visualisation Documentation Documentation for visualisation interfaces extension module. ## Index ```@index Pages = ["visualisation.md"] ``` ## Jet Visualisation Public Interfaces ```@autodocs Modules = [JetVisualisation] Order = [:function] ```
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
1348
# JetReconstruction.jl Examples This directory has a number of example files that show how to used the `JetReconstruction.jl` package. Because of extra dependencies in these scripts, one must use the `Project.toml` file in this directory. ## `jetreco.jl` This is a basic jet reconstruction example that shows how to call the package to perform a jet reconstruction, with different algorithms and (optionally) strategy, producing exclusive and inclusive jet selections. ## `instrumented-jetreco.jl` This is a more sophisticated example that allows performance measurements to be made of the reconstruction, as well as profiling (flamegraphs and memory profiling). ## `visualise-jets.jl` This script will produce a PNG/PDF showing the results of a jet reconstruction. This is a 3D plot where all the initial energy deposits are visualised, with colours that indicate in which final cluster the deposit ended up in. ## `visualise-jets.ipynb` This notebook will produce a visualisation of jet reconstruction in the browser. This is a 3D plot where all the initial energy deposits are visualised, with colours that indicate in which final cluster the deposit ended up in. ## `animate-reconstruction.jl` Performs jet reconstruction and then produces and animation of the process, showing how the jets merge from their different constituents.
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.4.1
d625cda16353a412e6e6e9fca65b8d36077b083f
docs
594
# Jet Reconstruction Test Suite ## Files - `events.hepmc3.gz` - 100 Pythia 13TeV events in HepMC3 format (compressed) - Unzip to `evemts.hepmc3` for actual use - `jet_collections_fastjet_akt.json` - JSON output from running anti-kt jet reconstruction using FastJet 3.4.1, with R=0.4 and p_t_min=5.0 - `jet_collections_fastjet_ca.json` - JSON output from running Cambridge/Achen jet reconstruction using FastJet 3.4.1, with R=0.4 and p_t_min=5.0 - `jet_collections_fastjet_ikt.json` - JSON output from running inclusive-kt jet reconstruction using FastJet 3.4.1, with R=0.4 and p_t_min=5.0
JetReconstruction
https://github.com/JuliaHEP/JetReconstruction.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1873
using BinaryProvider # requires BinaryProvider 0.3.0 or later # Parse some basic command-line arguments const verbose = "--verbose" in ARGS const prefix = Prefix(get([a for a in ARGS if a != "--verbose"], 1, joinpath(@__DIR__, "usr"))) products = [ FileProduct(prefix, "lib/ockl.amdgcn.bc", :rocmdevlibdir), ] # Download binaries from hosted location bin_prefix = "https://github.com/jpsamaroo/ROCmDeviceLibsDownloader/releases/download/v2.2.0" # Listing of files generated by BinaryBuilder: download_info = Dict( Linux(:x86_64, libc=:glibc) => ("$bin_prefix/ROCmDeviceLibsDownloader.v2.2.0.x86_64-linux-gnu.tar.gz", "4bd7c9aaa56f7e72d8707939b28106162df75786ab7a30c35622220aa3a4b7db"), Linux(:x86_64, libc=:musl) => ("$bin_prefix/ROCmDeviceLibsDownloader.v2.2.0.x86_64-linux-musl.tar.gz", "dafd049ddeb76491f85bbe7897b4e004326bb8af76e639e925748cad05391a20"), ) # Install unsatisfied or updated dependencies: unsatisfied = any(!satisfied(p; verbose=verbose) for p in products) dl_info = choose_download(download_info, platform_key_abi()) if dl_info === nothing && unsatisfied # If we don't have a compatible .tar.gz to download, complain. # Alternatively, you could attempt to install from a separate provider, # build from source or something even more ambitious here. error("Your platform (\"$(Sys.MACHINE)\", parsed as \"$(triplet(platform_key_abi()))\") is not supported by this package!") end # If we have a download, and we are unsatisfied (or the version we're # trying to install is not itself installed) then load it up! if unsatisfied || !isinstalled(dl_info...; prefix=prefix) # Download and install binaries install(dl_info...; prefix=prefix, force=true, verbose=verbose) end # Write out a deps.jl file that will contain mappings for our products write_deps_file(joinpath(@__DIR__, "deps.jl"), products, verbose=verbose)
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
249
using Documenter, AMDGPUnative makedocs( sitename="AMDGPUnative.jl", pages = [ "Home" => "index.md", "Quick Start" => "quickstart.md", "Global Variables" => "globals.md", "API Reference" => "api.md" ] )
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1418
module AMDGPUnative using LLVM, LLVM.Interop using GPUCompiler using HSARuntime, HSARuntime.HSA using Adapt using Libdl using Requires @enum DeviceRuntime HSA_rt OCL_rt const RUNTIME = Ref{DeviceRuntime}(HSA_rt) #= if get(ENV, "AMDGPUNATIVE_OPENCL", "") != "" RUNTIME[] = OCL_rt end =# include("runtime.jl") const configured = HSARuntime.configured # ROCm-Device-Libs bitcode path include(joinpath(@__DIR__, "..", "deps", "deps.jl")) const device_libs_path = joinpath(@__DIR__, "..", "deps", "usr", "lib") struct Adaptor end # Device sources must load _before_ the compiler infrastructure # because of generated functions. include(joinpath("device", "tools.jl")) include(joinpath("device", "pointer.jl")) include(joinpath("device", "array.jl")) include(joinpath("device", "gcn.jl")) include(joinpath("device", "runtime.jl")) include(joinpath("device", "llvm.jl")) include(joinpath("device", "globals.jl")) include("compiler.jl") include("execution_utils.jl") include("execution.jl") include("reflection.jl") function __init__() try # Try to load deps if possible check_deps() catch err @warn """ AMDGPUnative dependencies have not been built, some functionality may be missing. Please run Pkg.build("AMDGPUnative") and reload AMDGPUnative. """ end @require OpenCL="08131aa3-fb12-5dee-8b74-c09406e224a2" include("opencl.jl") end end # module
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1041
struct ROCCompilerParams <: AbstractCompilerParams end ROCCompilerJob = CompilerJob{GCNCompilerTarget,ROCCompilerParams} GPUCompiler.runtime_module(::ROCCompilerJob) = AMDGPUnative # filter out functions from device libs GPUCompiler.isintrinsic(job::ROCCompilerJob, fn::String) = invoke(GPUCompiler.isintrinsic, Tuple{CompilerJob{GCNCompilerTarget}, typeof(fn)}, job, fn) || startswith(fn, "rocm") function GPUCompiler.process_module!(job::ROCCompilerJob, mod::LLVM.Module) invoke(GPUCompiler.process_module!, Tuple{CompilerJob{GCNCompilerTarget}, typeof(mod)}, job, mod) #emit_exception_flag!(mod) end function GPUCompiler.link_libraries!(job::ROCCompilerJob, mod::LLVM.Module, undefined_fns::Vector{String}) invoke(GPUCompiler.link_libraries!, Tuple{CompilerJob{GCNCompilerTarget}, typeof(mod), typeof(undefined_fns)}, job, mod, undefined_fns) link_device_libs!(mod, job.target.dev_isa, undefined_fns) end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
14942
# Native execution support export @roc, rocconvert, rocfunction, nextwarp, prevwarp ## helper functions # split keyword arguments to `@roc` into ones affecting the macro itself, the compiler and # the code it generates, or the execution function split_kwargs(kwargs) macro_kws = [:dynamic] compiler_kws = [:name, :device, :queue] call_kws = [:gridsize, :groupsize, :config, :queue] alias_kws = Dict(:blocks=>:gridsize, :threads=>:groupsize, :agent=>:device, :stream=>:queue) macro_kwargs = [] compiler_kwargs = [] call_kwargs = [] for kwarg in kwargs if Meta.isexpr(kwarg, :(=)) key,val = kwarg.args oldkey = key if key in keys(alias_kws) key = alias_kws[key] kwarg = :($key=$val) end if isa(key, Symbol) if key in macro_kws push!(macro_kwargs, kwarg) elseif key in compiler_kws push!(compiler_kwargs, kwarg) elseif key in call_kws push!(call_kwargs, kwarg) else throw(ArgumentError("unknown keyword argument '$oldkey'")) end else throw(ArgumentError("non-symbolic keyword '$oldkey'")) end else throw(ArgumentError("non-keyword argument like option '$kwarg'")) end end return macro_kwargs, compiler_kwargs, call_kwargs end # assign arguments to variables, handle splatting function assign_args!(code, args) # handle splatting splats = map(arg -> Meta.isexpr(arg, :(...)), args) args = map(args, splats) do arg, splat splat ? arg.args[1] : arg end # assign arguments to variables vars = Tuple(gensym() for arg in args) map(vars, args) do var,arg push!(code.args, :($var = $arg)) end # convert the arguments, compile the function and call the kernel # while keeping the original arguments alive var_exprs = map(vars, args, splats) do var, arg, splat splat ? Expr(:(...), var) : var end return vars, var_exprs end # extract device/queue from arguments, filling in defaults if needed function extract_device(;device=nothing, agent=nothing, kwargs...) if device !== nothing return device elseif agent !== nothing return agent else return default_device() end end function extract_queue(device; queue=nothing, kwargs...) if queue !== nothing return queue else return default_queue(device) end end ## high-level @roc interface """ @roc [kwargs...] func(args...) High-level interface for executing code on a GPU. The `@roc` macro should prefix a call, with `func` a callable function or object that should return nothing. It will be compiled to a GCN function upon first use, and to a certain extent arguments will be converted and managed automatically using `rocconvert`. Finally, a call to `HSARuntime.roccall` is performed, scheduling a kernel launch on the specified (or default) HSA queue. Several keyword arguments are supported that influence the behavior of `@roc`. - `dynamic`: use dynamic parallelism to launch device-side kernels - arguments that influence kernel compilation: see [`rocfunction`](@ref) and [`dynamic_rocfunction`](@ref) - arguments that influence kernel launch: see [`AMDGPUnative.HostKernel`](@ref) and [`AMDGPUnative.DeviceKernel`](@ref) The underlying operations (argument conversion, kernel compilation, kernel call) can be performed explicitly when more control is needed, e.g. to reflect on the resource usage of a kernel to determine the launch configuration. A host-side kernel launch is done as follows: args = ... GC.@preserve args begin kernel_args = rocconvert.(args) kernel_tt = Tuple{Core.Typeof.(kernel_args)...} kernel = rocfunction(f, kernel_tt; compilation_kwargs) kernel(kernel_args...; launch_kwargs) end A device-side launch, aka. dynamic parallelism, is similar but more restricted: args = ... # GC.@preserve is not supported # we're on the device already, so no need to rocconvert kernel_tt = Tuple{Core.Typeof(args[1]), ...} # this needs to be fully inferred! kernel = dynamic_rocfunction(f, kernel_tt) # no compiler kwargs supported kernel(args...; launch_kwargs) """ macro roc(ex...) # destructure the `@roc` expression call = ex[end] kwargs = ex[1:end-1] # destructure the kernel call Meta.isexpr(call, :call) || throw(ArgumentError("second argument to @roc should be a function call")) f = call.args[1] args = call.args[2:end] code = quote end macro_kwargs, compiler_kwargs, call_kwargs = split_kwargs(kwargs) vars, var_exprs = assign_args!(code, args) # handle keyword arguments that influence the macro's behavior dynamic = false for kwarg in macro_kwargs key,val = kwarg.args if key == :dynamic isa(val, Bool) || throw(ArgumentError("`dynamic` keyword argument to @roc should be a constant value")) dynamic = val::Bool else throw(ArgumentError("Unsupported keyword argument '$key'")) end end # FIXME: macro hygiene wrt. escaping kwarg values (this broke with 1.5) # we esc() the whole thing now, necessitating gensyms... @gensym kernel_args kernel_tt device kernel queue signal if dynamic # FIXME: we could probably somehow support kwargs with constant values by either # saving them in a global Dict here, or trying to pick them up from the Julia # IR when processing the dynamic parallelism marker isempty(compiler_kwargs) || error("@roc dynamic parallelism does not support compiler keyword arguments") # dynamic, device-side kernel launch push!(code.args, quote # we're in kernel land already, so no need to rocconvert arguments local $kernel_tt = Tuple{$((:(Core.Typeof($var)) for var in var_exprs)...)} local $kernel = $dynamic_rocfunction($f, $kernel_tt) $kernel($(var_exprs...); $(call_kwargs...)) end) else # regular, host-side kernel launch # # convert the arguments, call the compiler and launch the kernel # while keeping the original arguments alive push!(code.args, quote GC.@preserve $(vars...) begin local $kernel_args = map(rocconvert, ($(var_exprs...),)) local $kernel_tt = Tuple{Core.Typeof.($kernel_args)...} #local $device = $extract_device(; $(call_kwargs...)) local $kernel = $rocfunction($f, $kernel_tt; $(compiler_kwargs...)) #local $queue = $extract_queue($device; $(call_kwargs...)) local $signal = $create_event() $kernel($kernel_args...; signal=$signal, $(call_kwargs...)) $signal end end) end return esc(code) end ## host to device value conversion # Base.RefValue isn't GPU compatible, so provide a compatible alternative struct ROCRefValue{T} <: Ref{T} x::T end Base.getindex(r::ROCRefValue) = r.x Base.setindex!(r::ROCRefValue{T}, value::T) where T = (r.x = value;) Adapt.adapt_structure(to::Adaptor, r::Base.RefValue) = ROCRefValue(adapt(to, r[])) ## interop with HSAArray function Base.convert(::Type{ROCDeviceArray{T,N,AS.Global}}, a::HSAArray{T,N}) where {T,N} ROCDeviceArray{T,N,AS.Global}(a.size, DevicePtr{T,AS.Global}(a.handle)) end Adapt.adapt_storage(::Adaptor, xs::HSAArray{T,N}) where {T,N} = convert(ROCDeviceArray{T,N,AS.Global}, xs) """ rocconvert(x) This function is called for every argument to be passed to a kernel, allowing it to be converted to a GPU-friendly format. By default, the function does nothing and returns the input object `x` as-is. Do not add methods to this function, but instead extend the underlying Adapt.jl package and register methods for the the `AMDGPUnative.Adaptor` type. """ rocconvert(arg) = adapt(Adaptor(), arg) ## abstract kernel functionality abstract type AbstractKernel{F,TT} end # FIXME: there doesn't seem to be a way to access the documentation for the call-syntax, # so attach it to the type -- https://github.com/JuliaDocs/Documenter.jl/issues/558 """ (::HostKernel)(args...; kwargs...) (::DeviceKernel)(args...; kwargs...) Low-level interface to call a compiled kernel, passing GPU-compatible arguments in `args`. For a higher-level interface, use [`AMDGPUnative.@roc`](@ref). The following keyword arguments are supported: - `groupsize` or `threads` (defaults to 1) - `gridsize` or `blocks` (defaults to 1) - `config`: callback function to dynamically compute the launch configuration. should accept a `HostKernel` and return a name tuple with any of the above as fields. - `queue` (defaults to the default queue) """ AbstractKernel @generated function call(kernel::AbstractKernel{F,TT}, args...; call_kwargs...) where {F,TT} sig = Base.signature_type(F, TT) args = (:F, (:( args[$i] ) for i in 1:length(args))...) # filter out ghost arguments that shouldn't be passed to_pass = map(!isghosttype, sig.parameters) call_t = Type[x[1] for x in zip(sig.parameters, to_pass) if x[2]] call_args = Union{Expr,Symbol}[x[1] for x in zip(args, to_pass) if x[2]] # replace non-isbits arguments (they should be unused, or compilation would have failed) # alternatively, make HSARuntime allow `launch` with non-isbits arguments. for (i,dt) in enumerate(call_t) if !isbitstype(dt) call_t[i] = Ptr{Any} call_args[i] = :C_NULL end end # finalize types call_tt = Base.to_tuple_type(call_t) quote Base.@_inline_meta roccall(kernel, $call_tt, $(call_args...); call_kwargs...) end end ## host-side kernels struct HostKernel{F,TT} <: AbstractKernel{F,TT} mod::ROCModule fun::ROCFunction end @doc (@doc AbstractKernel) HostKernel @inline function roccall(kernel::HostKernel, tt, args...; config=nothing, kwargs...) queue = get(kwargs, :queue, default_queue(default_device())) signal = get(kwargs, :signal, create_event()) if config !== nothing roccall(kernel.fun, tt, args...; kwargs..., config(kernel)..., queue=queue, signal=signal) else roccall(kernel.fun, tt, args...; kwargs..., queue=queue, signal=signal) end end ## host-side API """ rocfunction(f, tt=Tuple{}; kwargs...) Low-level interface to compile a function invocation for the currently-active GPU, returning a callable kernel object. For a higher-level interface, use [`@roc`](@ref). The following keyword arguments are supported: - `name`: override the name that the kernel will have in the generated code The output of this function is automatically cached, i.e. you can simply call `rocfunction` in a hot path without degrading performance. New code will be generated automatically, when when function changes, or when different types or keyword arguments are provided. """ function rocfunction(f::Core.Function, tt::Type=Tuple{}; name=nothing, kwargs...) source = FunctionSpec(f, tt, true, name) GPUCompiler.cached_compilation(_rocfunction, source; kwargs...)::HostKernel{f,tt} end # actual compilation function _rocfunction(source::FunctionSpec; device=default_device(), queue=default_queue(device), kwargs...) # compile to GCN target = GCNCompilerTarget(; dev_isa=default_isa(device), kwargs...) params = ROCCompilerParams() job = CompilerJob(target, source, params) obj, kernel_fn, undefined_fns, undefined_gbls = GPUCompiler.compile(:obj, job; strict=true) # settings to JIT based on Julia's debug setting jit_options = Dict{Any,Any}() #= TODO jit_options = Dict{HSARuntime.ROCjit_option,Any}() if Base.JLOptions().debug_level == 1 jit_options[HSARuntime.JIT_GENERATE_LINE_INFO] = true elseif Base.JLOptions().debug_level >= 2 jit_options[HSARuntime.JIT_GENERATE_DEBUG_INFO] = true end =# # calculate sizes for globals globals = map(gbl->Symbol(gbl.name)=>llvmsize(eltype(gbl.type)), filter(gbl->gbl.external, undefined_gbls)) # create executable and kernel obj = codeunits(obj) exe = create_executable(device, kernel_fn, obj; globals=globals) mod = ROCModule(exe, jit_options) fun = ROCFunction(mod, kernel_fn) kernel = HostKernel{source.f,source.tt}(mod, fun) #create_exceptions!(mod) return kernel end # https://github.com/JuliaLang/julia/issues/14919 (kernel::HostKernel)(args...; kwargs...) = call(kernel, args...; kwargs...) ## device-side kernels struct DeviceKernel{F,TT} <: AbstractKernel{F,TT} fun::Ptr{Cvoid} end @doc (@doc AbstractKernel) DeviceKernel @inline roccall(kernel::DeviceKernel, tt, args...; kwargs...) = dynamic_roccall(kernel.fun, tt, args...; kwargs...) # FIXME: duplication with HSARuntime.roccall @generated function dynamic_roccall(f::Ptr{Cvoid}, tt::Type, args...; blocks=UInt32(1), threads=UInt32(1), shmem=UInt32(0), stream=CuDefaultStream()) types = tt.parameters[1].parameters # the type of `tt` is Type{Tuple{<:DataType...}} ex = quote Base.@_inline_meta end # convert the argument values to match the kernel's signature (specified by the user) # (this mimics `lower-ccall` in julia-syntax.scm) converted_args = Vector{Symbol}(undef, length(args)) arg_ptrs = Vector{Symbol}(undef, length(args)) for i in 1:length(args) converted_args[i] = gensym() arg_ptrs[i] = gensym() push!(ex.args, :($(converted_args[i]) = Base.cconvert($(types[i]), args[$i]))) push!(ex.args, :($(arg_ptrs[i]) = Base.unsafe_convert($(types[i]), $(converted_args[i])))) end append!(ex.args, (quote #GC.@preserve $(converted_args...) begin launch(f, blocks, threads, shmem, stream, $(arg_ptrs...)) #end end).args) return ex end ## device-side API """ dynamic_rocfunction(f, tt=Tuple{}) Low-level interface to compile a function invocation for the currently-active GPU, returning a callable kernel object. Device-side equivalent of [`AMDGPUnative.rocfunction`](@ref). No keyword arguments are supported. """ @inline function dynamic_rocfunction(f::Core.Function, tt::Type=Tuple{}) fptr = GPUCompiler.deferred_codegen(Val(f), Val(tt)) DeviceKernel{f,tt}(fptr) end # https://github.com/JuliaLang/julia/issues/14919 (kernel::DeviceKernel)(args...; kwargs...) = call(kernel, args...; kwargs...)
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
6588
# Execution control # modeled after: CUDAdrv/src/execution.jl export ROCDim, ROCModule, ROCFunction, roccall mutable struct ROCModule{E} exe::RuntimeExecutable{E} options::Dict{Any,Any} end mutable struct ROCFunction mod::ROCModule entry::String end """ ROCDim3(x) ROCDim3((x,)) ROCDim3((x, y)) ROCDim3((x, y, x)) A type used to specify dimensions, consisting of 3 integers for the `x`, `y`, and `z` dimension, respectively. Unspecified dimensions default to `1`. Often accepted as argument through the `ROCDim` type alias, eg. in the case of [`roccall`](@ref) or [`launch`](@ref), allowing to pass dimensions as a plain integer or a tuple without having to construct an explicit `ROCDim3` object. """ struct ROCDim3 x::Cuint y::Cuint z::Cuint end ROCDim3(dims::Integer) = ROCDim3(dims, Cuint(1), Cuint(1)) ROCDim3(dims::NTuple{1,<:Integer}) = ROCDim3(dims[1], Cuint(1), Cuint(1)) ROCDim3(dims::NTuple{2,<:Integer}) = ROCDim3(dims[1], dims[2], Cuint(1)) ROCDim3(dims::NTuple{3,<:Integer}) = ROCDim3(dims[1], dims[2], dims[3]) # Type alias for conveniently specifying the dimensions # (e.g. `(len, 2)` instead of `ROCDim3((len, 2))`) const ROCDim = Union{Integer, Tuple{Integer}, Tuple{Integer, Integer}, Tuple{Integer, Integer, Integer}} function Base.getindex(dims::ROCDim3, idx::Int) return idx == 1 ? dims.x : idx == 2 ? dims.y : idx == 3 ? dims.z : error("Invalid dimension: $idx") end """ roccall(f::ROCFunction, types, values...; queue::RuntimeQueue, signal::RuntimeEvent, groupsize::ROCDim, gridsize::ROCDim) `ccall`-like interface for launching a ROC function `f` on a GPU. For example: vadd = ROCFunction(md, "vadd") a = rand(Float32, 10) b = rand(Float32, 10) ad = Mem.upload(a) bd = Mem.upload(b) c = zeros(Float32, 10) cd = Mem.alloc(c) roccall(vadd, (Ptr{Cfloat},Ptr{Cfloat},Ptr{Cfloat}), ad, bd, cd; gridsize=10) Mem.download!(c, cd) The `groupsize` and `gridsize` arguments control the launch configuration, and should both consist of either an integer, or a tuple of 1 to 3 integers (omitted dimensions default to 1). The `types` argument can contain both a tuple of types, and a tuple type, the latter being slightly faster. """ roccall @inline function roccall(f::ROCFunction, types::NTuple{N,DataType}, values::Vararg{Any,N}; queue::RuntimeQueue, signal::RuntimeEvent, kwargs...) where N # this cannot be inferred properly (because types only contains `DataType`s), # which results in the call `@generated _roccall` getting expanded upon first use _roccall(queue, signal, f, Tuple{types...}, values; kwargs...) end @inline function roccall(f::ROCFunction, tt::Type, values::Vararg{Any,N}; queue::RuntimeQueue, signal::RuntimeEvent, kwargs...) where N # in this case, the type of `tt` is `Tuple{<:DataType,...}`, # which means the generated function can be expanded earlier _roccall(queue, signal, f, tt, values; kwargs...) end # we need a generated function to get a tuple of converted arguments (using unsafe_convert), # without having to inspect the types at runtime @generated function _roccall(queue::RuntimeQueue, signal::RuntimeEvent, f::ROCFunction, tt::Type, args::NTuple{N,Any}; groupsize::ROCDim=1, gridsize::ROCDim=groupsize) where N # the type of `tt` is Type{Tuple{<:DataType...}} types = tt.parameters[1].parameters ex = Expr(:block) push!(ex.args, :(Base.@_inline_meta)) # convert the argument values to match the kernel's signature (specified by the user) # (this mimics `lower-ccall` in julia-syntax.scm) converted_args = Vector{Symbol}(undef, N) arg_ptrs = Vector{Symbol}(undef, N) for i in 1:N converted_args[i] = gensym() arg_ptrs[i] = gensym() push!(ex.args, :($(converted_args[i]) = Base.cconvert($(types[i]), args[$i]))) push!(ex.args, :($(arg_ptrs[i]) = Base.unsafe_convert($(types[i]), $(converted_args[i])))) end append!(ex.args, (quote GC.@preserve $(converted_args...) begin launch(queue, signal, f, groupsize, gridsize, ($(arg_ptrs...),)) end end).args) return ex end """ launch(queue::RuntimeQueue, signal::RuntimeEvent, f::ROCFunction, groupsize::ROCDim, gridsize::ROCDim, args...) Low-level call to launch a ROC function `f` on the GPU, using `groupsize` and `gridsize` as the grid and block configuration, respectively. The kernel is launched on `queue` and is waited on by `signal`. Arguments to a kernel should either be bitstype, in which case they will be copied to the internal kernel parameter buffer, or a pointer to device memory. This is a low-level call, preferably use [`roccall`](@ref) instead. """ @inline function launch(queue::RuntimeQueue, signal::RuntimeEvent, f::ROCFunction, groupsize::ROCDim, gridsize::ROCDim, args...) groupsize = ROCDim3(groupsize) gridsize = ROCDim3(gridsize) (groupsize.x>0 && groupsize.y>0 && groupsize.z>0) || throw(ArgumentError("Group dimensions should be non-null")) (gridsize.x>0 && gridsize.y>0 && gridsize.z>0) || throw(ArgumentError("Grid dimensions should be non-null")) _launch(queue, signal, f, groupsize, gridsize, args...) end # we need a generated function to get an args array, # without having to inspect the types at runtime @generated function _launch(queue::RuntimeQueue, signal::RuntimeEvent, f::ROCFunction, groupsize::ROCDim3, gridsize::ROCDim3, args::NTuple{N,Any}) where N all(isbitstype, args.parameters) || throw(ArgumentError("Arguments to kernel should be bitstype.")) ex = Expr(:block) push!(ex.args, :(Base.@_inline_meta)) # put arguments in Ref boxes so that we can get a pointers to them arg_refs = Vector{Symbol}(undef, N) for i in 1:N arg_refs[i] = gensym() push!(ex.args, :($(arg_refs[i]) = Base.RefValue(args[$i]))) end append!(ex.args, (quote GC.@preserve $(arg_refs...) begin # create kernel instance kern = create_kernel(get_device(queue), f.mod.exe, f.entry, args) # launch kernel launch_kernel(queue, kern, signal; groupsize=groupsize, gridsize=gridsize) end end).args) return ex end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
70
# OpenCL runtime interface to AMDGPUnative include("opencl/args.jl")
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
1694
# code reflection entry-points # forward the rest to GPUCompiler with an appropriate CompilerJob # # code_* replacements # for method in (:code_typed, :code_warntype, :code_llvm, :code_native) # only code_typed doesn't take an io argument args = method == :code_typed ? (:job,) : (:io, :job) @eval begin function $method(io::IO, @nospecialize(func), @nospecialize(types); kernel::Bool=false, kwargs...) source = FunctionSpec(func, Base.to_tuple_type(types), kernel) target = GCNCompilerTarget(; dev_isa=default_isa(default_device())) params = ROCCompilerParams() job = CompilerJob(target, source, params) GPUCompiler.$method($(args...); kwargs...) end $method(@nospecialize(func), @nospecialize(types); kwargs...) = $method(stdout, func, types; kwargs...) end end const code_gcn = code_native # # @device_code_* macros # export @device_code_lowered, @device_code_typed, @device_code_warntype, @device_code_llvm, @device_code_gcn, @device_code # forward the rest to GPUCompiler @eval $(Symbol("@device_code_lowered")) = $(getfield(GPUCompiler, Symbol("@device_code_lowered"))) @eval $(Symbol("@device_code_typed")) = $(getfield(GPUCompiler, Symbol("@device_code_typed"))) @eval $(Symbol("@device_code_warntype")) = $(getfield(GPUCompiler, Symbol("@device_code_warntype"))) @eval $(Symbol("@device_code_llvm")) = $(getfield(GPUCompiler, Symbol("@device_code_llvm"))) @eval $(Symbol("@device_code_gcn")) = $(getfield(GPUCompiler, Symbol("@device_code_native"))) @eval $(Symbol("@device_code")) = $(getfield(GPUCompiler, Symbol("@device_code")))
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
2176
struct RuntimeDevice{D} device::D end default_device() = RuntimeDevice(default_device(RUNTIME[])) default_device(::typeof(HSA_rt)) = HSARuntime.get_default_agent() struct RuntimeQueue{Q} queue::Q end default_queue(device) = RuntimeQueue(default_queue(RUNTIME[], device)) default_queue(::typeof(HSA_rt), device) = HSARuntime.get_default_queue(device.device) get_device(queue::RuntimeQueue{HSAQueue}) = RuntimeDevice(queue.queue.agent) default_isa(device::RuntimeDevice{HSAAgent}) = HSARuntime.get_first_isa(device.device) struct RuntimeEvent{E} event::E end create_event() = RuntimeEvent(create_event(RUNTIME[])) create_event(::typeof(HSA_rt)) = HSASignal() Base.wait(event::RuntimeEvent; kwargs...) = wait(event.event; kwargs...) struct RuntimeExecutable{E} exe::E end create_executable(device, entry, obj; globals=()) = RuntimeExecutable(create_executable(RUNTIME[], device, entry, obj; globals=globals)) function create_executable(::typeof(HSA_rt), device, entry, obj; globals=()) # link with ld.lld ld_path = HSARuntime.ld_lld_path @assert ld_path != "" "ld.lld was not found; cannot link kernel" path_exe = mktemp() do path_o, io_o write(io_o, obj) flush(io_o) path_exe = path_o*".exe" run(`$ld_path -shared -o $path_exe $path_o`) path_exe end data = read(path_exe) rm(path_exe) return HSAExecutable(device.device, data, entry; globals=globals) end HSARuntime.get_global(exe::RuntimeExecutable, sym::Symbol) = HSARuntime.get_global(exe.exe, sym) struct RuntimeKernel{K} kernel::K end create_kernel(device, exe, entry, args) = RuntimeKernel(create_kernel(RUNTIME[], device, exe, entry, args)) create_kernel(::typeof(HSA_rt), device, exe, entry, args) = HSAKernelInstance(device.device, exe.exe, entry, args) launch_kernel(queue, kern, event; kwargs...) = launch_kernel(RUNTIME[], queue, kern, event; kwargs...) launch_kernel(::typeof(HSA_rt), queue, kern, event; groupsize=nothing, gridsize=nothing) = HSARuntime.launch!(queue.queue, kern.kernel, event.event; workgroup_size=groupsize, grid_size=gridsize)
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git
[ "MIT" ]
0.3.2
ded41ceeba656be904da319cce975871831654c6
code
3918
# Contiguous on-device arrays export ROCDeviceArray, ROCDeviceVector, ROCDeviceMatrix, ROCBoundsError # construction """ ROCDeviceArray(dims, ptr) ROCDeviceArray{T}(dims, ptr) ROCDeviceArray{T,A}(dims, ptr) ROCDeviceArray{T,A,N}(dims, ptr) Construct an `N`-dimensional dense ROC device array with element type `T` wrapping a pointer, where `N` is determined from the length of `dims` and `T` is determined from the type of `ptr`. `dims` may be a single scalar, or a tuple of integers corresponding to the lengths in each dimension). If the rank `N` is supplied explicitly as in `Array{T,N}(dims)`, then it must match the length of `dims`. The same applies to the element type `T`, which should match the type of the pointer `ptr`. """ ROCDeviceArray # NOTE: we can't support the typical `tuple or series of integer` style # construction, because we're currently requiring a trailing pointer argument. struct ROCDeviceArray{T,N,A} <: AbstractArray{T,N} shape::Dims{N} ptr::DevicePtr{T,A} # inner constructors, fully parameterized, exact types (ie. Int not <:Integer) ROCDeviceArray{T,N,A}(shape::Dims{N}, ptr::DevicePtr{T,A}) where {T,A,N} = new(shape,ptr) end const ROCDeviceVector = ROCDeviceArray{T,1,A} where {T,A} const ROCDeviceMatrix = ROCDeviceArray{T,2,A} where {T,A} # outer constructors, non-parameterized ROCDeviceArray(dims::NTuple{N,<:Integer}, p::DevicePtr{T,A}) where {T,A,N} = ROCDeviceArray{T,N,A}(dims, p) ROCDeviceArray(len::Integer, p::DevicePtr{T,A}) where {T,A} = ROCDeviceVector{T,A}((len,), p) # outer constructors, partially parameterized ROCDeviceArray{T}(dims::NTuple{N,<:Integer}, p::DevicePtr{T,A}) where {T,A,N} = ROCDeviceArray{T,N,A}(dims, p) ROCDeviceArray{T}(len::Integer, p::DevicePtr{T,A}) where {T,A} = ROCDeviceVector{T,A}((len,), p) ROCDeviceArray{T,N}(dims::NTuple{N,<:Integer}, p::DevicePtr{T,A}) where {T,A,N} = ROCDeviceArray{T,N,A}(dims, p) ROCDeviceVector{T}(len::Integer, p::DevicePtr{T,A}) where {T,A} = ROCDeviceVector{T,A}((len,), p) # outer constructors, fully parameterized ROCDeviceArray{T,N,A}(dims::NTuple{N,<:Integer}, p::DevicePtr{T,A}) where {T,A,N} = ROCDeviceArray{T,N,A}(Int.(dims), p) ROCDeviceVector{T,A}(len::Integer, p::DevicePtr{T,A}) where {T,A} = ROCDeviceVector{T,A}((Int(len),), p) # getters Base.pointer(a::ROCDeviceArray) = a.ptr Base.pointer(a::ROCDeviceArray, i::Integer) = pointer(a) + (i - 1) * Base.elsize(a) Base.elsize(::Type{<:ROCDeviceArray{T}}) where {T} = sizeof(T) Base.size(g::ROCDeviceArray) = g.shape Base.length(g::ROCDeviceArray) = prod(g.shape) # conversions Base.unsafe_convert(::Type{DevicePtr{T,A}}, a::ROCDeviceArray{T,N,A}) where {T,A,N} = pointer(a) # indexing # FIXME: Boundschecking @inline function Base.getindex(A::ROCDeviceArray{T}, index::Integer) where {T} @boundscheck checkbounds(A, index) align = datatype_align(T) Base.unsafe_load(pointer(A), index, Val(align))::T end @inline function Base.setindex!(A::ROCDeviceArray{T}, x, index::Integer) where {T} @boundscheck checkbounds(A, index) align = datatype_align(T) Base.unsafe_store!(pointer(A), x, index, Val(align)) return A end # other Base.show(io::IO, a::ROCDeviceVector) = print(io, "$(length(a))-element device array at $(pointer(a))") Base.show(io::IO, a::ROCDeviceArray) = print(io, "$(join(a.shape, '×')) device array at $(pointer(a))") Base.show(io::IO, mime::MIME"text/plain", a::ROCDeviceArray) = show(io, a) @inline function Base.unsafe_view(A::ROCDeviceVector{T}, I::Vararg{Base.ViewIndex,1}) where {T} ptr = pointer(A) + (I[1].start-1)*sizeof(T) len = I[1].stop - I[1].start + 1 return ROCDeviceArray(len, ptr) end @inline function Base.iterate(A::ROCDeviceArray, i=1) if (i % UInt) - 1 < length(A) (@inbounds A[i], i + 1) else nothing end end
AMDGPUnative
https://github.com/JuliaGPU/AMDGPUnative.jl.git