diff --git a/Cargo.toml b/Cargo.toml index ab2e67ee1..550a7cc61 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,4 +1,5 @@ [package] +edition = "2018" name = "arrayfire" description = "ArrayFire is a high performance software library for parallel computing with an easy-to-use API. Its array based function set makes parallel programming simple. ArrayFire's multiple backends (CUDA, OpenCL and native CPU) make it platform independent and highly portable. A few lines of code in ArrayFire can replace dozens of lines of parallel computing code, saving you valuable time and lowering development costs. This crate provides Rust bindings for ArrayFire library." version = "3.6.0" diff --git a/build.rs b/build.rs index 6754a03dc..8e36d0112 100644 --- a/build.rs +++ b/build.rs @@ -2,18 +2,18 @@ #[macro_use] extern crate serde_derive; +extern crate rustc_version; extern crate serde; extern crate serde_json; -extern crate rustc_version; +use rustc_version::{version, Version}; +use std::convert::AsRef; use std::env; use std::fs; use std::fs::OpenOptions; use std::io::{ErrorKind, Read}; use std::path::PathBuf; use std::process::Command; -use std::convert::AsRef; -use rustc_version::{version, Version}; // Windows specific library file names static WIN_CUDA_LIB: &'static str = "afcuda"; @@ -63,14 +63,14 @@ fn fail(s: &str) -> ! { fn dir_exists(location: &str) -> bool { match fs::metadata(location) { - Ok(f) => f.is_dir(), + Ok(f) => f.is_dir(), Err(_) => false, } } fn file_exists(location: &str) -> bool { match fs::metadata(location) { - Ok(f) => f.is_file(), + Ok(f) => f.is_file(), Err(_) => false, } } @@ -78,14 +78,20 @@ fn file_exists(location: &str) -> bool { fn run(cmd: &mut Command, program: &str) { println!("running: {:?}", cmd); let status = match cmd.status() { - Ok(status) => status, - Err(ref e) if e.kind() == ErrorKind::NotFound => { - fail(&format!("failed to run cmd: {}\nis `{}` not installed?", e, program)); - } - Err(e) => fail(&format!("failed to execute command: {}", e)), - }; + Ok(status) => status, + Err(ref e) if e.kind() == ErrorKind::NotFound => { + fail(&format!( + "failed to run cmd: {}\nis `{}` not installed?", + e, program + )); + } + Err(e) => fail(&format!("failed to execute command: {}", e)), + }; if !status.success() { - fail(&format!("command did not execute successfully, got: {}", status)); + fail(&format!( + "command did not execute successfully, got: {}", + status + )); } } @@ -98,13 +104,13 @@ fn read_file(file_name: &std::path::PathBuf) -> String { .open(&file_path); let mut file = match options { - Ok(file)=> file, - Err(..) => panic!("error reading file"), - }; + Ok(file) => file, + Err(..) => panic!("error reading file"), + }; let mut s = String::new(); match file.read_to_string(&mut s) { - Ok(_) => s, + Ok(_) => s, Err(..) => panic!("Error reading file to a string"), } } @@ -121,81 +127,71 @@ fn prep_cmake_options(conf: &Config) -> Vec { match conf.build_type.as_ref() { "Release" | "RelWithDebInfo" | "Debug" => { options.push(format!("-DCMAKE_BUILD_TYPE:STRING={}", conf.build_type)); - }, + } _ => fail("Invalid value for build_type option"), }; match conf.build_cpu.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_BUILD_CPU:BOOL={}", - conf.build_cpu)); - }, + options.push(format!("-DAF_BUILD_CPU:BOOL={}", conf.build_cpu)); + } _ => fail("Invalid value for build_cpu option"), }; match conf.build_cuda.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_BUILD_CUDA:BOOL={}", - conf.build_cuda)); - }, + options.push(format!("-DAF_BUILD_CUDA:BOOL={}", conf.build_cuda)); + } _ => fail("Invalid value for build_cuda option"), }; match conf.build_opencl.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_BUILD_OPENCL:BOOL={}", - conf.build_opencl)); - }, + options.push(format!("-DAF_BUILD_OPENCL:BOOL={}", conf.build_opencl)); + } _ => fail("Invalid value for build_opencl option"), }; match conf.build_nonfree.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_BUILD_NONFREE:BOOL={}", - conf.build_nonfree)); - }, + options.push(format!("-DAF_BUILD_NONFREE:BOOL={}", conf.build_nonfree)); + } _ => fail("Invalid value for build_nonfree option"), }; match conf.build_examples.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_BUILD_EXAMPLES:BOOL={}", - conf.build_examples)); - }, + options.push(format!("-DAF_BUILD_EXAMPLES:BOOL={}", conf.build_examples)); + } _ => fail("Invalid value for build_examples option"), }; match conf.build_test.as_ref() { "ON" | "OFF" => { - options.push(format!("-DBUILD_TESTING:BOOL={}", - conf.build_test)); - }, + options.push(format!("-DBUILD_TESTING:BOOL={}", conf.build_test)); + } _ => fail("Invalid value for build_test option"), }; match conf.with_intelmkl.as_ref() { "ON" | "OFF" => { - options.push(format!("-DUSE_CPU_MKL:BOOL={0}", - conf.with_intelmkl)); - options.push(format!("-DUSE_OPENCL_MKL:BOOL={0}", - conf.with_intelmkl)); - }, + options.push(format!("-DUSE_CPU_MKL:BOOL={0}", conf.with_intelmkl)); + options.push(format!("-DUSE_OPENCL_MKL:BOOL={0}", conf.with_intelmkl)); + } _ => fail("Invalid value for with_intelmkl option"), }; match conf.with_imageio.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_WITH_IMAGEIO:BOOL={0}", - conf.with_imageio)); - }, + options.push(format!("-DAF_WITH_IMAGEIO:BOOL={0}", conf.with_imageio)); + } _ => fail("Invalid value for with_imageio option"), }; match conf.with_graphics.as_ref() { "ON" | "OFF" => { - options.push(format!("-DAF_WITH_GRAPHICS:BOOL={0}", - conf.with_graphics)); - }, + options.push(format!("-DAF_WITH_GRAPHICS:BOOL={0}", conf.with_graphics)); + } _ => fail("Invalid value for with_graphics option"), }; match conf.with_opencl_blas_lib.as_ref() { "clblast" => { options.push(format!("-DAF_OPENCL_BLAS_LIBRARY:STRING=CLBlast")); - }, + } "clblas" => { options.push(format!("-DAF_OPENCL_BLAS_LIBRARY:STRING=clBLAS")); - }, + } _ => fail("Invalid value for with_opencl_blas_lib option"), }; return options; @@ -210,29 +206,40 @@ fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) { let mut cmake_cmd = Command::new("cmake"); cmake_cmd.current_dir(&build_dir); - run(cmake_cmd.arg("..") - .arg("-T").arg(format!("{}", conf.win_vs_toolset)) - .arg("-G").arg(format!("{}", conf.win_cmake_generator)) - .args(&options) - .arg(format!("-DCMAKE_TOOLCHAIN_FILE:FILEPATH={}", - conf.vcpkg_toolchain_file)) - .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")) - , "cmake"); - - let mut make_cmd= Command::new("MSBuild.exe"); + run( + cmake_cmd + .arg("..") + .arg("-T") + .arg(format!("{}", conf.win_vs_toolset)) + .arg("-G") + .arg(format!("{}", conf.win_cmake_generator)) + .args(&options) + .arg(format!( + "-DCMAKE_TOOLCHAIN_FILE:FILEPATH={}", + conf.vcpkg_toolchain_file + )) + .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")), + "cmake", + ); + + let mut make_cmd = Command::new("MSBuild.exe"); make_cmd.current_dir(&build_dir); - run(make_cmd - .arg(format!("/m:{}", conf.build_threads)) - .arg(format!("/p:Configuration={}", conf.build_type)) - .arg(format!("ArrayFire.sln")), - "MSBuild"); - - let mut install_cmd= Command::new("MSBuild.exe"); + run( + make_cmd + .arg(format!("/m:{}", conf.build_threads)) + .arg(format!("/p:Configuration={}", conf.build_type)) + .arg(format!("ArrayFire.sln")), + "MSBuild", + ); + + let mut install_cmd = Command::new("MSBuild.exe"); install_cmd.current_dir(&build_dir); - run(install_cmd - .arg(format!("/p:Configuration={}", conf.build_type)) - .arg(format!("INSTALL.vcxproj")), - "Install"); + run( + install_cmd + .arg(format!("/p:Configuration={}", conf.build_type)) + .arg(format!("INSTALL.vcxproj")), + "Install", + ); } #[cfg(not(windows))] @@ -245,60 +252,77 @@ fn run_cmake_command(conf: &Config, build_dir: &std::path::PathBuf) { let mut cmake_cmd = Command::new("cmake"); cmake_cmd.current_dir(&build_dir); - run(cmake_cmd.arg("..") - .args(&options) - .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")) - .arg(format!("-DCUDA_HOST_COMPILER={}", conf.lnx_cuda_host_compiler)) - , "cmake"); - - let mut make_cmd= Command::new("make"); + run( + cmake_cmd + .arg("..") + .args(&options) + .arg(format!("-DCMAKE_INSTALL_PREFIX={}", "package")) + .arg(format!( + "-DCUDA_HOST_COMPILER={}", + conf.lnx_cuda_host_compiler + )), + "cmake", + ); + + let mut make_cmd = Command::new("make"); make_cmd.current_dir(&build_dir); - run(make_cmd - .arg(format!("-j{}", conf.build_threads)) - .arg(format!("install")), "make"); + run( + make_cmd + .arg(format!("-j{}", conf.build_threads)) + .arg(format!("install")), + "make", + ); } -fn backend_exists(name: &str) -> bool{ - let win_backend = name.to_string() + ".dll"; - let osx_backend = name.to_string() + ".dylib"; +fn backend_exists(name: &str) -> bool { + let win_backend = name.to_string() + ".dll"; + let osx_backend = name.to_string() + ".dylib"; let linux_backend = name.to_string() + ".so"; - return file_exists(&win_backend) - || file_exists(&osx_backend) - || file_exists(&linux_backend) + return file_exists(&win_backend) || file_exists(&osx_backend) || file_exists(&linux_backend); } -fn blob_backends(conf: &Config, - build_dir: &std::path::PathBuf) -> (Vec, Vec) { - let mut backend_dirs :Vec= Vec::new(); - let mut backends :Vec = Vec::new(); +fn blob_backends(conf: &Config, build_dir: &std::path::PathBuf) -> (Vec, Vec) { + let mut backend_dirs: Vec = Vec::new(); + let mut backends: Vec = Vec::new(); if conf.use_lib { - let afpath = match env::var("AF_PATH") { + let afpath = match env::var("AF_PATH") { Ok(af_path) => PathBuf::from(&af_path), - Err(_) => { - println!("WARNING! USE_LIB is defined, - but AF_PATH is not found,"); - println!("Trying to find libraries from - known default locations"); + Err(_) => { + println!( + "WARNING! USE_LIB is defined, + but AF_PATH is not found," + ); + println!( + "Trying to find libraries from + known default locations" + ); if cfg!(target_os = "windows") { PathBuf::from("C:\\Program Files\\ArrayFire\\v3\\") } else { PathBuf::from("/opt/arrayfire/") } - }, + } }; - let libpath = afpath.join("lib"); - backend_dirs.push(libpath.to_str().to_owned().unwrap().to_string()); + backend_dirs.push(afpath.join("lib").to_str().to_owned().unwrap().to_string()); + backend_dirs.push(afpath.join("lib64").to_str().to_owned().unwrap().to_string()); if !cfg!(target_os = "windows") { backend_dirs.push(String::from("/usr/local/lib")); backend_dirs.push(String::from("/usr/lib")); } } else { - backend_dirs.push(build_dir.join("package").join("lib") - .to_str().to_owned().unwrap().to_string()); + backend_dirs.push( + build_dir + .join("package") + .join("lib") + .to_str() + .to_owned() + .unwrap() + .to_string(), + ); } let mut uni_lib_exists = false; @@ -308,42 +332,50 @@ fn blob_backends(conf: &Config, for backend_dir in backend_dirs.iter() { let lib_dir = PathBuf::from(backend_dir); - let culib_name = if cfg!(windows) {WIN_CUDA_LIB} else {UNIX_CUDA_LIB}; - cud_lib_exists = cud_lib_exists || backend_exists(&lib_dir - .join(culib_name) - .to_string_lossy()); - let ocllib_name = if cfg!(windows) {WIN_OCL_LIB} else {UNIX_OCL_LIB}; - ocl_lib_exists = ocl_lib_exists || backend_exists(&lib_dir - .join(ocllib_name) - .to_string_lossy()); - let unilib_name = if cfg!(windows) {WIN_UNI_LIB} else {UNIX_UNI_LIB}; - uni_lib_exists = uni_lib_exists || backend_exists(&lib_dir - .join(unilib_name) - .to_string_lossy()); + let culib_name = if cfg!(windows) { + WIN_CUDA_LIB + } else { + UNIX_CUDA_LIB + }; + cud_lib_exists = + cud_lib_exists || backend_exists(&lib_dir.join(culib_name).to_string_lossy()); + let ocllib_name = if cfg!(windows) { + WIN_OCL_LIB + } else { + UNIX_OCL_LIB + }; + ocl_lib_exists = + ocl_lib_exists || backend_exists(&lib_dir.join(ocllib_name).to_string_lossy()); + let unilib_name = if cfg!(windows) { + WIN_UNI_LIB + } else { + UNIX_UNI_LIB + }; + uni_lib_exists = + uni_lib_exists || backend_exists(&lib_dir.join(unilib_name).to_string_lossy()); } - if ! conf.use_lib { + if !conf.use_lib { // blob in cuda deps if cud_lib_exists { if cfg!(windows) { backend_dirs.push(format!("{}\\lib\\x64", conf.win_cuda_sdk)); } else { let sdk_dir = format!("{}/{}", conf.lnx_cuda_sdk, "lib64"); - match dir_exists(&sdk_dir){ - true => { + match dir_exists(&sdk_dir) { + true => { backend_dirs.push(sdk_dir); - }, + } false => { - backend_dirs.push(format!("{}/{}", - conf.lnx_cuda_sdk, "lib")); - }, + backend_dirs.push(format!("{}/{}", conf.lnx_cuda_sdk, "lib")); + } }; } } //blob in opencl deps if ocl_lib_exists { - if ! cfg!(target_os = "macos") { + if !cfg!(target_os = "macos") { backends.push("OpenCL".to_string()); } if cfg!(windows) { @@ -351,8 +383,7 @@ fn blob_backends(conf: &Config, if dir_exists(&sdk_dir) { backend_dirs.push(sdk_dir); } else { - backend_dirs.push(format!("{}\\lib\\x86_64", - conf.win_opencl_sdk)); + backend_dirs.push(format!("{}\\lib\\x86_64", conf.win_opencl_sdk)); } } else { let sdk_dir = format!("{}/{}", conf.lnx_opencl_sdk, "lib64"); @@ -364,19 +395,25 @@ fn blob_backends(conf: &Config, } } - if conf.with_graphics=="ON" { + if conf.with_graphics == "ON" { if !conf.use_lib { - backend_dirs.push(build_dir.join("third_party") - .join("forge").join("lib") - .to_str().to_owned().unwrap() - .to_string()); + backend_dirs.push( + build_dir + .join("third_party") + .join("forge") + .join("lib") + .to_str() + .to_owned() + .unwrap() + .to_string(), + ); } } } if uni_lib_exists { backends.push("af".to_string()); - if !conf.use_lib && conf.with_graphics=="ON" { + if !conf.use_lib && conf.with_graphics == "ON" { backends.push("forge".to_string()); } } diff --git a/examples/acoustic_wave.rs b/examples/acoustic_wave.rs index 56ba3bc74..21b12b90a 100644 --- a/examples/acoustic_wave.rs +++ b/examples/acoustic_wave.rs @@ -1,6 +1,4 @@ -extern crate arrayfire as af; - -use af::*; +use arrayfire::*; use std::f64::consts::*; fn main() { @@ -10,20 +8,20 @@ fn main() { } fn normalise(a: &Array) -> Array { - (a/(max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32 + (a / (max_all(&abs(a)).0 as f32 * 2.0f32)) + 0.5f32 } fn acoustic_wave_simulation() { // Speed of sound - let c :f32 = 0.1; + let c: f32 = 0.1; // Distance step - let dx :f32 = 0.5; + let dx: f32 = 0.5; // Time step - let dt :f32 = 1.0; + let dt: f32 = 1.0; // Grid size. - let nx : u64 = 1500; - let ny : u64 = 1500; + let nx: u64 = 1500; + let ny: u64 = 1500; // Grid dimensions. let dims = Dim4::new(&[nx, ny, 1, 1]); @@ -34,34 +32,37 @@ fn acoustic_wave_simulation() { let mut p_dot = p.clone(); // Laplacian (Del^2) convolution kernel. - let laplacian_values: [f32; 9] = [0.0, 1.0, 0.0, - 1.0, -4.0, 1.0, - 0.0, 1.0, 0.0]; + let laplacian_values: [f32; 9] = [0.0, 1.0, 0.0, 1.0, -4.0, 1.0, 0.0, 1.0, 0.0]; let laplacian_kernel = Array::new(&laplacian_values, Dim4::new(&[3, 3, 1, 1])) / (dx * dx); // Create a window to show the waves. let mut win = Window::new(1000, 1000, "Waves".to_string()); // Hann windowed pulse. - let pulse_time :f32 = 100.0; - let centre_freq :f32 = 0.05; - let twopi = PI as f32 * 2.0; + let pulse_time: f32 = 100.0; + let centre_freq: f32 = 0.05; + let twopi = PI as f32 * 2.0; // Number of samples in pulse. - let pulse_n = (pulse_time/dt).floor() as u64; + let pulse_n = (pulse_time / dt).floor() as u64; - let i = range::(Dim4::new(&[pulse_n, 1, 1, 1]), 0); - let t = i.clone() * dt; + let i = range::(Dim4::new(&[pulse_n, 1, 1, 1]), 0); + let t = i.clone() * dt; let hmg_wnd = cos(&(i * (twopi / pulse_n as f32))) * -0.46f32 + 0.54f32; - let wave = sin(&(&t * centre_freq * twopi)); - let pulse = wave * hmg_wnd; + let wave = sin(&(&t * centre_freq * twopi)); + let pulse = wave * hmg_wnd; // Iteration count. let mut it = 0; while !win.is_closed() { // Convole with laplacian to get spacial second derivative. - let lap_p = convolve2(&p, &laplacian_kernel, ConvMode::DEFAULT, ConvDomain::SPATIAL); + let lap_p = convolve2( + &p, + &laplacian_kernel, + ConvMode::DEFAULT, + ConvDomain::SPATIAL, + ); // Calculate the updated pressure and d(pressure)/dt fields. p_dot += lap_p * (c * dt); p += &p_dot * dt; @@ -70,11 +71,15 @@ fn acoustic_wave_simulation() { // Location of the source. let seqs = &[Seq::new(700.0, 800.0, 1.0), Seq::new(800.0, 800.0, 1.0)]; // Set the pressure there. - p = assign_seq(&p, seqs, &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)])); + p = assign_seq( + &p, + seqs, + &index(&pulse, &[Seq::new(it as f64, it as f64, 1.0)]), + ); } // Draw the image. - win.set_colormap(af::ColorMap::BLUE); + win.set_colormap(ColorMap::BLUE); win.draw_image(&normalise(&p), None); it += 1; diff --git a/examples/conway.rs b/examples/conway.rs index 6aa45829a..c87f875d0 100644 --- a/examples/conway.rs +++ b/examples/conway.rs @@ -1,6 +1,4 @@ -extern crate arrayfire as af; - -use af::*; +use arrayfire::*; fn main() { set_device(0); diff --git a/examples/helloworld.rs b/examples/helloworld.rs index eb8354cab..53fd29c27 100644 --- a/examples/helloworld.rs +++ b/examples/helloworld.rs @@ -1,8 +1,4 @@ -#[macro_use(af_print)] -extern crate arrayfire as af; -extern crate num; - -use af::*; +use arrayfire::*; #[allow(unused_must_use)] fn main() { @@ -11,7 +7,10 @@ fn main() { print!("Info String:\n{}", info_string(true)); println!("Arrayfire version: {:?}", get_version()); let (name, platform, toolkit, compute) = device_info(); - print!("Name: {}\nPlatform: {}\nToolkit: {}\nCompute: {}\n", name, platform, toolkit, compute); + print!( + "Name: {}\nPlatform: {}\nToolkit: {}\nCompute: {}\n", + name, platform, toolkit, compute + ); println!("Revision: {}", get_revision()); let num_rows: u64 = 5; @@ -27,11 +26,11 @@ fn main() { af_print!("Create a 5-by-3 float matrix on the GPU", a); println!("Element-wise arithmetic"); - let b = add(&sin(&a), &1.5f32, false); + let b = add(&sin(&a), &1.5f32, false); let b2 = add(&sin(&a), &cos(&a), false); - let b3 = ! &a; + let b3 = !&a; af_print!("sin(a) + 1.5 a.k.a b => ", b); af_print!("sin(a) + cos(a) => ", b2); af_print!("!a => ", b3); @@ -84,5 +83,8 @@ fn main() { let u8_cnst = &constant(1 as u8, dims); af_print!("u8 constant array", u8_cnst); - println!("Is u8_cnst array float precision type ? {}", u8_cnst.is_single()); + println!( + "Is u8_cnst array float precision type ? {}", + u8_cnst.is_single() + ); } diff --git a/examples/histogram.rs b/examples/histogram.rs index 5bb3882d5..b2157ba79 100644 --- a/examples/histogram.rs +++ b/examples/histogram.rs @@ -1,6 +1,4 @@ -extern crate arrayfire as af; - -use af::*; +use arrayfire::*; use std::env; use std::path::PathBuf; @@ -11,7 +9,10 @@ fn main() { info(); let assets_dir = PathBuf::from(&env::var("CARGO_MANIFEST_DIR").unwrap()) - .join("arrayfire").join("assets").join("examples").join("images"); + .join("arrayfire") + .join("assets") + .join("examples") + .join("images"); let img_wnd = Window::new(480, 640, String::from("Input Image")); img_wnd.set_position(100, 100); @@ -28,7 +29,11 @@ fn main() { img_wnd.draw_image(&disp_img, None); hst_wnd.draw_hist(&hst, 0.0, 255.0, None); - if img_wnd.is_closed() == true { break; } - if hst_wnd.is_closed() == true { break; } + if img_wnd.is_closed() == true { + break; + } + if hst_wnd.is_closed() == true { + break; + } } } diff --git a/examples/pi.rs b/examples/pi.rs index 5fe1c79e4..1d6e91bb4 100644 --- a/examples/pi.rs +++ b/examples/pi.rs @@ -1,8 +1,5 @@ -#[macro_use(mem_info)] -extern crate arrayfire as af; - +use arrayfire::*; use std::time::Instant; -use af::*; #[allow(unused_must_use)] #[allow(unused_variables)] @@ -25,8 +22,8 @@ fn main() { let xplusy = &add(xsqrd, ysqrd, false); let root = &sqrt(xplusy); let cnst = &constant(1, dims); - let (real, imag) = sum_all(&le(root, cnst, false)); - let pi_val = real*4.0/(samples as f64); + let (real, imag) = sum_all(&le(root, cnst, false)); + let pi_val = real * 4.0 / (samples as f64); } println!("Estimated Pi Value in {:?}", start.elapsed()); diff --git a/examples/snow.rs b/examples/snow.rs index bdeb394f6..f078afa3d 100644 --- a/examples/snow.rs +++ b/examples/snow.rs @@ -1,6 +1,4 @@ -extern crate arrayfire as af; - -use af::*; +use arrayfire::*; #[allow(unused_variables)] #[allow(unused_must_use)] @@ -15,6 +13,8 @@ fn main() { loop { wnd.draw_image(&randu::(dims), None); - if wnd.is_closed() == true { break; } + if wnd.is_closed() == true { + break; + } } } diff --git a/examples/unified.rs b/examples/unified.rs index 6ed0e0b77..e70aa5d6d 100644 --- a/examples/unified.rs +++ b/examples/unified.rs @@ -1,59 +1,56 @@ -extern crate arrayfire as af; - -use af::*; +use arrayfire::*; #[cfg(op_assign)] fn helper(dims: Dim4) { - let mut a = randu::(dims); - let b = randu::(dims); - print(&a); - print(&b); - a += b; - print(&a); + let mut a = randu::(dims); + let b = randu::(dims); + print(&a); + print(&b); + a += b; + print(&a); } #[cfg(not(op_assign))] fn helper(dims: Dim4) { - let b = randu::(dims); - print(&b); + let b = randu::(dims); + print(&b); } #[allow(unused_must_use)] -fn test_backend(){ - info(); +fn test_backend() { + info(); - println!("Create a 10-by-10 matrix of random floats on the compute device"); - let num_rows: u64 = 10; - let num_cols: u64 = 10; - let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); + println!("Create a 10-by-10 matrix of random floats on the compute device"); + let num_rows: u64 = 10; + let num_cols: u64 = 10; + let dims = Dim4::new(&[num_rows, num_cols, 1, 1]); - helper(dims) + helper(dims) } - #[allow(unused_must_use)] fn main() { - println!("There are {:?} available backends", get_backend_count()); - let available = get_available_backends(); - - if available.contains(&Backend::CPU) { - println!("Evaluating CPU Backend..."); - set_backend(Backend::CPU); - println!("There are {} CPU compute devices", device_count()); - test_backend(); - } - - if available.contains(&Backend::CUDA) { - println!("Evaluating CUDA Backend..."); - set_backend(Backend::CUDA); - println!("There are {} CUDA compute devices", device_count()); - test_backend(); - } - - if available.contains(&Backend::OPENCL) { - println!("Evaluating OpenCL Backend..."); - set_backend(Backend::OPENCL); - println!("There are {} OpenCL compute devices", device_count()); - test_backend(); - } + println!("There are {:?} available backends", get_backend_count()); + let available = get_available_backends(); + + if available.contains(&Backend::CPU) { + println!("Evaluating CPU Backend..."); + set_backend(Backend::CPU); + println!("There are {} CPU compute devices", device_count()); + test_backend(); + } + + if available.contains(&Backend::CUDA) { + println!("Evaluating CUDA Backend..."); + set_backend(Backend::CUDA); + println!("There are {} CUDA compute devices", device_count()); + test_backend(); + } + + if available.contains(&Backend::OPENCL) { + println!("Evaluating OpenCL Backend..."); + set_backend(Backend::OPENCL); + println!("There are {} OpenCL compute devices", device_count()); + test_backend(); + } } diff --git a/src/algorithm/mod.rs b/src/algorithm/mod.rs index 35dad3d16..26d7192a1 100644 --- a/src/algorithm/mod.rs +++ b/src/algorithm/mod.rs @@ -1,14 +1,14 @@ extern crate libc; -use array::Array; -use defines::{AfError, BinaryOp}; -use error::HANDLE_ERROR; -use self::libc::{c_int, c_uint, c_double}; -use util::{AfArray, MutAfArray, MutDouble, MutUint}; -use util::{HasAfEnum, Scanable, RealNumber}; +use self::libc::{c_double, c_int, c_uint}; +use crate::array::Array; +use crate::defines::{AfError, BinaryOp}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, MutAfArray, MutDouble, MutUint}; +use crate::util::{HasAfEnum, RealNumber, Scanable}; #[allow(dead_code)] -extern { +extern "C" { fn af_sum(out: MutAfArray, input: AfArray, dim: c_int) -> c_int; fn af_sum_nan(out: MutAfArray, input: AfArray, dim: c_int, nanval: c_double) -> c_int; fn af_product(out: MutAfArray, input: AfArray, dim: c_int) -> c_int; @@ -41,33 +41,51 @@ extern { fn af_set_union(out: MutAfArray, first: AfArray, second: AfArray, is_unq: c_int) -> c_int; fn af_set_intersect(out: MutAfArray, one: AfArray, two: AfArray, is_unq: c_int) -> c_int; - fn af_sort_by_key(out_keys: MutAfArray, out_vals: MutAfArray, - in_keys: AfArray, in_vals: AfArray, dim: c_uint, ascend: c_int) -> c_int; + fn af_sort_by_key( + out_keys: MutAfArray, + out_vals: MutAfArray, + in_keys: AfArray, + in_vals: AfArray, + dim: c_uint, + ascend: c_int, + ) -> c_int; fn af_scan(out: MutAfArray, inp: AfArray, dim: c_int, op: c_uint, inclusive: c_int) -> c_int; - fn af_scan_by_key(out: MutAfArray, key: AfArray, inp: AfArray, - dim: c_int, op: c_uint, inclusive: c_int) -> c_int; + fn af_scan_by_key( + out: MutAfArray, + key: AfArray, + inp: AfArray, + dim: c_int, + op: c_uint, + inclusive: c_int, + ) -> c_int; } macro_rules! dim_reduce_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident, $out_type: ty) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident, $out_type: ty) => { #[doc=$doc_str] #[allow(unused_mut)] - pub fn $fn_name(input: &Array, dim: i32) -> Array< $out_type > - where T: HasAfEnum, $out_type: HasAfEnum + pub fn $fn_name(input: &Array, dim: i32) -> Array<$out_type> + where + T: HasAfEnum, + $out_type: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, - input.get() as AfArray, dim as c_int); + let err_val = $ffi_name( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Sum elements along a given dimension # Parameters @@ -92,9 +110,13 @@ dim_reduce_func_def!(" print(&c); ``` ", - sum, af_sum, T::AggregateOutType); + sum, + af_sum, + T::AggregateOutType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Compute product of elements along a given dimension # Parameters @@ -118,9 +140,14 @@ dim_reduce_func_def!(" let c = product(&a, 1); print(&c); ``` - ", product, af_product, T::AggregateOutType); + ", + product, + af_product, + T::AggregateOutType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Find minimum among elements of given dimension # Parameters @@ -144,9 +171,14 @@ dim_reduce_func_def!(" let c = min(&a, 1); print(&c); ``` - ", min, af_min, T::InType); + ", + min, + af_min, + T::InType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Find maximum among elements of given dimension # Parameters @@ -170,9 +202,14 @@ dim_reduce_func_def!(" let c = max(&a, 1); print(&c); ``` - ", max, af_max, T::InType); + ", + max, + af_max, + T::InType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Find if all of the values along a given dimension in the Array are true # Parameters @@ -196,9 +233,14 @@ dim_reduce_func_def!(" let c = all_true(&a, 1); print(&c); ``` - ", all_true, af_all_true, bool); + ", + all_true, + af_all_true, + bool +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Find if any of the values along a given dimension in the Array are true # Parameters @@ -222,9 +264,14 @@ dim_reduce_func_def!(" let c = any_true(&a, 1); print(&c); ``` - ", any_true, af_any_true, bool); + ", + any_true, + af_any_true, + bool +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Count number of non-zero elements along a given dimension # Parameters @@ -249,9 +296,14 @@ dim_reduce_func_def!(" let c = count(&a, 1); print(&c); ``` - ", count, af_count, u32); + ", + count, + af_count, + u32 +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Perform exclusive sum of elements along a given dimension # Parameters @@ -275,9 +327,14 @@ dim_reduce_func_def!(" let c = accum(&a, 1); print(&c); ``` - ", accum, af_accum, T::AggregateOutType); + ", + accum, + af_accum, + T::AggregateOutType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Calculate first order numerical difference along a given dimension # Parameters @@ -301,9 +358,14 @@ dim_reduce_func_def!(" let c = diff1(&a, 1); print(&c); ``` - ", diff1, af_diff1, T::InType); + ", + diff1, + af_diff1, + T::InType +); -dim_reduce_func_def!(" +dim_reduce_func_def!( + " Calculate second order numerical difference along a given dimension # Parameters @@ -327,7 +389,11 @@ dim_reduce_func_def!(" let c = diff2(&a, 1); print(&c); ``` - ", diff2, af_diff2, T::InType); + ", + diff2, + af_diff2, + T::InType +); /// Sum along specific dimension using user specified value instead of `NAN` values /// @@ -343,15 +409,19 @@ dim_reduce_func_def!(" /// # Return Values /// /// Array that is reduced along given dimension via addition operation -pub fn sum_nan(input: &Array, - dim: i32, nanval: f64) -> Array< T::AggregateOutType > - where T: HasAfEnum, - T::AggregateOutType: HasAfEnum +pub fn sum_nan(input: &Array, dim: i32, nanval: f64) -> Array +where + T: HasAfEnum, + T::AggregateOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_sum_nan(&mut temp as MutAfArray, input.get() as AfArray, - dim as c_int, nanval as c_double); + let err_val = af_sum_nan( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + nanval as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -370,39 +440,46 @@ pub fn sum_nan(input: &Array, /// # Return Values /// /// Array that is reduced along given dimension via multiplication operation -pub fn product_nan(input: &Array, - dim: i32, nanval: f64) -> Array< T::AggregateOutType > - where T: HasAfEnum, - T::AggregateOutType: HasAfEnum +pub fn product_nan(input: &Array, dim: i32, nanval: f64) -> Array +where + T: HasAfEnum, + T::AggregateOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_product_nan(&mut temp as MutAfArray, input.get() as AfArray, - dim as c_int, nanval as c_double); + let err_val = af_product_nan( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + nanval as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! all_reduce_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str] #[allow(unused_mut)] - pub fn $fn_name(input: &Array) -> (f64, f64) { + pub fn $fn_name(input: &Array) -> (f64, f64) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = $ffi_name(&mut real as MutDouble, - &mut imag as MutDouble, - input.get() as AfArray); + let err_val = $ffi_name( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } - ) + }; } -all_reduce_func_def!(" +all_reduce_func_def!( + " Sum all values of the Array # Parameters @@ -424,9 +501,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", sum_all(&a)); ``` - ", sum_all, af_sum_all); + ", + sum_all, + af_sum_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Product of all values of the Array # Parameters @@ -448,9 +529,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", product_all(&a)); ``` - ", product_all, af_product_all); + ", + product_all, + af_product_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Find minimum among all values of the Array # Parameters @@ -472,9 +557,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", min_all(&a)); ``` - ", min_all, af_min_all); + ", + min_all, + af_min_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Find maximum among all values of the Array # Parameters @@ -496,9 +585,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", max_all(&a)); ``` - ", max_all, af_max_all); + ", + max_all, + af_max_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Find if all values of Array are non-zero # Parameters @@ -518,9 +611,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", all_true_all(&a)); ``` - ", all_true_all, af_all_true_all); + ", + all_true_all, + af_all_true_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Find if any value of Array is non-zero # Parameters @@ -540,9 +637,13 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", any_true_all(&a)); ``` - ", any_true_all, af_any_true_all); + ", + any_true_all, + af_any_true_all +); -all_reduce_func_def!(" +all_reduce_func_def!( + " Count number of non-zero values in the Array # Parameters @@ -562,7 +663,10 @@ all_reduce_func_def!(" print(&a); println!(\"Result : {:?}\", count_all(&a)); ``` - ", count_all, af_count_all); + ", + count_all, + af_count_all +); /// Sum all values using user provided value for `NAN` /// @@ -583,8 +687,12 @@ pub fn sum_nan_all(input: &Array, val: f64) -> (f64, f64) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_sum_nan_all(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray, val as c_double); + let err_val = af_sum_nan_all( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + val as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) @@ -609,31 +717,40 @@ pub fn product_nan_all(input: &Array, val: f64) -> (f64, f64) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_product_nan_all(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray, val as c_double); + let err_val = af_product_nan_all( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + val as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } macro_rules! dim_ireduce_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident, $out_type: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident, $out_type: ident) => { #[doc=$doc_str] #[allow(unused_mut)] - pub fn $fn_name(input: &Array, dim: i32) -> (Array< T::$out_type >, Array) - where T: HasAfEnum, - T::$out_type: HasAfEnum + pub fn $fn_name(input: &Array, dim: i32) -> (Array, Array) + where + T: HasAfEnum, + T::$out_type: HasAfEnum, { let mut temp: i64 = 0; let mut idx: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, &mut idx as MutAfArray, - input.get() as AfArray, dim as c_int); + let err_val = $ffi_name( + &mut temp as MutAfArray, + &mut idx as MutAfArray, + input.get() as AfArray, + dim as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (temp.into(), idx.into()) } - ) + }; } dim_ireduce_func_def!(" @@ -663,24 +780,29 @@ dim_ireduce_func_def!(" ", imax, af_imax, InType); macro_rules! all_ireduce_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str] #[allow(unused_mut)] - pub fn $fn_name(input: &Array) -> (f64, f64, u32) { + pub fn $fn_name(input: &Array) -> (f64, f64, u32) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; let mut temp: u32 = 0; unsafe { - let err_val = $ffi_name(&mut real as MutDouble, &mut imag as MutDouble, - &mut temp as MutUint, input.get() as AfArray); + let err_val = $ffi_name( + &mut real as MutDouble, + &mut imag as MutDouble, + &mut temp as MutUint, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag, temp) } - ) + }; } -all_ireduce_func_def!(" +all_ireduce_func_def!( + " Find minimum and it's index in the whole Array # Parameters @@ -694,8 +816,12 @@ all_ireduce_func_def!(" * minimum element of Array in the first component. * second component of value zero if Array is of non-complex type. * index of minimum element in the third component. - ", imin_all, af_imin_all); -all_ireduce_func_def!(" + ", + imin_all, + af_imin_all +); +all_ireduce_func_def!( + " Find maximum and it's index in the whole Array # Parameters @@ -709,7 +835,10 @@ all_ireduce_func_def!(" - maximum element of Array in the first component. - second component of value zero if Array is of non-complex type. - index of maximum element in the third component. - ", imax_all, af_imax_all); + ", + imax_all, + af_imax_all +); /// Locate the indices of non-zero elements. /// @@ -723,7 +852,7 @@ all_ireduce_func_def!(" /// /// Array of indices where the input Array has non-zero values. #[allow(unused_mut)] -pub fn locate(input: &Array) -> Array { +pub fn locate(input: &Array) -> Array { let mut temp: i64 = 0; unsafe { let err_val = af_where(&mut temp as MutAfArray, input.get() as AfArray); @@ -748,12 +877,17 @@ pub fn locate(input: &Array) -> Array { /// Sorted Array. #[allow(unused_mut)] pub fn sort(input: &Array, dim: u32, ascending: bool) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_sort(&mut temp as MutAfArray, input.get() as AfArray, - dim as c_uint, ascending as c_int); + let err_val = af_sort( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_uint, + ascending as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -777,15 +911,19 @@ pub fn sort(input: &Array, dim: u32, ascending: bool) -> Array /// The second Array contains the original indices of the sorted values. #[allow(unused_mut)] pub fn sort_index(input: &Array, dim: u32, ascending: bool) -> (Array, Array) - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; let mut idx: i64 = 0; unsafe { - let err_val = af_sort_index(&mut temp as MutAfArray, - &mut idx as MutAfArray, - input.get() as AfArray, - dim as c_uint, ascending as c_int); + let err_val = af_sort_index( + &mut temp as MutAfArray, + &mut idx as MutAfArray, + input.get() as AfArray, + dim as c_uint, + ascending as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (temp.into(), idx.into()) @@ -810,19 +948,27 @@ pub fn sort_index(input: &Array, dim: u32, ascending: bool) -> (Array, /// /// The second Array contains the sorted values. #[allow(unused_mut)] -pub fn sort_by_key(keys: &Array, vals: &Array, dim: u32, - ascending: bool) -> (Array, Array) - where K: HasAfEnum + RealNumber, - V: HasAfEnum +pub fn sort_by_key( + keys: &Array, + vals: &Array, + dim: u32, + ascending: bool, +) -> (Array, Array) +where + K: HasAfEnum + RealNumber, + V: HasAfEnum, { let mut temp: i64 = 0; let mut temp2: i64 = 0; unsafe { - let err_val = af_sort_by_key(&mut temp as MutAfArray, - &mut temp2 as MutAfArray, - keys.get() as AfArray, - vals.get() as AfArray, - dim as c_uint, ascending as c_int); + let err_val = af_sort_by_key( + &mut temp as MutAfArray, + &mut temp2 as MutAfArray, + keys.get() as AfArray, + vals.get() as AfArray, + dim as c_uint, + ascending as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (temp.into(), temp2.into()) @@ -841,13 +987,16 @@ pub fn sort_by_key(keys: &Array, vals: &Array, dim: u32, /// An Array of unique values from the input Array. #[allow(unused_mut)] pub fn set_unique(input: &Array, is_sorted: bool) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_set_unique(&mut temp as MutAfArray, - input.get() as AfArray, - is_sorted as c_int); + let err_val = af_set_unique( + &mut temp as MutAfArray, + input.get() as AfArray, + is_sorted as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -866,12 +1015,17 @@ pub fn set_unique(input: &Array, is_sorted: bool) -> Array /// An Array with union of the input sets #[allow(unused_mut)] pub fn set_union(first: &Array, second: &Array, is_unique: bool) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_set_union(&mut temp as MutAfArray, first.get() as AfArray, - second.get() as AfArray, is_unique as c_int); + let err_val = af_set_union( + &mut temp as MutAfArray, + first.get() as AfArray, + second.get() as AfArray, + is_unique as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -890,12 +1044,17 @@ pub fn set_union(first: &Array, second: &Array, is_unique: bool) -> Arr /// An Array with intersection of the input sets #[allow(unused_mut)] pub fn set_intersect(first: &Array, second: &Array, is_unique: bool) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_set_intersect(&mut temp as MutAfArray, first.get() as AfArray, - second.get() as AfArray, is_unique as c_int); + let err_val = af_set_intersect( + &mut temp as MutAfArray, + first.get() as AfArray, + second.get() as AfArray, + is_unique as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -914,15 +1073,25 @@ pub fn set_intersect(first: &Array, second: &Array, is_unique: bool) -> /// # Return Values /// /// Output Array of scanned input -pub fn scan(input: &Array, dim: i32, - op: BinaryOp, inclusive: bool) -> Array< T::AggregateOutType > - where T: HasAfEnum, - T::AggregateOutType: HasAfEnum +pub fn scan( + input: &Array, + dim: i32, + op: BinaryOp, + inclusive: bool, +) -> Array +where + T: HasAfEnum, + T::AggregateOutType: HasAfEnum, { - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_scan(&mut temp as MutAfArray, input.get() as AfArray, - dim as c_int, op as c_uint, inclusive as c_int); + let err_val = af_scan( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + op as c_uint, + inclusive as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -942,18 +1111,28 @@ pub fn scan(input: &Array, dim: i32, /// # Return Values /// /// Output Array of scanned input -pub fn scan_by_key(key: &Array, input: &Array, - dim: i32, op: BinaryOp, - inclusive: bool) -> Array< V::AggregateOutType > - where V: HasAfEnum, - V::AggregateOutType: HasAfEnum, - K: HasAfEnum + Scanable +pub fn scan_by_key( + key: &Array, + input: &Array, + dim: i32, + op: BinaryOp, + inclusive: bool, +) -> Array +where + V: HasAfEnum, + V::AggregateOutType: HasAfEnum, + K: HasAfEnum + Scanable, { - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_scan_by_key(&mut temp as MutAfArray, key.get() as AfArray, - input.get() as AfArray, dim as c_int, - op as c_uint, inclusive as c_int); + let err_val = af_scan_by_key( + &mut temp as MutAfArray, + key.get() as AfArray, + input.get() as AfArray, + dim as c_int, + op as c_uint, + inclusive as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() diff --git a/src/arith/mod.rs b/src/arith/mod.rs index ea460157d..8d7eebc6d 100644 --- a/src/arith/mod.rs +++ b/src/arith/mod.rs @@ -1,20 +1,20 @@ extern crate libc; extern crate num; -use dim4::Dim4; -use array::Array; -use defines::{AfError}; -use error::HANDLE_ERROR; -use self::libc::{c_int}; -use data::{constant, ConstGenerator, tile}; +use self::libc::c_int; use self::num::Complex; -use num::Zero; -use util::{AfArray, HasAfEnum, ImplicitPromote, MutAfArray}; +use crate::array::Array; +use crate::data::{constant, tile, ConstGenerator}; +use crate::defines::AfError; +use crate::dim4::Dim4; +use crate::error::HANDLE_ERROR; +use crate::num::Zero; +use crate::util::{AfArray, HasAfEnum, ImplicitPromote, MutAfArray}; use std::ops::Neg; -use std::ops::{Add, Sub, Div, Mul, BitAnd, BitOr, BitXor, Not, Rem, Shl, Shr}; +use std::ops::{Add, BitAnd, BitOr, BitXor, Div, Mul, Not, Rem, Shl, Shr, Sub}; #[allow(dead_code)] -extern { +extern "C" { fn af_add(out: MutAfArray, lhs: AfArray, rhs: AfArray, batch: c_int) -> c_int; fn af_sub(out: MutAfArray, lhs: AfArray, rhs: AfArray, batch: c_int) -> c_int; fn af_mul(out: MutAfArray, lhs: AfArray, rhs: AfArray, batch: c_int) -> c_int; @@ -96,15 +96,15 @@ extern { /// Enables use of `!` on objects of type [Array](./struct.Array.html) impl<'f, T> Not for &'f Array - where T: HasAfEnum +where + T: HasAfEnum, { type Output = Array; fn not(self) -> Self::Output { let mut temp: i64 = 0; unsafe { - let err_val = af_not(&mut temp as MutAfArray, - self.get() as AfArray); + let err_val = af_not(&mut temp as MutAfArray, self.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -132,25 +132,54 @@ macro_rules! unary_func { unary_func!("Computes absolute value", abs, af_abs, AbsOutType); unary_func!("Computes phase value", arg, af_arg, ArgOutType); -unary_func!("Truncate the values in an Array", trunc, af_trunc, AbsOutType); -unary_func!("Computes the sign of input Array values", sign, af_sign, AbsOutType); +unary_func!( + "Truncate the values in an Array", + trunc, + af_trunc, + AbsOutType +); +unary_func!( + "Computes the sign of input Array values", + sign, + af_sign, + AbsOutType +); unary_func!("Round the values in an Array", round, af_round, AbsOutType); unary_func!("Floor the values in an Array", floor, af_floor, AbsOutType); unary_func!("Ceil the values in an Array", ceil, af_ceil, AbsOutType); unary_func!("Compute sigmoid function", sigmoid, af_sigmoid, AbsOutType); -unary_func!("Compute e raised to the power of value -1", expm1, af_expm1, AbsOutType); +unary_func!( + "Compute e raised to the power of value -1", + expm1, + af_expm1, + AbsOutType +); unary_func!("Compute error function value", erf, af_erf, AbsOutType); -unary_func!("Compute the complementary error function value", erfc, af_erfc, AbsOutType); +unary_func!( + "Compute the complementary error function value", + erfc, + af_erfc, + AbsOutType +); unary_func!("Compute logarithm base 10", log10, af_log10, AbsOutType); -unary_func!("Compute the logarithm of input Array + 1", log1p, af_log1p, AbsOutType); +unary_func!( + "Compute the logarithm of input Array + 1", + log1p, + af_log1p, + AbsOutType +); unary_func!("Compute logarithm base 2", log2, af_log2, AbsOutType); unary_func!("Compute the cube root", cbrt, af_cbrt, AbsOutType); unary_func!("Compute gamma function", tgamma, af_tgamma, AbsOutType); -unary_func!("Compute the logarithm of absolute values of gamma function", - lgamma, af_lgamma, AbsOutType); +unary_func!( + "Compute the logarithm of absolute values of gamma function", + lgamma, + af_lgamma, + AbsOutType +); unary_func!("Compute acosh", acosh, af_acosh, UnaryOutType); unary_func!("Compute acos", acos, af_acos, UnaryOutType); @@ -160,7 +189,12 @@ unary_func!("Compute atan", atan, af_atan, UnaryOutType); unary_func!("Compute atanh", atanh, af_atanh, UnaryOutType); unary_func!("Compute cos", cos, af_cos, UnaryOutType); unary_func!("Compute cosh", cosh, af_cosh, UnaryOutType); -unary_func!("Compute e raised to the power of value", exp, af_exp, UnaryOutType); +unary_func!( + "Compute e raised to the power of value", + exp, + af_exp, + UnaryOutType +); unary_func!("Compute the natural logarithm", log, af_log, UnaryOutType); unary_func!("Compute sin", sin, af_sin, UnaryOutType); unary_func!("Compute sinh", sinh, af_sinh, UnaryOutType); @@ -168,12 +202,42 @@ unary_func!("Compute the square root", sqrt, af_sqrt, UnaryOutType); unary_func!("Compute tan", tan, af_tan, UnaryOutType); unary_func!("Compute tanh", tanh, af_tanh, UnaryOutType); -unary_func!("Extract real values from a complex Array", real, af_real, AbsOutType); -unary_func!("Extract imaginary values from a complex Array", imag, af_imag, AbsOutType); -unary_func!("Create a complex Array from real Array", cplx, af_cplx, ComplexOutType); -unary_func!("Compute the complex conjugate", conjg, af_conjg, ComplexOutType); -unary_func!("Compute two raised to the power of value", pow2, af_pow2, UnaryOutType); -unary_func!("Compute the factorial", factorial, af_factorial, UnaryOutType); +unary_func!( + "Extract real values from a complex Array", + real, + af_real, + AbsOutType +); +unary_func!( + "Extract imaginary values from a complex Array", + imag, + af_imag, + AbsOutType +); +unary_func!( + "Create a complex Array from real Array", + cplx, + af_cplx, + ComplexOutType +); +unary_func!( + "Compute the complex conjugate", + conjg, + af_conjg, + ComplexOutType +); +unary_func!( + "Compute two raised to the power of value", + pow2, + af_pow2, + UnaryOutType +); +unary_func!( + "Compute the factorial", + factorial, + af_factorial, + UnaryOutType +); macro_rules! unary_boolean_func { [$doc_str: expr, $fn_name: ident, $ffi_fn: ident] => ( @@ -197,39 +261,73 @@ unary_boolean_func!("Check if values are infinity", isinf, af_isinf); unary_boolean_func!("Check if values are NaN", isnan, af_isnan); macro_rules! binary_func { - ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => { #[doc=$doc_str] /// /// This is an element wise binary operation. #[allow(unused_mut)] - pub fn $fn_name(lhs: &Array, - rhs: &Array, - batch: bool) -> Array< A::Output > - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + pub fn $fn_name(lhs: &Array, rhs: &Array, batch: bool) -> Array + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_fn(&mut temp as MutAfArray, - lhs.get() as AfArray, rhs.get() as AfArray, - batch as c_int); + let err_val = $ffi_fn( + &mut temp as MutAfArray, + lhs.get() as AfArray, + rhs.get() as AfArray, + batch as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } - Into::< Array< A::Output> >::into(temp) + Into::>::into(temp) } - ) + }; } -binary_func!("Elementwise AND(bit) operation of two Arrays", bitand, af_bitand); -binary_func!("Elementwise OR(bit) operation of two Arrays", bitor, af_bitor); -binary_func!("Elementwise XOR(bit) operation of two Arrays", bitxor, af_bitxor); -binary_func!("Elementwise not equals comparison of two Arrays", neq, af_neq); -binary_func!("Elementwise logical and operation of two Arrays", and, af_and); +binary_func!( + "Elementwise AND(bit) operation of two Arrays", + bitand, + af_bitand +); +binary_func!( + "Elementwise OR(bit) operation of two Arrays", + bitor, + af_bitor +); +binary_func!( + "Elementwise XOR(bit) operation of two Arrays", + bitxor, + af_bitxor +); +binary_func!( + "Elementwise not equals comparison of two Arrays", + neq, + af_neq +); +binary_func!( + "Elementwise logical and operation of two Arrays", + and, + af_and +); binary_func!("Elementwise logical or operation of two Arrays", or, af_or); -binary_func!("Elementwise minimum operation of two Arrays", minof, af_minof); -binary_func!("Elementwise maximum operation of two Arrays", maxof, af_maxof); -binary_func!("Compute length of hypotenuse of two Arrays", hypot, af_hypot); +binary_func!( + "Elementwise minimum operation of two Arrays", + minof, + af_minof +); +binary_func!( + "Elementwise maximum operation of two Arrays", + maxof, + af_maxof +); +binary_func!( + "Compute length of hypotenuse of two Arrays", + hypot, + af_hypot +); /// Type Trait to convert to an [Array](./struct.Array.html) /// @@ -259,20 +357,21 @@ pub trait Convertable { type OutType; /// Get an Array of implementors type - fn convert(&self) -> Array< Self::OutType > - where ::OutType: HasAfEnum; + fn convert(&self) -> Array + where + ::OutType: HasAfEnum; } macro_rules! convertable_type_def { - ($rust_type: ty) => ( + ($rust_type: ty) => { impl Convertable for $rust_type { type OutType = $rust_type; - fn convert(&self) -> Array< Self::OutType > { - constant(*self, Dim4::new(&[1,1,1,1])) + fn convert(&self) -> Array { + constant(*self, Dim4::new(&[1, 1, 1, 1])) } } - ) + }; } convertable_type_def!(Complex); @@ -291,25 +390,27 @@ convertable_type_def!(bool); impl Convertable for Array { type OutType = T; - fn convert(&self) -> Array< Self::OutType > { + fn convert(&self) -> Array { self.clone() } } macro_rules! overloaded_binary_func { - ($doc_str: expr, $fn_name: ident, $help_name: ident, $ffi_name: ident) => ( - fn $help_name(lhs: &Array, - rhs: &Array, - batch: bool) -> Array< A::Output > - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + ($doc_str: expr, $fn_name: ident, $help_name: ident, $ffi_name: ident) => { + fn $help_name(lhs: &Array, rhs: &Array, batch: bool) -> Array + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, - lhs.get() as AfArray, rhs.get() as AfArray, - batch as c_int); + let err_val = $ffi_name( + &mut temp as MutAfArray, + lhs.get() as AfArray, + rhs.get() as AfArray, + batch as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -346,29 +447,36 @@ macro_rules! overloaded_binary_func { ///# Note /// /// The trait `Convertable` essentially translates to a scalar native type on rust or Array. - pub fn $fn_name (arg1: &T, arg2: &U, batch: bool) - -> Array< <::OutType as ImplicitPromote<::OutType>>::Output > - where T: Convertable, - U: Convertable, - ::OutType: HasAfEnum + ImplicitPromote<::OutType>, - ::OutType: HasAfEnum + ImplicitPromote<::OutType>, - <::OutType as ImplicitPromote<::OutType>>::Output: HasAfEnum + pub fn $fn_name( + arg1: &T, + arg2: &U, + batch: bool, + ) -> Array< + <::OutType as ImplicitPromote<::OutType>>::Output, + > + where + T: Convertable, + U: Convertable, + ::OutType: HasAfEnum + ImplicitPromote<::OutType>, + ::OutType: HasAfEnum + ImplicitPromote<::OutType>, + <::OutType as ImplicitPromote<::OutType>>::Output: + HasAfEnum, { let lhs = arg1.convert(); // Convert to Array let rhs = arg2.convert(); // Convert to Array match (lhs.is_scalar(), rhs.is_scalar()) { - ( true, false) => { + (true, false) => { let l = tile(&lhs, rhs.dims()); $help_name(&l, &rhs, batch) - }, - (false, true) => { + } + (false, true) => { let r = tile(&rhs, lhs.dims()); $help_name(&lhs, &r, batch) - }, + } _ => $help_name(&lhs, &rhs, batch), } } - ) + }; } overloaded_binary_func!("Addition of two Arrays", add, add_helper, af_add); @@ -378,28 +486,77 @@ overloaded_binary_func!("Division of two Arrays", div, div_helper, af_div); overloaded_binary_func!("Compute remainder from two Arrays", rem, rem_helper, af_rem); overloaded_binary_func!("Compute left shift", shiftl, shiftl_helper, af_bitshiftl); overloaded_binary_func!("Compute right shift", shiftr, shiftr_helper, af_bitshiftr); -overloaded_binary_func!("Perform `less than` comparison operation", lt, lt_helper, af_lt); -overloaded_binary_func!("Perform `greater than` comparison operation", gt, gt_helper, af_gt); -overloaded_binary_func!("Perform `less than equals` comparison operation", le, le_helper, af_le); -overloaded_binary_func!("Perform `greater than equals` comparison operation", ge, ge_helper, af_ge); -overloaded_binary_func!("Perform `equals` comparison operation", eq, eq_helper, af_eq); -overloaded_binary_func!("Compute modulo of two Arrays", modulo, modulo_helper, af_mod); -overloaded_binary_func!("Calculate atan2 of two Arrays", atan2, atan2_helper, af_atan2); -overloaded_binary_func!("Create complex array from two Arrays", cplx2, cplx2_helper, af_cplx2); +overloaded_binary_func!( + "Perform `less than` comparison operation", + lt, + lt_helper, + af_lt +); +overloaded_binary_func!( + "Perform `greater than` comparison operation", + gt, + gt_helper, + af_gt +); +overloaded_binary_func!( + "Perform `less than equals` comparison operation", + le, + le_helper, + af_le +); +overloaded_binary_func!( + "Perform `greater than equals` comparison operation", + ge, + ge_helper, + af_ge +); +overloaded_binary_func!( + "Perform `equals` comparison operation", + eq, + eq_helper, + af_eq +); +overloaded_binary_func!( + "Compute modulo of two Arrays", + modulo, + modulo_helper, + af_mod +); +overloaded_binary_func!( + "Calculate atan2 of two Arrays", + atan2, + atan2_helper, + af_atan2 +); +overloaded_binary_func!( + "Create complex array from two Arrays", + cplx2, + cplx2_helper, + af_cplx2 +); overloaded_binary_func!("Compute root", root, root_helper, af_root); overloaded_binary_func!("Computer power", pow, pow_helper, af_pow); -fn clamp_helper(inp: &Array, lo: &Array, hi: &Array, batch: bool) - -> Array< >::Output > - where X: HasAfEnum + ImplicitPromote, - Y: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum +fn clamp_helper( + inp: &Array, + lo: &Array, + hi: &Array, + batch: bool, +) -> Array<>::Output> +where + X: HasAfEnum + ImplicitPromote, + Y: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_clamp(&mut temp as MutAfArray, inp.get() as AfArray, - lo.get() as AfArray, hi.get() as AfArray, - batch as c_int); + let err_val = af_clamp( + &mut temp as MutAfArray, + inp.get() as AfArray, + lo.get() as AfArray, + hi.get() as AfArray, + batch as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -423,41 +580,47 @@ fn clamp_helper(inp: &Array, lo: &Array, hi: &Array, batch: bool) /// # Note /// /// The trait `Convertable` essentially translates to a scalar native type on rust or Array. -pub fn clamp(input: &Array, arg1: &C, arg2: &C, batch: bool) - -> Array< ::OutType>>::Output > - where T: HasAfEnum + ImplicitPromote<::OutType>, - C: Convertable, - ::OutType: HasAfEnum + ImplicitPromote, - ::OutType>>::Output: HasAfEnum +pub fn clamp( + input: &Array, + arg1: &C, + arg2: &C, + batch: bool, +) -> Array<::OutType>>::Output> +where + T: HasAfEnum + ImplicitPromote<::OutType>, + C: Convertable, + ::OutType: HasAfEnum + ImplicitPromote, + ::OutType>>::Output: HasAfEnum, { let lo = arg1.convert(); // Convert to Array let hi = arg2.convert(); // Convert to Array match (lo.is_scalar(), hi.is_scalar()) { - ( true, false) => { + (true, false) => { let l = tile(&lo, hi.dims()); clamp_helper(&input, &l, &hi, batch) - }, - (false, true) => { + } + (false, true) => { let r = tile(&hi, lo.dims()); clamp_helper(&input, &lo, &r, batch) - }, - ( true, true) => { + } + (true, true) => { let l = tile(&lo, input.dims()); let r = tile(&hi, input.dims()); clamp_helper(&input, &l, &r, batch) - }, + } _ => clamp_helper(&input, &lo, &hi, batch), } } macro_rules! arith_scalar_func { - ($rust_type: ty, $op_name:ident, $fn_name: ident) => ( + ($rust_type: ty, $op_name:ident, $fn_name: ident) => { impl<'f, T> $op_name<$rust_type> for &'f Array - where T: HasAfEnum + ImplicitPromote<$rust_type>, - $rust_type: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + T: HasAfEnum + ImplicitPromote<$rust_type>, + $rust_type: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: $rust_type) -> Self::Output { let temp = rhs.clone(); @@ -466,27 +629,28 @@ macro_rules! arith_scalar_func { } impl $op_name<$rust_type> for Array - where T: HasAfEnum + ImplicitPromote<$rust_type>, - $rust_type: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + T: HasAfEnum + ImplicitPromote<$rust_type>, + $rust_type: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: $rust_type) -> Self::Output { let temp = rhs.clone(); $fn_name(&self, &temp, false) } } - ) + }; } macro_rules! arith_scalar_spec { - ($ty_name:ty) => ( + ($ty_name:ty) => { arith_scalar_func!($ty_name, Add, add); arith_scalar_func!($ty_name, Sub, sub); arith_scalar_func!($ty_name, Mul, mul); arith_scalar_func!($ty_name, Div, div); - ) + }; } arith_scalar_spec!(Complex); @@ -500,13 +664,14 @@ arith_scalar_spec!(i32); arith_scalar_spec!(u8); macro_rules! arith_func { - ($op_name:ident, $fn_name:ident, $delegate:ident) => ( + ($op_name:ident, $fn_name:ident, $delegate:ident) => { impl $op_name> for Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: Array) -> Self::Output { $delegate(&self, &rhs, false) @@ -514,11 +679,12 @@ macro_rules! arith_func { } impl<'a, A, B> $op_name<&'a Array> for Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: &'a Array) -> Self::Output { $delegate(&self, rhs, false) @@ -526,11 +692,12 @@ macro_rules! arith_func { } impl<'a, A, B> $op_name> for &'a Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: Array) -> Self::Output { $delegate(self, &rhs, false) @@ -538,110 +705,114 @@ macro_rules! arith_func { } impl<'a, 'b, A, B> $op_name<&'a Array> for &'b Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, { - type Output = Array< >::Output >; + type Output = Array<>::Output>; fn $fn_name(self, rhs: &'a Array) -> Self::Output { $delegate(self, rhs, false) } } - ) + }; } -arith_func!(Add , add , add ); -arith_func!(Sub , sub , sub ); -arith_func!(Mul , mul , mul ); -arith_func!(Div , div , div ); -arith_func!(Rem , rem , rem ); -arith_func!(Shl , shl , shiftl); -arith_func!(Shr , shr , shiftr); +arith_func!(Add, add, add); +arith_func!(Sub, sub, sub); +arith_func!(Mul, mul, mul); +arith_func!(Div, div, div); +arith_func!(Rem, rem, rem); +arith_func!(Shl, shl, shiftl); +arith_func!(Shr, shr, shiftr); arith_func!(BitAnd, bitand, bitand); -arith_func!(BitOr , bitor , bitor ); +arith_func!(BitOr, bitor, bitor); arith_func!(BitXor, bitxor, bitxor); #[cfg(op_assign)] mod op_assign { -use array::Array; -use super::*; -use index::{Indexer, assign_gen}; -use seq::Seq; -use std::mem; -use std::ops::{AddAssign, SubAssign, DivAssign, MulAssign, RemAssign}; -use std::ops::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign}; - -macro_rules! arith_assign_func { - ($op_name:ident, $fn_name:ident, $func: ident) => ( - impl $op_name> for Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum, - >::Output: HasAfEnum - { - #[allow(unused_variables)] - fn $fn_name(&mut self, rhs: Array) { - let tmp_seq = Seq::::default(); - let mut idxrs = Indexer::new(); - for n in 0..self.numdims() { - idxrs.set_index(&tmp_seq, n, Some(false)); + use super::*; + use crate::array::Array; + use crate::index::{assign_gen, Indexer}; + use crate::seq::Seq; + use std::mem; + use std::ops::{AddAssign, DivAssign, MulAssign, RemAssign, SubAssign}; + use std::ops::{BitAndAssign, BitOrAssign, BitXorAssign, ShlAssign, ShrAssign}; + + macro_rules! arith_assign_func { + ($op_name:ident, $fn_name:ident, $func: ident) => { + impl $op_name> for Array + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, + >::Output: HasAfEnum, + { + #[allow(unused_variables)] + fn $fn_name(&mut self, rhs: Array) { + let tmp_seq = Seq::::default(); + let mut idxrs = Indexer::new(); + for n in 0..self.numdims() { + idxrs.set_index(&tmp_seq, n, Some(false)); + } + let opres = $func(self as &Array, &rhs, false).cast::(); + let tmp = assign_gen(self as &Array, &idxrs, &opres); + let old = mem::replace(self, tmp); } - let opres = $func(self as &Array, &rhs, false).cast::(); - let tmp = assign_gen(self as &Array, &idxrs, &opres); - let old = mem::replace(self, tmp); } - } - ) -} + }; + } -arith_assign_func!(AddAssign, add_assign, add); -arith_assign_func!(SubAssign, sub_assign, sub); -arith_assign_func!(MulAssign, mul_assign, mul); -arith_assign_func!(DivAssign, div_assign, div); -arith_assign_func!(RemAssign, rem_assign, rem); -arith_assign_func!(ShlAssign, shl_assign, shiftl); -arith_assign_func!(ShrAssign, shr_assign, shiftr); - -macro_rules! bit_assign_func { - ($op_name:ident, $fn_name:ident, $func: ident) => ( - impl $op_name> for Array - where A: HasAfEnum + ImplicitPromote, - B: HasAfEnum + ImplicitPromote, - >::Output: HasAfEnum, - >::Output: HasAfEnum - { - #[allow(unused_variables)] - fn $fn_name(&mut self, rhs: Array) { - let tmp_seq = Seq::::default(); - let mut idxrs = Indexer::new(); - for n in 0..self.numdims() { - idxrs.set_index(&tmp_seq, n, Some(false)); + arith_assign_func!(AddAssign, add_assign, add); + arith_assign_func!(SubAssign, sub_assign, sub); + arith_assign_func!(MulAssign, mul_assign, mul); + arith_assign_func!(DivAssign, div_assign, div); + arith_assign_func!(RemAssign, rem_assign, rem); + arith_assign_func!(ShlAssign, shl_assign, shiftl); + arith_assign_func!(ShrAssign, shr_assign, shiftr); + + macro_rules! bit_assign_func { + ($op_name:ident, $fn_name:ident, $func: ident) => { + impl $op_name> for Array + where + A: HasAfEnum + ImplicitPromote, + B: HasAfEnum + ImplicitPromote, + >::Output: HasAfEnum, + >::Output: HasAfEnum, + { + #[allow(unused_variables)] + fn $fn_name(&mut self, rhs: Array) { + let tmp_seq = Seq::::default(); + let mut idxrs = Indexer::new(); + for n in 0..self.numdims() { + idxrs.set_index(&tmp_seq, n, Some(false)); + } + let opres = $func(self as &Array, &rhs, false).cast::(); + let tmp = assign_gen(self as &Array, &idxrs, &opres); + let old = mem::replace(self, tmp); } - let opres = $func(self as &Array, &rhs, false).cast::(); - let tmp = assign_gen(self as &Array, &idxrs, &opres); - let old = mem::replace(self, tmp); } - } - ) -} + }; + } -bit_assign_func!(BitAndAssign, bitand_assign, bitand); -bit_assign_func!(BitOrAssign, bitor_assign, bitor); -bit_assign_func!(BitXorAssign, bitxor_assign, bitxor); + bit_assign_func!(BitAndAssign, bitand_assign, bitand); + bit_assign_func!(BitOrAssign, bitor_assign, bitor); + bit_assign_func!(BitXorAssign, bitxor_assign, bitxor); } ///Implement negation trait for Array impl Neg for Array - where T: HasAfEnum+Zero+ConstGenerator, - ::OutType: HasAfEnum, - ::OutType: ImplicitPromote, - T: ImplicitPromote<::OutType>, - <::OutType as ImplicitPromote>::Output: HasAfEnum +where + T: HasAfEnum + Zero + ConstGenerator, + ::OutType: HasAfEnum, + ::OutType: ImplicitPromote, + T: ImplicitPromote<::OutType>, + <::OutType as ImplicitPromote>::Output: HasAfEnum, { - type Output = Array< <::OutType as ImplicitPromote>::Output >; + type Output = Array<<::OutType as ImplicitPromote>::Output>; fn neg(self) -> Self::Output { let cnst = constant(T::zero(), self.dims()); diff --git a/src/array.rs b/src/array.rs index bc94c7ae4..6ea64c42d 100644 --- a/src/array.rs +++ b/src/array.rs @@ -1,12 +1,12 @@ extern crate libc; -use dim4::Dim4; -use defines::{AfError, DType, Backend}; -use error::HANDLE_ERROR; -use util::{AfArray, DimT, HasAfEnum, MutAfArray, MutVoidPtr}; -use self::libc::{c_void, c_int, c_uint, c_longlong, c_char}; -use std::marker::PhantomData; +use self::libc::{c_char, c_int, c_longlong, c_uint, c_void}; +use crate::defines::{AfError, Backend, DType}; +use crate::dim4::Dim4; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, HasAfEnum, MutAfArray, MutVoidPtr}; use std::ffi::CString; +use std::marker::PhantomData; // Some unused functions from array.h in C-API of ArrayFire // af_copy_array @@ -14,18 +14,29 @@ use std::ffi::CString; // af_get_data_ref_count #[allow(dead_code)] -extern { - fn af_create_array(out: MutAfArray, data: *const c_void, - ndims: c_uint, dims: *const DimT, aftype: c_uint) -> c_int; - - fn af_create_handle(out: MutAfArray, ndims: c_uint, dims: *const DimT, aftype: c_uint) -> c_int; +extern "C" { + fn af_create_array( + out: MutAfArray, + data: *const c_void, + ndims: c_uint, + dims: *const DimT, + aftype: c_uint, + ) -> c_int; + + fn af_create_handle(out: MutAfArray, ndims: c_uint, dims: *const DimT, aftype: c_uint) + -> c_int; fn af_get_elements(out: MutAfArray, arr: AfArray) -> c_int; fn af_get_type(out: *mut c_uint, arr: AfArray) -> c_int; - fn af_get_dims(dim0: *mut c_longlong, dim1: *mut c_longlong, dim2: *mut c_longlong, - dim3: *mut c_longlong, arr: AfArray) -> c_int; + fn af_get_dims( + dim0: *mut c_longlong, + dim1: *mut c_longlong, + dim2: *mut c_longlong, + dim3: *mut c_longlong, + arr: AfArray, + ) -> c_int; fn af_get_numdims(result: *mut c_uint, arr: AfArray) -> c_int; @@ -81,12 +92,24 @@ extern { fn af_get_device_id(device: *mut c_int, input: AfArray) -> c_int; - fn af_create_strided_array(arr: MutAfArray, data: *const c_void, offset: DimT, - ndims: c_uint, dims: *const DimT, strides: *const DimT, - aftype: c_uint, stype: c_uint) -> c_int; - - fn af_get_strides(s0: *mut DimT, s1: *mut DimT, s2: *mut DimT, s3: *mut DimT, - arr: AfArray) -> c_int; + fn af_create_strided_array( + arr: MutAfArray, + data: *const c_void, + offset: DimT, + ndims: c_uint, + dims: *const DimT, + strides: *const DimT, + aftype: c_uint, + stype: c_uint, + ) -> c_int; + + fn af_get_strides( + s0: *mut DimT, + s1: *mut DimT, + s2: *mut DimT, + s3: *mut DimT, + arr: AfArray, + ) -> c_int; fn af_get_offset(offset: *mut DimT, arr: AfArray) -> c_int; @@ -135,7 +158,10 @@ macro_rules! is_func { ) } -impl Array where T: HasAfEnum { +impl Array +where + T: HasAfEnum, +{ /// Constructs a new Array object /// /// # Examples @@ -151,11 +177,13 @@ impl Array where T: HasAfEnum { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_create_array(&mut temp as MutAfArray, - slice.as_ptr() as *const c_void, - dims.ndims() as c_uint, - dims.get().as_ptr() as * const c_longlong, - aftype as c_uint); + let err_val = af_create_array( + &mut temp as MutAfArray, + slice.as_ptr() as *const c_void, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const c_longlong, + aftype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -165,18 +193,20 @@ impl Array where T: HasAfEnum { /// /// The data pointed by the slice passed to this function can possibily be offseted using an additional `offset` parameter. #[allow(unused_mut)] - pub fn new_strided(slice: &[T], offset: i64, - dims: Dim4, strides: Dim4) -> Array { + pub fn new_strided(slice: &[T], offset: i64, dims: Dim4, strides: Dim4) -> Array { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_create_strided_array(&mut temp as MutAfArray, - slice.as_ptr() as *const c_void, - offset as DimT, - dims.ndims() as c_uint, - dims.get().as_ptr() as * const c_longlong, - strides.get().as_ptr() as * const c_longlong, - aftype as c_uint, 1 as c_uint); + let err_val = af_create_strided_array( + &mut temp as MutAfArray, + slice.as_ptr() as *const c_void, + offset as DimT, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const c_longlong, + strides.get().as_ptr() as *const c_longlong, + aftype as c_uint, + 1 as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -195,10 +225,12 @@ impl Array where T: HasAfEnum { let aftype = T::get_af_dtype(); unsafe { let mut temp: i64 = 0; - let err_val = af_create_handle(&mut temp as MutAfArray, - dims.ndims() as c_uint, - dims.get().as_ptr() as * const c_longlong, - aftype as c_uint); + let err_val = af_create_handle( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const c_longlong, + aftype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); temp.into() } @@ -219,7 +251,7 @@ impl Array where T: HasAfEnum { (0, 1) => Backend::CPU, (0, 2) => Backend::CUDA, (0, 3) => Backend::OPENCL, - _ => Backend::DEFAULT, + _ => Backend::DEFAULT, } } } @@ -265,9 +297,13 @@ impl Array where T: HasAfEnum { let mut ret1: i64 = 0; let mut ret2: i64 = 0; let mut ret3: i64 = 0; - let err_val = af_get_dims(&mut ret0 as *mut DimT, &mut ret1 as *mut DimT, - &mut ret2 as *mut DimT, &mut ret3 as *mut DimT, - self.handle as AfArray); + let err_val = af_get_dims( + &mut ret0 as *mut DimT, + &mut ret1 as *mut DimT, + &mut ret2 as *mut DimT, + &mut ret3 as *mut DimT, + self.handle as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); Dim4::new(&[ret0 as u64, ret1 as u64, ret2 as u64, ret3 as u64]) } @@ -280,9 +316,13 @@ impl Array where T: HasAfEnum { let mut ret1: i64 = 0; let mut ret2: i64 = 0; let mut ret3: i64 = 0; - let err_val = af_get_strides(&mut ret0 as *mut DimT, &mut ret1 as *mut DimT, - &mut ret2 as *mut DimT, &mut ret3 as *mut DimT, - self.handle as AfArray); + let err_val = af_get_strides( + &mut ret0 as *mut DimT, + &mut ret1 as *mut DimT, + &mut ret2 as *mut DimT, + &mut ret3 as *mut DimT, + self.handle as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); Dim4::new(&[ret0 as u64, ret1 as u64, ret2 as u64, ret3 as u64]) } @@ -349,22 +389,54 @@ impl Array where T: HasAfEnum { is_func!("Check if Array is a row", is_row, af_is_row); is_func!("Check if Array is a column", is_column, af_is_column); is_func!("Check if Array is a vector", is_vector, af_is_vector); - is_func!("Check if Array is of complex type", is_complex, af_is_complex); - is_func!("Check if Array's numerical type is of double precision", is_double, af_is_double); - is_func!("Check if Array's numerical type is of single precision", is_single, af_is_single); + is_func!( + "Check if Array is of complex type", + is_complex, + af_is_complex + ); + is_func!( + "Check if Array's numerical type is of double precision", + is_double, + af_is_double + ); + is_func!( + "Check if Array's numerical type is of single precision", + is_single, + af_is_single + ); is_func!("Check if Array is of real type", is_real, af_is_real); - is_func!("Check if Array is of single precision", is_floating, af_is_floating); - is_func!("Check if Array is of integral type", is_integer, af_is_integer); + is_func!( + "Check if Array is of single precision", + is_floating, + af_is_floating + ); + is_func!( + "Check if Array is of integral type", + is_integer, + af_is_integer + ); is_func!("Check if Array is of boolean type", is_bool, af_is_bool); - is_func!("Check if Array's memory layout is continuous and one dimensional", is_linear, af_is_linear); - is_func!("Check if Array's memory is owned by it and not a view of another Array", is_owner, af_is_owner); + is_func!( + "Check if Array's memory layout is continuous and one dimensional", + is_linear, + af_is_linear + ); + is_func!( + "Check if Array's memory is owned by it and not a view of another Array", + is_owner, + af_is_owner + ); /// Cast the Array data type to `target_type` pub fn cast(&self) -> Array { let trgt_type = O::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_cast(&mut temp as MutAfArray, self.handle as AfArray, trgt_type as c_uint); + let err_val = af_cast( + &mut temp as MutAfArray, + self.handle as AfArray, + trgt_type as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -431,7 +503,10 @@ impl Array where T: HasAfEnum { /// resource id, an 64 bit integer impl Into> for i64 { fn into(self) -> Array { - Array {handle: self, _marker: PhantomData} + Array { + handle: self, + _marker: PhantomData, + } } } @@ -443,7 +518,10 @@ impl Into> for i64 { /// /// To create a deep copy use /// [copy()](http://arrayfire.org/arrayfire-rust/arrayfire/struct.Array.html#method.copy) -impl Clone for Array where T: HasAfEnum { +impl Clone for Array +where + T: HasAfEnum, +{ fn clone(&self) -> Array { unsafe { let mut temp: i64 = 0; @@ -457,7 +535,10 @@ impl Clone for Array where T: HasAfEnum { } /// To free resources when Array goes out of scope -impl Drop for Array where T: HasAfEnum { +impl Drop for Array +where + T: HasAfEnum, +{ fn drop(&mut self) { unsafe { let ret_val = af_release_array(self.handle); @@ -498,8 +579,11 @@ impl Drop for Array where T: HasAfEnum { pub fn print(input: &Array) { let emptystring = CString::new("").unwrap(); unsafe { - let err_val = af_print_array_gen(emptystring.to_bytes_with_nul().as_ptr() as *const c_char, - input.get() as AfArray, 4); + let err_val = af_print_array_gen( + emptystring.to_bytes_with_nul().as_ptr() as *const c_char, + input.get() as AfArray, + 4, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -539,9 +623,14 @@ pub fn print(input: &Array) { pub fn print_gen(msg: String, input: &Array, precision: Option) { let emptystring = CString::new(msg.as_bytes()).unwrap(); unsafe { - let err_val = af_print_array_gen(emptystring.to_bytes_with_nul().as_ptr() as *const c_char, - input.get() as AfArray, - match precision {Some(p)=>p, None=>4} as c_int); + let err_val = af_print_array_gen( + emptystring.to_bytes_with_nul().as_ptr() as *const c_char, + input.get() as AfArray, + match precision { + Some(p) => p, + None => 4, + } as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } } diff --git a/src/backend.rs b/src/backend.rs index df434e1b8..059786d65 100644 --- a/src/backend.rs +++ b/src/backend.rs @@ -1,10 +1,10 @@ extern crate libc; -use defines::{AfError, Backend}; -use error::HANDLE_ERROR; use self::libc::{c_int, c_uint, uint8_t}; +use crate::defines::{AfError, Backend}; +use crate::error::HANDLE_ERROR; -extern { +extern "C" { fn af_set_backend(bknd: uint8_t) -> c_int; fn af_get_backend_count(num_backends: *mut c_uint) -> c_int; fn af_get_available_backends(backends: *mut c_int) -> c_int; @@ -34,7 +34,6 @@ pub fn get_backend_count() -> u32 { } } - /// Get the available backends #[allow(unused_mut)] pub fn get_available_backends() -> Vec { @@ -44,9 +43,15 @@ pub fn get_available_backends() -> Vec { HANDLE_ERROR(AfError::from(err_val)); let mut b = Vec::new(); - if temp & 0b0100 == 0b0100 { b.push(Backend::OPENCL); } - if temp & 0b0010 == 0b0010 { b.push(Backend::CUDA); } - if temp & 0b0001 == 0b0001 { b.push(Backend::CPU); } + if temp & 0b0100 == 0b0100 { + b.push(Backend::OPENCL); + } + if temp & 0b0010 == 0b0010 { + b.push(Backend::CUDA); + } + if temp & 0b0001 == 0b0001 { + b.push(Backend::CPU); + } b } diff --git a/src/blas/mod.rs b/src/blas/mod.rs index 06a9cc7b0..e7796fd45 100644 --- a/src/blas/mod.rs +++ b/src/blas/mod.rs @@ -1,20 +1,25 @@ extern crate libc; -use array::Array; -use defines::AfError; -use defines::MatProp; -use error::HANDLE_ERROR; -use self::libc::{c_uint, c_int}; -use util::{AfArray, MutAfArray, to_u32}; -use util::{FloatingPoint, HasAfEnum}; +use self::libc::{c_int, c_uint}; +use crate::array::Array; +use crate::defines::AfError; +use crate::defines::MatProp; +use crate::error::HANDLE_ERROR; +use crate::util::{to_u32, AfArray, MutAfArray}; +use crate::util::{FloatingPoint, HasAfEnum}; #[allow(dead_code)] -extern { - fn af_matmul(out: MutAfArray, lhs: AfArray, rhs: AfArray, - optlhs: c_uint, optrhs: c_uint) -> c_int; +extern "C" { + fn af_matmul( + out: MutAfArray, + lhs: AfArray, + rhs: AfArray, + optlhs: c_uint, + optrhs: c_uint, + ) -> c_int; - fn af_dot(out: MutAfArray, lhs: AfArray, rhs: AfArray, - optlhs: c_uint, optrhs: c_uint) -> c_int; + fn af_dot(out: MutAfArray, lhs: AfArray, rhs: AfArray, optlhs: c_uint, optrhs: c_uint) + -> c_int; fn af_transpose(out: MutAfArray, arr: AfArray, conjugate: c_int) -> c_int; fn af_transpose_inplace(arr: AfArray, conjugate: c_int) -> c_int; @@ -33,15 +38,19 @@ extern { /// /// The result Array of matrix multiplication #[allow(unused_mut)] -pub fn matmul(lhs: &Array, rhs: &Array, - optlhs: MatProp, optrhs: MatProp) -> Array - where T: HasAfEnum + FloatingPoint +pub fn matmul(lhs: &Array, rhs: &Array, optlhs: MatProp, optrhs: MatProp) -> Array +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_matmul(&mut temp as MutAfArray, - lhs.get() as AfArray, rhs.get() as AfArray, - to_u32(optlhs) as c_uint, to_u32(optrhs) as c_uint); + let err_val = af_matmul( + &mut temp as MutAfArray, + lhs.get() as AfArray, + rhs.get() as AfArray, + to_u32(optlhs) as c_uint, + to_u32(optrhs) as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -62,15 +71,19 @@ pub fn matmul(lhs: &Array, rhs: &Array, /// /// The result of dot product. #[allow(unused_mut)] -pub fn dot(lhs: &Array, rhs: &Array, - optlhs: MatProp, optrhs: MatProp) -> Array - where T: HasAfEnum + FloatingPoint +pub fn dot(lhs: &Array, rhs: &Array, optlhs: MatProp, optrhs: MatProp) -> Array +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_dot(&mut temp as MutAfArray, - lhs.get() as AfArray, rhs.get() as AfArray, - to_u32(optlhs) as c_uint, to_u32(optrhs) as c_uint); + let err_val = af_dot( + &mut temp as MutAfArray, + lhs.get() as AfArray, + rhs.get() as AfArray, + to_u32(optlhs) as c_uint, + to_u32(optrhs) as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -91,8 +104,11 @@ pub fn dot(lhs: &Array, rhs: &Array, pub fn transpose(arr: &Array, conjugate: bool) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_transpose(&mut temp as MutAfArray, - arr.get() as AfArray, conjugate as c_int); + let err_val = af_transpose( + &mut temp as MutAfArray, + arr.get() as AfArray, + conjugate as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() diff --git a/src/data/mod.rs b/src/data/mod.rs index 0d266c5d5..e917a757f 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -1,34 +1,54 @@ extern crate libc; extern crate num; -use array::Array; -use dim4::Dim4; -use defines::{AfError}; -use error::HANDLE_ERROR; -use self::libc::{c_int, c_uint, c_double}; +use self::libc::{c_double, c_int, c_uint}; use self::num::Complex; -use util::{AfArray, DimT, HasAfEnum, Intl, MutAfArray, Uintl}; +use crate::array::Array; +use crate::defines::AfError; +use crate::dim4::Dim4; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, HasAfEnum, Intl, MutAfArray, Uintl}; use std::vec::Vec; #[allow(dead_code)] -extern { - fn af_constant(out: MutAfArray, val: c_double, - ndims: c_uint, dims: *const DimT, afdtype: c_int) -> c_int; - - fn af_constant_complex(out: MutAfArray, real: c_double, imag: c_double, - ndims: c_uint, dims: *const DimT, afdtype: c_int) -> c_int; - - fn af_constant_long(out: MutAfArray, val: Intl, - ndims: c_uint, dims: *const DimT) -> c_int; - - fn af_constant_ulong(out: MutAfArray, val: Uintl, - ndims: c_uint, dims: *const DimT) -> c_int; - - fn af_range(out: MutAfArray, ndims: c_uint, dims: *const DimT, - seq_dims: c_int, afdtype: c_uint) -> c_int; - - fn af_iota(out: MutAfArray, ndims: c_uint, dims: *const DimT, - t_ndims: c_uint, tdims: *const DimT, afdtype: c_uint) -> c_int; +extern "C" { + fn af_constant( + out: MutAfArray, + val: c_double, + ndims: c_uint, + dims: *const DimT, + afdtype: c_int, + ) -> c_int; + + fn af_constant_complex( + out: MutAfArray, + real: c_double, + imag: c_double, + ndims: c_uint, + dims: *const DimT, + afdtype: c_int, + ) -> c_int; + + fn af_constant_long(out: MutAfArray, val: Intl, ndims: c_uint, dims: *const DimT) -> c_int; + + fn af_constant_ulong(out: MutAfArray, val: Uintl, ndims: c_uint, dims: *const DimT) -> c_int; + + fn af_range( + out: MutAfArray, + ndims: c_uint, + dims: *const DimT, + seq_dims: c_int, + afdtype: c_uint, + ) -> c_int; + + fn af_iota( + out: MutAfArray, + ndims: c_uint, + dims: *const DimT, + t_ndims: c_uint, + tdims: *const DimT, + afdtype: c_uint, + ) -> c_int; fn af_identity(out: MutAfArray, ndims: c_uint, dims: *const DimT, afdtype: c_uint) -> c_int; fn af_diag_create(out: MutAfArray, arr: AfArray, num: c_int) -> c_int; @@ -81,7 +101,8 @@ pub trait ConstGenerator { /// /// - `dims` are the dimensions of the output constant [Array](./struct.Array.html) fn generate(&self, dims: Dim4) -> Array - where Self::OutType: HasAfEnum; + where + Self::OutType: HasAfEnum; } #[allow(unused_mut)] @@ -91,9 +112,12 @@ impl ConstGenerator for i64 { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant_long(&mut temp as MutAfArray, *self as Intl, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT); + let err_val = af_constant_long( + &mut temp as MutAfArray, + *self as Intl, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -107,9 +131,12 @@ impl ConstGenerator for u64 { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant_ulong(&mut temp as MutAfArray, *self as Uintl, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT); + let err_val = af_constant_ulong( + &mut temp as MutAfArray, + *self as Uintl, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -123,10 +150,14 @@ impl ConstGenerator for Complex { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant_complex(&mut temp as MutAfArray, - (*self).re as c_double, (*self).im as c_double, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT, 1); + let err_val = af_constant_complex( + &mut temp as MutAfArray, + (*self).re as c_double, + (*self).im as c_double, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + 1, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -140,10 +171,14 @@ impl ConstGenerator for Complex { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant_complex(&mut temp as MutAfArray, - (*self).re as c_double, (*self).im as c_double, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT, 3); + let err_val = af_constant_complex( + &mut temp as MutAfArray, + (*self).re as c_double, + (*self).im as c_double, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + 3, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -157,9 +192,13 @@ impl ConstGenerator for bool { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant(&mut temp as MutAfArray, *self as c_int as c_double, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT, 4); + let err_val = af_constant( + &mut temp as MutAfArray, + *self as c_int as c_double, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + 4, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -167,7 +206,7 @@ impl ConstGenerator for bool { } macro_rules! cnst { - ($rust_type:ty, $ffi_type:expr) => ( + ($rust_type:ty, $ffi_type:expr) => { #[allow(unused_mut)] impl ConstGenerator for $rust_type { type OutType = $rust_type; @@ -175,25 +214,28 @@ macro_rules! cnst { fn generate(&self, dims: Dim4) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_constant(&mut temp as MutAfArray, *self as c_double, - dims.ndims() as c_uint, - dims.get().as_ptr() as *const DimT, $ffi_type); + let err_val = af_constant( + &mut temp as MutAfArray, + *self as c_double, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + $ffi_type, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } } - ) + }; } -cnst!(f32 , 0); -cnst!(f64 , 2); -cnst!(i32 , 5); -cnst!(u32 , 6); -cnst!(u8 , 7); -cnst!(i16 , 10); -cnst!(u16 , 11); - +cnst!(f32, 0); +cnst!(f64, 2); +cnst!(i32, 5); +cnst!(u32, 6); +cnst!(u8, 7); +cnst!(i16, 10); +cnst!(u16, 11); /// Create an Array with constant value /// @@ -220,7 +262,9 @@ cnst!(u16 , 11); /// /// An Array of given dimensions with constant value pub fn constant(cnst: G, dims: Dim4) -> Array -where G::OutType: HasAfEnum { +where + G::OutType: HasAfEnum, +{ cnst.generate(dims) } @@ -241,9 +285,13 @@ pub fn range(dims: Dim4, seq_dim: i32) -> Array { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_range(&mut temp as MutAfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT, - seq_dim as c_int, aftype as c_uint); + let err_val = af_range( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + seq_dim as c_int, + aftype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -266,10 +314,14 @@ pub fn iota(dims: Dim4, tdims: Dim4) -> Array { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val =af_iota(&mut temp as MutAfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT, - tdims.ndims() as c_uint, tdims.get().as_ptr() as *const DimT, - aftype as c_uint); + let err_val = af_iota( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + tdims.ndims() as c_uint, + tdims.get().as_ptr() as *const DimT, + aftype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -289,9 +341,12 @@ pub fn identity(dims: Dim4) -> Array { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_identity(&mut temp as MutAfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT, - aftype as c_uint); + let err_val = af_identity( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + aftype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -310,10 +365,16 @@ pub fn identity(dims: Dim4) -> Array { /// An Array with values as a diagonal Matrix #[allow(unused_mut)] pub fn diag_create(input: &Array, dim: i32) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_diag_create(&mut temp as MutAfArray, input.get() as AfArray, dim as c_int); + let err_val = af_diag_create( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -331,11 +392,16 @@ where T: HasAfEnum { /// An Array with values of the diagonal from input Array #[allow(unused_mut)] pub fn diag_extract(input: &Array, dim: i32) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_diag_extract(&mut temp as MutAfArray, - input.get() as AfArray, dim as c_int); + let err_val = af_diag_extract( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -354,11 +420,17 @@ where T: HasAfEnum { /// Concatenated Array #[allow(unused_mut)] pub fn join(dim: i32, first: &Array, second: &Array) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_join(&mut temp as MutAfArray, dim as c_int, - first.get() as AfArray, second.get() as AfArray); + let err_val = af_join( + &mut temp as MutAfArray, + dim as c_int, + first.get() as AfArray, + second.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -375,23 +447,29 @@ where T: HasAfEnum { /// /// Concatenated Array #[allow(unused_mut)] -pub fn join_many(dim: i32, inputs: Vec< &Array >) -> Array -where T: HasAfEnum { +pub fn join_many(dim: i32, inputs: Vec<&Array>) -> Array +where + T: HasAfEnum, +{ let mut v = Vec::new(); for i in inputs { v.push(i.get()); } let mut temp: i64 = 0; unsafe { - let err_val = af_join_many(&mut temp as MutAfArray, dim as c_int, - v.len() as c_uint, v.as_ptr() as *const AfArray); + let err_val = af_join_many( + &mut temp as MutAfArray, + dim as c_int, + v.len() as c_uint, + v.as_ptr() as *const AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! data_func_def { - ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -404,23 +482,33 @@ macro_rules! data_func_def { /// An Array with modified data. #[allow(unused_mut)] pub fn $fn_name(input: &Array, dims: Dim4) -> Array - where T: HasAfEnum { + where + T: HasAfEnum, + { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, input.get() as AfArray, - dims[0] as c_uint, dims[1] as c_uint, - dims[2] as c_uint, dims[3] as c_uint); + let err_val = $ffi_name( + &mut temp as MutAfArray, + input.get() as AfArray, + dims[0] as c_uint, + dims[1] as c_uint, + dims[2] as c_uint, + dims[3] as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } -data_func_def!("Tile the input array along specified dimension", tile, af_tile); +data_func_def!( + "Tile the input array along specified dimension", + tile, + af_tile +); data_func_def!("Reorder the array in specified order", reorder, af_reorder); - ///"Circular shift of values along specified dimension /// ///# Parameters @@ -445,18 +533,24 @@ data_func_def!("Reorder the array in specified order", reorder, af_reorder); /// ``` #[allow(unused_mut)] pub fn shift(input: &Array, offsets: &[i32; 4]) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_shift(&mut temp as MutAfArray, input.get() as AfArray, - offsets[0] as c_int, offsets[1] as c_int, - offsets[2] as c_int, offsets[3] as c_int); + let err_val = af_shift( + &mut temp as MutAfArray, + input.get() as AfArray, + offsets[0] as c_int, + offsets[1] as c_int, + offsets[2] as c_int, + offsets[3] as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - /// Change the shape of the Array /// /// # Parameters @@ -468,11 +562,17 @@ where T: HasAfEnum { /// Reshaped Array #[allow(unused_mut)] pub fn moddims(input: &Array, dims: Dim4) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_moddims(&mut temp as MutAfArray, input.get() as AfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT); + let err_val = af_moddims( + &mut temp as MutAfArray, + input.get() as AfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -481,7 +581,9 @@ where T: HasAfEnum { /// Flatten the multidimensional Array to an 1D Array #[allow(unused_mut)] pub fn flat(input: &Array) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { let err_val = af_flat(&mut temp as MutAfArray, input.get() as AfArray); @@ -502,10 +604,16 @@ where T: HasAfEnum { /// Flipped Array #[allow(unused_mut)] pub fn flip(input: &Array, dim: u32) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_flip(&mut temp as MutAfArray, input.get() as AfArray, dim as c_uint); + let err_val = af_flip( + &mut temp as MutAfArray, + input.get() as AfArray, + dim as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -522,11 +630,16 @@ where T: HasAfEnum { /// Array #[allow(unused_mut)] pub fn lower(input: &Array, is_unit_diag: bool) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_lower(&mut temp as MutAfArray, - input.get() as AfArray, is_unit_diag as c_int); + let err_val = af_lower( + &mut temp as MutAfArray, + input.get() as AfArray, + is_unit_diag as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -543,11 +656,16 @@ where T: HasAfEnum { /// Array #[allow(unused_mut)] pub fn upper(input: &Array, is_unit_diag: bool) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_upper(&mut temp as MutAfArray, - input.get() as AfArray, is_unit_diag as c_int); + let err_val = af_upper( + &mut temp as MutAfArray, + input.get() as AfArray, + is_unit_diag as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -575,11 +693,17 @@ where T: HasAfEnum { /// An Array #[allow(unused_mut)] pub fn select(a: &Array, cond: &Array, b: &Array) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_select(&mut temp as MutAfArray, cond.get() as AfArray, - a.get() as AfArray, b.get() as AfArray); + let err_val = af_select( + &mut temp as MutAfArray, + cond.get() as AfArray, + a.get() as AfArray, + b.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -607,11 +731,17 @@ where T: HasAfEnum { /// An Array #[allow(unused_mut)] pub fn selectl(a: f64, cond: &Array, b: &Array) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_select_scalar_l(&mut temp as MutAfArray, cond.get() as AfArray, - a as c_double, b.get() as AfArray); + let err_val = af_select_scalar_l( + &mut temp as MutAfArray, + cond.get() as AfArray, + a as c_double, + b.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -639,11 +769,17 @@ where T: HasAfEnum { /// An Array #[allow(unused_mut)] pub fn selectr(a: &Array, cond: &Array, b: f64) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let mut temp: i64 = 0; unsafe { - let err_val = af_select_scalar_r(&mut temp as MutAfArray, cond.get() as AfArray, - a.get() as AfArray, b as c_double); + let err_val = af_select_scalar_r( + &mut temp as MutAfArray, + cond.get() as AfArray, + a.get() as AfArray, + b as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -670,10 +806,15 @@ where T: HasAfEnum { /// None #[allow(unused_mut)] pub fn replace(a: &mut Array, cond: &Array, b: &Array) -where T: HasAfEnum { +where + T: HasAfEnum, +{ unsafe { - let err_val = af_replace(a.get() as MutAfArray, - cond.get() as AfArray, b.get() as AfArray); + let err_val = af_replace( + a.get() as MutAfArray, + cond.get() as AfArray, + b.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -699,10 +840,12 @@ where T: HasAfEnum { /// None #[allow(unused_mut)] pub fn replace_scalar(a: &mut Array, cond: &Array, b: f64) -where T: HasAfEnum { +where + T: HasAfEnum, +{ unsafe { - let err_val = af_replace_scalar(a.get() as MutAfArray, - cond.get() as AfArray, b as c_double); + let err_val = + af_replace_scalar(a.get() as MutAfArray, cond.get() as AfArray, b as c_double); HANDLE_ERROR(AfError::from(err_val)); } } diff --git a/src/defines.rs b/src/defines.rs index 969b0af59..458383bfa 100644 --- a/src/defines.rs +++ b/src/defines.rs @@ -1,55 +1,55 @@ extern crate num; +use self::num::Complex; use std::error::Error; -use std::fmt::{Display, Formatter}; use std::fmt::Error as FmtError; -use self::num::Complex; +use std::fmt::{Display, Formatter}; /// Error codes #[repr(i32)] #[derive(Clone, Copy, Debug, PartialEq)] pub enum AfError { /// The function returned successfully - SUCCESS = 0, + SUCCESS = 0, // 100-199 Errors in environment /// The system or device ran out of memory - ERR_NO_MEM = 101, + ERR_NO_MEM = 101, /// There was an error in the device driver - ERR_DRIVER = 102, + ERR_DRIVER = 102, /// There was an error with the runtime environment - ERR_RUNTIME = 103, + ERR_RUNTIME = 103, // 200-299 Errors in input parameters /// The input array is not a valid Array object - ERR_INVALID_ARRAY = 201, + ERR_INVALID_ARRAY = 201, /// One of the function arguments is incorrect - ERR_ARG = 202, + ERR_ARG = 202, /// The size is incorrect - ERR_SIZE = 203, + ERR_SIZE = 203, /// The type is not suppported by this function - ERR_TYPE = 204, + ERR_TYPE = 204, /// The type of the input arrays are not compatible - ERR_DIFF_TYPE = 205, + ERR_DIFF_TYPE = 205, /// Function does not support GFOR / batch mode - ERR_BATCH = 207, + ERR_BATCH = 207, /// Input does not belong to the current device - ERR_DEVICE = 208, + ERR_DEVICE = 208, // 300-399 Errors for missing software features /// The option is not supported - ERR_NOT_SUPPORTED = 301, + ERR_NOT_SUPPORTED = 301, /// This build of ArrayFire does not support this feature ERR_NOT_CONFIGURED = 302, // 400-499 Errors for missing hardware features /// This device does not support double - ERR_NO_DBL = 401, + ERR_NO_DBL = 401, /// This build of ArrayFire was not built with graphics or this device does /// not support graphics - ERR_NO_GFX = 402, + ERR_NO_GFX = 402, // 900-999 Errors from upstream libraries and runtimes /// There was an internal error either in ArrayFire or in a project /// upstream - ERR_INTERNAL = 998, + ERR_INTERNAL = 998, /// Unknown Error - ERR_UNKNOWN = 999 + ERR_UNKNOWN = 999, } /// Compute/Acceleration Backend @@ -59,19 +59,19 @@ pub enum Backend { /// Default backend order: OpenCL -> CUDA -> CPU DEFAULT = 0, /// CPU a.k.a sequential algorithms - CPU = 1, + CPU = 1, /// CUDA Compute Backend - CUDA = 2, + CUDA = 2, /// OpenCL Compute Backend - OPENCL = 4 + OPENCL = 4, } impl Display for Backend { fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> { let text = match *self { - Backend::OPENCL => "OpenCL", - Backend::CUDA => "Cuda", - Backend::CPU => "CPU", + Backend::OPENCL => "OpenCL", + Backend::CUDA => "Cuda", + Backend::CPU => "CPU", Backend::DEFAULT => "Default", }; write!(f, "{}", text) @@ -87,23 +87,23 @@ impl Display for AfError { impl Error for AfError { fn description(&self) -> &str { match *self { - AfError::SUCCESS => "Function returned successfully", - AfError::ERR_NO_MEM => "System or Device ran out of memory", - AfError::ERR_DRIVER => "Error in the device driver", - AfError::ERR_RUNTIME => "Error with the runtime environment", - AfError::ERR_INVALID_ARRAY => "Iput Array is not a valid object", - AfError::ERR_ARG => "One of the function arguments is incorrect", - AfError::ERR_SIZE => "Size is incorrect", - AfError::ERR_TYPE => "Type is not suppported by this function", - AfError::ERR_DIFF_TYPE => "Type of the input arrays are not compatible", - AfError::ERR_BATCH => "Function does not support GFOR / batch mode", - AfError::ERR_DEVICE => "Input does not belong to the current device", - AfError::ERR_NOT_SUPPORTED => "Unsupported operation/parameter option", + AfError::SUCCESS => "Function returned successfully", + AfError::ERR_NO_MEM => "System or Device ran out of memory", + AfError::ERR_DRIVER => "Error in the device driver", + AfError::ERR_RUNTIME => "Error with the runtime environment", + AfError::ERR_INVALID_ARRAY => "Iput Array is not a valid object", + AfError::ERR_ARG => "One of the function arguments is incorrect", + AfError::ERR_SIZE => "Size is incorrect", + AfError::ERR_TYPE => "Type is not suppported by this function", + AfError::ERR_DIFF_TYPE => "Type of the input arrays are not compatible", + AfError::ERR_BATCH => "Function does not support GFOR / batch mode", + AfError::ERR_DEVICE => "Input does not belong to the current device", + AfError::ERR_NOT_SUPPORTED => "Unsupported operation/parameter option", AfError::ERR_NOT_CONFIGURED => "This build of ArrayFire does not support this feature", - AfError::ERR_NO_DBL => "This device does not support double", - AfError::ERR_NO_GFX => "This build of ArrayFire has no graphics support", - AfError::ERR_INTERNAL => "Error either in ArrayFire or in a project upstream", - AfError::ERR_UNKNOWN => "Unknown Error", + AfError::ERR_NO_DBL => "This device does not support double", + AfError::ERR_NO_GFX => "This build of ArrayFire has no graphics support", + AfError::ERR_INTERNAL => "Error either in ArrayFire or in a project upstream", + AfError::ERR_UNKNOWN => "Unknown Error", } } } @@ -121,13 +121,13 @@ pub enum DType { /// 64 bit complex float C64 = 3, /// 8 bit boolean - B8 = 4, + B8 = 4, /// 32 bit signed integer S32 = 5, /// 32 bit unsigned integer U32 = 6, /// 8 bit unsigned integer - U8 = 7, + U8 = 7, /// 64 bit signed integer S64 = 8, /// 64 bit unsigned integer @@ -145,23 +145,23 @@ pub enum InterpType { /// Nearest Neighbor interpolation method NEAREST = 0, /// Linear interpolation method - LINEAR = 1, + LINEAR = 1, /// Bilinear interpolation method - BILINEAR= 2, + BILINEAR = 2, /// Cubic interpolation method - CUBIC = 3, + CUBIC = 3, /// Floor indexed - LOWER = 4, + LOWER = 4, /// Linear interpolation with cosine smoothing - LINEAR_COSINE = 5, + LINEAR_COSINE = 5, /// Bilinear interpolation with cosine smoothing BILINEAR_COSINE = 6, /// Bicubic interpolation - BICUBIC = 7, + BICUBIC = 7, /// Cubic interpolation with Catmull-Rom splines - CUBIC_SPLINE = 8, + CUBIC_SPLINE = 8, /// Bicubic interpolation with Catmull-Rom splines - BICUBIC_SPLINE = 9 + BICUBIC_SPLINE = 9, } /// Helps determine how to pad kernels along borders @@ -181,7 +181,7 @@ pub enum Connectivity { /// North-East-South-West (N-E-S-W) connectivity from given pixel/point FOUR = 4, /// N-NE-E-SE-S-SW-W-NW connectivity from given pixel/point - EIGHT = 8 + EIGHT = 8, } /// Helps determine the size of output of convolution @@ -191,7 +191,7 @@ pub enum ConvMode { /// Default convolution mode where output size is same as input size DEFAULT = 0, /// Output of convolution is expanded based on signal and filter sizes - EXPAND = 1, + EXPAND = 1, } /// Helps determine if convolution is in Spatial or Frequency domain @@ -199,11 +199,11 @@ pub enum ConvMode { #[derive(Clone, Copy, Debug, PartialEq)] pub enum ConvDomain { /// ArrayFire chooses whether the convolution will be in spatial domain or frequency domain - AUTO = 0, + AUTO = 0, /// Convoltion in spatial domain - SPATIAL = 1, + SPATIAL = 1, /// Convolution in frequency domain - FREQUENCY= 2, + FREQUENCY = 2, } /// Error metric used by `matchTemplate` function @@ -213,19 +213,19 @@ pub enum MatchType { /// Sum of Absolute Differences SAD = 0, /// Zero-mean Sum of Absolute Differences - ZSAD= 1, + ZSAD = 1, /// Locally scaled Sum of Absolute Differences - LSAD= 2, + LSAD = 2, /// Sum of Squared Differences SSD = 3, /// Zero-mean Sum of Squared Differences - ZSSD= 4, + ZSSD = 4, /// Localy scaled Sum of Squared Differences - LSSD= 5, + LSSD = 5, /// Normalized Cross Correlation NCC = 6, /// Zero-mean Normalized Cross Correlation - ZNCC= 7, + ZNCC = 7, /// Sum of Hamming Distances SHD = 8, } @@ -237,9 +237,9 @@ pub enum ColorSpace { /// Grayscale color space GRAY = 0, /// Red-Green-Blue color space - RGB = 1, + RGB = 1, /// Hue-Saturation-value color space - HSV = 2, + HSV = 2, } /// Helps determine the type of a Matrix @@ -276,19 +276,19 @@ pub enum MatProp { #[derive(Clone, Copy, Debug, PartialEq)] pub enum NormType { /// Treats input as a vector and return sum of absolute values - VECTOR_1 = 0, + VECTOR_1 = 0, /// Treats input as vector and return max of absolute values - VECTOR_INF = 1, + VECTOR_INF = 1, /// Treats input as vector and returns euclidean norm - VECTOR_2 = 2, + VECTOR_2 = 2, /// Treats input as vector and returns the p-norm - VECTOR_P = 3, + VECTOR_P = 3, /// Return the max of column sums - MATRIX_1 = 4, + MATRIX_1 = 4, /// Return the max of row sums - MATRIX_INF = 5, + MATRIX_INF = 5, /// Returns the max singular value (Currently not supported) - MATRIX_2 = 6, + MATRIX_2 = 6, /// Returns Lpq-norm MATRIX_L_PQ = 7, } @@ -300,17 +300,17 @@ pub enum ColorMap { /// Default color map is grayscale range [0-1] DEFAULT = 0, /// Visible spectrum color map - SPECTRUM= 1, + SPECTRUM = 1, /// Colors - COLORS = 2, + COLORS = 2, /// Red hue map - RED = 3, + RED = 3, /// Mood color map - MOOD = 4, + MOOD = 4, /// Heat color map - HEAT = 5, + HEAT = 5, /// Blue hue map - BLUE = 6, + BLUE = 6, } /// YCbCr Standards @@ -332,7 +332,7 @@ pub enum HomographyType { /// RANdom SAmple Consensus algorithm RANSAC = 0, /// Least Median of Squares - LMEDS = 1, + LMEDS = 1, } /// Plotting markers @@ -340,21 +340,21 @@ pub enum HomographyType { #[derive(Clone, Copy, Debug, PartialEq)] pub enum MarkerType { /// No marker - NONE = 0, + NONE = 0, /// Pointer marker - POINT = 1, + POINT = 1, /// Hollow circle marker - CIRCLE = 2, + CIRCLE = 2, /// Hollow Square marker - SQUARE = 3, + SQUARE = 3, /// Hollow Triangle marker TRIANGLE = 4, /// Cross-hair marker - CROSS = 5, + CROSS = 5, /// Plus symbol marker - PLUS = 6, + PLUS = 6, /// Start symbol marker - STAR = 7 + STAR = 7, } /// Image moment types @@ -362,15 +362,15 @@ pub enum MarkerType { #[derive(Clone, Copy, Debug, PartialEq)] pub enum MomentType { /// Central moment of order (0 + 0) - M00 = 1, // 1<<0 + M00 = 1, // 1<<0 /// Central moment of order (0 + 1) - M01 = 2, // 1<<1 + M01 = 2, // 1<<1 /// Central moment of order (1 + 0) - M10 = 4, // 1<<2 + M10 = 4, // 1<<2 /// Central moment of order (1 + 1) - M11 = 8, // 1<<3 + M11 = 8, // 1<<3 /// All central moments of order (0,0), (0,1), (1,0) and (1,1) - FIRST_ORDER = 1<<0 | 1<<1 | 1<<2 | 1<<3 + FIRST_ORDER = 1 << 0 | 1 << 1 | 1 << 2 | 1 << 3, } /// Sparse storage format type @@ -380,11 +380,11 @@ pub enum SparseFormat { /// Dense format DENSE = 0, /// Compressed sparse row format - CSR = 1, + CSR = 1, /// Compressed sparse coloumn format - CSC = 2, + CSC = 2, /// Coordinate list (row, coloumn, value) tuples. - COO = 3 + COO = 3, } /// Binary operation types for generalized scan functions @@ -398,7 +398,7 @@ pub enum BinaryOp { /// Minimum operation MIN = 2, /// Maximum operation - MAX = 3 + MAX = 3, } /// Random engine types @@ -406,21 +406,21 @@ pub enum BinaryOp { #[derive(Clone, Copy, Debug, PartialEq)] pub enum RandomEngineType { ///Philox variant with N=4, W=32 and Rounds=10 - PHILOX_4X32_10 = 100, + PHILOX_4X32_10 = 100, ///Threefry variant with N=2, W=32 and Rounds=16 - THREEFRY_2X32_16 = 200, + THREEFRY_2X32_16 = 200, ///Mersenne variant with MEXP = 11213 - MERSENNE_GP11213 = 300 + MERSENNE_GP11213 = 300, } /// Default Philon RandomEngine that points to [PHILOX_4X32_10](./enum.RandomEngineType.html) -pub const PHILOX : RandomEngineType = RandomEngineType::PHILOX_4X32_10; +pub const PHILOX: RandomEngineType = RandomEngineType::PHILOX_4X32_10; /// Default Threefry RandomEngine that points to [THREEFRY_2X32_16](./enum.RandomEngineType.html) -pub const THREEFRY : RandomEngineType = RandomEngineType::THREEFRY_2X32_16; +pub const THREEFRY: RandomEngineType = RandomEngineType::THREEFRY_2X32_16; /// Default Mersenne RandomEngine that points to [MERSENNE_GP11213](./enum.RandomEngineType.html) -pub const MERSENNE : RandomEngineType = RandomEngineType::MERSENNE_GP11213; +pub const MERSENNE: RandomEngineType = RandomEngineType::MERSENNE_GP11213; /// Default RandomEngine that defaults to [PHILOX](./constant.PHILOX.html) -pub const DEFAULT_RANDOM_ENGINE : RandomEngineType = PHILOX; +pub const DEFAULT_RANDOM_ENGINE: RandomEngineType = PHILOX; /// Scalar value types #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/src/device/mod.rs b/src/device/mod.rs index b806d8634..c62482cc7 100644 --- a/src/device/mod.rs +++ b/src/device/mod.rs @@ -1,26 +1,34 @@ extern crate libc; -use defines::{AfError}; -use error::HANDLE_ERROR; -use self::libc::{c_int, size_t, c_char}; -use std::ffi::{CStr, CString}; +use self::libc::{c_char, c_int, size_t}; +use crate::defines::AfError; +use crate::error::HANDLE_ERROR; +use crate::util::free_host; use std::borrow::Cow; -use util::free_host; +use std::ffi::{CStr, CString}; -extern { +extern "C" { fn af_get_version(major: *mut c_int, minor: *mut c_int, patch: *mut c_int) -> c_int; fn af_get_revision() -> *const c_char; fn af_info() -> c_int; fn af_info_string(str: *mut *mut c_char, verbose: bool) -> c_int; - fn af_device_info(d_name: *mut c_char, d_platform: *mut c_char, - d_toolkit: *mut c_char, d_compute: *mut c_char) -> c_int; + fn af_device_info( + d_name: *mut c_char, + d_platform: *mut c_char, + d_toolkit: *mut c_char, + d_compute: *mut c_char, + ) -> c_int; fn af_init() -> c_int; fn af_get_device_count(nDevices: *mut c_int) -> c_int; fn af_get_dbl_support(available: *mut c_int, device: c_int) -> c_int; fn af_set_device(device: c_int) -> c_int; fn af_get_device(device: *mut c_int) -> c_int; - fn af_device_mem_info(alloc_bytes: *mut size_t, alloc_buffers: *mut size_t, - lock_bytes: *mut size_t, lock_buffers: *mut size_t) -> c_int; + fn af_device_mem_info( + alloc_bytes: *mut size_t, + alloc_buffers: *mut size_t, + lock_bytes: *mut size_t, + lock_buffers: *mut size_t, + ) -> c_int; fn af_print_mem_info(msg: *const c_char, device_id: c_int) -> c_int; fn af_set_mem_step_size(step_bytes: size_t) -> c_int; fn af_get_mem_step_size(step_bytes: *mut size_t) -> c_int; @@ -37,8 +45,11 @@ pub fn get_version() -> (i32, i32, i32) { let mut maj: i32 = 0; let mut min: i32 = 0; let mut pat: i32 = 0; - let err_val = af_get_version(&mut maj as *mut c_int, - &mut min as *mut c_int, &mut pat as *mut c_int); + let err_val = af_get_version( + &mut maj as *mut c_int, + &mut min as *mut c_int, + &mut pat as *mut c_int, + ); HANDLE_ERROR(AfError::from(err_val)); (maj, min, pat) } @@ -49,9 +60,7 @@ pub fn get_version() -> (i32, i32, i32) { /// # Return Values /// This returns a `Cow<'static, str>` as the string is constructed at compile time. pub fn get_revision() -> Cow<'static, str> { - unsafe { - CStr::from_ptr(af_get_revision()).to_string_lossy() - } + unsafe { CStr::from_ptr(af_get_revision()).to_string_lossy() } } /// Print library meta-info @@ -105,15 +114,27 @@ pub fn device_info() -> (String, String, String, String) { let mut toolkit = [0 as c_char; 64]; let mut compute = [0 as c_char; 10]; unsafe { - let err_val = af_device_info(&mut name[0], - &mut platform[0], - &mut toolkit[0], - &mut compute[0]); + let err_val = af_device_info( + &mut name[0], + &mut platform[0], + &mut toolkit[0], + &mut compute[0], + ); HANDLE_ERROR(AfError::from(err_val)); - (CStr::from_ptr(name.as_mut_ptr()).to_string_lossy().into_owned(), - CStr::from_ptr(platform.as_mut_ptr()).to_string_lossy().into_owned(), - CStr::from_ptr(toolkit.as_mut_ptr()).to_string_lossy().into_owned(), - CStr::from_ptr(compute.as_mut_ptr()).to_string_lossy().into_owned()) + ( + CStr::from_ptr(name.as_mut_ptr()) + .to_string_lossy() + .into_owned(), + CStr::from_ptr(platform.as_mut_ptr()) + .to_string_lossy() + .into_owned(), + CStr::from_ptr(toolkit.as_mut_ptr()) + .to_string_lossy() + .into_owned(), + CStr::from_ptr(compute.as_mut_ptr()) + .to_string_lossy() + .into_owned(), + ) } } @@ -198,10 +219,12 @@ pub fn device_mem_info() -> (usize, usize, usize, usize) { let mut o1: usize = 0; let mut o2: usize = 0; let mut o3: usize = 0; - let err_val = af_device_mem_info(&mut o0 as *mut size_t, - &mut o1 as *mut size_t, - &mut o2 as *mut size_t, - &mut o3 as *mut size_t); + let err_val = af_device_mem_info( + &mut o0 as *mut size_t, + &mut o1 as *mut size_t, + &mut o2 as *mut size_t, + &mut o3 as *mut size_t, + ); HANDLE_ERROR(AfError::from(err_val)); (o0, o1, o2, o3) } @@ -224,10 +247,12 @@ pub fn print_mem_info(msg: String, device: i32) { let cmsg = CString::new(msg.as_bytes()); match cmsg { Ok(v) => { - let err_val = af_print_mem_info(v.to_bytes_with_nul().as_ptr() as * const c_char, - device as c_int); + let err_val = af_print_mem_info( + v.to_bytes_with_nul().as_ptr() as *const c_char, + device as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); - }, + } Err(_) => HANDLE_ERROR(AfError::ERR_INTERNAL), } } diff --git a/src/dim4.rs b/src/dim4.rs index cc31b3bba..97d78f7bb 100644 --- a/src/dim4.rs +++ b/src/dim4.rs @@ -10,7 +10,7 @@ pub struct Dim4 { /// Default trait for Dim4 returns an Array of dimensions [1, 1, 1, 1] impl Default for Dim4 { fn default() -> Dim4 { - Dim4 { dims:[1, 1, 1, 1] } + Dim4 { dims: [1, 1, 1, 1] } } } @@ -30,7 +30,7 @@ impl Default for Dim4 { impl Index for Dim4 { type Output = u64; - fn index<'a>(&'a self, _index: usize) ->&'a u64 { + fn index<'a>(&'a self, _index: usize) -> &'a u64 { &self.dims[_index] } } @@ -47,7 +47,11 @@ impl Index for Dim4 { /// ``` impl fmt::Display for Dim4 { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "[{} {} {} {}]", self.dims[0], self.dims[1], self.dims[2], self.dims[3]) + write!( + f, + "[{} {} {} {}]", + self.dims[0], self.dims[1], self.dims[2], self.dims[3] + ) } } @@ -61,12 +65,12 @@ impl Dim4 { /// let dims = Dim4::new(&[4, 4, 2, 1]); /// ``` pub fn new(dims: &[u64; 4]) -> Dim4 { - Dim4 { dims: dims.clone(), } + Dim4 { dims: dims.clone() } } /// Get the number of elements represented by Dim4 object pub fn elements(&self) -> u64 { - self.dims[0]*self.dims[1]*self.dims[2]*self.dims[3] + self.dims[0] * self.dims[1] * self.dims[2] * self.dims[3] } /// Get the number of dimensions of Dim4 @@ -76,11 +80,16 @@ impl Dim4 { 0 => 0, 1 => 1, _ => { - if self.dims[3] != 1 { 4 } - else if self.dims[2] != 1 { 3 } - else if self.dims[1] != 1 { 2 } - else { 1 } - }, + if self.dims[3] != 1 { + 4 + } else if self.dims[2] != 1 { + 3 + } else if self.dims[1] != 1 { + 2 + } else { + 1 + } + } } } diff --git a/src/error.rs b/src/error.rs index c3ee8a4fe..9e3680bf9 100644 --- a/src/error.rs +++ b/src/error.rs @@ -1,15 +1,15 @@ extern crate libc; -use std::ops::{Deref, DerefMut}; -use defines::AfError; -use self::libc::{c_int, c_char}; -use std::ffi::CStr; +use self::libc::{c_char, c_int}; +use crate::defines::AfError; +use crate::util::{free_host, DimT, MutDimT}; use std::error::Error; +use std::ffi::CStr; +use std::ops::{Deref, DerefMut}; use std::sync::RwLock; -use util::{DimT, free_host, MutDimT}; #[allow(dead_code)] -extern { +extern "C" { fn af_get_last_error(str: *mut *mut c_char, len: *mut DimT) -> c_int; } @@ -24,7 +24,7 @@ pub struct Callback { impl Callback { /// Associated function to create a new Callback object pub fn new(callback: ErrorCallback) -> Self { - Callback {cb: callback} + Callback { cb: callback } } /// call invokes the error callback with `error_code`. @@ -36,14 +36,17 @@ impl Callback { /// Default error handling callback provided by ArrayFire crate pub fn handle_error_general(error_code: AfError) { match error_code { - AfError::SUCCESS => {}, /* No-op */ - _ => panic!("Error message: {}\nLast error: {}", - error_code.description(), get_last_error()), + AfError::SUCCESS => {} /* No-op */ + _ => panic!( + "Error message: {}\nLast error: {}", + error_code.description(), + get_last_error() + ), } } lazy_static! { - static ref ERROR_HANDLER_LOCK: RwLock< Callback > = + static ref ERROR_HANDLER_LOCK: RwLock = RwLock::new(Callback::new(handle_error_general)); } @@ -77,7 +80,7 @@ lazy_static! { pub fn register_error_handler(cb_value: Callback) { let mut gaurd = match ERROR_HANDLER_LOCK.write() { Ok(g) => g, - Err(_)=> panic!("Failed to acquire lock to register error handler"), + Err(_) => panic!("Failed to acquire lock to register error handler"), }; *gaurd.deref_mut() = cb_value; @@ -87,7 +90,7 @@ pub fn register_error_handler(cb_value: Callback) { pub fn HANDLE_ERROR(error_code: AfError) { let gaurd = match ERROR_HANDLER_LOCK.read() { Ok(g) => g, - Err(_)=> panic!("Failed to acquire lock while handling FFI return value"), + Err(_) => panic!("Failed to acquire lock while handling FFI return value"), }; (*gaurd.deref()).call(error_code); diff --git a/src/graphics.rs b/src/graphics.rs index b2cadfeb4..3bf245a8a 100644 --- a/src/graphics.rs +++ b/src/graphics.rs @@ -1,16 +1,16 @@ extern crate libc; -use array::Array; -use defines::AfError; -use defines::{ColorMap, MarkerType}; -use error::HANDLE_ERROR; -use self::libc::{c_int, c_uint, c_float, c_double, c_char}; +use self::libc::{c_char, c_double, c_float, c_int, c_uint}; +use crate::array::Array; +use crate::defines::AfError; +use crate::defines::{ColorMap, MarkerType}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, CellPtr, HasAfEnum, MutWndHandle, WndHandle}; use std::ffi::CString; use std::ptr; -use util::{AfArray, CellPtr, HasAfEnum, MutWndHandle, WndHandle}; #[allow(dead_code)] -extern { +extern "C" { fn af_create_window(out: MutWndHandle, w: c_int, h: c_int, title: *const c_char) -> c_int; fn af_set_position(wnd: WndHandle, x: c_uint, y: c_uint) -> c_int; @@ -18,42 +18,104 @@ extern { fn af_set_size(wnd: WndHandle, w: c_uint, h: c_uint) -> c_int; fn af_set_visibility(wnd: WndHandle, is_visible: c_int) -> c_int; - fn af_set_axes_titles(wnd: WndHandle, - xtitle: *const c_char, ytitle: *const c_char, ztitle: *const c_char, - props: CellPtr) -> c_int; - fn af_set_axes_limits_compute(wnd: WndHandle, x: AfArray, y: AfArray, z: AfArray, - exact: c_int, props: CellPtr) -> c_int; - fn af_set_axes_limits_2d(wnd: WndHandle, xmin: c_float, xmax: c_float, - ymin: c_float, ymax: c_float, - exact: c_int, props: CellPtr) -> c_int; - fn af_set_axes_limits_3d(wnd: WndHandle, xmin: c_float, xmax: c_float, - ymin: c_float, ymax: c_float, - zmin: c_float, zmax: c_float, - exact: c_int, props: CellPtr) -> c_int; + fn af_set_axes_titles( + wnd: WndHandle, + xtitle: *const c_char, + ytitle: *const c_char, + ztitle: *const c_char, + props: CellPtr, + ) -> c_int; + fn af_set_axes_limits_compute( + wnd: WndHandle, + x: AfArray, + y: AfArray, + z: AfArray, + exact: c_int, + props: CellPtr, + ) -> c_int; + fn af_set_axes_limits_2d( + wnd: WndHandle, + xmin: c_float, + xmax: c_float, + ymin: c_float, + ymax: c_float, + exact: c_int, + props: CellPtr, + ) -> c_int; + fn af_set_axes_limits_3d( + wnd: WndHandle, + xmin: c_float, + xmax: c_float, + ymin: c_float, + ymax: c_float, + zmin: c_float, + zmax: c_float, + exact: c_int, + props: CellPtr, + ) -> c_int; fn af_draw_image(wnd: WndHandle, arr: AfArray, props: CellPtr) -> c_int; - fn af_draw_hist(wnd: WndHandle, x: AfArray, - minval: c_double, maxval: c_double, props: CellPtr) -> c_int; - fn af_draw_surface(wnd: WndHandle, xvals: AfArray, yvals: AfArray, S: AfArray, - props: CellPtr) -> c_int; + fn af_draw_hist( + wnd: WndHandle, + x: AfArray, + minval: c_double, + maxval: c_double, + props: CellPtr, + ) -> c_int; + fn af_draw_surface( + wnd: WndHandle, + xvals: AfArray, + yvals: AfArray, + S: AfArray, + props: CellPtr, + ) -> c_int; fn af_draw_plot_2d(wnd: WndHandle, x: AfArray, y: AfArray, props: CellPtr) -> c_int; - fn af_draw_plot_3d(wnd: WndHandle, x: AfArray, y: AfArray, z: AfArray, props: CellPtr) -> c_int; + fn af_draw_plot_3d(wnd: WndHandle, x: AfArray, y: AfArray, z: AfArray, props: CellPtr) + -> c_int; fn af_draw_plot_nd(wnd: WndHandle, P: AfArray, props: CellPtr) -> c_int; - fn af_draw_scatter_2d(wnd: WndHandle, x: AfArray, y: AfArray, - marker: c_int, props: CellPtr) -> c_int; - fn af_draw_scatter_3d(wnd: WndHandle, x: AfArray, y: AfArray, z: AfArray, - marker: c_int, props: CellPtr) -> c_int; - fn af_draw_scatter_nd(wnd: WndHandle, P: AfArray, - marker: c_int, props: CellPtr) -> c_int; - - fn af_draw_vector_field_2d(wnd: WndHandle, xpnts: AfArray, ypnts: AfArray, - xdirs: AfArray, ydirs: AfArray, props: CellPtr) -> c_int; - fn af_draw_vector_field_3d(wnd: WndHandle, xpnts: AfArray, ypnts: AfArray, - xdirs: AfArray, ydirs: AfArray, zdirs: AfArray, zdirs: AfArray, - props: CellPtr) -> c_int; - fn af_draw_vector_field_nd(wnd: WndHandle, pnts: AfArray, dirs: AfArray, props: CellPtr) -> c_int; + fn af_draw_scatter_2d( + wnd: WndHandle, + x: AfArray, + y: AfArray, + marker: c_int, + props: CellPtr, + ) -> c_int; + fn af_draw_scatter_3d( + wnd: WndHandle, + x: AfArray, + y: AfArray, + z: AfArray, + marker: c_int, + props: CellPtr, + ) -> c_int; + fn af_draw_scatter_nd(wnd: WndHandle, P: AfArray, marker: c_int, props: CellPtr) -> c_int; + + fn af_draw_vector_field_2d( + wnd: WndHandle, + xpnts: AfArray, + ypnts: AfArray, + xdirs: AfArray, + ydirs: AfArray, + props: CellPtr, + ) -> c_int; + fn af_draw_vector_field_3d( + wnd: WndHandle, + xpnts: AfArray, + ypnts: AfArray, + xdirs: AfArray, + ydirs: AfArray, + zdirs: AfArray, + zdirs: AfArray, + props: CellPtr, + ) -> c_int; + fn af_draw_vector_field_nd( + wnd: WndHandle, + pnts: AfArray, + dirs: AfArray, + props: CellPtr, + ) -> c_int; fn af_grid(wnd: WndHandle, rows: c_int, cols: c_int) -> c_int; fn af_show(wnd: WndHandle) -> c_int; @@ -113,7 +175,12 @@ pub struct Window { /// Used to create Window object from native(ArrayFire) resource handle impl From for Window { fn from(t: u64) -> Window { - Window {handle: t, row: -1, col: -1, cmap: ColorMap::DEFAULT} + Window { + handle: t, + row: -1, + col: -1, + cmap: ColorMap::DEFAULT, + } } } @@ -123,7 +190,10 @@ impl Drop for Window { let err_val = af_destroy_window(self.handle); match err_val { 0 => (), - _ => panic!("Window object destruction failed with error code: {}", err_val), + _ => panic!( + "Window object destruction failed with error code: {}", + err_val + ), } } } @@ -142,19 +212,24 @@ impl Window { /// /// Window Object #[allow(unused_mut)] - pub fn new(width: i32, height: i32, title: String) -> Window { + pub fn new(width: i32, height: i32, title: String) -> Window { unsafe { let mut temp: u64 = 0; let cstr_ret = CString::new(title); match cstr_ret { Ok(cstr) => { - let err_val = af_create_window(&mut temp as MutWndHandle, - width as c_int, height as c_int, - cstr.as_ptr()); + let err_val = af_create_window( + &mut temp as MutWndHandle, + width as c_int, + height as c_int, + cstr.as_ptr(), + ); HANDLE_ERROR(AfError::from(err_val)); Window::from(temp) - }, - Err(_) => panic!("String creation failed while prepping params for window creation."), + } + Err(_) => { + panic!("String creation failed while prepping params for window creation.") + } } } } @@ -182,11 +257,10 @@ impl Window { let cstr_ret = CString::new(title); match cstr_ret { Ok(cstr) => { - let err_val = af_set_title(self.handle as WndHandle, - cstr.as_ptr()); + let err_val = af_set_title(self.handle as WndHandle, cstr.as_ptr()); HANDLE_ERROR(AfError::from(err_val)); - }, - Err(_) => HANDLE_ERROR(AfError::ERR_INTERNAL), + } + Err(_) => HANDLE_ERROR(AfError::ERR_INTERNAL), } } } @@ -281,16 +355,23 @@ impl Window { /// - `ylabel` is y axis title /// - `zlabel` is z axis title pub fn set_axes_titles(&mut self, xlabel: String, ylabel: String, zlabel: String) { - let cprops = &Cell {row: self.row, col: self.col, title: ptr::null(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: ptr::null(), + cmap: self.cmap, + }; let xstr = CString::new(xlabel).unwrap(); let ystr = CString::new(ylabel).unwrap(); let zstr = CString::new(zlabel).unwrap(); unsafe { - let err_val = af_set_axes_titles(self.handle as WndHandle, - xstr.as_ptr(), - ystr.as_ptr(), - zstr.as_ptr(), - cprops as *const Cell as CellPtr); + let err_val = af_set_axes_titles( + self.handle as WndHandle, + xstr.as_ptr(), + ystr.as_ptr(), + zstr.as_ptr(), + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -309,23 +390,33 @@ impl Window { /// - `exact` indicates if the exact min/max values from `xrange`, `yrange` and `zrange` /// are to extracted. If exact is false then the most significant digit is rounded up /// to next power of 2 and the magnitude remains the same. - pub fn set_axes_limits_compute(&mut self, - xrange: &Array, - yrange: &Array, - zrange: Option<&Array>, - exact: bool) - where T: HasAfEnum + pub fn set_axes_limits_compute( + &mut self, + xrange: &Array, + yrange: &Array, + zrange: Option<&Array>, + exact: bool, + ) where + T: HasAfEnum, { - let cprops = &Cell {row: self.row, col: self.col, title: ptr::null(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: ptr::null(), + cmap: self.cmap, + }; unsafe { - let err_val = af_set_axes_limits_compute(self.handle as WndHandle, - xrange.get() as AfArray, - yrange.get() as AfArray, - match zrange { - Some(z) => z.get() as AfArray, - None => 0, - }, exact as c_int, - cprops as *const Cell as CellPtr); + let err_val = af_set_axes_limits_compute( + self.handle as WndHandle, + xrange.get() as AfArray, + yrange.get() as AfArray, + match zrange { + Some(z) => z.get() as AfArray, + None => 0, + }, + exact as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -345,11 +436,22 @@ impl Window { /// are to extracted. If exact is false then the most significant digit is rounded up /// to next power of 2 and the magnitude remains the same. pub fn set_axes_limits_2d(&mut self, xmin: f32, xmax: f32, ymin: f32, ymax: f32, exact: bool) { - let cprops = &Cell {row: self.row, col: self.col, title: ptr::null(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: ptr::null(), + cmap: self.cmap, + }; unsafe { - let err_val = af_set_axes_limits_2d(self.handle as WndHandle, xmin as c_float, - xmax as c_float, ymin as c_float, ymax as c_float, - exact as c_int, cprops as *const Cell as CellPtr); + let err_val = af_set_axes_limits_2d( + self.handle as WndHandle, + xmin as c_float, + xmax as c_float, + ymin as c_float, + ymax as c_float, + exact as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -370,14 +472,34 @@ impl Window { /// - `exact` indicates if the exact min/max values from `xrange`, `yrange` and `zrange` /// are to extracted. If exact is false then the most significant digit is rounded up /// to next power of 2 and the magnitude remains the same. - pub fn set_axes_limits_3d(&mut self, xmin: f32, xmax: f32, ymin: f32, ymax: f32, - zmin: f32, zmax: f32, exact: bool) { - let cprops = &Cell {row: self.row, col: self.col, title: ptr::null(), cmap: self.cmap}; + pub fn set_axes_limits_3d( + &mut self, + xmin: f32, + xmax: f32, + ymin: f32, + ymax: f32, + zmin: f32, + zmax: f32, + exact: bool, + ) { + let cprops = &Cell { + row: self.row, + col: self.col, + title: ptr::null(), + cmap: self.cmap, + }; unsafe { - let err_val = af_set_axes_limits_3d(self.handle as WndHandle, xmin as c_float, - xmax as c_float, ymin as c_float, ymax as c_float, - zmin as c_float, zmax as c_float, - exact as c_int, cprops as *const Cell as CellPtr); + let err_val = af_set_axes_limits_3d( + self.handle as WndHandle, + xmin as c_float, + xmax as c_float, + ymin as c_float, + ymax as c_float, + zmin as c_float, + zmax as c_float, + exact as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -390,17 +512,26 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_image(&self, input: &Array, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_image(self.handle as WndHandle, input.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_image( + self.handle as WndHandle, + input.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -414,18 +545,27 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_plot2(&self, x: &Array, y: &Array, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_plot_2d(self.handle as WndHandle, - x.get() as AfArray, y.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_plot_2d( + self.handle as WndHandle, + x.get() as AfArray, + y.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -440,18 +580,28 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_plot3(&self, x: &Array, y: &Array, z: &Array, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_plot_3d(self.handle as WndHandle, - x.get() as AfArray, y.get() as AfArray, z.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_plot_3d( + self.handle as WndHandle, + x.get() as AfArray, + y.get() as AfArray, + z.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -464,17 +614,26 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_plot(&self, points: &Array, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_plot_nd(self.handle as WndHandle, points.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_plot_nd( + self.handle as WndHandle, + points.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -489,18 +648,28 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_hist(&self, hst: &Array, minval: f64, maxval: f64, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_hist(self.handle as WndHandle, hst.get() as AfArray, - minval as c_double, maxval as c_double, - cprops as *const Cell as CellPtr); + let err_val = af_draw_hist( + self.handle as WndHandle, + hst.get() as AfArray, + minval as c_double, + maxval as c_double, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -514,23 +683,34 @@ impl Window { /// - `z` is the z coordinates of the surface plot /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_surface(&self, - xvals: &Array, yvals: &Array, zvals: &Array, - title: Option) - where T: HasAfEnum + pub fn draw_surface( + &self, + xvals: &Array, + yvals: &Array, + zvals: &Array, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_surface(self.handle as WndHandle, - xvals.get() as AfArray, - yvals.get() as AfArray, - zvals.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_surface( + self.handle as WndHandle, + xvals.get() as AfArray, + yvals.get() as AfArray, + zvals.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -544,20 +724,34 @@ impl Window { /// - `marker` is of enum type [MarkerType](./enum.MarkerType.html) /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_scatter2(&self, xvals: &Array, yvals: &Array, - marker: MarkerType, title: Option) - where T: HasAfEnum + pub fn draw_scatter2( + &self, + xvals: &Array, + yvals: &Array, + marker: MarkerType, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_scatter_2d(self.handle as WndHandle, - xvals.get() as AfArray, yvals.get() as AfArray, - marker as c_int, cprops as *const Cell as CellPtr); + let err_val = af_draw_scatter_2d( + self.handle as WndHandle, + xvals.get() as AfArray, + yvals.get() as AfArray, + marker as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -572,21 +766,36 @@ impl Window { /// - `marker` is of enum type [MarkerType](./enum.MarkerType.html) /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_scatter3(&self, - xvals: &Array, yvals: &Array, zvals: &Array, - marker: MarkerType, title: Option) - where T: HasAfEnum + pub fn draw_scatter3( + &self, + xvals: &Array, + yvals: &Array, + zvals: &Array, + marker: MarkerType, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_scatter_3d(self.handle as WndHandle, xvals.get() as AfArray, - yvals.get() as AfArray, zvals.get() as AfArray, - marker as c_int, cprops as *const Cell as CellPtr); + let err_val = af_draw_scatter_3d( + self.handle as WndHandle, + xvals.get() as AfArray, + yvals.get() as AfArray, + zvals.get() as AfArray, + marker as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -600,17 +809,27 @@ impl Window { /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. pub fn draw_scatter(&self, vals: &Array, marker: MarkerType, title: Option) - where T: HasAfEnum + where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_scatter_nd(self.handle as WndHandle, vals.get() as AfArray, - marker as c_int, cprops as *const Cell as CellPtr); + let err_val = af_draw_scatter_nd( + self.handle as WndHandle, + vals.get() as AfArray, + marker as c_int, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -625,23 +844,36 @@ impl Window { /// - `ydirs` is an Array containing direction component of y coord /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_vector_field2(&self, - xpnts: &Array, ypnts: &Array, - xdirs: &Array, ydirs: &Array, - title: Option) - where T: HasAfEnum + pub fn draw_vector_field2( + &self, + xpnts: &Array, + ypnts: &Array, + xdirs: &Array, + ydirs: &Array, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_vector_field_2d(self.handle as WndHandle, - xpnts.get() as AfArray, ypnts.get() as AfArray, - xdirs.get() as AfArray, ydirs.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_vector_field_2d( + self.handle as WndHandle, + xpnts.get() as AfArray, + ypnts.get() as AfArray, + xdirs.get() as AfArray, + ydirs.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -658,24 +890,40 @@ impl Window { /// - `zdirs` is an Array containing direction component of z coord /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_vector_field3(&self, - xpnts: &Array, ypnts: &Array, zpnts: &Array, - xdirs: &Array, ydirs: &Array, zdirs: &Array, - title: Option) - where T: HasAfEnum + pub fn draw_vector_field3( + &self, + xpnts: &Array, + ypnts: &Array, + zpnts: &Array, + xdirs: &Array, + ydirs: &Array, + zdirs: &Array, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_vector_field_3d(self.handle as WndHandle, xpnts.get() as AfArray, - ypnts.get() as AfArray, zpnts.get() as AfArray, - xdirs.get() as AfArray, ydirs.get() as AfArray, - zdirs.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_vector_field_3d( + self.handle as WndHandle, + xpnts.get() as AfArray, + ypnts.get() as AfArray, + zpnts.get() as AfArray, + xdirs.get() as AfArray, + ydirs.get() as AfArray, + zdirs.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -689,21 +937,32 @@ impl Window { /// Array. /// - `title` parameter has effect only in multiview mode, where this string /// is displayed as the respective cell/view title. - pub fn draw_vector_field(&self, - points: &Array, directions: &Array, - title: Option) - where T: HasAfEnum + pub fn draw_vector_field( + &self, + points: &Array, + directions: &Array, + title: Option, + ) where + T: HasAfEnum, { let tstr = match title { Some(s) => s, - None => format!("Cell({},{}))", self.col, self.row) + None => format!("Cell({},{}))", self.col, self.row), }; let tstr = CString::new(tstr).unwrap(); - let cprops = &Cell {row: self.row, col: self.col, title: tstr.as_ptr(), cmap: self.cmap}; + let cprops = &Cell { + row: self.row, + col: self.col, + title: tstr.as_ptr(), + cmap: self.cmap, + }; unsafe { - let err_val = af_draw_vector_field_nd(self.handle as WndHandle, - points.get() as AfArray, directions.get() as AfArray, - cprops as *const Cell as CellPtr); + let err_val = af_draw_vector_field_nd( + self.handle as WndHandle, + points.get() as AfArray, + directions.get() as AfArray, + cprops as *const Cell as CellPtr, + ); HANDLE_ERROR(AfError::from(err_val)); } } diff --git a/src/image/mod.rs b/src/image/mod.rs index 1d69f7de3..5b0ce894b 100644 --- a/src/image/mod.rs +++ b/src/image/mod.rs @@ -1,13 +1,13 @@ extern crate libc; -use array::Array; -use defines::{AfError, BorderType, CannyThresholdType, ColorSpace, Connectivity}; -use defines::{DiffusionEq, FluxFn, InterpType, MomentType, YCCStd}; -use error::HANDLE_ERROR; -use util::{AfArray, DimT, MutAfArray}; -use util::{FloatingPoint, HasAfEnum, RealNumber, ImageNativeType, ImageFilterType}; -use util::{RealFloating, EdgeComputable, MomentsComputable, GrayRGBConvertible}; -use self::libc::{c_uint, c_int, c_float, c_double, c_char}; +use self::libc::{c_char, c_double, c_float, c_int, c_uint}; +use crate::array::Array; +use crate::defines::{AfError, BorderType, CannyThresholdType, ColorSpace, Connectivity}; +use crate::defines::{DiffusionEq, FluxFn, InterpType, MomentType, YCCStd}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, MutAfArray}; +use crate::util::{EdgeComputable, GrayRGBConvertible, MomentsComputable, RealFloating}; +use crate::util::{FloatingPoint, HasAfEnum, ImageFilterType, ImageNativeType, RealNumber}; use std::ffi::CString; // unused functions from image.h header @@ -16,7 +16,7 @@ use std::ffi::CString; // af_delete_image_memory #[allow(dead_code)] -extern { +extern "C" { fn af_cast(out: MutAfArray, arr: AfArray, aftype: c_uint) -> c_int; fn af_gradient(dx: MutAfArray, dy: MutAfArray, arr: AfArray) -> c_int; fn af_load_image(out: MutAfArray, filename: *const c_char, iscolor: c_int) -> c_int; @@ -24,26 +24,70 @@ extern { fn af_load_image_native(out: MutAfArray, filename: *const c_char) -> c_int; fn af_save_image_native(filename: *const c_char, input: AfArray) -> c_int; - fn af_resize(out: MutAfArray, input: AfArray, - odim0: DimT, odim1: DimT, method: c_uint) -> c_int; - - fn af_transform(out: MutAfArray, input: AfArray, trans: AfArray, - odim0: DimT, odim1: DimT, method: c_uint, is_inverse: c_int) -> c_int; - - fn af_rotate(out: MutAfArray, input: AfArray, theta: c_float, crop: c_int, - method: c_uint) -> c_int; - - fn af_translate(out: MutAfArray, input: AfArray, trans0: c_float, trans1: c_float, - odim0: DimT, odim1: DimT, method: c_uint) -> c_int; - - fn af_scale(out: MutAfArray, input: AfArray, scale0: c_float, scale1: c_float, - odim0: DimT, odim1: DimT, method: c_uint) -> c_int; - - fn af_skew(out: MutAfArray, input: AfArray, skew0: c_float, skew1: c_float, - odim0: DimT, odim1: DimT, method: c_uint, is_inverse: c_int) -> c_int; - - fn af_histogram(out: MutAfArray, input: AfArray, nbins: c_uint, - minval: c_double, maxval: c_double) -> c_int; + fn af_resize( + out: MutAfArray, + input: AfArray, + odim0: DimT, + odim1: DimT, + method: c_uint, + ) -> c_int; + + fn af_transform( + out: MutAfArray, + input: AfArray, + trans: AfArray, + odim0: DimT, + odim1: DimT, + method: c_uint, + is_inverse: c_int, + ) -> c_int; + + fn af_rotate( + out: MutAfArray, + input: AfArray, + theta: c_float, + crop: c_int, + method: c_uint, + ) -> c_int; + + fn af_translate( + out: MutAfArray, + input: AfArray, + trans0: c_float, + trans1: c_float, + odim0: DimT, + odim1: DimT, + method: c_uint, + ) -> c_int; + + fn af_scale( + out: MutAfArray, + input: AfArray, + scale0: c_float, + scale1: c_float, + odim0: DimT, + odim1: DimT, + method: c_uint, + ) -> c_int; + + fn af_skew( + out: MutAfArray, + input: AfArray, + skew0: c_float, + skew1: c_float, + odim0: DimT, + odim1: DimT, + method: c_uint, + is_inverse: c_int, + ) -> c_int; + + fn af_histogram( + out: MutAfArray, + input: AfArray, + nbins: c_uint, + minval: c_double, + maxval: c_double, + ) -> c_int; fn af_dilate(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int; fn af_dilate3(out: MutAfArray, input: AfArray, mask: AfArray) -> c_int; @@ -57,38 +101,67 @@ extern { fn af_hsv2rgb(out: MutAfArray, input: AfArray) -> c_int; fn af_rgb2hsv(out: MutAfArray, input: AfArray) -> c_int; - fn af_bilateral(out: MutAfArray, input: AfArray, - sp_sig: c_float, ch_sig: c_float, iscolor: c_int) -> c_int; - - fn af_mean_shift(out: MutAfArray, input: AfArray, sp_sig: c_float, - ch_sig: c_float, iter: c_uint, iscolor: c_int) -> c_int; - - fn af_medfilt(out: MutAfArray, input: AfArray, - wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; + fn af_bilateral( + out: MutAfArray, + input: AfArray, + sp_sig: c_float, + ch_sig: c_float, + iscolor: c_int, + ) -> c_int; + + fn af_mean_shift( + out: MutAfArray, + input: AfArray, + sp_sig: c_float, + ch_sig: c_float, + iter: c_uint, + iscolor: c_int, + ) -> c_int; + + fn af_medfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; fn af_medfilt1(out: MutAfArray, input: AfArray, wlen: DimT, etype: c_uint) -> c_int; - fn af_minfilt(out: MutAfArray, input: AfArray, - wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; - - fn af_maxfilt(out: MutAfArray, input: AfArray, - wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; - - fn af_gaussian_kernel(out: MutAfArray, rows: c_int, cols: c_int, - sigma_r: c_double, sigma_c: c_double) -> c_int; - - fn af_color_space(out: MutAfArray, input: AfArray, - tospace: c_uint, fromspace: c_uint) -> c_int; - - fn af_unwrap(out: MutAfArray, input: AfArray, wx: DimT, wy: DimT, sx: DimT, sy: DimT, - px: DimT, py: DimT, is_column: c_int) -> c_int; - - fn af_wrap(out: MutAfArray, input: AfArray, - ox: DimT, oy: DimT, - wx: DimT, wy: DimT, - sx: DimT, sy: DimT, - px: DimT, py: DimT, - is_column: c_int) -> c_int; + fn af_minfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; + + fn af_maxfilt(out: MutAfArray, input: AfArray, wlen: DimT, wwid: DimT, etype: c_uint) -> c_int; + + fn af_gaussian_kernel( + out: MutAfArray, + rows: c_int, + cols: c_int, + sigma_r: c_double, + sigma_c: c_double, + ) -> c_int; + + fn af_color_space(out: MutAfArray, input: AfArray, tospace: c_uint, fromspace: c_uint) + -> c_int; + + fn af_unwrap( + out: MutAfArray, + input: AfArray, + wx: DimT, + wy: DimT, + sx: DimT, + sy: DimT, + px: DimT, + py: DimT, + is_column: c_int, + ) -> c_int; + + fn af_wrap( + out: MutAfArray, + input: AfArray, + ox: DimT, + oy: DimT, + wx: DimT, + wy: DimT, + sx: DimT, + sy: DimT, + px: DimT, + py: DimT, + is_column: c_int, + ) -> c_int; fn af_sat(out: MutAfArray, input: AfArray) -> c_int; @@ -97,14 +170,27 @@ extern { fn af_is_image_io_available(out: *mut c_int) -> c_int; fn af_transform_coordinates(out: MutAfArray, tf: AfArray, d0: c_float, d1: c_float) -> c_int; - fn af_moments(out: MutAfArray, input: AfArray, moment: c_int) ->c_int; - fn af_moments_all(out: *mut c_double, input: AfArray, moment: c_int) ->c_int; - - fn af_canny(out: MutAfArray, input: AfArray, thres_type: c_int, low: c_float, high: c_float, - swindow: c_uint, is_fast: c_int) -> c_int; - fn af_anisotropic_diffusion(out: MutAfArray, input: AfArray, dt: c_float, - K: c_float, iters: c_uint, fftype: c_int, - diff_kind: c_int) -> c_int; + fn af_moments(out: MutAfArray, input: AfArray, moment: c_int) -> c_int; + fn af_moments_all(out: *mut c_double, input: AfArray, moment: c_int) -> c_int; + + fn af_canny( + out: MutAfArray, + input: AfArray, + thres_type: c_int, + low: c_float, + high: c_float, + swindow: c_uint, + is_fast: c_int, + ) -> c_int; + fn af_anisotropic_diffusion( + out: MutAfArray, + input: AfArray, + dt: c_float, + K: c_float, + iters: c_uint, + fftype: c_int, + diff_kind: c_int, + ) -> c_int; } /// Calculate the gradients @@ -124,13 +210,17 @@ extern { /// The second Array is `dy` which is the gradient along the 2nd dimension. #[allow(unused_mut)] pub fn gradient(input: &Array) -> (Array, Array) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut dx: i64 = 0; let mut dy: i64 = 0; unsafe { - let err_val = af_gradient(&mut dx as MutAfArray, &mut dy as MutAfArray, - input.get() as AfArray); + let err_val = af_gradient( + &mut dx as MutAfArray, + &mut dy as MutAfArray, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (dx.into(), dy.into()) @@ -150,17 +240,22 @@ pub fn gradient(input: &Array) -> (Array, Array) /// An Array with pixel values loaded from the image #[allow(unused_mut)] pub fn load_image(filename: String, is_color: bool) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let cstr_param = match CString::new(filename) { Ok(cstr) => cstr, - Err(_) => panic!("CString creation from input filename failed"), + Err(_) => panic!("CString creation from input filename failed"), }; let trgt_type = T::get_af_dtype(); let mut img: i64 = 0; unsafe { let mut temp: i64 = 0; - let err1 = af_load_image(&mut temp as MutAfArray, cstr_param.as_ptr(), is_color as c_int); + let err1 = af_load_image( + &mut temp as MutAfArray, + cstr_param.as_ptr(), + is_color as c_int, + ); HANDLE_ERROR(AfError::from(err1)); let err2 = af_cast(&mut img as MutAfArray, temp as AfArray, trgt_type as c_uint); HANDLE_ERROR(AfError::from(err2)); @@ -188,11 +283,12 @@ pub fn load_image(filename: String, is_color: bool) -> Array /// An Array with pixel values loaded from the image #[allow(unused_mut)] pub fn load_image_native(filename: String) -> Array - where T: HasAfEnum + ImageNativeType +where + T: HasAfEnum + ImageNativeType, { let cstr_param = match CString::new(filename) { Ok(cstr) => cstr, - Err(_) => panic!("CString creation from input filename failed"), + Err(_) => panic!("CString creation from input filename failed"), }; let trgt_type = T::get_af_dtype(); let mut img: i64 = 0; @@ -214,11 +310,12 @@ pub fn load_image_native(filename: String) -> Array /// - `input` is the Array to be stored into the image file #[allow(unused_mut)] pub fn save_image(filename: String, input: &Array) - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let cstr_param = match CString::new(filename) { Ok(cstr) => cstr, - Err(_) => panic!("CString creation from input filename failed"), + Err(_) => panic!("CString creation from input filename failed"), }; unsafe { let err_val = af_save_image(cstr_param.as_ptr(), input.get() as AfArray); @@ -244,11 +341,12 @@ pub fn save_image(filename: String, input: &Array) /// - `input` is the Array to be saved. Should be U8 for saving 8-bit image, U16 for 16-bit image, and F32 for 32-bit image. #[allow(unused_mut)] pub fn save_image_native(filename: String, input: &Array) - where T: HasAfEnum + ImageNativeType +where + T: HasAfEnum + ImageNativeType, { let cstr_param = match CString::new(filename) { Ok(cstr) => cstr, - Err(_) => panic!("CString creation from input filename failed"), + Err(_) => panic!("CString creation from input filename failed"), }; unsafe { let err_val = af_save_image_native(cstr_param.as_ptr(), input.get() as AfArray); @@ -277,13 +375,21 @@ pub fn save_image_native(filename: String, input: &Array) /// /// Resized Array #[allow(unused_mut)] -pub fn resize(input: &Array, - odim0: i64, odim1: i64, - method: InterpType) -> Array { +pub fn resize( + input: &Array, + odim0: i64, + odim1: i64, + method: InterpType, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_resize(&mut temp as MutAfArray, input.get() as AfArray, - odim0 as DimT, odim1 as DimT, method as c_uint); + let err_val = af_resize( + &mut temp as MutAfArray, + input.get() as AfArray, + odim0 as DimT, + odim1 as DimT, + method as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -319,15 +425,25 @@ pub fn resize(input: &Array, /// /// Transformed Array #[allow(unused_mut)] -pub fn transform(input: &Array, trans: &Array, - odim0: i64, odim1: i64, - method: InterpType, is_inverse: bool) -> Array { +pub fn transform( + input: &Array, + trans: &Array, + odim0: i64, + odim1: i64, + method: InterpType, + is_inverse: bool, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_transform(&mut temp as MutAfArray, - input.get() as AfArray, trans.get() as AfArray, - odim0 as DimT, odim1 as DimT, - method as c_uint, is_inverse as c_int); + let err_val = af_transform( + &mut temp as MutAfArray, + input.get() as AfArray, + trans.get() as AfArray, + odim0 as DimT, + odim1 as DimT, + method as c_uint, + is_inverse as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -363,12 +479,21 @@ pub fn transform(input: &Array, trans: &Array, /// /// Rotated Array #[allow(unused_mut)] -pub fn rotate(input: &Array, theta: f64, crop: bool, - method: InterpType) -> Array { +pub fn rotate( + input: &Array, + theta: f64, + crop: bool, + method: InterpType, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_rotate(&mut temp as MutAfArray, input.get() as AfArray, - theta as c_float, crop as c_int, method as c_uint); + let err_val = af_rotate( + &mut temp as MutAfArray, + input.get() as AfArray, + theta as c_float, + crop as c_int, + method as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -402,15 +527,25 @@ pub fn rotate(input: &Array, theta: f64, crop: bool, /// /// Translated Image(Array). #[allow(unused_mut)] -pub fn translate(input: &Array, trans0: f32, trans1: f32, - odim0: i64, odim1: i64, method: InterpType) -> Array { +pub fn translate( + input: &Array, + trans0: f32, + trans1: f32, + odim0: i64, + odim1: i64, + method: InterpType, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_translate(&mut temp as MutAfArray, - input.get() as AfArray, - trans0 as c_float, trans1 as c_float, - odim0 as DimT, odim1 as DimT, - method as c_uint); + let err_val = af_translate( + &mut temp as MutAfArray, + input.get() as AfArray, + trans0 as c_float, + trans1 as c_float, + odim0 as DimT, + odim1 as DimT, + method as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -435,15 +570,25 @@ pub fn translate(input: &Array, trans0: f32, trans1: f32, /// /// Translated Image(Array). #[allow(unused_mut)] -pub fn scale(input: &Array, scale0: f32, scale1: f32, - odim0: i64, odim1: i64, method: InterpType) -> Array { +pub fn scale( + input: &Array, + scale0: f32, + scale1: f32, + odim0: i64, + odim1: i64, + method: InterpType, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_scale(&mut temp as MutAfArray, - input.get() as AfArray, - scale0 as c_float, scale1 as c_float, - odim0 as DimT, odim1 as DimT, - method as c_uint); + let err_val = af_scale( + &mut temp as MutAfArray, + input.get() as AfArray, + scale0 as c_float, + scale1 as c_float, + odim0 as DimT, + odim1 as DimT, + method as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -474,17 +619,27 @@ pub fn scale(input: &Array, scale0: f32, scale1: f32, /// /// Skewed Image #[allow(unused_mut)] -pub fn skew(input: &Array, - skew0: f32, skew1: f32, - odim0: i64, odim1: i64, - method: InterpType, - is_inverse: bool) -> Array { +pub fn skew( + input: &Array, + skew0: f32, + skew1: f32, + odim0: i64, + odim1: i64, + method: InterpType, + is_inverse: bool, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_skew(&mut temp as MutAfArray, input.get() as AfArray, - skew0 as c_float, skew1 as c_float, - odim0 as DimT, odim1 as DimT, - method as c_uint, is_inverse as c_int); + let err_val = af_skew( + &mut temp as MutAfArray, + input.get() as AfArray, + skew0 as c_float, + skew1 as c_float, + odim0 as DimT, + odim1 as DimT, + method as c_uint, + is_inverse as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -514,14 +669,19 @@ pub fn skew(input: &Array, /// /// Histogram of input Array #[allow(unused_mut)] -pub fn histogram(input: &Array, nbins: u32, - minval: f64, maxval: f64) -> Array - where T: HasAfEnum + RealNumber +pub fn histogram(input: &Array, nbins: u32, minval: f64, maxval: f64) -> Array +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_histogram(&mut temp as MutAfArray, input.get() as AfArray, - nbins as c_uint, minval as c_double, maxval as c_double); + let err_val = af_histogram( + &mut temp as MutAfArray, + input.get() as AfArray, + nbins as c_uint, + minval as c_double, + maxval as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -548,12 +708,16 @@ pub fn histogram(input: &Array, nbins: u32, /// Dilated Image(Array) #[allow(unused_mut)] pub fn dilate(input: &Array, mask: &Array) -> Array - where T: HasAfEnum + ImageFilterType +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_dilate(&mut temp as MutAfArray, - input.get() as AfArray, mask.get() as AfArray); + let err_val = af_dilate( + &mut temp as MutAfArray, + input.get() as AfArray, + mask.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -581,12 +745,16 @@ pub fn dilate(input: &Array, mask: &Array) -> Array /// Eroded Image(Array) #[allow(unused_mut)] pub fn erode(input: &Array, mask: &Array) -> Array - where T: HasAfEnum + ImageFilterType +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_erode(&mut temp as MutAfArray, - input.get() as AfArray, mask.get() as AfArray); + let err_val = af_erode( + &mut temp as MutAfArray, + input.get() as AfArray, + mask.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -607,12 +775,16 @@ pub fn erode(input: &Array, mask: &Array) -> Array /// Dilated Volume(Array) #[allow(unused_mut)] pub fn dilate3(input: &Array, mask: &Array) -> Array - where T: HasAfEnum + ImageFilterType +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_dilate3(&mut temp as MutAfArray, - input.get() as AfArray, mask.get() as AfArray); + let err_val = af_dilate3( + &mut temp as MutAfArray, + input.get() as AfArray, + mask.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -633,12 +805,16 @@ pub fn dilate3(input: &Array, mask: &Array) -> Array /// Eroded Volume(Array) #[allow(unused_mut)] pub fn erode3(input: &Array, mask: &Array) -> Array - where T: HasAfEnum + ImageFilterType +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_erode3(&mut temp as MutAfArray, - input.get() as AfArray, mask.get() as AfArray); + let err_val = af_erode3( + &mut temp as MutAfArray, + input.get() as AfArray, + mask.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -664,16 +840,25 @@ pub fn erode3(input: &Array, mask: &Array) -> Array /// /// Filtered Image - Array #[allow(unused_mut)] -pub fn bilateral(input: &Array, spatial_sigma: f32, chromatic_sigma: f32, - iscolor: bool) -> Array< T::AbsOutType > - where T: HasAfEnum + ImageFilterType, - T::AbsOutType: HasAfEnum +pub fn bilateral( + input: &Array, + spatial_sigma: f32, + chromatic_sigma: f32, + iscolor: bool, +) -> Array +where + T: HasAfEnum + ImageFilterType, + T::AbsOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_bilateral(&mut temp as MutAfArray, input.get() as AfArray, - spatial_sigma as c_float, chromatic_sigma as c_float, - iscolor as c_int); + let err_val = af_bilateral( + &mut temp as MutAfArray, + input.get() as AfArray, + spatial_sigma as c_float, + chromatic_sigma as c_float, + iscolor as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -700,23 +885,33 @@ pub fn bilateral(input: &Array, spatial_sigma: f32, chromatic_sigma: f32, /// /// Filtered Image - Array #[allow(unused_mut)] -pub fn mean_shift(input: &Array, - spatial_sigma: f32, chromatic_sigma: f32, - iter: u32, iscolor: bool) -> Array - where T: HasAfEnum + RealNumber +pub fn mean_shift( + input: &Array, + spatial_sigma: f32, + chromatic_sigma: f32, + iter: u32, + iscolor: bool, +) -> Array +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_mean_shift(&mut temp as MutAfArray, input.get() as AfArray, - spatial_sigma as c_float, chromatic_sigma as c_float, - iter as c_uint, iscolor as c_int); + let err_val = af_mean_shift( + &mut temp as MutAfArray, + input.get() as AfArray, + spatial_sigma as c_float, + chromatic_sigma as c_float, + iter as c_uint, + iscolor as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! filt_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -730,24 +925,37 @@ macro_rules! filt_func_def { /// /// An Array with filtered image data. #[allow(unused_mut)] - pub fn $fn_name(input: &Array, wlen: u64, wwid: u64, - etype: BorderType) -> Array - where T: HasAfEnum + ImageFilterType + pub fn $fn_name(input: &Array, wlen: u64, wwid: u64, etype: BorderType) -> Array + where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, input.get() as AfArray, - wlen as DimT, wwid as DimT, etype as c_uint); + let err_val = $ffi_name( + &mut temp as MutAfArray, + input.get() as AfArray, + wlen as DimT, + wwid as DimT, + etype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } filt_func_def!("Median filter", medfilt, af_medfilt); -filt_func_def!("Box filter with minimum as box operation", minfilt, af_minfilt); -filt_func_def!("Box filter with maximum as box operation", maxfilt, af_maxfilt); +filt_func_def!( + "Box filter with minimum as box operation", + minfilt, + af_minfilt +); +filt_func_def!( + "Box filter with maximum as box operation", + maxfilt, + af_maxfilt +); /// Creates a Gaussian Kernel. /// @@ -774,9 +982,13 @@ filt_func_def!("Box filter with maximum as box operation", maxfilt, af_maxfilt); pub fn gaussian_kernel(rows: i32, cols: i32, sigma_r: f64, sigma_c: f64) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_gaussian_kernel(&mut temp as MutAfArray, - rows as c_int, cols as c_int, - sigma_r as c_double, sigma_c as c_double); + let err_val = af_gaussian_kernel( + &mut temp as MutAfArray, + rows as c_int, + cols as c_int, + sigma_r as c_double, + sigma_c as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -817,15 +1029,18 @@ pub fn gaussian_kernel(rows: i32, cols: i32, sigma_r: f64, sigma_c: f64) -> Arra /// /// An Array with input image values in target color space #[allow(unused_mut)] -pub fn color_space(input: &Array, - tospace: ColorSpace, - fromspace: ColorSpace) -> Array - where T: HasAfEnum + RealNumber +pub fn color_space(input: &Array, tospace: ColorSpace, fromspace: ColorSpace) -> Array +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_color_space(&mut temp as MutAfArray, input.get() as AfArray, - tospace as c_uint, fromspace as c_uint); + let err_val = af_color_space( + &mut temp as MutAfArray, + input.get() as AfArray, + tospace as c_uint, + fromspace as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -850,13 +1065,18 @@ pub fn color_space(input: &Array, /// Array with labels indicating different regions #[allow(unused_mut)] pub fn regions(input: &Array, conn: Connectivity) -> Array - where OutType: HasAfEnum + RealNumber +where + OutType: HasAfEnum + RealNumber, { let otype = OutType::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_regions(&mut temp as MutAfArray, input.get() as AfArray, - conn as c_uint, otype as c_uint); + let err_val = af_regions( + &mut temp as MutAfArray, + input.get() as AfArray, + conn as c_uint, + otype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -880,16 +1100,20 @@ pub fn regions(input: &Array, conn: Connectivity) -> Array(input: &Array, - ker_size: u32) -> (Array< T::SobelOutType >, Array< T::SobelOutType >) - where T: HasAfEnum + ImageFilterType, - T::SobelOutType: HasAfEnum +pub fn sobel(input: &Array, ker_size: u32) -> (Array, Array) +where + T: HasAfEnum + ImageFilterType, + T::SobelOutType: HasAfEnum, { let mut dx: i64 = 0; let mut dy: i64 = 0; unsafe { - let err_val = af_sobel_operator(&mut dx as MutAfArray, &mut dy as MutAfArray, - input.get() as AfArray, ker_size as c_uint); + let err_val = af_sobel_operator( + &mut dx as MutAfArray, + &mut dy as MutAfArray, + input.get() as AfArray, + ker_size as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } (dx.into(), dy.into()) @@ -906,19 +1130,23 @@ pub fn sobel(input: &Array, /// Equalized Array #[allow(unused_mut)] pub fn hist_equal(input: &Array, hist: &Array) -> Array - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut temp: i64 = 0; unsafe { - let err_val = af_hist_equal(&mut temp as MutAfArray, - input.get() as AfArray, hist.get() as AfArray); + let err_val = af_hist_equal( + &mut temp as MutAfArray, + input.get() as AfArray, + hist.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! grayrgb_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -932,28 +1160,35 @@ macro_rules! grayrgb_func_def { ///An Array with image data in target color space #[allow(unused_mut)] pub fn $fn_name(input: &Array, r: f32, g: f32, b: f32) -> Array - where T: HasAfEnum + GrayRGBConvertible + where + T: HasAfEnum + GrayRGBConvertible, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, input.get() as AfArray, - r as c_float, g as c_float, b as c_float); + let err_val = $ffi_name( + &mut temp as MutAfArray, + input.get() as AfArray, + r as c_float, + g as c_float, + b as c_float, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } grayrgb_func_def!("Color(RGB) to Grayscale conversion", rgb2gray, af_rgb2gray); grayrgb_func_def!("Grayscale to Color(RGB) conversion", gray2rgb, af_gray2rgb); macro_rules! hsvrgb_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_name: ident) => { #[doc=$doc_str] #[allow(unused_mut)] pub fn $fn_name(input: &Array) -> Array - where T: HasAfEnum + RealFloating + where + T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { @@ -962,7 +1197,7 @@ macro_rules! hsvrgb_func_def { } temp.into() } - ) + }; } hsvrgb_func_def!("HSV to RGB color space conversion", hsv2rgb, af_hsv2rgb); @@ -1038,15 +1273,29 @@ hsvrgb_func_def!("RGB to HSV color space conversion", rgb2hsv, af_rgb2hsv); /// 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 0 0 0 0 0 /// 16 17 18 19 0 21 22 23 24 0 26 27 28 29 0 31 32 33 34 0 0 0 0 0 0 /// ``` -pub fn unwrap(input: &Array, - wx: i64, wy: i64, - sx: i64, sy: i64, - px: i64, py: i64, - is_column: bool) -> Array { +pub fn unwrap( + input: &Array, + wx: i64, + wy: i64, + sx: i64, + sy: i64, + px: i64, + py: i64, + is_column: bool, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_unwrap(&mut temp as MutAfArray, input.get() as AfArray, - wx, wy, sx, sy, px, py, is_column as c_int); + let err_val = af_unwrap( + &mut temp as MutAfArray, + input.get() as AfArray, + wx, + wy, + sx, + sy, + px, + py, + is_column as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1075,14 +1324,33 @@ pub fn unwrap(input: &Array, /// # Return Values /// /// Image(Array) created from unwrapped Image(Array) -pub fn wrap(input: &Array, - ox: i64, oy: i64, wx: i64, wy: i64, - sx: i64, sy: i64, px: i64, py: i64, - is_column: bool) -> Array { +pub fn wrap( + input: &Array, + ox: i64, + oy: i64, + wx: i64, + wy: i64, + sx: i64, + sy: i64, + px: i64, + py: i64, + is_column: bool, +) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_wrap(&mut temp as MutAfArray, input.get() as AfArray, - ox, oy, wx, wy, sx, sy, px, py, is_column as c_int); + let err_val = af_wrap( + &mut temp as MutAfArray, + input.get() as AfArray, + ox, + oy, + wx, + wy, + sx, + sy, + px, + py, + is_column as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1097,9 +1365,10 @@ pub fn wrap(input: &Array, /// # Return Values /// /// Summed area table (a.k.a Integral Image) of the input image. -pub fn sat(input: &Array) -> Array< T::AggregateOutType > - where T: HasAfEnum + RealNumber, - T::AggregateOutType: HasAfEnum +pub fn sat(input: &Array) -> Array +where + T: HasAfEnum + RealNumber, + T::AggregateOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { @@ -1130,12 +1399,16 @@ pub fn sat(input: &Array) -> Array< T::AggregateOutType > /// /// Image(Array) in YCbCr color space pub fn rgb2ycbcr(input: &Array, standard: YCCStd) -> Array - where T: HasAfEnum + RealFloating +where + T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_rgb2ycbcr(&mut temp as MutAfArray, input.get() as AfArray, - standard as c_int); + let err_val = af_rgb2ycbcr( + &mut temp as MutAfArray, + input.get() as AfArray, + standard as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1168,12 +1441,16 @@ pub fn rgb2ycbcr(input: &Array, standard: YCCStd) -> Array /// /// Image(Array) in RGB color space pub fn ycbcr2rgb(input: &Array, standard: YCCStd) -> Array - where T: HasAfEnum + RealFloating +where + T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_ycbcr2rgb(&mut temp as MutAfArray, input.get() as AfArray, - standard as c_int); + let err_val = af_ycbcr2rgb( + &mut temp as MutAfArray, + input.get() as AfArray, + standard as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1214,13 +1491,17 @@ pub fn is_imageio_available() -> bool { /// /// Transformed coordinates pub fn transform_coords(tf: &Array, d0: f32, d1: f32) -> Array - where T: HasAfEnum + RealFloating +where + T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_transform_coordinates(&mut temp as MutAfArray, - tf.get() as AfArray, - d0 as c_float, d1 as c_float); + let err_val = af_transform_coordinates( + &mut temp as MutAfArray, + tf.get() as AfArray, + d0 as c_float, + d1 as c_float, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1238,13 +1519,16 @@ pub fn transform_coords(tf: &Array, d0: f32, d1: f32) -> Array /// /// Moments Array pub fn moments(input: &Array, moment: MomentType) -> Array - where T: HasAfEnum + MomentsComputable +where + T: HasAfEnum + MomentsComputable, { let mut temp: i64 = 0; unsafe { - let err_val = af_moments(&mut temp as MutAfArray, - input.get() as AfArray, - moment as c_int); + let err_val = af_moments( + &mut temp as MutAfArray, + input.get() as AfArray, + moment as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1262,13 +1546,16 @@ pub fn moments(input: &Array, moment: MomentType) -> Array /// /// Moment value of the whole image pub fn moments_all(input: &Array, moment: MomentType) -> f64 - where T: HasAfEnum + MomentsComputable +where + T: HasAfEnum + MomentsComputable, { let mut temp: f64 = 0.0; unsafe { - let err_val = af_moments_all(&mut temp as *mut c_double, - input.get() as AfArray, - moment as c_int); + let err_val = af_moments_all( + &mut temp as *mut c_double, + input.get() as AfArray, + moment as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp @@ -1286,12 +1573,17 @@ pub fn moments_all(input: &Array, moment: MomentType) -> f64 /// /// An Array with filtered image data. pub fn medfilt1(input: &Array, wlen: u64, etype: BorderType) -> Array - where T: HasAfEnum + ImageFilterType +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_medfilt1(&mut temp as MutAfArray, input.get() as AfArray, - wlen as DimT, etype as c_uint); + let err_val = af_medfilt1( + &mut temp as MutAfArray, + input.get() as AfArray, + wlen as DimT, + etype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1314,16 +1606,28 @@ pub fn medfilt1(input: &Array, wlen: u64, etype: BorderType) -> Array /// /// An Array of binary type [DType::B8](./enum.DType.html) indicating edges(All pixels with /// non-zero values are edges). -pub fn canny(input: &Array, threshold_type: CannyThresholdType, - low: f32, hight: f32, - sobel_window: u32, is_fast: bool) -> Array - where T: HasAfEnum + EdgeComputable +pub fn canny( + input: &Array, + threshold_type: CannyThresholdType, + low: f32, + hight: f32, + sobel_window: u32, + is_fast: bool, +) -> Array +where + T: HasAfEnum + EdgeComputable, { let mut temp: i64 = 0; unsafe { - let err_val = af_canny(&mut temp as MutAfArray, input.get() as AfArray, - threshold_type as c_int, low as c_float, hight as c_float, - sobel_window as c_uint, is_fast as c_int); + let err_val = af_canny( + &mut temp as MutAfArray, + input.get() as AfArray, + threshold_type as c_int, + low as c_float, + hight as c_float, + sobel_window as c_uint, + is_fast as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -1403,21 +1707,29 @@ pub fn canny(input: &Array, threshold_type: CannyThresholdType, /// - R. Whitaker and X. Xue. `Variable-Conductance, Level-Set Curvature /// for Image Denoising`, International Conference on Image Processing, /// 2001 pp. 142-145, Vol.3. -pub fn anisotropic_diffusion(img: &Array, - dt: f32, k: f32, iters: u32, - fftype: FluxFn, - diff_kind: DiffusionEq) -> Array< T::AbsOutType > - where T: HasAfEnum + EdgeComputable, - T::AbsOutType: HasAfEnum +pub fn anisotropic_diffusion( + img: &Array, + dt: f32, + k: f32, + iters: u32, + fftype: FluxFn, + diff_kind: DiffusionEq, +) -> Array +where + T: HasAfEnum + EdgeComputable, + T::AbsOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_anisotropic_diffusion(&mut temp as MutAfArray, - img.get() as AfArray, - dt as c_float, k as c_float, - iters as c_uint, - fftype as c_int, - diff_kind as c_int); + let err_val = af_anisotropic_diffusion( + &mut temp as MutAfArray, + img.get() as AfArray, + dt as c_float, + k as c_float, + iters as c_uint, + fftype as c_int, + diff_kind as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() diff --git a/src/index.rs b/src/index.rs index e8c0b5c47..8d6ec9df2 100644 --- a/src/index.rs +++ b/src/index.rs @@ -1,26 +1,44 @@ extern crate libc; -use array::Array; -use defines::AfError; -use error::HANDLE_ERROR; -use seq::Seq; use self::libc::{c_double, c_int, c_uint}; -use util::{AfArray, AfIndex, DimT, HasAfEnum, MutAfArray, MutAfIndex}; +use crate::array::Array; +use crate::defines::AfError; +use crate::error::HANDLE_ERROR; +use crate::seq::Seq; +use crate::util::{AfArray, AfIndex, DimT, HasAfEnum, MutAfArray, MutAfIndex}; use std::marker::PhantomData; #[allow(dead_code)] -extern { +extern "C" { fn af_create_indexers(indexers: MutAfIndex) -> c_int; fn af_set_array_indexer(indexer: AfIndex, idx: AfArray, dim: DimT) -> c_int; - fn af_set_seq_indexer(indexer: AfIndex, idx: *const SeqInternal, dim: DimT, is_batch: c_int) -> c_int; + fn af_set_seq_indexer( + indexer: AfIndex, + idx: *const SeqInternal, + dim: DimT, + is_batch: c_int, + ) -> c_int; fn af_release_indexers(indexers: AfIndex) -> c_int; - fn af_index(out: MutAfArray, input: AfArray, ndims: c_uint, index: *const SeqInternal) -> c_int; + fn af_index(out: MutAfArray, input: AfArray, ndims: c_uint, index: *const SeqInternal) + -> c_int; fn af_lookup(out: MutAfArray, arr: AfArray, indices: AfArray, dim: c_uint) -> c_int; - fn af_assign_seq(out: MutAfArray, lhs: AfArray, ndims: c_uint, indices: *const SeqInternal, rhs: AfArray) -> c_int; + fn af_assign_seq( + out: MutAfArray, + lhs: AfArray, + ndims: c_uint, + indices: *const SeqInternal, + rhs: AfArray, + ) -> c_int; fn af_index_gen(out: MutAfArray, input: AfArray, ndims: DimT, indices: AfIndex) -> c_int; - fn af_assign_gen(out: MutAfArray, lhs: AfArray, ndims: DimT, indices: AfIndex, rhs: AfArray) -> c_int; + fn af_assign_gen( + out: MutAfArray, + lhs: AfArray, + ndims: DimT, + indices: AfIndex, + rhs: AfArray, + ) -> c_int; } /// Struct to manage an array of resources of type `af_indexer_t`(ArrayFire C struct) @@ -106,8 +124,8 @@ impl Indexable for Array { #[allow(unused_variables)] fn set(&self, idxr: &mut Indexer, dim: u32, is_batch: Option) { unsafe { - let err_val = af_set_array_indexer(idxr.get() as AfIndex, self.get() as AfArray, - dim as DimT); + let err_val = + af_set_array_indexer(idxr.get() as AfIndex, self.get() as AfArray, dim as DimT); HANDLE_ERROR(AfError::from(err_val)); } } @@ -117,12 +135,18 @@ impl Indexable for Array { /// /// This is used in functions [index_gen](./fn.index_gen.html) and /// [assign_gen](./fn.assign_gen.html) -impl Indexable for Seq where c_double: From { +impl Indexable for Seq +where + c_double: From, +{ fn set(&self, idxr: &mut Indexer, dim: u32, is_batch: Option) { unsafe { - let err_val = af_set_seq_indexer(idxr.get() as AfIndex, - &SeqInternal::from_seq(self) as *const SeqInternal, - dim as DimT, is_batch.unwrap() as c_int); + let err_val = af_set_seq_indexer( + idxr.get() as AfIndex, + &SeqInternal::from_seq(self) as *const SeqInternal, + dim as DimT, + is_batch.unwrap() as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } } @@ -137,14 +161,20 @@ impl<'object> Indexer<'object> { let err_val = af_create_indexers(&mut temp as MutAfIndex); HANDLE_ERROR(AfError::from(err_val)); } - Indexer{handle: temp, count: 0, marker: PhantomData} + Indexer { + handle: temp, + count: 0, + marker: PhantomData, + } } /// Set either [Array](./struct.Array.html) or [Seq](./struct.Seq.html) to index an Array along `idx` dimension pub fn set_index<'s, T>(&'s mut self, idx: &'object T, dim: u32, is_batch: Option) - where T : Indexable + 'object { + where + T: Indexable + 'object, + { idx.set(self, dim, is_batch); - self.count = self.count+1; + self.count = self.count + 1; } /// Get number of indexing objects set @@ -184,15 +214,20 @@ impl<'object> Drop for Indexer<'object> { /// print(&sub); /// ``` pub fn index(input: &Array, seqs: &[Seq]) -> Array - where c_double: From, IO: HasAfEnum +where + c_double: From, + IO: HasAfEnum, { let mut temp: i64 = 0; unsafe { // TODO: allocating a whole new array on the heap just for this is BAD let seqs: Vec = seqs.iter().map(|s| SeqInternal::from_seq(s)).collect(); - let err_val = af_index(&mut temp as MutAfArray - , input.get() as AfArray, seqs.len() as u32 - , seqs.as_ptr() as *const SeqInternal); + let err_val = af_index( + &mut temp as MutAfArray, + input.get() as AfArray, + seqs.len() as u32, + seqs.as_ptr() as *const SeqInternal, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -212,32 +247,48 @@ pub fn index(input: &Array, seqs: &[Seq]) -> Array /// ``` #[allow(dead_code)] pub fn row(input: &Array, row_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - index(input, &[Seq::new(row_num as f64, row_num as f64, 1.0), Seq::default()]) + index( + input, + &[ + Seq::new(row_num as f64, row_num as f64, 1.0), + Seq::default(), + ], + ) } #[allow(dead_code)] /// Set `row_num`^th row in `input` Array to a new Array `new_row` pub fn set_row(input: &Array, new_row: &Array, row_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::new(row_num as f64, row_num as f64, 1.0), Seq::default()]; + let seqs = [ + Seq::new(row_num as f64, row_num as f64, 1.0), + Seq::default(), + ]; assign_seq(input, &seqs, new_row) } #[allow(dead_code)] /// Get an Array with all rows from `first` to `last` in the `input` Array pub fn rows(input: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - index(input, &[Seq::new(first as f64, last as f64, 1.0), Seq::default()]) + index( + input, + &[Seq::new(first as f64, last as f64, 1.0), Seq::default()], + ) } #[allow(dead_code)] /// Set rows from `first` to `last` in `input` Array with rows from Array `new_rows` pub fn set_rows(input: &Array, new_rows: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { let seqs = [Seq::new(first as f64, last as f64, 1.0), Seq::default()]; assign_seq(input, &seqs, new_rows) @@ -257,32 +308,48 @@ pub fn set_rows(input: &Array, new_rows: &Array, first: u64, last: u64) /// ``` #[allow(dead_code)] pub fn col(input: &Array, col_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - index(input, &[Seq::default(), Seq::new(col_num as f64, col_num as f64, 1.0)]) + index( + input, + &[ + Seq::default(), + Seq::new(col_num as f64, col_num as f64, 1.0), + ], + ) } #[allow(dead_code)] /// Set `col_num`^th col in `input` Array to a new Array `new_col` pub fn set_col(input: &Array, new_col: &Array, col_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::default(), Seq::new(col_num as f64, col_num as f64, 1.0)]; + let seqs = [ + Seq::default(), + Seq::new(col_num as f64, col_num as f64, 1.0), + ]; assign_seq(input, &seqs, new_col) } #[allow(dead_code)] /// Get all cols from `first` to `last` in the `input` Array pub fn cols(input: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - index(input, &[Seq::default(), Seq::new(first as f64, last as f64, 1.0)]) + index( + input, + &[Seq::default(), Seq::new(first as f64, last as f64, 1.0)], + ) } #[allow(dead_code)] /// Set cols from `first` to `last` in `input` Array with cols from Array `new_cols` pub fn set_cols(input: &Array, new_cols: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { let seqs = [Seq::default(), Seq::new(first as f64, last as f64, 1.0)]; assign_seq(input, &seqs, new_cols) @@ -293,9 +360,14 @@ pub fn set_cols(input: &Array, new_cols: &Array, first: u64, last: u64) /// /// Note. Slices indicate that the indexing is along 3rd dimension pub fn slice(input: &Array, slice_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::default(), Seq::default(), Seq::new(slice_num as f64, slice_num as f64, 1.0)]; + let seqs = [ + Seq::default(), + Seq::default(), + Seq::new(slice_num as f64, slice_num as f64, 1.0), + ]; index(input, &seqs) } @@ -304,9 +376,14 @@ pub fn slice(input: &Array, slice_num: u64) -> Array /// /// Slices indicate that the indexing is along 3rd dimension pub fn set_slice(input: &Array, new_slice: &Array, slice_num: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::default(), Seq::default(), Seq::new(slice_num as f64, slice_num as f64, 1.0)]; + let seqs = [ + Seq::default(), + Seq::default(), + Seq::new(slice_num as f64, slice_num as f64, 1.0), + ]; assign_seq(input, &seqs, new_slice) } @@ -315,9 +392,14 @@ pub fn set_slice(input: &Array, new_slice: &Array, slice_num: u64) -> A /// /// Slices indicate that the indexing is along 3rd dimension pub fn slices(input: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::default(), Seq::default(), Seq::new(first as f64, last as f64, 1.0)]; + let seqs = [ + Seq::default(), + Seq::default(), + Seq::new(first as f64, last as f64, 1.0), + ]; index(input, &seqs) } @@ -326,9 +408,14 @@ pub fn slices(input: &Array, first: u64, last: u64) -> Array /// /// Slices indicate that the indexing is along 3rd dimension pub fn set_slices(input: &Array, new_slices: &Array, first: u64, last: u64) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { - let seqs = [Seq::default() , Seq::default(), Seq::new(first as f64, last as f64, 1.0)]; + let seqs = [ + Seq::default(), + Seq::default(), + Seq::new(first as f64, last as f64, 1.0), + ]; assign_seq(input, &seqs, new_slices) } @@ -337,13 +424,18 @@ pub fn set_slices(input: &Array, new_slices: &Array, first: u64, last: /// Given a dimension `seq_dim`, `indices` are lookedup in `input` and returned as a new /// Array if found pub fn lookup(input: &Array, indices: &Array, seq_dim: i32) -> Array - where T: HasAfEnum, - I: HasAfEnum +where + T: HasAfEnum, + I: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_lookup(&mut temp as MutAfArray, input.get() as AfArray, - indices.get() as AfArray, seq_dim as c_uint); + let err_val = af_lookup( + &mut temp as MutAfArray, + input.get() as AfArray, + indices.get() as AfArray, + seq_dim as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -376,16 +468,21 @@ pub fn lookup(input: &Array, indices: &Array, seq_dim: i32) -> Array /// // 2.0 2.0 2.0 /// ``` pub fn assign_seq(lhs: &Array, seqs: &[Seq], rhs: &Array) -> Array - where c_double: From, - I: HasAfEnum +where + c_double: From, + I: HasAfEnum, { let mut temp: i64 = 0; // TODO: allocating a whole new array on the heap just for this is BAD let seqs: Vec = seqs.iter().map(|s| SeqInternal::from_seq(s)).collect(); unsafe { - let err_val = af_assign_seq(&mut temp as MutAfArray, lhs.get() as AfArray, - seqs.len() as c_uint, seqs.as_ptr() as *const SeqInternal, - rhs.get() as AfArray); + let err_val = af_assign_seq( + &mut temp as MutAfArray, + lhs.get() as AfArray, + seqs.len() as c_uint, + seqs.as_ptr() as *const SeqInternal, + rhs.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -421,12 +518,17 @@ pub fn assign_seq(lhs: &Array, seqs: &[Seq], rhs: &Array) - /// // 0.4587 0.6793 0.0346 /// ``` pub fn index_gen(input: &Array, indices: Indexer) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { let mut temp: i64 = 0; - unsafe{ - let err_val = af_index_gen(&mut temp as MutAfArray, input.get() as AfArray, - indices.len() as DimT, indices.get() as AfIndex); + unsafe { + let err_val = af_index_gen( + &mut temp as MutAfArray, + input.get() as AfArray, + indices.len() as DimT, + indices.get() as AfIndex, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -465,13 +567,18 @@ pub fn index_gen(input: &Array, indices: Indexer) -> Array /// // 0.5328 0.9347 0.0535 /// ``` pub fn assign_gen(lhs: &Array, indices: &Indexer, rhs: &Array) -> Array - where T: HasAfEnum +where + T: HasAfEnum, { let mut temp: i64 = 0; - unsafe{ - let err_val = af_assign_gen(&mut temp as MutAfArray, lhs.get() as AfArray, - indices.len() as DimT, indices.get() as AfIndex, - rhs.get() as AfArray); + unsafe { + let err_val = af_assign_gen( + &mut temp as MutAfArray, + lhs.get() as AfArray, + indices.len() as DimT, + indices.get() as AfIndex, + rhs.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -485,7 +592,10 @@ struct SeqInternal { } impl SeqInternal { - fn from_seq(s: &Seq) -> Self where c_double: From { + fn from_seq(s: &Seq) -> Self + where + c_double: From, + { SeqInternal { begin: From::from(s.begin()), end: From::from(s.end()), diff --git a/src/lapack/mod.rs b/src/lapack/mod.rs index 62889d40b..e93e6c3f6 100644 --- a/src/lapack/mod.rs +++ b/src/lapack/mod.rs @@ -1,14 +1,14 @@ extern crate libc; -use array::Array; -use defines::{AfError, MatProp, NormType}; -use error::HANDLE_ERROR; -use util::{AfArray, MutAfArray, MutDouble, to_u32}; -use util::{FloatingPoint, HasAfEnum}; -use self::libc::{c_int, c_uint, c_double}; +use self::libc::{c_double, c_int, c_uint}; +use crate::array::Array; +use crate::defines::{AfError, MatProp, NormType}; +use crate::error::HANDLE_ERROR; +use crate::util::{to_u32, AfArray, MutAfArray, MutDouble}; +use crate::util::{FloatingPoint, HasAfEnum}; #[allow(dead_code)] -extern { +extern "C" { fn af_svd(u: MutAfArray, s: MutAfArray, vt: MutAfArray, input: AfArray) -> c_int; fn af_svd_inplace(u: MutAfArray, s: MutAfArray, vt: MutAfArray, input: AfArray) -> c_int; fn af_lu(lower: MutAfArray, upper: MutAfArray, pivot: MutAfArray, input: AfArray) -> c_int; @@ -50,17 +50,21 @@ extern { /// /// The third Array is the output array containing V ^ H #[allow(unused_mut)] -pub fn svd(input: &Array) -> (Array, Array< T::BaseType >, Array) - where T: HasAfEnum + FloatingPoint, - T::BaseType: HasAfEnum +pub fn svd(input: &Array) -> (Array, Array, Array) +where + T: HasAfEnum + FloatingPoint, + T::BaseType: HasAfEnum, { let mut u: i64 = 0; let mut s: i64 = 0; let mut vt: i64 = 0; unsafe { - let err_val = af_svd(&mut u as MutAfArray, &mut s as MutAfArray, - &mut vt as MutAfArray, - input.get() as AfArray); + let err_val = af_svd( + &mut u as MutAfArray, + &mut s as MutAfArray, + &mut vt as MutAfArray, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (u.into(), s.into(), vt.into()) @@ -91,16 +95,21 @@ pub fn svd(input: &Array) -> (Array, Array< T::BaseType >, Array) /// /// The third Array is the output array containing V ^ H #[allow(unused_mut)] -pub fn svd_inplace(input: &mut Array) -> (Array, Array< T::BaseType >, Array) - where T: HasAfEnum + FloatingPoint, - T::BaseType: HasAfEnum +pub fn svd_inplace(input: &mut Array) -> (Array, Array, Array) +where + T: HasAfEnum + FloatingPoint, + T::BaseType: HasAfEnum, { let mut u: i64 = 0; let mut s: i64 = 0; let mut vt: i64 = 0; unsafe { - let err_val = af_svd_inplace(&mut u as MutAfArray, &mut s as MutAfArray, - &mut vt as MutAfArray, input.get() as AfArray); + let err_val = af_svd_inplace( + &mut u as MutAfArray, + &mut s as MutAfArray, + &mut vt as MutAfArray, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (u.into(), s.into(), vt.into()) @@ -123,14 +132,19 @@ pub fn svd_inplace(input: &mut Array) -> (Array, Array< T::BaseType >, /// The third Array will contain the permutation indices to map the input to the decomposition. #[allow(unused_mut)] pub fn lu(input: &Array) -> (Array, Array, Array) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut lower: i64 = 0; let mut upper: i64 = 0; let mut pivot: i64 = 0; unsafe { - let err_val = af_lu(&mut lower as MutAfArray, &mut upper as MutAfArray, - &mut pivot as MutAfArray, input.get() as AfArray); + let err_val = af_lu( + &mut lower as MutAfArray, + &mut upper as MutAfArray, + &mut pivot as MutAfArray, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (lower.into(), upper.into(), pivot.into()) @@ -149,12 +163,16 @@ pub fn lu(input: &Array) -> (Array, Array, Array) /// matrix is modified in place, only pivot values are returned. #[allow(unused_mut)] pub fn lu_inplace(input: &mut Array, is_lapack_piv: bool) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut pivot: i64 = 0; unsafe { - let err_val = af_lu_inplace(&mut pivot as MutAfArray, input.get() as AfArray, - is_lapack_piv as c_int); + let err_val = af_lu_inplace( + &mut pivot as MutAfArray, + input.get() as AfArray, + is_lapack_piv as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } pivot.into() @@ -178,14 +196,19 @@ pub fn lu_inplace(input: &mut Array, is_lapack_piv: bool) -> Array /// using q and r #[allow(unused_mut)] pub fn qr(input: &Array) -> (Array, Array, Array) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut q: i64 = 0; let mut r: i64 = 0; let mut tau: i64 = 0; unsafe { - let err_val = af_qr(&mut q as MutAfArray, &mut r as MutAfArray, - &mut tau as MutAfArray, input.get() as AfArray); + let err_val = af_qr( + &mut q as MutAfArray, + &mut r as MutAfArray, + &mut tau as MutAfArray, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (q.into(), r.into(), tau.into()) @@ -202,7 +225,8 @@ pub fn qr(input: &Array) -> (Array, Array, Array) /// An Array with additional information needed for unpacking the data. #[allow(unused_mut)] pub fn qr_inplace(input: &mut Array) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut tau: i64 = 0; unsafe { @@ -229,13 +253,18 @@ pub fn qr_inplace(input: &mut Array) -> Array /// which the decomposition failed. #[allow(unused_mut)] pub fn cholesky(input: &Array, is_upper: bool) -> (Array, i32) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; let mut info: i32 = 0; unsafe { - let err_val = af_cholesky(&mut temp as MutAfArray, &mut info as *mut c_int, - input.get() as AfArray, is_upper as c_int); + let err_val = af_cholesky( + &mut temp as MutAfArray, + &mut info as *mut c_int, + input.get() as AfArray, + is_upper as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (temp.into(), info) @@ -254,12 +283,16 @@ pub fn cholesky(input: &Array, is_upper: bool) -> (Array, i32) /// it will contain the rank at which the decomposition failed. #[allow(unused_mut)] pub fn cholesky_inplace(input: &mut Array, is_upper: bool) -> i32 - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut info: i32 = 0; unsafe { - let err_val = af_cholesky_inplace(&mut info as *mut c_int, input.get() as AfArray, - is_upper as c_int); + let err_val = af_cholesky_inplace( + &mut info as *mut c_int, + input.get() as AfArray, + is_upper as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } info @@ -280,12 +313,17 @@ pub fn cholesky_inplace(input: &mut Array, is_upper: bool) -> i32 /// An Array which is the matrix of unknown variables #[allow(unused_mut)] pub fn solve(a: &Array, b: &Array, options: MatProp) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_solve(&mut temp as MutAfArray, a.get() as AfArray, - b.get() as AfArray, to_u32(options) as c_uint); + let err_val = af_solve( + &mut temp as MutAfArray, + a.get() as AfArray, + b.get() as AfArray, + to_u32(options) as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -306,15 +344,19 @@ pub fn solve(a: &Array, b: &Array, options: MatProp) -> Array /// /// An Array which is the matrix of unknown variables #[allow(unused_mut)] -pub fn solve_lu(a: &Array, piv: &Array, b: &Array, - options: MatProp) -> Array - where T: HasAfEnum + FloatingPoint +pub fn solve_lu(a: &Array, piv: &Array, b: &Array, options: MatProp) -> Array +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_solve_lu(&mut temp as MutAfArray, a.get() as AfArray, - piv.get() as AfArray, b.get() as AfArray, - to_u32(options) as c_uint); + let err_val = af_solve_lu( + &mut temp as MutAfArray, + a.get() as AfArray, + piv.get() as AfArray, + b.get() as AfArray, + to_u32(options) as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -334,13 +376,16 @@ pub fn solve_lu(a: &Array, piv: &Array, b: &Array, /// An Array with values of the inverse of input matrix. #[allow(unused_mut)] pub fn inverse(input: &Array, options: MatProp) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_inverse(&mut temp as MutAfArray, - input.get() as AfArray, - to_u32(options) as c_uint); + let err_val = af_inverse( + &mut temp as MutAfArray, + input.get() as AfArray, + to_u32(options) as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -358,13 +403,16 @@ pub fn inverse(input: &Array, options: MatProp) -> Array /// An unsigned 32-bit integer which is the rank of the input matrix. #[allow(unused_mut)] pub fn rank(input: &Array, tol: f64) -> u32 - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut temp: u32 = 0; unsafe { - let err_val = af_rank(&mut temp as *mut c_uint, - input.get() as AfArray, - tol as c_double); + let err_val = af_rank( + &mut temp as *mut c_uint, + input.get() as AfArray, + tol as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } temp @@ -383,13 +431,17 @@ pub fn rank(input: &Array, tol: f64) -> u32 /// If the input matrix is non-complex type, only first values of tuple contains the result. #[allow(unused_mut)] pub fn det(input: &Array) -> (f64, f64) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_det(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray); + let err_val = af_det( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) @@ -411,13 +463,18 @@ pub fn det(input: &Array) -> (f64, f64) /// A 64-bit floating point value that contains the norm of input matrix. #[allow(unused_mut)] pub fn norm(input: &Array, ntype: NormType, p: f64, q: f64) -> f64 - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let mut out: f64 = 0.0; unsafe { - let err_val = af_norm(&mut out as MutDouble, input.get() as AfArray, - ntype as c_uint, - p as c_double, q as c_double); + let err_val = af_norm( + &mut out as MutDouble, + input.get() as AfArray, + ntype as c_uint, + p as c_double, + q as c_double, + ); HANDLE_ERROR(AfError::from(err_val)); } out diff --git a/src/lib.rs b/src/lib.rs index f91a8d4cc..720097f4c 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -25,122 +25,124 @@ //! - [Indexing](./indexing.html) //! - [Configure ArrayFire Environment](./configuring_arrayfire_environment.html) -#![doc(html_logo_url = "http://www.arrayfire.com/logos/arrayfire_logo_symbol.png", - html_favicon_url = "http://www.rust-lang.org/favicon.ico", - html_root_url = "http://arrayfire.com/docs/rust")] +#![doc( + html_logo_url = "http://www.arrayfire.com/logos/arrayfire_logo_symbol.png", + html_favicon_url = "http://www.rust-lang.org/favicon.ico", + html_root_url = "http://arrayfire.com/docs/rust" +)] #![warn(missing_docs)] #![allow(non_camel_case_types)] #[macro_use] extern crate lazy_static; -#[cfg(feature="core")] -pub use array::*; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::array::*; +#[cfg(feature = "core")] mod array; -#[cfg(feature="algorithm")] -pub use algorithm::*; -#[cfg(feature="algorithm")] +#[cfg(feature = "algorithm")] +pub use crate::algorithm::*; +#[cfg(feature = "algorithm")] mod algorithm; -#[cfg(feature="arithmetic")] -pub use arith::*; -#[cfg(feature="arithmetic")] +#[cfg(feature = "arithmetic")] +pub use crate::arith::*; +#[cfg(feature = "arithmetic")] mod arith; -#[cfg(feature="core")] -pub use backend::*; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::backend::*; +#[cfg(feature = "core")] mod backend; -#[cfg(feature="blas")] -pub use blas::*; -#[cfg(feature="blas")] +#[cfg(feature = "blas")] +pub use crate::blas::*; +#[cfg(feature = "blas")] mod blas; -#[cfg(feature="data")] -pub use data::*; -#[cfg(feature="data")] +#[cfg(feature = "data")] +pub use crate::data::*; +#[cfg(feature = "data")] mod data; -#[cfg(feature="core")] -pub use device::*; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::device::*; +#[cfg(feature = "core")] mod device; -#[cfg(feature="core")] -pub use defines::*; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::defines::*; +#[cfg(feature = "core")] mod defines; -#[cfg(feature="core")] -pub use dim4::Dim4; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::dim4::Dim4; +#[cfg(feature = "core")] mod dim4; -#[cfg(feature="core")] -pub use error::{Callback, ErrorCallback, register_error_handler, handle_error_general}; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::error::{handle_error_general, register_error_handler, Callback, ErrorCallback}; +#[cfg(feature = "core")] mod error; -#[cfg(feature="indexing")] -pub use index::*; -#[cfg(feature="indexing")] +#[cfg(feature = "indexing")] +pub use crate::index::*; +#[cfg(feature = "indexing")] mod index; -#[cfg(feature="indexing")] -pub use seq::Seq; -#[cfg(feature="indexing")] +#[cfg(feature = "indexing")] +pub use crate::seq::Seq; +#[cfg(feature = "indexing")] mod seq; -#[cfg(feature="graphics")] -pub use graphics::Window; -#[cfg(feature="graphics")] +#[cfg(feature = "graphics")] +pub use crate::graphics::Window; +#[cfg(feature = "graphics")] mod graphics; -#[cfg(feature="image")] -pub use image::*; -#[cfg(feature="image")] +#[cfg(feature = "image")] +pub use crate::image::*; +#[cfg(feature = "image")] mod image; -#[cfg(feature="lapack")] -pub use lapack::*; -#[cfg(feature="lapack")] +#[cfg(feature = "lapack")] +pub use crate::lapack::*; +#[cfg(feature = "lapack")] mod lapack; -#[cfg(feature="macros")] +#[cfg(feature = "macros")] mod macros; mod num; -#[cfg(feature="random")] -pub use random::*; -#[cfg(feature="random")] +#[cfg(feature = "random")] +pub use crate::random::*; +#[cfg(feature = "random")] mod random; -#[cfg(feature="signal")] -pub use signal::*; -#[cfg(feature="signal")] +#[cfg(feature = "signal")] +pub use crate::signal::*; +#[cfg(feature = "signal")] mod signal; -#[cfg(feature="sparse")] -pub use sparse::*; -#[cfg(feature="sparse")] +#[cfg(feature = "sparse")] +pub use crate::sparse::*; +#[cfg(feature = "sparse")] mod sparse; -#[cfg(feature="statistics")] -pub use statistics::*; -#[cfg(feature="statistics")] +#[cfg(feature = "statistics")] +pub use crate::statistics::*; +#[cfg(feature = "statistics")] mod statistics; -#[cfg(feature="core")] -pub use util::{HasAfEnum, ImplicitPromote, get_size}; -#[cfg(feature="core")] +#[cfg(feature = "core")] +pub use crate::util::{get_size, HasAfEnum, ImplicitPromote}; +#[cfg(feature = "core")] mod util; -#[cfg(feature="vision")] -pub use vision::*; -#[cfg(feature="vision")] +#[cfg(feature = "vision")] +pub use crate::vision::*; +#[cfg(feature = "vision")] mod vision; // headers that are not exposed through rust wrapper are given follows: diff --git a/src/macros.rs b/src/macros.rs index d427af28d..a085f017c 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -36,15 +36,12 @@ /// # Examples /// /// ```rust -/// # #[macro_use(mem_info)] extern crate arrayfire; -/// # fn main() { -/// use arrayfire::{Dim4, device_mem_info, print, randu}; -/// -/// let dims = Dim4::new(&[5, 5, 1, 1]); -/// let a = randu::(dims); -/// print(&a); -/// mem_info!("Hello!"); -/// # } +/// use arrayfire::{Dim4, device_mem_info, print, randu, mem_info}; +/// +/// let dims = Dim4::new(&[5, 5, 1, 1]); +/// let a = randu::(dims); +/// print(&a); +/// mem_info!("Hello!"); /// ``` /// /// Sample Output: @@ -73,17 +70,13 @@ macro_rules! mem_info { /// # Examples /// /// ```rust -/// # #[macro_use] extern crate arrayfire; -/// -/// # fn main() { -/// use arrayfire::{Dim4, join_many, print, randu}; +/// use arrayfire::{Dim4, join_many, print, randu}; /// -/// let a = &randu::(Dim4::new(&[5, 3, 1, 1])); -/// let b = &randu::(Dim4::new(&[5, 3, 1, 1])); -/// let c = &randu::(Dim4::new(&[5, 3, 1, 1])); -/// let d = join_many![2; a, b, c]; -/// print(&d); -/// # } +/// let a = &randu::(Dim4::new(&[5, 3, 1, 1])); +/// let b = &randu::(Dim4::new(&[5, 3, 1, 1])); +/// let c = &randu::(Dim4::new(&[5, 3, 1, 1])); +/// let d = join_many![2; a, b, c]; +/// print(&d); /// ``` /// /// # Panics @@ -109,14 +102,10 @@ macro_rules! join_many { /// # Examples /// /// ```rust -/// # #[macro_use] extern crate arrayfire; -/// -/// # fn main() { -/// use arrayfire::{Dim4, print_gen, randu}; -/// let dims = Dim4::new(&[3, 1, 1, 1]); -/// let a = randu::(dims); -/// af_print!("Create a 5-by-3 matrix of random floats on the GPU", a); -/// # } +/// use arrayfire::{Dim4, print_gen, randu, af_print}; +/// let dims = Dim4::new(&[3, 1, 1, 1]); +/// let a = randu::(dims); +/// af_print!("Create a 5-by-3 matrix of random floats on the GPU", a); /// ``` /// #[macro_export] diff --git a/src/num.rs b/src/num.rs index d5858d486..27f5ab263 100644 --- a/src/num.rs +++ b/src/num.rs @@ -7,9 +7,13 @@ pub trait One { } macro_rules! zero_impl { - ( $t:ident, $z:expr ) => ( - impl Zero for $t { fn zero() -> Self { $z } } - ) + ( $t:ident, $z:expr ) => { + impl Zero for $t { + fn zero() -> Self { + $z + } + } + }; } zero_impl!(u8, 0); @@ -25,11 +29,14 @@ zero_impl!(isize, 0); zero_impl!(f32, 0.0); zero_impl!(f64, 0.0); - macro_rules! one_impl { - ( $t:ident, $o:expr ) => ( - impl One for $t { fn one() -> Self { $o } } - ) + ( $t:ident, $o:expr ) => { + impl One for $t { + fn one() -> Self { + $o + } + } + }; } one_impl!(u8, 1); diff --git a/src/random/mod.rs b/src/random/mod.rs index 7159e90ab..d2591da36 100644 --- a/src/random/mod.rs +++ b/src/random/mod.rs @@ -1,15 +1,15 @@ extern crate libc; -use array::Array; -use dim4::Dim4; -use defines::{AfError, RandomEngineType}; -use error::HANDLE_ERROR; use self::libc::{c_int, c_uint}; -use util::{FloatingPoint, HasAfEnum}; -use util::{DimT, MutAfArray, MutRandEngine, RandEngine, Uintl}; +use crate::array::Array; +use crate::defines::{AfError, RandomEngineType}; +use crate::dim4::Dim4; +use crate::error::HANDLE_ERROR; +use crate::util::{DimT, MutAfArray, MutRandEngine, RandEngine, Uintl}; +use crate::util::{FloatingPoint, HasAfEnum}; #[allow(dead_code)] -extern { +extern "C" { fn af_set_seed(seed: Uintl) -> c_int; fn af_get_seed(seed: *mut Uintl) -> c_int; @@ -27,10 +27,20 @@ extern { fn af_get_default_random_engine(engine: MutRandEngine) -> c_int; fn af_set_default_random_engine_type(rtype: c_uint) -> c_int; - fn af_random_uniform(out: MutAfArray, ndims: c_uint, dims: *const DimT, - aftype: c_uint, engine: RandEngine) -> c_int; - fn af_random_normal(out: MutAfArray, ndims: c_uint, dims: *const DimT, - aftype: c_uint, engine: RandEngine) -> c_int; + fn af_random_uniform( + out: MutAfArray, + ndims: c_uint, + dims: *const DimT, + aftype: c_uint, + engine: RandEngine, + ) -> c_int; + fn af_random_normal( + out: MutAfArray, + ndims: c_uint, + dims: *const DimT, + aftype: c_uint, + engine: RandEngine, + ) -> c_int; } /// Set seed for random number generation @@ -79,10 +89,19 @@ macro_rules! data_gen_def { ) } -data_gen_def!("Create random numbers from uniform distribution", - randu, af_randu, HasAfEnum); -data_gen_def!("Create random numbers from normal distribution", - randn, af_randn, HasAfEnum, FloatingPoint); +data_gen_def!( + "Create random numbers from uniform distribution", + randu, + af_randu, + HasAfEnum +); +data_gen_def!( + "Create random numbers from normal distribution", + randn, + af_randn, + HasAfEnum, + FloatingPoint +); /// Random number generator engine /// @@ -94,7 +113,7 @@ pub struct RandomEngine { /// Used for creating RandomEngine object from native resource id impl From for RandomEngine { fn from(t: i64) -> RandomEngine { - RandomEngine {handle: t} + RandomEngine { handle: t } } } @@ -112,8 +131,14 @@ impl RandomEngine { pub fn new(rengine: RandomEngineType, seed: Option) -> RandomEngine { let mut temp: i64 = 0; unsafe { - let err_val = af_create_random_engine(&mut temp as MutRandEngine, rengine as c_uint, - match seed {Some(s) => s, None => 0} as Uintl); + let err_val = af_create_random_engine( + &mut temp as MutRandEngine, + rengine as c_uint, + match seed { + Some(s) => s, + None => 0, + } as Uintl, + ); HANDLE_ERROR(AfError::from(err_val)); } RandomEngine::from(temp) @@ -123,8 +148,8 @@ impl RandomEngine { pub fn get_type(&self) -> RandomEngineType { let mut temp: u32 = 0; unsafe { - let err_val = af_random_engine_get_type(&mut temp as *mut c_uint, - self.handle as RandEngine); + let err_val = + af_random_engine_get_type(&mut temp as *mut c_uint, self.handle as RandEngine); HANDLE_ERROR(AfError::from(err_val)); } RandomEngineType::from(temp) @@ -133,8 +158,8 @@ impl RandomEngine { /// Get random engine type pub fn set_type(&mut self, engine_type: RandomEngineType) { unsafe { - let err_val = af_random_engine_set_type(&mut self.handle as MutRandEngine, - engine_type as c_uint); + let err_val = + af_random_engine_set_type(&mut self.handle as MutRandEngine, engine_type as c_uint); HANDLE_ERROR(AfError::from(err_val)); } } @@ -142,8 +167,8 @@ impl RandomEngine { /// Set seed for random engine pub fn set_seed(&mut self, seed: u64) { unsafe { - let err_val = af_random_engine_set_seed(&mut self.handle as MutRandEngine, - seed as Uintl); + let err_val = + af_random_engine_set_seed(&mut self.handle as MutRandEngine, seed as Uintl); HANDLE_ERROR(AfError::from(err_val)); } } @@ -152,7 +177,8 @@ impl RandomEngine { pub fn get_seed(&self) -> u64 { let mut seed: u64 = 0; unsafe { - let err_val = af_random_engine_get_seed(&mut seed as *mut Uintl, self.handle as RandEngine); + let err_val = + af_random_engine_get_seed(&mut seed as *mut Uintl, self.handle as RandEngine); HANDLE_ERROR(AfError::from(err_val)); } seed @@ -169,7 +195,8 @@ impl Clone for RandomEngine { fn clone(&self) -> RandomEngine { unsafe { let mut temp: i64 = 0; - let err_val = af_retain_random_engine(&mut temp as MutRandEngine, self.handle as RandEngine); + let err_val = + af_retain_random_engine(&mut temp as MutRandEngine, self.handle as RandEngine); HANDLE_ERROR(AfError::from(err_val)); RandomEngine::from(temp) } @@ -188,9 +215,9 @@ impl Drop for RandomEngine { /// Get default random engine pub fn get_default_random_engine() -> RandomEngine { - let mut handle : i64 = 0; + let mut handle: i64 = 0; unsafe { - let mut temp : i64 = 0; + let mut temp: i64 = 0; let mut err_val = af_get_default_random_engine(&mut temp as MutRandEngine); HANDLE_ERROR(AfError::from(err_val)); err_val = af_retain_random_engine(&mut handle as MutRandEngine, temp as RandEngine); @@ -222,13 +249,19 @@ pub fn set_default_random_engine_type(rtype: RandomEngineType) { /// /// An Array with uniform numbers generated using random engine pub fn random_uniform(dims: Dim4, engine: &RandomEngine) -> Array -where T: HasAfEnum { +where + T: HasAfEnum, +{ let aftype = T::get_af_dtype(); - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_random_uniform(&mut temp as MutAfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT, - aftype as c_uint, engine.get() as RandEngine); + let err_val = af_random_uniform( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + aftype as c_uint, + engine.get() as RandEngine, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -245,14 +278,19 @@ where T: HasAfEnum { /// /// An Array with normal numbers generated using random engine pub fn random_normal(dims: Dim4, engine: &RandomEngine) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { let aftype = T::get_af_dtype(); - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_random_normal(&mut temp as MutAfArray, - dims.ndims() as c_uint, dims.get().as_ptr() as *const DimT, - aftype as c_uint, engine.get() as RandEngine); + let err_val = af_random_normal( + &mut temp as MutAfArray, + dims.ndims() as c_uint, + dims.get().as_ptr() as *const DimT, + aftype as c_uint, + engine.get() as RandEngine, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() diff --git a/src/seq.rs b/src/seq.rs index 643fde357..b3d95147a 100644 --- a/src/seq.rs +++ b/src/seq.rs @@ -1,8 +1,8 @@ extern crate libc; -use std::fmt; +use crate::num::{One, Zero}; use std::default::Default; -use num::{One, Zero}; +use std::fmt; /// Sequences are used for indexing Arrays #[derive(Copy, Clone)] @@ -14,23 +14,35 @@ pub struct Seq { } /// Default `Seq` spans all the elements along a dimension -impl Default for Seq { +impl Default for Seq { fn default() -> Self { - Seq { begin: One::one(), end: One::one(), step: Zero::zero() } + Seq { + begin: One::one(), + end: One::one(), + step: Zero::zero(), + } } } /// Enables use of `Seq` with `{}` format in print statements impl fmt::Display for Seq { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "[begin: {}, end: {}, step: {}]", self.begin, self.end, self.step) + write!( + f, + "[begin: {}, end: {}, step: {}]", + self.begin, self.end, self.step + ) } } impl Seq { /// Create a `Seq` that goes from `begin` to `end` at a step size of `step` pub fn new(begin: T, end: T, step: T) -> Self { - Seq { begin: begin, end: end, step: step, } + Seq { + begin: begin, + end: end, + step: step, + } } /// Get begin index of Seq diff --git a/src/signal/mod.rs b/src/signal/mod.rs index 67c0cfb0e..7a0111dc0 100644 --- a/src/signal/mod.rs +++ b/src/signal/mod.rs @@ -1,41 +1,72 @@ extern crate libc; extern crate num; -use array::Array; -use defines::{AfError, ConvDomain, ConvMode, InterpType}; -use error::HANDLE_ERROR; +use self::libc::{c_double, c_float, c_int, c_longlong, c_uint, size_t}; use self::num::Complex; -use self::libc::{c_uint, c_int, c_float, c_double, c_longlong, size_t}; -use util::{ComplexFloating, FloatingPoint, HasAfEnum, RealFloating}; -use util::{AfArray, MutAfArray}; +use crate::array::Array; +use crate::defines::{AfError, ConvDomain, ConvMode, InterpType}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, MutAfArray}; +use crate::util::{ComplexFloating, FloatingPoint, HasAfEnum, RealFloating}; #[allow(dead_code)] -extern { - fn af_approx1(out: MutAfArray, inp: AfArray, pos: AfArray, - method: c_int, off_grid: c_float) -> c_int; - - fn af_approx2(out: MutAfArray, inp: AfArray, pos0: AfArray, pos1: AfArray, - method: c_int, off_grid: c_float) -> c_int; +extern "C" { + fn af_approx1( + out: MutAfArray, + inp: AfArray, + pos: AfArray, + method: c_int, + off_grid: c_float, + ) -> c_int; + + fn af_approx2( + out: MutAfArray, + inp: AfArray, + pos0: AfArray, + pos1: AfArray, + method: c_int, + off_grid: c_float, + ) -> c_int; fn af_set_fft_plan_cache_size(cache_size: size_t) -> c_int; - fn af_fft(out: MutAfArray, arr: AfArray, - nfac: c_double, odim0: c_longlong) -> c_int; - - fn af_fft2(out: MutAfArray, arr: AfArray, nfac: c_double, - odim0: c_longlong, odim1: c_longlong) -> c_int; - - fn af_fft3(out: MutAfArray, arr: AfArray, nfac: c_double, - odim0: c_longlong, odim1: c_longlong, odim2: c_longlong) -> c_int; - - fn af_ifft(out: MutAfArray, arr: AfArray, - nfac: c_double, odim0: c_longlong) -> c_int; - - fn af_ifft2(out: MutAfArray, arr: AfArray, nfac: c_double, - odim0: c_longlong, odim1: c_longlong) -> c_int; - - fn af_ifft3(out: MutAfArray, arr: AfArray, nfac: c_double, - odim0: c_longlong, odim1: c_longlong, odim2: c_longlong) -> c_int; + fn af_fft(out: MutAfArray, arr: AfArray, nfac: c_double, odim0: c_longlong) -> c_int; + + fn af_fft2( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + odim0: c_longlong, + odim1: c_longlong, + ) -> c_int; + + fn af_fft3( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + odim0: c_longlong, + odim1: c_longlong, + odim2: c_longlong, + ) -> c_int; + + fn af_ifft(out: MutAfArray, arr: AfArray, nfac: c_double, odim0: c_longlong) -> c_int; + + fn af_ifft2( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + odim0: c_longlong, + odim1: c_longlong, + ) -> c_int; + + fn af_ifft3( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + odim0: c_longlong, + odim1: c_longlong, + odim2: c_longlong, + ) -> c_int; fn af_fft_inplace(arr: AfArray, nfac: c_double) -> c_int; fn af_fft2_inplace(arr: AfArray, nfac: c_double) -> c_int; @@ -44,12 +75,22 @@ extern { fn af_ifft2_inplace(arr: AfArray, nfac: c_double) -> c_int; fn af_ifft3_inplace(arr: AfArray, nfac: c_double) -> c_int; - fn af_fft_r2c(out: MutAfArray, arr: AfArray, - nfac: c_double, pad0: c_longlong) -> c_int; - fn af_fft2_r2c(out: MutAfArray, arr: AfArray, - nfac: c_double, pad0: c_longlong, pad1: c_longlong) -> c_int; - fn af_fft3_r2c(out: MutAfArray, arr: AfArray, - nfac: c_double, pad0: c_longlong, pad1: c_longlong, pad2: c_longlong) -> c_int; + fn af_fft_r2c(out: MutAfArray, arr: AfArray, nfac: c_double, pad0: c_longlong) -> c_int; + fn af_fft2_r2c( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + pad0: c_longlong, + pad1: c_longlong, + ) -> c_int; + fn af_fft3_r2c( + out: MutAfArray, + arr: AfArray, + nfac: c_double, + pad0: c_longlong, + pad1: c_longlong, + pad2: c_longlong, + ) -> c_int; fn af_fft_c2r(out: MutAfArray, input: AfArray, nfac: c_double, is_odd: c_int) -> c_int; fn af_fft2_c2r(out: MutAfArray, input: AfArray, nfac: c_double, is_odd: c_int) -> c_int; @@ -80,15 +121,25 @@ extern { /// /// An Array with interpolated values #[allow(unused_mut)] -pub fn approx1(input: &Array, pos: &Array

, - method: InterpType, off_grid: f32) -> Array - where T: HasAfEnum + FloatingPoint, - P: HasAfEnum + RealFloating +pub fn approx1( + input: &Array, + pos: &Array

, + method: InterpType, + off_grid: f32, +) -> Array +where + T: HasAfEnum + FloatingPoint, + P: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_approx1(&mut temp as MutAfArray, input.get() as AfArray, - pos.get() as AfArray, method as c_int, off_grid as c_float); + let err_val = af_approx1( + &mut temp as MutAfArray, + input.get() as AfArray, + pos.get() as AfArray, + method as c_int, + off_grid as c_float, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -109,16 +160,27 @@ pub fn approx1(input: &Array, pos: &Array

, /// # Return Values /// /// An Array with interpolated values -pub fn approx2(input: &Array, pos0: &Array

, pos1: &Array

, - method: InterpType, off_grid: f32) -> Array - where T: HasAfEnum + FloatingPoint, - P: HasAfEnum + RealFloating +pub fn approx2( + input: &Array, + pos0: &Array

, + pos1: &Array

, + method: InterpType, + off_grid: f32, +) -> Array +where + T: HasAfEnum + FloatingPoint, + P: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_approx2(&mut temp as MutAfArray, input.get() as AfArray, - pos0.get() as AfArray, pos1.get() as AfArray, - method as c_int, off_grid as c_float); + let err_val = af_approx2( + &mut temp as MutAfArray, + input.get() as AfArray, + pos0.get() as AfArray, + pos1.get() as AfArray, + method as c_int, + off_grid as c_float, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -150,16 +212,19 @@ pub fn set_fft_plan_cache_size(cache_size: usize) { /// /// Transformed Array #[allow(unused_mut)] -pub fn fft(input: &Array, norm_factor: f64, - odim0: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn fft(input: &Array, norm_factor: f64, odim0: i64) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong); + let err_val = af_fft( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -179,16 +244,25 @@ pub fn fft(input: &Array, norm_factor: f64, /// /// Transformed Array #[allow(unused_mut)] -pub fn fft2(input: &Array, norm_factor: f64, - odim0: i64, odim1: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn fft2( + input: &Array, + norm_factor: f64, + odim0: i64, + odim1: i64, +) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft2(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong, odim1 as c_longlong); + let err_val = af_fft2( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + odim1 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -209,16 +283,27 @@ pub fn fft2(input: &Array, norm_factor: f64, /// /// Transformed Array #[allow(unused_mut)] -pub fn fft3(input: &Array, norm_factor: f64, - odim0: i64, odim1: i64, odim2: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn fft3( + input: &Array, + norm_factor: f64, + odim0: i64, + odim1: i64, + odim2: i64, +) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft3(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong, odim1 as c_longlong, odim2 as c_longlong); + let err_val = af_fft3( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + odim1 as c_longlong, + odim2 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -238,15 +323,19 @@ pub fn fft3(input: &Array, norm_factor: f64, /// /// Transformed Array #[allow(unused_mut)] -pub fn ifft(input: &Array, norm_factor: f64, odim0: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn ifft(input: &Array, norm_factor: f64, odim0: i64) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_ifft(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong); + let err_val = af_ifft( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -266,16 +355,25 @@ pub fn ifft(input: &Array, norm_factor: f64, odim0: i64) -> Array< T::Comp /// /// Transformed Array #[allow(unused_mut)] -pub fn ifft2(input: &Array, norm_factor: f64, - odim0: i64, odim1: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn ifft2( + input: &Array, + norm_factor: f64, + odim0: i64, + odim1: i64, +) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_ifft2(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong, odim1 as c_longlong); + let err_val = af_ifft2( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + odim1 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -296,23 +394,34 @@ pub fn ifft2(input: &Array, norm_factor: f64, /// /// Transformed Array #[allow(unused_mut)] -pub fn ifft3(input: &Array, norm_factor: f64, - odim0: i64, odim1: i64, odim2: i64) -> Array< T::ComplexOutType > - where T: HasAfEnum + FloatingPoint, - ::ComplexOutType: HasAfEnum +pub fn ifft3( + input: &Array, + norm_factor: f64, + odim0: i64, + odim1: i64, + odim2: i64, +) -> Array +where + T: HasAfEnum + FloatingPoint, + ::ComplexOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_ifft3(&mut temp as MutAfArray, - input.get() as AfArray, norm_factor as c_double, - odim0 as c_longlong, odim1 as c_longlong, odim2 as c_longlong); + let err_val = af_ifft3( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + odim0 as c_longlong, + odim1 as c_longlong, + odim2 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! conv_func_def { - ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -328,21 +437,30 @@ macro_rules! conv_func_def { /// /// Convolved Array #[allow(unused_mut)] - pub fn $fn_name(signal: &Array, filter: &Array, - mode: ConvMode, domain: ConvDomain) -> Array - where T: HasAfEnum, - F: HasAfEnum + pub fn $fn_name( + signal: &Array, + filter: &Array, + mode: ConvMode, + domain: ConvDomain, + ) -> Array + where + T: HasAfEnum, + F: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, - signal.get() as AfArray, filter.get() as AfArray, - mode as c_uint, domain as c_uint); + let err_val = $ffi_name( + &mut temp as MutAfArray, + signal.get() as AfArray, + filter.get() as AfArray, + mode as c_uint, + domain as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } conv_func_def!("1d convolution", convolve1, af_convolve1); @@ -362,23 +480,32 @@ conv_func_def!("3d convolution", convolve3, af_convolve3); /// /// The convolved Array #[allow(unused_mut)] -pub fn convolve2_sep(cfilt: &Array, rfilt: &Array, signal: &Array, - mode: ConvMode) -> Array - where T: HasAfEnum, - F: HasAfEnum +pub fn convolve2_sep( + cfilt: &Array, + rfilt: &Array, + signal: &Array, + mode: ConvMode, +) -> Array +where + T: HasAfEnum, + F: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_convolve2_sep(&mut temp as MutAfArray, - cfilt.get() as AfArray, rfilt.get() as AfArray, - signal.get() as AfArray, mode as c_uint); + let err_val = af_convolve2_sep( + &mut temp as MutAfArray, + cfilt.get() as AfArray, + rfilt.get() as AfArray, + signal.get() as AfArray, + mode as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! fft_conv_func_def { - ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => ( + ($doc_str: expr, $fn_name:ident, $ffi_name: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -392,25 +519,41 @@ macro_rules! fft_conv_func_def { /// /// Convolved Array #[allow(unused_mut)] - pub fn $fn_name(signal: &Array, filter: &Array, - mode: ConvMode) -> Array - where T: HasAfEnum, - F: HasAfEnum + pub fn $fn_name(signal: &Array, filter: &Array, mode: ConvMode) -> Array + where + T: HasAfEnum, + F: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_name(&mut temp as MutAfArray, signal.get() as AfArray, - filter.get() as AfArray, mode as c_uint); + let err_val = $ffi_name( + &mut temp as MutAfArray, + signal.get() as AfArray, + filter.get() as AfArray, + mode as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } -fft_conv_func_def!("1d convolution using fast-fourier transform", fft_convolve1, af_fft_convolve1); -fft_conv_func_def!("2d convolution using fast-fourier transform", fft_convolve2, af_fft_convolve2); -fft_conv_func_def!("3d convolution using fast-fourier transform", fft_convolve3, af_fft_convolve3); +fft_conv_func_def!( + "1d convolution using fast-fourier transform", + fft_convolve1, + af_fft_convolve1 +); +fft_conv_func_def!( + "2d convolution using fast-fourier transform", + fft_convolve2, + af_fft_convolve2 +); +fft_conv_func_def!( + "3d convolution using fast-fourier transform", + fft_convolve3, + af_fft_convolve3 +); /// Finite impulse filter /// @@ -424,12 +567,17 @@ fft_conv_func_def!("3d convolution using fast-fourier transform", fft_convolve3, /// Filtered Array #[allow(unused_mut)] pub fn fir(b: &Array, x: &Array) -> Array - where B: HasAfEnum, - X: HasAfEnum +where + B: HasAfEnum, + X: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fir(&mut temp as MutAfArray, b.get() as AfArray, x.get() as AfArray); + let err_val = af_fir( + &mut temp as MutAfArray, + b.get() as AfArray, + x.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -450,8 +598,12 @@ pub fn fir(b: &Array, x: &Array) -> Array pub fn iir(b: &Array, a: &Array, x: &Array) -> Array { let mut temp: i64 = 0; unsafe { - let err_val = af_iir(&mut temp as MutAfArray, - b.get() as AfArray, a.get() as AfArray, x.get() as AfArray); + let err_val = af_iir( + &mut temp as MutAfArray, + b.get() as AfArray, + a.get() as AfArray, + x.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -464,7 +616,8 @@ pub fn iir(b: &Array, a: &Array, x: &Array) -> Array { /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn fft_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_fft_inplace(input.get() as AfArray, norm_factor as c_double); @@ -479,7 +632,8 @@ pub fn fft_inplace(input: &mut Array, norm_factor: f64) /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn fft2_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_fft2_inplace(input.get() as AfArray, norm_factor as c_double); @@ -494,7 +648,8 @@ pub fn fft2_inplace(input: &mut Array, norm_factor: f64) /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn fft3_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_fft3_inplace(input.get() as AfArray, norm_factor as c_double); @@ -509,7 +664,8 @@ pub fn fft3_inplace(input: &mut Array, norm_factor: f64) /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn ifft_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_ifft_inplace(input.get() as AfArray, norm_factor as c_double); @@ -524,7 +680,8 @@ pub fn ifft_inplace(input: &mut Array, norm_factor: f64) /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn ifft2_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_ifft2_inplace(input.get() as AfArray, norm_factor as c_double); @@ -539,7 +696,8 @@ pub fn ifft2_inplace(input: &mut Array, norm_factor: f64) /// - `input` is the input Array /// - `norm_factor` is the normalization factor pub fn ifft3_inplace(input: &mut Array, norm_factor: f64) - where T: HasAfEnum + ComplexFloating +where + T: HasAfEnum + ComplexFloating, { unsafe { let err_val = af_ifft3_inplace(input.get() as AfArray, norm_factor as c_double); @@ -558,14 +716,19 @@ pub fn ifft3_inplace(input: &mut Array, norm_factor: f64) /// # Return Values /// /// Complex Array -pub fn fft_r2c(input: &Array, norm_factor: f64, pad0: i64) -> Array< Complex > - where T: HasAfEnum + RealFloating, - Complex: HasAfEnum +pub fn fft_r2c(input: &Array, norm_factor: f64, pad0: i64) -> Array> +where + T: HasAfEnum + RealFloating, + Complex: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft_r2c(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, pad0 as c_longlong); + let err_val = af_fft_r2c( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + pad0 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -583,15 +746,20 @@ pub fn fft_r2c(input: &Array, norm_factor: f64, pad0: i64) -> Array< Compl /// # Return Values /// /// Complex Array -pub fn fft2_r2c(input: &Array, norm_factor: f64, - pad0: i64, pad1: i64) -> Array< Complex > - where T: HasAfEnum + RealFloating, - Complex: HasAfEnum +pub fn fft2_r2c(input: &Array, norm_factor: f64, pad0: i64, pad1: i64) -> Array> +where + T: HasAfEnum + RealFloating, + Complex: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft2_r2c(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, pad0 as c_longlong, pad1 as c_longlong); + let err_val = af_fft2_r2c( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + pad0 as c_longlong, + pad1 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -610,16 +778,27 @@ pub fn fft2_r2c(input: &Array, norm_factor: f64, /// # Return Values /// /// Complex Array -pub fn fft3_r2c(input: &Array, norm_factor: f64, - pad0: i64, pad1: i64, pad2: i64) -> Array< Complex > - where T: HasAfEnum + RealFloating, - Complex: HasAfEnum +pub fn fft3_r2c( + input: &Array, + norm_factor: f64, + pad0: i64, + pad1: i64, + pad2: i64, +) -> Array> +where + T: HasAfEnum + RealFloating, + Complex: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft3_r2c(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, pad0 as c_longlong, - pad1 as c_longlong, pad2 as c_longlong); + let err_val = af_fft3_r2c( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + pad0 as c_longlong, + pad1 as c_longlong, + pad2 as c_longlong, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -636,15 +815,19 @@ pub fn fft3_r2c(input: &Array, norm_factor: f64, /// # Return Values /// /// Complex Array -pub fn fft_c2r(input: &Array, - norm_factor: f64, is_odd: bool) -> Array< T::BaseType > - where T: HasAfEnum + ComplexFloating, - ::BaseType: HasAfEnum +pub fn fft_c2r(input: &Array, norm_factor: f64, is_odd: bool) -> Array +where + T: HasAfEnum + ComplexFloating, + ::BaseType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft_c2r(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, is_odd as c_int); + let err_val = af_fft_c2r( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + is_odd as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -661,15 +844,19 @@ pub fn fft_c2r(input: &Array, /// # Return Values /// /// Complex Array -pub fn fft2_c2r(input: &Array, - norm_factor: f64, is_odd: bool) -> Array< T::BaseType > - where T: HasAfEnum + ComplexFloating, - ::BaseType: HasAfEnum +pub fn fft2_c2r(input: &Array, norm_factor: f64, is_odd: bool) -> Array +where + T: HasAfEnum + ComplexFloating, + ::BaseType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft2_c2r(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, is_odd as c_int); + let err_val = af_fft2_c2r( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + is_odd as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -686,15 +873,19 @@ pub fn fft2_c2r(input: &Array, /// # Return Values /// /// Complex Array -pub fn fft3_c2r(input: &Array, - norm_factor: f64, is_odd: bool) -> Array< T::BaseType > - where T: HasAfEnum + ComplexFloating, - ::BaseType: HasAfEnum +pub fn fft3_c2r(input: &Array, norm_factor: f64, is_odd: bool) -> Array +where + T: HasAfEnum + ComplexFloating, + ::BaseType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_fft3_c2r(&mut temp as MutAfArray, input.get() as AfArray, - norm_factor as c_double, is_odd as c_int); + let err_val = af_fft3_c2r( + &mut temp as MutAfArray, + input.get() as AfArray, + norm_factor as c_double, + is_odd as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() diff --git a/src/sparse/mod.rs b/src/sparse/mod.rs index 5052c5f94..f85bdc205 100644 --- a/src/sparse/mod.rs +++ b/src/sparse/mod.rs @@ -1,20 +1,36 @@ extern crate libc; -use array::Array; -use defines::{AfError, SparseFormat}; -use error::HANDLE_ERROR; -use self::libc::{c_uint, c_void, c_int}; -use util::{AfArray, DimT, MutAfArray, MutDimT}; -use util::{FloatingPoint, HasAfEnum}; +use self::libc::{c_int, c_uint, c_void}; +use crate::array::Array; +use crate::defines::{AfError, SparseFormat}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, MutAfArray, MutDimT}; +use crate::util::{FloatingPoint, HasAfEnum}; #[allow(dead_code)] -extern { - fn af_create_sparse_array(out: MutAfArray, nRows: DimT, nCols: DimT, vals: AfArray, - rowIdx: AfArray, colIdx: AfArray, stype: c_uint) -> c_int; +extern "C" { + fn af_create_sparse_array( + out: MutAfArray, + nRows: DimT, + nCols: DimT, + vals: AfArray, + rowIdx: AfArray, + colIdx: AfArray, + stype: c_uint, + ) -> c_int; - fn af_create_sparse_array_from_ptr(out: MutAfArray, nRows: DimT, nCols: DimT, nNZ: DimT, - values: *const c_void, rowIdx: *const c_int, colIdx: *const c_int, - aftype: c_uint, stype: c_uint, src: c_uint) -> c_int; + fn af_create_sparse_array_from_ptr( + out: MutAfArray, + nRows: DimT, + nCols: DimT, + nNZ: DimT, + values: *const c_void, + rowIdx: *const c_int, + colIdx: *const c_int, + aftype: c_uint, + stype: c_uint, + src: c_uint, + ) -> c_int; fn af_create_sparse_array_from_dense(out: MutAfArray, dense: AfArray, stype: c_uint) -> c_int; @@ -22,8 +38,13 @@ extern { fn af_sparse_to_dense(out: MutAfArray, sparse: AfArray) -> c_int; - fn af_sparse_get_info(vals: MutAfArray, rIdx: MutAfArray, cIdx: MutAfArray, stype: *mut c_uint, - input: AfArray) -> c_int; + fn af_sparse_get_info( + vals: MutAfArray, + rIdx: MutAfArray, + cIdx: MutAfArray, + stype: *mut c_uint, + input: AfArray, + ) -> c_int; fn af_sparse_get_values(out: MutAfArray, input: AfArray) -> c_int; @@ -59,17 +80,28 @@ extern { /// /// This function only uses references of the input arrays to create the /// sparse data structure and does not perform deep copies. -pub fn sparse(rows: u64, cols: u64, - values: &Array, - row_indices: &Array, col_indices: &Array, - format: SparseFormat) -> Array - where T: HasAfEnum + FloatingPoint +pub fn sparse( + rows: u64, + cols: u64, + values: &Array, + row_indices: &Array, + col_indices: &Array, + format: SparseFormat, +) -> Array +where + T: HasAfEnum + FloatingPoint, { let mut temp: i64 = 0; unsafe { - let err_val = af_create_sparse_array(&mut temp as MutAfArray, rows as DimT, cols as DimT, - values.get() as AfArray, row_indices.get() as AfArray, - col_indices.get() as AfArray, format as c_uint); + let err_val = af_create_sparse_array( + &mut temp as MutAfArray, + rows as DimT, + cols as DimT, + values.get() as AfArray, + row_indices.get() as AfArray, + col_indices.get() as AfArray, + format as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -99,20 +131,33 @@ pub fn sparse(rows: u64, cols: u64, /// /// The rules for deep copy/shallow copy/reference are the same as for creating a /// regular [Array](./struct.Array.html). -pub fn sparse_from_host(rows: u64, cols: u64, nzz: u64, - values: &[T], row_indices: &[i32], col_indices: &[i32], - format: SparseFormat) -> Array - where T: HasAfEnum + FloatingPoint +pub fn sparse_from_host( + rows: u64, + cols: u64, + nzz: u64, + values: &[T], + row_indices: &[i32], + col_indices: &[i32], + format: SparseFormat, +) -> Array +where + T: HasAfEnum + FloatingPoint, { let aftype = T::get_af_dtype(); let mut temp: i64 = 0; unsafe { - let err_val = af_create_sparse_array_from_ptr(&mut temp as MutAfArray, - rows as DimT, cols as DimT, nzz as DimT, - values.as_ptr() as *const c_void, - row_indices.as_ptr() as *const c_int, - col_indices.as_ptr() as *const c_int, - aftype as c_uint, format as c_uint, 1); + let err_val = af_create_sparse_array_from_ptr( + &mut temp as MutAfArray, + rows as DimT, + cols as DimT, + nzz as DimT, + values.as_ptr() as *const c_void, + row_indices.as_ptr() as *const c_int, + col_indices.as_ptr() as *const c_int, + aftype as c_uint, + format as c_uint, + 1, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -129,12 +174,16 @@ pub fn sparse_from_host(rows: u64, cols: u64, nzz: u64, /// /// Sparse Array pub fn sparse_from_dense(dense: &Array, format: SparseFormat) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_create_sparse_array_from_dense(&mut temp as MutAfArray, dense.get() as AfArray, - format as c_uint); + let err_val = af_create_sparse_array_from_dense( + &mut temp as MutAfArray, + dense.get() as AfArray, + format as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -151,13 +200,16 @@ pub fn sparse_from_dense(dense: &Array, format: SparseFormat) -> Array /// /// Sparse Array in targe sparse format. pub fn sparse_convert_to(input: &Array, format: SparseFormat) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_sparse_convert_to(&mut temp as MutAfArray, - input.get() as AfArray, - format as c_uint); + let err_val = af_sparse_convert_to( + &mut temp as MutAfArray, + input.get() as AfArray, + format as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -173,12 +225,12 @@ pub fn sparse_convert_to(input: &Array, format: SparseFormat) -> Array /// /// Dense Array pub fn sparse_to_dense(input: &Array) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut temp : i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_sparse_to_dense(&mut temp as MutAfArray, - input.get() as AfArray); + let err_val = af_sparse_to_dense(&mut temp as MutAfArray, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -194,19 +246,29 @@ pub fn sparse_to_dense(input: &Array) -> Array /// /// A tuple of values, row indices, column indices Arrays and SparseFormat enum. pub fn sparse_get_info(input: &Array) -> (Array, Array, Array, SparseFormat) - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut val : i64 = 0; - let mut row : i64 = 0; - let mut col : i64 = 0; + let mut val: i64 = 0; + let mut row: i64 = 0; + let mut col: i64 = 0; let mut stype: u32 = 0; unsafe { - let err_val = af_sparse_get_info(&mut val as MutAfArray, &mut row as MutAfArray, - &mut col as MutAfArray, &mut stype as *mut c_uint, - input.get() as AfArray); + let err_val = af_sparse_get_info( + &mut val as MutAfArray, + &mut row as MutAfArray, + &mut col as MutAfArray, + &mut stype as *mut c_uint, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } - (val.into(), row.into(), col.into(), SparseFormat::from(stype)) + ( + val.into(), + row.into(), + col.into(), + SparseFormat::from(stype), + ) } /// Get values of sparse Array @@ -219,9 +281,10 @@ pub fn sparse_get_info(input: &Array) -> (Array, Array, Array /// /// Sparse array values pub fn sparse_get_values(input: &Array) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut val : i64 = 0; + let mut val: i64 = 0; unsafe { let err_val = af_sparse_get_values(&mut val as MutAfArray, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); @@ -239,9 +302,10 @@ pub fn sparse_get_values(input: &Array) -> Array /// /// Array with row indices values of sparse Array pub fn sparse_get_row_indices(input: &Array) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut val : i64 = 0; + let mut val: i64 = 0; unsafe { let err_val = af_sparse_get_row_idx(&mut val as MutAfArray, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); @@ -259,9 +323,10 @@ pub fn sparse_get_row_indices(input: &Array) -> Array /// /// Array with coloumn indices values of sparse Array pub fn sparse_get_col_indices(input: &Array) -> Array - where T: HasAfEnum + FloatingPoint +where + T: HasAfEnum + FloatingPoint, { - let mut val : i64 = 0; + let mut val: i64 = 0; unsafe { let err_val = af_sparse_get_col_idx(&mut val as MutAfArray, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); @@ -278,8 +343,8 @@ pub fn sparse_get_col_indices(input: &Array) -> Array /// # Return Values /// /// Number of non-zero elements of sparse Array -pub fn sparse_get_nnz(input: &Array) -> i64 { - let mut count : i64 = 0; +pub fn sparse_get_nnz(input: &Array) -> i64 { + let mut count: i64 = 0; unsafe { let err_val = af_sparse_get_nnz(&mut count as *mut DimT, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); @@ -296,8 +361,8 @@ pub fn sparse_get_nnz(input: &Array) -> i64 { /// # Return Values /// /// Sparse array format -pub fn sparse_get_format(input: &Array) -> SparseFormat { - let mut stype : u32 = 0; +pub fn sparse_get_format(input: &Array) -> SparseFormat { + let mut stype: u32 = 0; unsafe { let err_val = af_sparse_get_storage(&mut stype as *mut c_uint, input.get() as AfArray); HANDLE_ERROR(AfError::from(err_val)); diff --git a/src/statistics/mod.rs b/src/statistics/mod.rs index f9d1c3d44..793f2f5ed 100644 --- a/src/statistics/mod.rs +++ b/src/statistics/mod.rs @@ -1,15 +1,15 @@ extern crate libc; -use array::Array; -use defines::{AfError, TopkFn}; -use error::HANDLE_ERROR; use self::libc::{c_int, c_uint}; -use util::{AfArray, DimT, MutAfArray, MutDouble}; -use util::{RealNumber, CovarianceComputable}; -use util::{HasAfEnum, MedianComputable, RealFloating}; +use crate::array::Array; +use crate::defines::{AfError, TopkFn}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, MutAfArray, MutDouble}; +use crate::util::{CovarianceComputable, RealNumber}; +use crate::util::{HasAfEnum, MedianComputable, RealFloating}; #[allow(dead_code)] -extern { +extern "C" { fn af_mean(out: MutAfArray, arr: AfArray, dim: DimT) -> c_int; fn af_stdev(out: MutAfArray, arr: AfArray, dim: DimT) -> c_int; fn af_median(out: MutAfArray, arr: AfArray, dim: DimT) -> c_int; @@ -29,8 +29,14 @@ extern { fn af_var_all_weighted(real: MutDouble, imag: MutDouble, arr: AfArray, wts: AfArray) -> c_int; fn af_corrcoef(real: MutDouble, imag: MutDouble, X: AfArray, Y: AfArray) -> c_int; - fn af_topk(vals: MutAfArray, idxs: MutAfArray, arr: AfArray, k: c_int, - dim: c_int, order: c_uint) -> c_int; + fn af_topk( + vals: MutAfArray, + idxs: MutAfArray, + arr: AfArray, + k: c_int, + dim: c_int, + order: c_uint, + ) -> c_int; } /// Find the median along a given dimension @@ -46,19 +52,19 @@ extern { /// median needs to be found. Array size along `dim` will be reduced to one. #[allow(unused_mut)] pub fn median(input: &Array, dim: i64) -> Array - where T: HasAfEnum + MedianComputable +where + T: HasAfEnum + MedianComputable, { let mut temp: i64 = 0; unsafe { - let err_val = af_median(&mut temp as MutAfArray, - input.get() as AfArray, dim as DimT); + let err_val = af_median(&mut temp as MutAfArray, input.get() as AfArray, dim as DimT); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } macro_rules! stat_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -71,25 +77,30 @@ macro_rules! stat_func_def { /// An Array whose size is equal to input except along the dimension which /// the stat operation is performed. Array size along `dim` will be reduced to one. #[allow(unused_mut)] - pub fn $fn_name(input: &Array, dim: i64) -> Array< T::MeanOutType > - where T: HasAfEnum, T::MeanOutType: HasAfEnum + pub fn $fn_name(input: &Array, dim: i64) -> Array + where + T: HasAfEnum, + T::MeanOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_fn(&mut temp as MutAfArray, - input.get() as AfArray, dim as DimT); + let err_val = $ffi_fn(&mut temp as MutAfArray, input.get() as AfArray, dim as DimT); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } stat_func_def!("Mean along specified dimension", mean, af_mean); -stat_func_def!("Standard deviation along specified dimension", stdev, af_stdev); +stat_func_def!( + "Standard deviation along specified dimension", + stdev, + af_stdev +); macro_rules! stat_wtd_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -103,26 +114,41 @@ macro_rules! stat_wtd_func_def { /// An Array whose size is equal to input except along the dimension which /// the stat operation is performed. Array size along `dim` will be reduced to one. #[allow(unused_mut)] - pub fn $fn_name(input: &Array, - weights: &Array, - dim: i64) -> Array< T::MeanOutType > - where T: HasAfEnum, - T::MeanOutType: HasAfEnum, - W: HasAfEnum + RealFloating + pub fn $fn_name( + input: &Array, + weights: &Array, + dim: i64, + ) -> Array + where + T: HasAfEnum, + T::MeanOutType: HasAfEnum, + W: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = $ffi_fn(&mut temp as MutAfArray, input.get() as AfArray, - weights.get() as AfArray, dim as DimT); + let err_val = $ffi_fn( + &mut temp as MutAfArray, + input.get() as AfArray, + weights.get() as AfArray, + dim as DimT, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() } - ) + }; } -stat_wtd_func_def!("Weighted mean along specified dimension", mean_weighted, af_mean_weighted); -stat_wtd_func_def!("Weight variance along specified dimension", var_weighted, af_var_weighted); +stat_wtd_func_def!( + "Weighted mean along specified dimension", + mean_weighted, + af_mean_weighted +); +stat_wtd_func_def!( + "Weight variance along specified dimension", + var_weighted, + af_var_weighted +); /// Compute Variance along a specific dimension /// @@ -136,13 +162,19 @@ stat_wtd_func_def!("Weight variance along specified dimension", var_weighted, af /// /// Array with variance of input Array `arr` along dimension `dim`. #[allow(unused_mut)] -pub fn var(arr: &Array, isbiased: bool, dim: i64) -> Array< T::MeanOutType > - where T: HasAfEnum, T::MeanOutType: HasAfEnum +pub fn var(arr: &Array, isbiased: bool, dim: i64) -> Array +where + T: HasAfEnum, + T::MeanOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_var(&mut temp as MutAfArray, arr.get() as AfArray, - isbiased as c_int, dim as DimT); + let err_val = af_var( + &mut temp as MutAfArray, + arr.get() as AfArray, + isbiased as c_int, + dim as DimT, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -160,14 +192,19 @@ pub fn var(arr: &Array, isbiased: bool, dim: i64) -> Array< T::MeanOutType /// /// An Array with Covariance values #[allow(unused_mut)] -pub fn cov(x: &Array, y: &Array, isbiased: bool) -> Array< T::MeanOutType > - where T: HasAfEnum + CovarianceComputable, - T::MeanOutType: HasAfEnum +pub fn cov(x: &Array, y: &Array, isbiased: bool) -> Array +where + T: HasAfEnum + CovarianceComputable, + T::MeanOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_cov(&mut temp as MutAfArray, x.get() as AfArray, - y.get() as AfArray, isbiased as c_int); + let err_val = af_cov( + &mut temp as MutAfArray, + x.get() as AfArray, + y.get() as AfArray, + isbiased as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -184,20 +221,23 @@ pub fn cov(x: &Array, y: &Array, isbiased: bool) -> Array< T::MeanOutTy /// /// A tuple of 64-bit floating point values that has the variance of `input` Array. #[allow(unused_mut)] -pub fn var_all(input: &Array, isbiased: bool) -> (f64, f64) -{ +pub fn var_all(input: &Array, isbiased: bool) -> (f64, f64) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_var_all(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray, isbiased as c_int); + let err_val = af_var_all( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + isbiased as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } macro_rules! stat_all_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -208,21 +248,28 @@ macro_rules! stat_all_func_def { /// /// A tuple of 64-bit floating point values with the stat values. #[allow(unused_mut)] - pub fn $fn_name(input: &Array) -> (f64, f64) { + pub fn $fn_name(input: &Array) -> (f64, f64) { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = $ffi_fn(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray); + let err_val = $ffi_fn( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } - ) + }; } stat_all_func_def!("Compute mean of all data", mean_all, af_mean_all); -stat_all_func_def!("Compute standard deviation of all data", stdev_all, af_stdev_all); +stat_all_func_def!( + "Compute standard deviation of all data", + stdev_all, + af_stdev_all +); /// Compute median of all data /// @@ -235,21 +282,24 @@ stat_all_func_def!("Compute standard deviation of all data", stdev_all, af_stdev /// A tuple of 64-bit floating point values with the median #[allow(unused_mut)] pub fn median_all(input: &Array) -> (f64, f64) - where T: HasAfEnum + MedianComputable +where + T: HasAfEnum + MedianComputable, { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_median_all(&mut real as MutDouble, - &mut imag as MutDouble, - input.get() as AfArray); + let err_val = af_median_all( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } macro_rules! stat_wtd_all_func_def { - ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => ( + ($doc_str: expr, $fn_name: ident, $ffi_fn: ident) => { #[doc=$doc_str] /// ///# Parameters @@ -262,25 +312,36 @@ macro_rules! stat_wtd_all_func_def { /// A tuple of 64-bit floating point values with the stat values. #[allow(unused_mut)] pub fn $fn_name(input: &Array, weights: &Array) -> (f64, f64) - where T: HasAfEnum, - W: HasAfEnum + RealFloating + where + T: HasAfEnum, + W: HasAfEnum + RealFloating, { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = $ffi_fn(&mut real as MutDouble, &mut imag as MutDouble, - input.get() as AfArray, weights.get() as AfArray); + let err_val = $ffi_fn( + &mut real as MutDouble, + &mut imag as MutDouble, + input.get() as AfArray, + weights.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) } - ) + }; } -stat_wtd_all_func_def!("Compute weighted mean of all data", - mean_all_weighted, af_mean_all_weighted); -stat_wtd_all_func_def!("Compute weighted variance of all data", - var_all_weighted, af_var_all_weighted); +stat_wtd_all_func_def!( + "Compute weighted mean of all data", + mean_all_weighted, + af_mean_all_weighted +); +stat_wtd_all_func_def!( + "Compute weighted variance of all data", + var_all_weighted, + af_var_all_weighted +); /// Compute correlation coefficient /// @@ -293,13 +354,18 @@ stat_wtd_all_func_def!("Compute weighted variance of all data", /// A tuple of 64-bit floating point values with the coefficients. #[allow(unused_mut)] pub fn corrcoef(x: &Array, y: &Array) -> (f64, f64) - where T: HasAfEnum + RealNumber +where + T: HasAfEnum + RealNumber, { let mut real: f64 = 0.0; let mut imag: f64 = 0.0; unsafe { - let err_val = af_corrcoef(&mut real as MutDouble, &mut imag as MutDouble, - x.get() as AfArray, y.get() as AfArray); + let err_val = af_corrcoef( + &mut real as MutDouble, + &mut imag as MutDouble, + x.get() as AfArray, + y.get() as AfArray, + ); HANDLE_ERROR(AfError::from(err_val)); } (real, imag) @@ -329,14 +395,20 @@ pub fn corrcoef(x: &Array, y: &Array) -> (f64, f64) /// with the second Array containing the indices of the topk values in the input /// data. pub fn topk(input: &Array, k: u32, dim: i32, order: TopkFn) -> (Array, Array) - where T: HasAfEnum +where + T: HasAfEnum, { let mut t0: i64 = 0; let mut t1: i64 = 0; unsafe { - let err_val = af_topk(&mut t0 as MutAfArray, &mut t1 as MutAfArray, - input.get() as AfArray, k as c_int, dim as c_int, - order as c_uint); + let err_val = af_topk( + &mut t0 as MutAfArray, + &mut t1 as MutAfArray, + input.get() as AfArray, + k as c_int, + dim as c_int, + order as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } (t0.into(), t1.into()) diff --git a/src/util.rs b/src/util.rs index e8c26babb..d527847b4 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,37 +1,39 @@ extern crate libc; extern crate num; -use defines::{AfError, ColorMap, ConvDomain, ConvMode, DType, InterpType, MatProp, MatchType}; -use defines::{SparseFormat, BinaryOp, RandomEngineType}; -use error::HANDLE_ERROR; -use std::mem; +use self::libc::{c_int, c_uint, c_void, size_t}; use self::num::Complex; -use num::Zero; -use self::libc::{c_uint, c_int, size_t, c_void}; - -pub type AfArray = self::libc::c_longlong; -pub type AfIndex = self::libc::c_longlong; -pub type CellPtr = *const self::libc::c_void; -pub type Complex32 = Complex; -pub type Complex64 = Complex; -pub type DimT = self::libc::c_longlong; -pub type Feat = *const self::libc::c_void; -pub type Intl = self::libc::c_longlong; -pub type MutAfArray = *mut self::libc::c_longlong; -pub type MutAfIndex = *mut self::libc::c_longlong; -pub type MutDimT = *mut self::libc::c_longlong; -pub type MutDouble = *mut self::libc::c_double; -pub type MutFeat = *mut *mut self::libc::c_void; +use crate::defines::{ + AfError, ColorMap, ConvDomain, ConvMode, DType, InterpType, MatProp, MatchType, +}; +use crate::defines::{BinaryOp, RandomEngineType, SparseFormat}; +use crate::error::HANDLE_ERROR; +use crate::num::Zero; +use std::mem; + +pub type AfArray = self::libc::c_longlong; +pub type AfIndex = self::libc::c_longlong; +pub type CellPtr = *const self::libc::c_void; +pub type Complex32 = Complex; +pub type Complex64 = Complex; +pub type DimT = self::libc::c_longlong; +pub type Feat = *const self::libc::c_void; +pub type Intl = self::libc::c_longlong; +pub type MutAfArray = *mut self::libc::c_longlong; +pub type MutAfIndex = *mut self::libc::c_longlong; +pub type MutDimT = *mut self::libc::c_longlong; +pub type MutDouble = *mut self::libc::c_double; +pub type MutFeat = *mut *mut self::libc::c_void; pub type MutRandEngine = *mut self::libc::c_longlong; -pub type MutUint = *mut self::libc::c_uint; -pub type MutVoidPtr = *mut self::libc::c_ulonglong; -pub type MutWndHandle = *mut self::libc::c_ulonglong; -pub type RandEngine = self::libc::c_longlong; -pub type Uintl = self::libc::c_ulonglong; -pub type WndHandle = self::libc::c_ulonglong; +pub type MutUint = *mut self::libc::c_uint; +pub type MutVoidPtr = *mut self::libc::c_ulonglong; +pub type MutWndHandle = *mut self::libc::c_ulonglong; +pub type RandEngine = self::libc::c_longlong; +pub type Uintl = self::libc::c_ulonglong; +pub type WndHandle = self::libc::c_ulonglong; #[allow(dead_code)] -extern { +extern "C" { fn af_get_size_of(size: *mut size_t, aftype: c_uint) -> c_int; fn af_alloc_host(ptr: *mut *const c_void, bytes: DimT) -> c_int; @@ -112,17 +114,17 @@ impl From for MatchType { pub fn to_u32(t: MatProp) -> u32 { match t { - MatProp::NONE => 0, - MatProp::TRANS => 1, - MatProp::CTRANS => 2, - MatProp::UPPER => 32, - MatProp::LOWER => 64, - MatProp::DIAGUNIT => 128, - MatProp::SYM => 512, - MatProp::POSDEF => 1024, - MatProp::ORTHOG => 2048, - MatProp::TRIDIAG => 4096, - MatProp::BLOCKDIAG => 8192, + MatProp::NONE => 0, + MatProp::TRANS => 1, + MatProp::CTRANS => 2, + MatProp::UPPER => 32, + MatProp::LOWER => 64, + MatProp::DIAGUNIT => 128, + MatProp::SYM => 512, + MatProp::POSDEF => 1024, + MatProp::ORTHOG => 2048, + MatProp::TRIDIAG => 4096, + MatProp::BLOCKDIAG => 8192, } } @@ -211,7 +213,9 @@ impl HasAfEnum for Complex { type AggregateOutType = Self; type SobelOutType = Self; - fn get_af_dtype() -> DType { DType::C32 } + fn get_af_dtype() -> DType { + DType::C32 + } } impl HasAfEnum for Complex { type InType = Self; @@ -224,9 +228,11 @@ impl HasAfEnum for Complex { type AggregateOutType = Self; type SobelOutType = Self; - fn get_af_dtype() -> DType { DType::C64 } + fn get_af_dtype() -> DType { + DType::C64 + } } -impl HasAfEnum for f32 { +impl HasAfEnum for f32 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -237,9 +243,11 @@ impl HasAfEnum for f32 { type AggregateOutType = Self; type SobelOutType = Self; - fn get_af_dtype() -> DType { DType::F32 } + fn get_af_dtype() -> DType { + DType::F32 + } } -impl HasAfEnum for f64 { +impl HasAfEnum for f64 { type InType = Self; type BaseType = Self; type AbsOutType = f64; @@ -250,7 +258,9 @@ impl HasAfEnum for f64 { type AggregateOutType = Self; type SobelOutType = Self; - fn get_af_dtype() -> DType { DType::F64 } + fn get_af_dtype() -> DType { + DType::F64 + } } impl HasAfEnum for bool { type InType = Self; @@ -263,9 +273,11 @@ impl HasAfEnum for bool { type AggregateOutType = u32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::B8 } + fn get_af_dtype() -> DType { + DType::B8 + } } -impl HasAfEnum for u8 { +impl HasAfEnum for u8 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -276,9 +288,11 @@ impl HasAfEnum for u8 { type AggregateOutType = u32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::U8 } + fn get_af_dtype() -> DType { + DType::U8 + } } -impl HasAfEnum for i16 { +impl HasAfEnum for i16 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -289,9 +303,11 @@ impl HasAfEnum for i16 { type AggregateOutType = i32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::S16 } + fn get_af_dtype() -> DType { + DType::S16 + } } -impl HasAfEnum for u16 { +impl HasAfEnum for u16 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -302,9 +318,11 @@ impl HasAfEnum for u16 { type AggregateOutType = u32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::U16 } + fn get_af_dtype() -> DType { + DType::U16 + } } -impl HasAfEnum for i32 { +impl HasAfEnum for i32 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -315,9 +333,11 @@ impl HasAfEnum for i32 { type AggregateOutType = i32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::S32 } + fn get_af_dtype() -> DType { + DType::S32 + } } -impl HasAfEnum for u32 { +impl HasAfEnum for u32 { type InType = Self; type BaseType = Self; type AbsOutType = f32; @@ -328,9 +348,11 @@ impl HasAfEnum for u32 { type AggregateOutType = u32; type SobelOutType = i32; - fn get_af_dtype() -> DType { DType::U32 } + fn get_af_dtype() -> DType { + DType::U32 + } } -impl HasAfEnum for i64 { +impl HasAfEnum for i64 { type InType = Self; type BaseType = Self; type AbsOutType = f64; @@ -341,9 +363,11 @@ impl HasAfEnum for i64 { type AggregateOutType = Self; type SobelOutType = i64; - fn get_af_dtype() -> DType { DType::S64 } + fn get_af_dtype() -> DType { + DType::S64 + } } -impl HasAfEnum for u64 { +impl HasAfEnum for u64 { type InType = Self; type BaseType = Self; type AbsOutType = f64; @@ -354,7 +378,9 @@ impl HasAfEnum for u64 { type AggregateOutType = Self; type SobelOutType = i64; - fn get_af_dtype() -> DType { DType::U64 } + fn get_af_dtype() -> DType { + DType::U64 + } } impl From for SparseFormat { @@ -373,7 +399,10 @@ impl From for BinaryOp { impl From for RandomEngineType { fn from(t: u32) -> RandomEngineType { - assert!(RandomEngineType::PHILOX_4X32_10 as u32 <= t && t <= RandomEngineType::MERSENNE_GP11213 as u32); + assert!( + RandomEngineType::PHILOX_4X32_10 as u32 <= t + && t <= RandomEngineType::MERSENNE_GP11213 as u32 + ); unsafe { mem::transmute(t) } } } @@ -569,25 +598,45 @@ implicit!(bool, u8 => u8); impl Zero for Complex64 { fn zero() -> Self { - Complex64{re: 0.0, im: 0.0} + Complex64 { re: 0.0, im: 0.0 } } } impl Zero for Complex32 { fn zero() -> Self { - Complex32{re: 0.0, im: 0.0} + Complex32 { re: 0.0, im: 0.0 } } } pub trait FloatingPoint { - fn is_real() -> bool { false } - fn is_complex() -> bool { false } + fn is_real() -> bool { + false + } + fn is_complex() -> bool { + false + } } -impl FloatingPoint for Complex { fn is_complex() -> bool { true } } -impl FloatingPoint for Complex { fn is_complex() -> bool { true } } -impl FloatingPoint for f64 { fn is_real() -> bool { true } } -impl FloatingPoint for f32 { fn is_real() -> bool { true } } +impl FloatingPoint for Complex { + fn is_complex() -> bool { + true + } +} +impl FloatingPoint for Complex { + fn is_complex() -> bool { + true + } +} +impl FloatingPoint for f64 { + fn is_real() -> bool { + true + } +} +impl FloatingPoint for f32 { + fn is_real() -> bool { + true + } +} pub trait RealFloating {} @@ -607,8 +656,8 @@ impl RealNumber for i32 {} impl RealNumber for u32 {} impl RealNumber for i16 {} impl RealNumber for u16 {} -impl RealNumber for u8 {} -impl RealNumber for bool{} +impl RealNumber for u8 {} +impl RealNumber for bool {} impl RealNumber for u64 {} impl RealNumber for i64 {} @@ -623,7 +672,7 @@ pub trait ImageNativeType {} impl ImageNativeType for f32 {} impl ImageNativeType for u16 {} -impl ImageNativeType for u8 {} +impl ImageNativeType for u8 {} pub trait ImageFilterType {} @@ -633,8 +682,8 @@ impl ImageFilterType for i32 {} impl ImageFilterType for u32 {} impl ImageFilterType for i16 {} impl ImageFilterType for u16 {} -impl ImageFilterType for u8 {} -impl ImageFilterType for bool{} +impl ImageFilterType for u8 {} +impl ImageFilterType for bool {} // TODO Rust haven't stabilized trait aliases yet pub trait GrayRGBConvertible {} @@ -645,7 +694,7 @@ impl GrayRGBConvertible for i32 {} impl GrayRGBConvertible for u32 {} impl GrayRGBConvertible for i16 {} impl GrayRGBConvertible for u16 {} -impl GrayRGBConvertible for u8 {} +impl GrayRGBConvertible for u8 {} // TODO Rust haven't stabilized trait aliases yet pub trait MomentsComputable {} @@ -656,7 +705,7 @@ impl MomentsComputable for i32 {} impl MomentsComputable for u32 {} impl MomentsComputable for i16 {} impl MomentsComputable for u16 {} -impl MomentsComputable for u8 {} +impl MomentsComputable for u8 {} // TODO Rust haven't stabilized trait aliases yet pub trait MedianComputable {} @@ -667,7 +716,7 @@ impl MedianComputable for i32 {} impl MedianComputable for u32 {} impl MedianComputable for i16 {} impl MedianComputable for u16 {} -impl MedianComputable for u8 {} +impl MedianComputable for u8 {} // TODO Rust haven't stabilized trait aliases yet pub trait EdgeComputable {} @@ -678,7 +727,7 @@ impl EdgeComputable for i32 {} impl EdgeComputable for u32 {} impl EdgeComputable for i16 {} impl EdgeComputable for u16 {} -impl EdgeComputable for u8 {} +impl EdgeComputable for u8 {} pub trait CovarianceComputable {} @@ -688,6 +737,6 @@ impl CovarianceComputable for i32 {} impl CovarianceComputable for u32 {} impl CovarianceComputable for i16 {} impl CovarianceComputable for u16 {} -impl CovarianceComputable for u8 {} +impl CovarianceComputable for u8 {} impl CovarianceComputable for u64 {} impl CovarianceComputable for i64 {} diff --git a/src/vision/mod.rs b/src/vision/mod.rs index 4acbc202c..bc80d4a54 100644 --- a/src/vision/mod.rs +++ b/src/vision/mod.rs @@ -1,18 +1,18 @@ extern crate libc; +use self::libc::{c_double, c_float, c_int, c_longlong, c_uint, c_void}; +use crate::array::Array; +use crate::defines::{AfError, HomographyType, MatchType}; +use crate::error::HANDLE_ERROR; +use crate::util::{AfArray, DimT, Feat, MutAfArray, MutFeat}; +use crate::util::{HasAfEnum, ImageFilterType, RealFloating}; use std::mem; -use array::Array; -use defines::{AfError, HomographyType, MatchType}; -use error::HANDLE_ERROR; -use util::{AfArray, DimT, Feat, MutAfArray, MutFeat}; -use util::{HasAfEnum, RealFloating, ImageFilterType}; -use self::libc::{c_void, c_uint, c_int, c_float, c_double, c_longlong}; // af_sift and af_gloh uses patented algorithms, so didn't add them // they are built using installer builds #[allow(dead_code)] -extern { +extern "C" { fn af_create_features(feat: MutFeat, num: DimT) -> c_int; fn af_retain_features(feat: MutFeat, feat: Feat) -> c_int; fn af_get_features_num(num: *mut DimT, feat: Feat) -> c_int; @@ -23,35 +23,100 @@ extern { fn af_get_features_size(out: MutAfArray, feat: Feat) -> c_int; fn af_release_features(feat: *mut c_void) -> c_int; - fn af_fast(out: MutFeat, input: AfArray, thr: c_float, arc_len: c_uint, non_max: c_int, - feature_ratio: c_float, edge: c_uint) -> c_int; - - fn af_harris(out: MutFeat, input: AfArray, m: c_uint, r: c_float, s: c_float, bs: c_uint, k: c_float) -> c_int; - - fn af_orb(out: MutFeat, desc: MutAfArray, arr: AfArray, fast_thr: c_float, max_feat: c_uint, - scl_fctr: c_float, levels: c_uint, blur_img: c_int) -> c_int; - - fn af_hamming_matcher(idx: MutAfArray, dist: MutAfArray, - query: AfArray, train: AfArray, - dist_dim: DimT, n_dist: c_uint) -> c_int; - - fn af_nearest_neighbour(idx: MutAfArray, dist: MutAfArray, q: AfArray, t: AfArray, - dist_dim: DimT, n_dist: c_uint, dist_type: c_int) -> c_int; - - fn af_match_template(out: MutAfArray, search_img: AfArray, template_img: AfArray, - mtype: c_uint) -> c_int; - - fn af_susan(feat: MutFeat, i: AfArray, r: c_uint, d: c_float, g: c_float, f: c_float, e: c_uint) -> c_int; + fn af_fast( + out: MutFeat, + input: AfArray, + thr: c_float, + arc_len: c_uint, + non_max: c_int, + feature_ratio: c_float, + edge: c_uint, + ) -> c_int; + + fn af_harris( + out: MutFeat, + input: AfArray, + m: c_uint, + r: c_float, + s: c_float, + bs: c_uint, + k: c_float, + ) -> c_int; + + fn af_orb( + out: MutFeat, + desc: MutAfArray, + arr: AfArray, + fast_thr: c_float, + max_feat: c_uint, + scl_fctr: c_float, + levels: c_uint, + blur_img: c_int, + ) -> c_int; + + fn af_hamming_matcher( + idx: MutAfArray, + dist: MutAfArray, + query: AfArray, + train: AfArray, + dist_dim: DimT, + n_dist: c_uint, + ) -> c_int; + + fn af_nearest_neighbour( + idx: MutAfArray, + dist: MutAfArray, + q: AfArray, + t: AfArray, + dist_dim: DimT, + n_dist: c_uint, + dist_type: c_int, + ) -> c_int; + + fn af_match_template( + out: MutAfArray, + search_img: AfArray, + template_img: AfArray, + mtype: c_uint, + ) -> c_int; + + fn af_susan( + feat: MutFeat, + i: AfArray, + r: c_uint, + d: c_float, + g: c_float, + f: c_float, + e: c_uint, + ) -> c_int; fn af_dog(out: MutAfArray, i: AfArray, r1: c_int, r2: c_int) -> c_int; - fn af_homography(H: MutAfArray, inliers: *mut c_int, x_src: AfArray, y_src: AfArray, - x_dst: AfArray, y_dst: AfArray, htype: c_int, inlier_thr: c_float, - iterations: c_uint, otype: c_int) -> c_int; - - fn af_gloh(out: MutFeat, desc: MutAfArray, input: AfArray, n_layers: c_uint, - contrast_thr: c_float, edge_thr: c_float, init_sigma: c_float, - double_input: c_double, intensity_scale: c_float, feature_ratio: c_float) -> c_int; + fn af_homography( + H: MutAfArray, + inliers: *mut c_int, + x_src: AfArray, + y_src: AfArray, + x_dst: AfArray, + y_dst: AfArray, + htype: c_int, + inlier_thr: c_float, + iterations: c_uint, + otype: c_int, + ) -> c_int; + + fn af_gloh( + out: MutFeat, + desc: MutAfArray, + input: AfArray, + n_layers: c_uint, + contrast_thr: c_float, + edge_thr: c_float, + init_sigma: c_float, + double_input: c_double, + intensity_scale: c_float, + feature_ratio: c_float, + ) -> c_int; } /// A set of Array objects (usually, used in Computer vision context) @@ -96,10 +161,9 @@ impl Features { pub fn new(n: u64) -> Features { unsafe { let mut temp: i64 = 0; - let err_val = af_create_features(&mut temp as *mut c_longlong as MutFeat, - n as DimT); + let err_val = af_create_features(&mut temp as *mut c_longlong as MutFeat, n as DimT); HANDLE_ERROR(AfError::from(err_val)); - Features {feat: temp} + Features { feat: temp } } } @@ -107,8 +171,10 @@ impl Features { pub fn num_features(&self) -> i64 { unsafe { let mut temp: i64 = 0; - let err_val = af_get_features_num(&mut temp as *mut DimT, - self.feat as *const c_longlong as Feat); + let err_val = af_get_features_num( + &mut temp as *mut DimT, + self.feat as *const c_longlong as Feat, + ); HANDLE_ERROR(AfError::from(err_val)); temp } @@ -117,7 +183,11 @@ impl Features { feat_func_def!("Get x coordinates Array", xpos, af_get_features_xpos); feat_func_def!("Get y coordinates Array", ypos, af_get_features_ypos); feat_func_def!("Get score Array", score, af_get_features_score); - feat_func_def!("Get orientation Array", orientation, af_get_features_orientation); + feat_func_def!( + "Get orientation Array", + orientation, + af_get_features_orientation + ); feat_func_def!("Get features size Array", size, af_get_features_size); /// Get the internal handle for [Features](./struct.Features.html) object @@ -130,10 +200,12 @@ impl Clone for Features { fn clone(&self) -> Features { unsafe { let mut temp: i64 = 0; - let ret_val = af_retain_features(&mut temp as *mut c_longlong as MutFeat, - self.feat as *const c_longlong as Feat); + let ret_val = af_retain_features( + &mut temp as *mut c_longlong as MutFeat, + self.feat as *const c_longlong as Feat, + ); HANDLE_ERROR(AfError::from(ret_val)); - Features {feat: temp} + Features { feat: temp } } } } @@ -176,22 +248,31 @@ impl Drop for Features { /// for x and y coordinates and score, while array oreientation is set to 0 as FAST does not /// compute orientation. Size is set to 1 as FAST does not compute multiple scales. #[allow(unused_mut)] -pub fn fast(input: &Array, - thr: f32, - arc_len: u32, - non_max: bool, - feat_ratio: f32, - edge: u32) -> Features - where T: HasAfEnum + ImageFilterType +pub fn fast( + input: &Array, + thr: f32, + arc_len: u32, + non_max: bool, + feat_ratio: f32, + edge: u32, +) -> Features +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_fast(&mut temp as *mut c_longlong as MutFeat, - input.get() as AfArray, thr as c_float, arc_len as c_uint, - non_max as c_int, feat_ratio as c_float, edge as c_uint); + let err_val = af_fast( + &mut temp as *mut c_longlong as MutFeat, + input.get() as AfArray, + thr as c_float, + arc_len as c_uint, + non_max as c_int, + feat_ratio as c_float, + edge as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } - Features {feat: temp} + Features { feat: temp } } /// Harris corner detector. @@ -216,23 +297,31 @@ pub fn fast(input: &Array, /// for x and y coordinates and score, while array oreientation & size are set to 0 & 1, /// respectively, since harris doesn't compute that information #[allow(unused_mut)] -pub fn harris(input: &Array, - max_corners: u32, - min_response: f32, - sigma: f32, - block_size: u32, - k_thr: f32) -> Features - where T: HasAfEnum + RealFloating +pub fn harris( + input: &Array, + max_corners: u32, + min_response: f32, + sigma: f32, + block_size: u32, + k_thr: f32, +) -> Features +where + T: HasAfEnum + RealFloating, { let mut temp: i64 = 0; unsafe { - let err_val = af_harris(&mut temp as *mut c_longlong as MutFeat, - input.get() as AfArray, max_corners as c_uint, - min_response as c_float, sigma as c_float, block_size as c_uint, - k_thr as c_float); + let err_val = af_harris( + &mut temp as *mut c_longlong as MutFeat, + input.get() as AfArray, + max_corners as c_uint, + min_response as c_float, + sigma as c_float, + block_size as c_uint, + k_thr as c_float, + ); HANDLE_ERROR(AfError::from(err_val)); } - Features {feat: temp} + Features { feat: temp } } /// ORB feature descriptor @@ -258,23 +347,33 @@ pub fn harris(input: &Array, /// /// This function returns a tuple of [`Features`](./struct.Features.html) and [`Array`](./struct.Array.html). The features objects composed of Arrays for x and y coordinates, score, orientation and size of selected features. The Array object is a two dimensional Array of size Nx8 where N is number of selected features. #[allow(unused_mut)] -pub fn orb(input: &Array, - fast_thr: f32, max_feat: u32, - scl_fctr: f32, levels: u32, - blur_img: bool) -> (Features, Array) - where T: HasAfEnum + RealFloating +pub fn orb( + input: &Array, + fast_thr: f32, + max_feat: u32, + scl_fctr: f32, + levels: u32, + blur_img: bool, +) -> (Features, Array) +where + T: HasAfEnum + RealFloating, { let mut f: i64 = 0; let mut d: i64 = 0; unsafe { - let err_val = af_orb(&mut f as *mut c_longlong as MutFeat, - &mut d as MutAfArray, - input.get() as AfArray, fast_thr as c_float, - max_feat as c_uint, scl_fctr as c_float, - levels as c_uint, blur_img as c_int); + let err_val = af_orb( + &mut f as *mut c_longlong as MutFeat, + &mut d as MutAfArray, + input.get() as AfArray, + fast_thr as c_float, + max_feat as c_uint, + scl_fctr as c_float, + levels as c_uint, + blur_img as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } - (Features {feat: f}, d.into()) + (Features { feat: f }, d.into()) } /// Hamming feature matcher @@ -310,19 +409,27 @@ pub fn orb(input: &Array, /// equal to n_dist. The value at position IxJ indicates the Hamming distance of the Jth smallest /// distance to the Ith query value in the train data array. #[allow(unused_mut)] -pub fn hamming_matcher(query: &Array, - train: &Array, - dist_dims: i64, - n_dist: u32) -> (Array, Array< T::AggregateOutType >) - where T: HasAfEnum + ImageFilterType, - T::AggregateOutType: HasAfEnum +pub fn hamming_matcher( + query: &Array, + train: &Array, + dist_dims: i64, + n_dist: u32, +) -> (Array, Array) +where + T: HasAfEnum + ImageFilterType, + T::AggregateOutType: HasAfEnum, { let mut idx: i64 = 0; - let mut dist:i64 = 0; + let mut dist: i64 = 0; unsafe { - let err_val = af_hamming_matcher(&mut idx as MutAfArray, &mut dist as MutAfArray, - query.get() as AfArray, train.get() as AfArray, - dist_dims as DimT, n_dist as c_uint); + let err_val = af_hamming_matcher( + &mut idx as MutAfArray, + &mut dist as MutAfArray, + query.get() as AfArray, + train.get() as AfArray, + dist_dims as DimT, + n_dist as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } (idx.into(), dist.into()) @@ -361,20 +468,29 @@ pub fn hamming_matcher(query: &Array, /// and N is equal to `n_dist`. The value at position IxJ indicates the distance of the Jth smallest /// distance to the Ith query value in the train data array based on the `dist_type` chosen. #[allow(unused_mut)] -pub fn nearest_neighbour(query: &Array, - train: &Array, - dist_dim: i64, - n_dist: u32, - dist_type: MatchType) -> (Array, Array< T::AggregateOutType >) - where T: HasAfEnum + ImageFilterType, - T::AggregateOutType: HasAfEnum +pub fn nearest_neighbour( + query: &Array, + train: &Array, + dist_dim: i64, + n_dist: u32, + dist_type: MatchType, +) -> (Array, Array) +where + T: HasAfEnum + ImageFilterType, + T::AggregateOutType: HasAfEnum, { let mut idx: i64 = 0; let mut dist: i64 = 0; unsafe { - let err_val = af_nearest_neighbour(&mut idx as MutAfArray, &mut dist as MutAfArray, - query.get() as AfArray, train.get() as AfArray, - dist_dim as DimT, n_dist as c_uint, dist_type as c_int); + let err_val = af_nearest_neighbour( + &mut idx as MutAfArray, + &mut dist as MutAfArray, + query.get() as AfArray, + train.get() as AfArray, + dist_dim as DimT, + n_dist as c_uint, + dist_type as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (idx.into(), dist.into()) @@ -395,17 +511,23 @@ pub fn nearest_neighbour(query: &Array, /// /// This function returns an Array with disparity values for the window starting at corresponding pixel position. #[allow(unused_mut)] -pub fn match_template(search_img: &Array, - template_img: &Array, - mtype: MatchType) -> Array< T::AbsOutType > - where T: HasAfEnum + ImageFilterType, - T::AbsOutType: HasAfEnum +pub fn match_template( + search_img: &Array, + template_img: &Array, + mtype: MatchType, +) -> Array +where + T: HasAfEnum + ImageFilterType, + T::AbsOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_match_template(&mut temp as MutAfArray, - search_img.get() as AfArray, template_img.get() as AfArray, - mtype as c_uint); + let err_val = af_match_template( + &mut temp as MutAfArray, + search_img.get() as AfArray, + template_img.get() as AfArray, + mtype as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -451,21 +573,31 @@ pub fn match_template(search_img: &Array, /// # Return Values /// An object of type [Features](./struct.Features.html) composed of arrays for x and y coordinates, score, orientation and size of selected features. #[allow(unused_mut)] -pub fn susan(input: &Array, - radius: u32, diff_thr: f32, - geom_thr: f32, feature_ratio: f32, - edge: u32) -> Features - where T: HasAfEnum + ImageFilterType +pub fn susan( + input: &Array, + radius: u32, + diff_thr: f32, + geom_thr: f32, + feature_ratio: f32, + edge: u32, +) -> Features +where + T: HasAfEnum + ImageFilterType, { let mut temp: i64 = 0; unsafe { - let err_val = af_susan(&mut temp as *mut c_longlong as MutFeat, - input.get() as AfArray, radius as c_uint, - diff_thr as c_float, geom_thr as c_float, feature_ratio as c_float, - edge as c_uint); + let err_val = af_susan( + &mut temp as *mut c_longlong as MutFeat, + input.get() as AfArray, + radius as c_uint, + diff_thr as c_float, + geom_thr as c_float, + feature_ratio as c_float, + edge as c_uint, + ); HANDLE_ERROR(AfError::from(err_val)); } - Features {feat: temp} + Features { feat: temp } } /// Difference of Gaussians. @@ -483,14 +615,19 @@ pub fn susan(input: &Array, /// /// Difference of smoothed inputs - An Array. #[allow(unused_mut)] -pub fn dog(input: &Array, radius1: i32, radius2: i32) -> Array< T::AbsOutType > - where T: HasAfEnum + ImageFilterType, - T::AbsOutType: HasAfEnum +pub fn dog(input: &Array, radius1: i32, radius2: i32) -> Array +where + T: HasAfEnum + ImageFilterType, + T::AbsOutType: HasAfEnum, { let mut temp: i64 = 0; unsafe { - let err_val = af_dog(&mut temp as MutAfArray, input.get() as AfArray, - radius1 as c_int, radius2 as c_int); + let err_val = af_dog( + &mut temp as MutAfArray, + input.get() as AfArray, + radius1 as c_int, + radius2 as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } temp.into() @@ -527,21 +664,34 @@ pub fn dog(input: &Array, radius1: i32, radius2: i32) -> Array< T::AbsOutT /// /// - `H` is a 3x3 array containing the estimated homography. /// - `inliers` is the number of inliers that the homography was estimated to comprise, in the case that htype is AF_HOMOGRAPHY_RANSAC, a higher inlier_thr value will increase the estimated inliers. Note that if the number of inliers is too low, it is likely that a bad homography will be returned. -pub fn homography(x_src: &Array, y_src: &Array, - x_dst: &Array, y_dst: &Array, - htype: HomographyType, inlier_thr: f32, - iterations: u32) -> (Array, i32) - where OutType: HasAfEnum + RealFloating +pub fn homography( + x_src: &Array, + y_src: &Array, + x_dst: &Array, + y_dst: &Array, + htype: HomographyType, + inlier_thr: f32, + iterations: u32, +) -> (Array, i32) +where + OutType: HasAfEnum + RealFloating, { let otype = OutType::get_af_dtype(); let mut inliers: i32 = 0; - let mut temp: i64 = 0; + let mut temp: i64 = 0; unsafe { - let err_val = af_homography(&mut temp as MutAfArray, &mut inliers as *mut c_int, - x_src.get() as AfArray, y_src.get() as AfArray, - x_dst.get() as AfArray, y_dst.get() as AfArray, - htype as c_int, inlier_thr as c_float, - iterations as c_uint, otype as c_int); + let err_val = af_homography( + &mut temp as MutAfArray, + &mut inliers as *mut c_int, + x_src.get() as AfArray, + y_src.get() as AfArray, + x_dst.get() as AfArray, + y_dst.get() as AfArray, + htype as c_int, + inlier_thr as c_float, + iterations as c_uint, + otype as c_int, + ); HANDLE_ERROR(AfError::from(err_val)); } (temp.into(), inliers) diff --git a/tests/lib.rs b/tests/lib.rs index ba7365b21..71e16e7c0 100644 --- a/tests/lib.rs +++ b/tests/lib.rs @@ -1,18 +1,17 @@ -extern crate arrayfire as af; - use std::error::Error; use std::thread; -use af::*; + +use ::arrayfire::*; macro_rules! implement_handler { - ($fn_name:ident) => ( + ($fn_name:ident) => { pub fn $fn_name(error_code: AfError) { match error_code { - AfError::SUCCESS => {}, /* No-op */ + AfError::SUCCESS => {} /* No-op */ _ => panic!("Error message: {}", error_code.description()), } } - ) + }; } implement_handler!(handler_sample1); @@ -23,23 +22,31 @@ implement_handler!(handler_sample4); #[allow(unused_must_use)] #[test] fn check_error_handler_mutation() { - - let children = (0..4).map(|i| { - thread::Builder::new().name(format!("child {}",i+1).to_string()).spawn(move || { - let target_device = i%af::device_count(); - println!("Thread {:?} 's target device is {}", thread::current(), target_device); - match i { - 0 => register_error_handler(Callback::new(handler_sample1)), - 1 => register_error_handler(Callback::new(handler_sample2)), - 2 => register_error_handler(Callback::new(handler_sample3)), - 3 => register_error_handler(Callback::new(handler_sample4)), - _ => panic!("Impossible scenario"), - } - }).ok().expect("Failed to launch a thread") - }).collect::< Vec<_> >(); + let children = (0..4) + .map(|i| { + thread::Builder::new() + .name(format!("child {}", i + 1).to_string()) + .spawn(move || { + let target_device = i % arrayfire::device_count(); + println!( + "Thread {:?} 's target device is {}", + thread::current(), + target_device + ); + match i { + 0 => register_error_handler(Callback::new(handler_sample1)), + 1 => register_error_handler(Callback::new(handler_sample2)), + 2 => register_error_handler(Callback::new(handler_sample3)), + 3 => register_error_handler(Callback::new(handler_sample4)), + _ => panic!("Impossible scenario"), + } + }) + .ok() + .expect("Failed to launch a thread") + }) + .collect::>(); for c in children { c.join(); } - }