arrayfire/core/
defines.rs

1use num::Complex;
2use std::fmt::Error as FmtError;
3use std::fmt::{Display, Formatter};
4
5#[cfg(feature = "afserde")]
6use serde::{Deserialize, Serialize};
7
8/// Error codes
9#[repr(u32)]
10#[derive(Clone, Copy, Debug, PartialEq)]
11#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
12pub enum AfError {
13    /// The function returned successfully
14    SUCCESS = 0,
15    // 100-199 Errors in environment
16    /// The system or device ran out of memory
17    ERR_NO_MEM = 101,
18    /// There was an error in the device driver
19    ERR_DRIVER = 102,
20    /// There was an error with the runtime environment
21    ERR_RUNTIME = 103,
22    // 200-299 Errors in input parameters
23    /// The input array is not a valid Array object
24    ERR_INVALID_ARRAY = 201,
25    /// One of the function arguments is incorrect
26    ERR_ARG = 202,
27    /// The size is incorrect
28    ERR_SIZE = 203,
29    /// The type is not suppported by this function
30    ERR_TYPE = 204,
31    /// The type of the input arrays are not compatible
32    ERR_DIFF_TYPE = 205,
33    /// Function does not support GFOR / batch mode
34    ERR_BATCH = 207,
35    /// Input does not belong to the current device
36    ERR_DEVICE = 208,
37    // 300-399 Errors for missing software features
38    /// The option is not supported
39    ERR_NOT_SUPPORTED = 301,
40    /// This build of ArrayFire does not support this feature
41    ERR_NOT_CONFIGURED = 302,
42    // 400-499 Errors for missing hardware features
43    /// This device does not support double
44    ERR_NO_DBL = 401,
45    /// This build of ArrayFire was not built with graphics or this device does
46    /// not support graphics
47    ERR_NO_GFX = 402,
48    // 900-999 Errors from upstream libraries and runtimes
49    /// There was an internal error either in ArrayFire or in a project
50    /// upstream
51    ERR_INTERNAL = 998,
52    /// Unknown Error
53    ERR_UNKNOWN = 999,
54}
55
56/// Compute/Acceleration Backend
57#[repr(u32)]
58#[derive(Clone, Copy, Debug, PartialEq)]
59#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
60pub enum Backend {
61    /// Default backend order: OpenCL -> CUDA -> CPU
62    DEFAULT = 0,
63    /// CPU a.k.a sequential algorithms
64    CPU = 1,
65    /// CUDA Compute Backend
66    CUDA = 2,
67    /// OpenCL Compute Backend
68    OPENCL = 4,
69}
70
71impl Display for Backend {
72    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
73        let text = match *self {
74            Backend::OPENCL => "OpenCL",
75            Backend::CUDA => "Cuda",
76            Backend::CPU => "CPU",
77            Backend::DEFAULT => "Default",
78        };
79        write!(f, "{}", text)
80    }
81}
82
83impl Display for AfError {
84    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
85        let text = match *self {
86            AfError::SUCCESS => "Function returned successfully",
87            AfError::ERR_NO_MEM => "System or Device ran out of memory",
88            AfError::ERR_DRIVER => "Error in the device driver",
89            AfError::ERR_RUNTIME => "Error with the runtime environment",
90            AfError::ERR_INVALID_ARRAY => "Iput Array is not a valid object",
91            AfError::ERR_ARG => "One of the function arguments is incorrect",
92            AfError::ERR_SIZE => "Size is incorrect",
93            AfError::ERR_TYPE => "Type is not suppported by this function",
94            AfError::ERR_DIFF_TYPE => "Type of the input arrays are not compatible",
95            AfError::ERR_BATCH => "Function does not support GFOR / batch mode",
96            AfError::ERR_DEVICE => "Input does not belong to the current device",
97            AfError::ERR_NOT_SUPPORTED => "Unsupported operation/parameter option",
98            AfError::ERR_NOT_CONFIGURED => "This build of ArrayFire does not support this feature",
99            AfError::ERR_NO_DBL => "This device does not support double",
100            AfError::ERR_NO_GFX => "This build of ArrayFire has no graphics support",
101            AfError::ERR_INTERNAL => "Error either in ArrayFire or in a project upstream",
102            AfError::ERR_UNKNOWN => "Unknown Error",
103        };
104        write!(f, "{}", text)
105    }
106}
107
108/// Types of Array data type
109#[repr(u32)]
110#[derive(Clone, Copy, Debug, PartialEq)]
111#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
112pub enum DType {
113    /// 32 bit float
114    F32 = 0,
115    /// 32 bit complex float
116    C32 = 1,
117    /// 64 bit float
118    F64 = 2,
119    /// 64 bit complex float
120    C64 = 3,
121    /// 8 bit boolean
122    B8 = 4,
123    /// 32 bit signed integer
124    S32 = 5,
125    /// 32 bit unsigned integer
126    U32 = 6,
127    /// 8 bit unsigned integer
128    U8 = 7,
129    /// 64 bit signed integer
130    S64 = 8,
131    /// 64 bit unsigned integer
132    U64 = 9,
133    /// 16 bit signed integer
134    S16 = 10,
135    /// 16 bit unsigned integer
136    U16 = 11,
137    /// 16 bit floating point
138    F16 = 12,
139}
140
141/// Dictates the interpolation method to be used by a function
142#[repr(u32)]
143#[derive(Clone, Copy, Debug, PartialEq)]
144#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
145pub enum InterpType {
146    /// Nearest Neighbor interpolation method
147    NEAREST = 0,
148    /// Linear interpolation method
149    LINEAR = 1,
150    /// Bilinear interpolation method
151    BILINEAR = 2,
152    /// Cubic interpolation method
153    CUBIC = 3,
154    /// Floor indexed
155    LOWER = 4,
156    /// Linear interpolation with cosine smoothing
157    LINEAR_COSINE = 5,
158    /// Bilinear interpolation with cosine smoothing
159    BILINEAR_COSINE = 6,
160    /// Bicubic interpolation
161    BICUBIC = 7,
162    /// Cubic interpolation with Catmull-Rom splines
163    CUBIC_SPLINE = 8,
164    /// Bicubic interpolation with Catmull-Rom splines
165    BICUBIC_SPLINE = 9,
166}
167
168/// Helps determine how to pad kernels along borders
169#[repr(u32)]
170#[derive(Clone, Copy, Debug, PartialEq)]
171#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
172pub enum BorderType {
173    /// Pad using zeros
174    ZERO = 0,
175    /// Pad using mirrored values along border
176    SYMMETRIC = 1,
177
178    /// Out of bound values are clamped to the edge
179    CLAMP_TO_EDGE,
180
181    /// Out of bound values are mapped to range of the dimension in cyclic fashion
182    PERIODIC,
183}
184
185/// Used by `regions` function to identify type of connectivity
186#[repr(u32)]
187#[derive(Clone, Copy, Debug, PartialEq)]
188#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
189pub enum Connectivity {
190    /// North-East-South-West (N-E-S-W) connectivity from given pixel/point
191    FOUR = 4,
192    /// N-NE-E-SE-S-SW-W-NW connectivity from given pixel/point
193    EIGHT = 8,
194}
195
196/// Helps determine the size of output of convolution
197#[repr(u32)]
198#[derive(Clone, Copy, Debug, PartialEq)]
199#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
200pub enum ConvMode {
201    /// Default convolution mode where output size is same as input size
202    DEFAULT = 0,
203    /// Output of convolution is expanded based on signal and filter sizes
204    EXPAND = 1,
205}
206
207/// Helps determine if convolution is in Spatial or Frequency domain
208#[repr(u32)]
209#[derive(Clone, Copy, Debug, PartialEq)]
210#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
211pub enum ConvDomain {
212    /// ArrayFire chooses whether the convolution will be in spatial domain or frequency domain
213    AUTO = 0,
214    /// Convoltion in spatial domain
215    SPATIAL = 1,
216    /// Convolution in frequency domain
217    FREQUENCY = 2,
218}
219
220/// Error metric used by `matchTemplate` function
221#[repr(u32)]
222#[derive(Clone, Copy, Debug, PartialEq)]
223#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
224pub enum MatchType {
225    /// Sum of Absolute Differences
226    SAD = 0,
227    /// Zero-mean Sum of Absolute Differences
228    ZSAD = 1,
229    /// Locally scaled Sum of Absolute Differences
230    LSAD = 2,
231    /// Sum of Squared Differences
232    SSD = 3,
233    /// Zero-mean Sum of Squared Differences
234    ZSSD = 4,
235    /// Localy scaled Sum of Squared Differences
236    LSSD = 5,
237    /// Normalized Cross Correlation
238    NCC = 6,
239    /// Zero-mean Normalized Cross Correlation
240    ZNCC = 7,
241    /// Sum of Hamming Distances
242    SHD = 8,
243}
244
245/// Identify the color space of given image(Array)
246#[repr(u32)]
247#[derive(Clone, Copy, Debug, PartialEq)]
248#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
249pub enum ColorSpace {
250    /// Grayscale color space
251    GRAY = 0,
252    /// Red-Green-Blue color space
253    RGB = 1,
254    /// Hue-Saturation-value color space
255    HSV = 2,
256}
257
258/// Helps determine the type of a Matrix
259#[repr(u32)]
260#[derive(Clone, Copy, Debug, PartialEq)]
261#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
262pub enum MatProp {
263    /// Default (no-op)
264    NONE = 0,
265    /// Data needs to be transposed
266    TRANS = 1,
267    /// Data needs to be conjugate transposed
268    CTRANS = 2,
269    /// Matrix is upper triangular
270    CONJ = 4,
271    /// Matrix needs to be conjugate
272    UPPER = 32,
273    /// Matrix is lower triangular
274    LOWER = 64,
275    /// Matrix diagonal has unitary values
276    DIAGUNIT = 128,
277    /// Matrix is symmetric
278    SYM = 512,
279    /// Matrix is positive definite
280    POSDEF = 1024,
281    /// Matrix is orthogonal
282    ORTHOG = 2048,
283    /// Matrix is tri-diagonal
284    TRIDIAG = 4096,
285    /// Matrix is block-diagonal
286    BLOCKDIAG = 8192,
287}
288
289/// Norm type
290#[allow(non_camel_case_types)]
291#[repr(u32)]
292#[derive(Clone, Copy, Debug, PartialEq)]
293#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
294pub enum NormType {
295    /// Treats input as a vector and return sum of absolute values
296    VECTOR_1 = 0,
297    /// Treats input as vector and return max of absolute values
298    VECTOR_INF = 1,
299    /// Treats input as vector and returns euclidean norm
300    VECTOR_2 = 2,
301    /// Treats input as vector and returns the p-norm
302    VECTOR_P = 3,
303    /// Return the max of column sums
304    MATRIX_1 = 4,
305    /// Return the max of row sums
306    MATRIX_INF = 5,
307    /// Returns the max singular value (Currently not supported)
308    MATRIX_2 = 6,
309    /// Returns Lpq-norm
310    MATRIX_L_PQ = 7,
311}
312
313/// Dictates what color map is used for Image rendering
314#[repr(u32)]
315#[derive(Clone, Copy, Debug, PartialEq)]
316#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
317pub enum ColorMap {
318    /// Default color map is grayscale range [0-1]
319    DEFAULT = 0,
320    /// Visible spectrum color map
321    SPECTRUM = 1,
322    /// Colors
323    COLORS = 2,
324    /// Red hue map
325    RED = 3,
326    /// Mood color map
327    MOOD = 4,
328    /// Heat color map
329    HEAT = 5,
330    /// Blue hue map
331    BLUE = 6,
332}
333
334/// YCbCr Standards
335#[repr(u32)]
336#[derive(Clone, Copy, Debug, PartialEq)]
337#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
338pub enum YCCStd {
339    /// ITU-R BT.601 (formerly CCIR 601) standard
340    YCC_601 = 601,
341    /// ITU-R BT.709 standard
342    YCC_709 = 709,
343    /// ITU-R BT.2020 standard
344    YCC_2020 = 2020,
345}
346
347/// Homography type
348#[repr(u32)]
349#[derive(Clone, Copy, Debug, PartialEq)]
350#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
351pub enum HomographyType {
352    /// RANdom SAmple Consensus algorithm
353    RANSAC = 0,
354    /// Least Median of Squares
355    LMEDS = 1,
356}
357
358/// Plotting markers
359#[repr(u32)]
360#[derive(Clone, Copy, Debug, PartialEq)]
361#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
362pub enum MarkerType {
363    /// No marker
364    NONE = 0,
365    /// Pointer marker
366    POINT = 1,
367    /// Hollow circle marker
368    CIRCLE = 2,
369    /// Hollow Square marker
370    SQUARE = 3,
371    /// Hollow Triangle marker
372    TRIANGLE = 4,
373    /// Cross-hair marker
374    CROSS = 5,
375    /// Plus symbol marker
376    PLUS = 6,
377    /// Start symbol marker
378    STAR = 7,
379}
380
381/// Image moment types
382#[repr(u32)]
383#[derive(Clone, Copy, Debug, PartialEq)]
384#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
385pub enum MomentType {
386    /// Central moment of order (0 + 0)
387    M00 = 1, // 1<<0
388    /// Central moment of order (0 + 1)
389    M01 = 2, // 1<<1
390    /// Central moment of order (1 + 0)
391    M10 = 4, // 1<<2
392    /// Central moment of order (1 + 1)
393    M11 = 8, // 1<<3
394    /// All central moments of order (0,0), (0,1), (1,0) and (1,1)
395    FIRST_ORDER = 1 | 1 << 1 | 1 << 2 | 1 << 3,
396}
397
398/// Sparse storage format type
399#[repr(u32)]
400#[derive(Clone, Copy, Debug, PartialEq)]
401#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
402pub enum SparseFormat {
403    /// Dense format
404    DENSE = 0,
405    /// Compressed sparse row format
406    CSR = 1,
407    /// Compressed sparse coloumn format
408    CSC = 2,
409    /// Coordinate list (row, coloumn, value) tuples.
410    COO = 3,
411}
412
413/// Binary operation types for generalized scan functions
414#[repr(u32)]
415#[derive(Clone, Copy, Debug, PartialEq)]
416#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
417pub enum BinaryOp {
418    /// Addition operation
419    ADD = 0,
420    /// Multiplication operation
421    MUL = 1,
422    /// Minimum operation
423    MIN = 2,
424    /// Maximum operation
425    MAX = 3,
426}
427
428/// Random engine types
429#[repr(u32)]
430#[derive(Clone, Copy, Debug, PartialEq)]
431#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
432pub enum RandomEngineType {
433    ///Philox variant with N=4, W=32 and Rounds=10
434    PHILOX_4X32_10 = 100,
435    ///Threefry variant with N=2, W=32 and Rounds=16
436    THREEFRY_2X32_16 = 200,
437    ///Mersenne variant with MEXP = 11213
438    MERSENNE_GP11213 = 300,
439}
440
441/// Default Philon RandomEngine that points to [PHILOX_4X32_10](./enum.RandomEngineType.html)
442pub const PHILOX: RandomEngineType = RandomEngineType::PHILOX_4X32_10;
443/// Default Threefry RandomEngine that points to [THREEFRY_2X32_16](./enum.RandomEngineType.html)
444pub const THREEFRY: RandomEngineType = RandomEngineType::THREEFRY_2X32_16;
445/// Default Mersenne RandomEngine that points to [MERSENNE_GP11213](./enum.RandomEngineType.html)
446pub const MERSENNE: RandomEngineType = RandomEngineType::MERSENNE_GP11213;
447/// Default RandomEngine that defaults to [PHILOX](./constant.PHILOX.html)
448pub const DEFAULT_RANDOM_ENGINE: RandomEngineType = PHILOX;
449
450#[cfg(feature = "afserde")]
451#[derive(Serialize, Deserialize)]
452#[serde(remote = "Complex")]
453struct ComplexDef<T> {
454    re: T,
455    im: T,
456}
457
458/// Scalar value types
459#[derive(Clone, Copy, Debug, PartialEq)]
460#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
461pub enum Scalar {
462    /// 32 bit float
463    F32(f32),
464    /// 32 bit complex float
465    #[cfg_attr(feature = "afserde", serde(with = "ComplexDef"))]
466    C32(Complex<f32>),
467    /// 64 bit float
468    F64(f64),
469    /// 64 bit complex float
470    #[cfg_attr(feature = "afserde", serde(with = "ComplexDef"))]
471    C64(Complex<f64>),
472    /// 8 bit boolean
473    B8(bool),
474    /// 32 bit signed integer
475    S32(i32),
476    /// 32 bit unsigned integer
477    U32(u32),
478    /// 8 bit unsigned integer
479    U8(u8),
480    /// 64 bit signed integer
481    S64(i64),
482    /// 64 bit unsigned integer
483    U64(u64),
484    /// 16 bit signed integer
485    S16(i16),
486    /// 16 bit unsigned integer
487    U16(u16),
488}
489
490/// Canny edge detector threshold operations types
491#[repr(u32)]
492#[derive(Clone, Copy, Debug, PartialEq)]
493#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
494pub enum CannyThresholdType {
495    /// User has to define canny thresholds manually
496    MANUAL = 0,
497    /// Determine canny algorithm high threshold using Otsu algorithm automatically
498    OTSU = 1,
499}
500
501/// Anisotropic diffusion flux equation types
502#[repr(u32)]
503#[derive(Clone, Copy, Debug, PartialEq)]
504#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
505pub enum DiffusionEq {
506    /// Quadratic flux function
507    QUADRATIC = 1,
508    /// Exponential flux function
509    EXPONENTIAL = 2,
510    /// Default flux function, a.k.a exponential
511    DEFAULT = 0,
512}
513
514/// Diffusion equation types
515#[repr(u32)]
516#[derive(Clone, Copy, Debug, PartialEq)]
517#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
518pub enum FluxFn {
519    /// Quadratic flux function
520    GRADIENT = 1,
521    /// Modified curvature diffusion equation
522    MCDE = 2,
523    /// Default diffusion method, Gradient
524    DEFAULT = 0,
525}
526
527/// topk function ordering
528#[repr(u32)]
529#[derive(Clone, Copy, Debug, PartialEq)]
530#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
531pub enum TopkFn {
532    /// Top k min values
533    MIN = 1,
534    /// Top k max values
535    MAX = 2,
536    /// Default option(max)
537    DEFAULT = 0,
538}
539
540/// Iterative Deconvolution Algorithm
541#[repr(u32)]
542#[derive(Clone, Copy, Debug, PartialEq)]
543#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
544pub enum IterativeDeconvAlgo {
545    /// Land-Weber Algorithm
546    LANDWEBER = 1,
547    /// Richardson-Lucy Algorithm
548    RICHARDSONLUCY = 2,
549    /// Default is Land-Weber algorithm
550    DEFAULT = 0,
551}
552
553/// Inverse Deconvolution Algorithm
554#[repr(u32)]
555#[derive(Clone, Copy, Debug, PartialEq)]
556#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
557pub enum InverseDeconvAlgo {
558    /// Tikhonov algorithm
559    TIKHONOV = 1,
560    /// Default is Tikhonov algorithm
561    DEFAULT = 0,
562}
563
564/// Gradient mode for convolution
565#[repr(u32)]
566#[derive(Clone, Copy, Debug, PartialEq)]
567#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
568pub enum ConvGradientType {
569    /// Filter Gradient
570    FILTER = 1,
571    /// Data Gradient
572    DATA = 2,
573    /// Biased Gradient
574    BIAS = 3,
575    /// Default is Data Gradient
576    DEFAULT = 0,
577}
578
579/// Gradient mode for convolution
580#[repr(u32)]
581#[derive(Clone, Copy, Debug, PartialEq)]
582#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
583pub enum VarianceBias {
584    /// Sample variance
585    SAMPLE = 1,
586    /// Population variance
587    POPULATION = 2,
588    /// Default (Population) variance
589    DEFAULT = 0,
590}
591
592/// Gradient mode for convolution
593#[repr(u32)]
594#[derive(Clone, Copy, Debug, PartialEq)]
595#[cfg_attr(feature = "afserde", derive(Serialize, Deserialize))]
596pub enum CublasMathMode {
597    /// To indicate use of Tensor Cores on CUDA capable GPUs
598    TENSOR_OP = 1,
599    /// Default i.e. tensor core operations will be avoided by the library
600    DEFAULT = 0,
601}
602
603#[cfg(test)]
604mod tests {
605    #[cfg(feature = "afserde")]
606    mod serde_tests {
607        #[test]
608        fn test_enum_serde() {
609            use super::super::AfError;
610
611            let err_code = AfError::ERR_NO_MEM;
612            let serd = match serde_json::to_string(&err_code) {
613                Ok(serialized_str) => serialized_str,
614                Err(e) => e.to_string(),
615            };
616            assert_eq!(serd, "\"ERR_NO_MEM\"");
617
618            let deserd: AfError = serde_json::from_str(&serd).unwrap();
619            assert_eq!(deserd, AfError::ERR_NO_MEM);
620        }
621
622        #[test]
623        fn test_scalar_serde() {
624            use super::super::Scalar;
625            use num::Complex;
626
627            let scalar = Scalar::C32(Complex {
628                re: 1.0f32,
629                im: 1.0f32,
630            });
631            let serd = match serde_json::to_string(&scalar) {
632                Ok(serialized_str) => serialized_str,
633                Err(e) => e.to_string(),
634            };
635
636            let deserd: Scalar = serde_json::from_str(&serd).unwrap();
637            assert_eq!(deserd, scalar);
638        }
639    }
640}