### Build and Run ArrayFire Examples on Linux Source: https://arrayfire.org/docs/installing These commands demonstrate how to build and run the ArrayFire examples on a Linux system after installation. It involves copying example files, navigating to the directory, configuring with CMake, compiling with make, and finally executing the 'helloworld' example for different backends (CPU, CUDA, OneAPI, OpenCL). ```bash cp -r /opt/arrayfire/share/ArrayFire/examples /tmp/examples cd /tmp/examples mkdir build cd build cmake .. make ./helloworld/helloworld_{cpu,cuda,oneapi,opencl} ``` -------------------------------- ### Makefile Example for ArrayFire CPU Backend Source: https://arrayfire.org/docs/using_on_linux This snippet provides a minimal Makefile example for building an ArrayFire project using the CPU backend. It manually specifies include paths, library paths, and the library to link. ```makefile LIBS=-lafcpu LIB_PATHS=-L/opt/arrayfire/lib INCLUDES=-I/opt/arrayfire/include CC=g++ $(COMPILER_OPTIONS) COMPILER_OPTIONS=-std=c++11 -g all: main.cpp Makefile $(CC) main.cpp -o test $(INCLUDES) $(LIBS) $(LIB_PATHS) ``` -------------------------------- ### System Information and Configuration Source: https://arrayfire.org/docs/image_processing_2filters_8cpp-example Functions for getting system information and setting the device. ```APIDOC ## info ### Description Prints the ArrayFire library version and system information. ### Method N/A (C++ function signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ## setDevice ### Description Sets the current device. ### Method N/A (C++ function signature) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### ArrayFire Initialization and Device Info Source: https://arrayfire.org/docs/image_processing_2adaptive_thresholding_8cpp-example Initializes the ArrayFire library, sets the compute device, and prints device information. This is a common setup step for ArrayFire applications. ```cpp #include #include #include #include using namespace af; using std::abs; typedef enum { MEAN = 0, MEDIAN, MINMAX_AVG } LocalThresholdType; int main(int argc, char **argv) { try { int device = argc > 1 ? atoi(argv[1]) : 0; af::setDevice(device); af::info(); array sudoku = loadImage(ASSETS_DIR "/examples/images/sudoku.jpg", true); array mnt = adaptiveThreshold(sudoku, MEAN, 37, 10); array mdt = adaptiveThreshold(sudoku, MEDIAN, 7, 4); array mmt = adaptiveThreshold(sudoku, MINMAX_AVG, 11, 4); array itt = 255.0f - iterativeThreshold(sudoku); af::Window wnd("Adaptive Thresholding Algorithms"); printf("Press ESC while the window is in focus to exit\n"); while (!wnd.close()) { wnd.grid(2, 3); ``` -------------------------------- ### Main Function and Device Setup (C++) Source: https://arrayfire.org/docs/machine_learning_2bagging_8cpp-example The main function initializes the ArrayFire environment, sets the computation device, and calls the bagging demonstration function. It includes error handling for ArrayFire exceptions. ```cpp int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { setDevice(device); af::info(); bagging_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Install ArrayFire on Linux using Installer Source: https://arrayfire.org/docs/installing This command executes the ArrayFire Linux installer script. The `--include-subdir` flag ensures subdirectories are included, and `--prefix=/opt` specifies the installation directory. This is a common method for installing ArrayFire on Linux systems when package managers are not used or supported. ```bash ./ArrayFire_*_Linux_x86_64.sh --include-subdir --prefix=/opt ``` -------------------------------- ### ArrayFire Main Function Setup and Exception Handling Source: https://arrayfire.org/docs/machine_learning_2naive_bayes_8cpp-example The main function initializes ArrayFire, sets the device, and calls the Naive Bayes demo function. It includes basic command-line argument parsing for device selection, console output, and percentage of data to use. It also incorporates ArrayFire exception handling. ```cpp int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); naive_bayes_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Raytracing Scene Setup and Initialization Source: https://arrayfire.org/docs/pde_2bhrt_8cpp-example This function initializes the raytracing scene, including camera parameters, object definitions, and background settings. It sets up the camera's position, look-at point, field of view, and focal length. It also defines scene objects like accretion disks and loads a background image. Finally, it generates initial rays from the camera and calls the `generate_image` function to render the scene. ```cpp void raytracing(uint32_t width, uint32_t height) { // Set the parameters of the raytraced image double vfov = radians(90.0); double focal_length = 0.01; // Set the parameters of the camera af::array global_vertical = af::array(3, {0.0, 0.0, 1.0}); af::array camera_position = af::array(3, {-7.0, 6.0, 2.0}); af::array camera_lookat = af::array(3, {0.0, 0.0, 0.0}); double accretion_inner_radius = M * 3.0; double accretion_outter_radius = M * 8.0; double simulation_tolerance = 1e-6; double max_simulation_time = 12.; uint32_t num_steps_per_collide_check = 1; // Set the background of the scene auto bg_image = af::loadimage(ASSETS_DIR "/examples/images/westerlund.jpg", true); auto background = Background(bg_image); // Set the objects living in the scene std::vector > objects; if (scene != Scene::WORMHOLE) objects.push_back(std::make_unique( af::array(3, {0.0, 0.0, 0.0}), af::array(3, {0.0, 0.0, 1.0}), accretion_inner_radius, accretion_outter_radius)); // Generate rays from the camera auto camera = Camera(camera_position, camera_lookat, vfov, focal_length, width, height); auto pair = camera.generate_viewport_4rays(); auto ray4_pos = pair.first; auto ray4_vel = pair.second; auto begin = std::chrono::high_resolution_clock::now(); // Generate raytraced image auto image = generate_image( ray4_pos, ray4_vel, objects, background, width, height, max_simulation_time, simulation_tolerance, num_steps_per_collide_check); auto end = std::chrono::high_resolution_clock::now(); std::cout << "\nSimulation took: " << std::chrono::duration_cast(end - begin).count() << " s" << std::endl; // Save image af::saveImage("result.png", image); } ``` -------------------------------- ### ArrayFire Installation Directory Structure Source: https://arrayfire.org/docs/using_on_linux This snippet details the typical directory structure after installing ArrayFire. It shows the locations of header files, libraries for different backends, and CMake configuration scripts. ```text include/arrayfire.h - Primary ArrayFire include file include/af/*.h - Additional include files lib/libaf* - CPU, CUDA, oneAPI, and OpenCL libraries (.a, .so) lib/libforge* - Visualization library lib/libcu* - CUDA backend dependencies lib/libOpenCL.so - OpenCL ICD Loader library share/ArrayFire/cmake/* - CMake config (find) scripts share/ArrayFire/examples/* - All ArrayFire examples ``` -------------------------------- ### CMake Build Instructions Source: https://arrayfire.org/docs/using_on_linux These commands illustrate the process of generating build instructions using CMake and then compiling the project. It includes instructions for out-of-source builds and specifying a non-standard ArrayFire installation path. ```bash cd your-project-directory mkdir build cd build cmake .. make ``` ```bash cmake -DArrayFire_DIR=/home/user/ArrayFire .. c则make .. ``` -------------------------------- ### Bagging Demo Initialization (C++) Source: https://arrayfire.org/docs/machine_learning_2bagging_8cpp-example Initializes data for the Bagging demo. This function is responsible for loading training and testing datasets (images and labels) and determining the number of training samples, testing samples, and classes. It serves as a setup step before running the bagging algorithm. ```cpp void bagging_demo(bool console, int perc) { array train_images, train_labels; array test_images, test_labels; int num_train, num_test, num_classes; ``` -------------------------------- ### Setup Sparse and Dense Inputs for Conjugate Gradient Method (C++) Source: https://arrayfire.org/docs/benchmarks_2cg_8cpp-example This C++ function generates a random input matrix 'A', makes it positive definite, and then creates both a dense and a sparse version of 'A'. It also generates a random vector 'x0' and computes 'b' such that b = A*x0. The function then prints the sparsity and memory usage of the dense and sparse matrices. ```cpp #include #include using namespace af; static size_t dimension = 4 * 1024; static const int maxIter = 10; static const int sparsityFactor = 7; static array A; static array spA; // Sparse A static array x0; static array b; void setupInputs() { // Generate a random input: A array T = randu(dimension, dimension, f32); // Create 0s in input. // Anything that is no divisible by sparsityFactor will become 0. A = floor(T * 1000); A = A * ((A % sparsityFactor) == 0) / 1000; // Make it positive definite A = transpose(A) + A + A.dims(0) * identity(A.dims(0), A.dims(0), f32); // Make A sparse as spA spA = sparse(A); // Generate x0: Random guess x0 = randu(A.dims(0), f32); // Generate b b = matmul(A, x0); std::cout << "Sparsity of A = " << 100.f * (float)sparseGetNNZ(spA) / (float)spA.elements() << "%" << std::endl; std::cout << "Memory Usage of A = " << A.bytes() / (1024.f * 1024.f) << " MB" << std::endl; std::cout << "Memory Usage of spA = " << (sparseGetValues(spA).bytes() + sparseGetRowIdx(spA).bytes() + sparseGetColIdx(spA).bytes()) / (1024.f * 1024.f) << " MB" << std::endl; } ``` -------------------------------- ### ArrayFire Main Function Example (C++) Source: https://arrayfire.org/docs/machine_learning_2deep_belief_net_8cpp-example Demonstrates setting the ArrayFire device, displaying device information, and executing a demo function. It includes error handling for ArrayFire exceptions. ```cpp int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); return dbn_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Conjugate Gradient Solver Example Source: https://arrayfire.org/docs/benchmarks_2cg_8cpp-example Demonstrates the usage of ArrayFire for solving linear systems using the conjugate gradient method, both for dense and sparse matrices. Includes timing comparisons. ```c++ int main(int, char **) { af::info(); setupInputs(); std::cout << "Verifying Dense Conjugate Gradient:" << std::endl; checkConjugateGradient(A); std::cout << "Verifying Sparse Conjugate Gradient:" << std::endl; checkConjugateGradient(spA); af::sync(); std::cout << "Dense Conjugate Gradient Time: " << timeit(denseConjugateGradient) * 1000 << "ms" << std::endl; std::cout << "Sparse Conjugate Gradient Time: " << timeit(sparseConjugateGradient) * 1000 << "ms" << std::endl; return 0; } ``` -------------------------------- ### Example Function Source: https://arrayfire.org/docs/util_8h_source An example function demonstrating custom function integration. ```APIDOC ## Example Function ### Description This is an example function provided for documentation purposes, demonstrating how custom functions can be integrated into the ArrayFire API. ### Method #### `af::exampleFunction(const array& in, const af_someenum_t param)` Performs an operation defined by the example function on the input array `in` with the given parameter `param`. #### `af_example_function(af_array* out, const af_array in, const af_someenum_t param)` C-style interface for the example function. ### Request Example ```cpp // C++ Example af::array input_array = af::randu(5, 5); af::array result_array = af::exampleFunction(input_array, AF_SOMEENUM_VALUE); // C Example af_array c_input_array; af_random_uniform(&c_input_array, 5, 5); af_array c_result_array; af_example_function(&c_result_array, c_input_array, AF_SOMEENUM_VALUE); ``` ### Response Returns the processed array as `af::array` (C++) or `af_array` (C). ``` -------------------------------- ### ArrayFire Main Function Example in C++ Source: https://arrayfire.org/docs/image_processing_2image_editing_8cpp-example This C++ code demonstrates the main function for an ArrayFire application. It initializes the ArrayFire device, loads sample images, performs various image manipulations (like blending, contrast/brightness adjustment, unsharp masking, zooming), and applies transformations. This serves as a practical example of integrating ArrayFire's functionalities. ```cpp int main(int argc, char **argv) {\ntry {\nint device = argc > 1 ? atoi(argv[1]) : 0;\naf::setDevice(device);\naf::info();\narray man = loadImage(ASSETS_DIR "/examples/images/man.jpg", true);\narray fight = loadImage(ASSETS_DIR "/examples/images/fight.jpg", true);\narray nature =\nresize(loadImage(ASSETS_DIR "/examples/images/nature.jpg", true),\nfight.dims(0), fight.dims(1));\narray intensity = colorSpace(fight, AF_GRAY, AF_RGB);\narray mask = clamp(intensity, 10.0f, 255.0f) > 0.0f;\narray blend = alphaBlend(fight, nature, mask);\narray highcon = changeContrast(man, 0.3);\narray highbright = changeBrightness(man, 0.2);\narray translated = translate(man, 100, 100, 200, 126);\narray sharp = usm(man, 3, 1.2);\narray zoom = digZoom(man, 28, 10, 192, 192);\n\n// Additional example usage would follow here...\n\n} catch (af::exception& e) {\nfprintf(stderr, "%s\n", e.what());\nreturn 1;\n}\nreturn 0;\n} ``` -------------------------------- ### Simple Enum Example Source: https://arrayfire.org/docs/defines_8h A basic enumeration example. ```APIDOC ## Enum: af_someenum_t ### Description A simple example enumeration. ### Enumerators - **AF_ID** (int): An identifier. ### Definition defines.h:428 ``` -------------------------------- ### Install Tegra Prerequisites Source: https://arrayfire.org/docs/installing This command installs essential libraries required for ArrayFire on NVIDIA Tegra devices. It installs the development versions of OpenBLAS and LAPACKE, which are crucial for numerical computations performed by ArrayFire. ```bash sudo apt install libopenblas-dev liblapacke-dev ``` -------------------------------- ### Initialize ArrayFire and Run KNN Demo (C++) Source: https://arrayfire.org/docs/machine_learning_2knn_8cpp-example This snippet demonstrates initializing the ArrayFire library by setting the device, printing device information, and then executing a KNN demo. It includes basic error handling for ArrayFire exceptions. Dependencies include the ArrayFire library. ```cpp int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); knn_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Install ArrayFire on macOS Source: https://arrayfire.org/docs/installing This command installs ArrayFire on macOS using the provided package installer. The `sudo installer` command executes the package, and `-pkg` specifies the package file, while `-target /` indicates the root directory as the installation target. This is the standard method for installing macOS applications distributed as .pkg files. ```bash sudo installer -pkg Arrayfire-*_OSX.pkg -target / ``` -------------------------------- ### CMake: Specify Non-Standard ArrayFire Installation Path Source: https://arrayfire.org/docs/using_on_osx This command shows how to inform CMake about a non-standard ArrayFire installation path using the `ArrayFire_DIR` variable. This is useful when ArrayFire is not installed in the default system locations. ```bash cmake -DArrayFire_DIR=/home/user/ArrayFire .. # or using ccmake: c CMAKE_INSTALL_PREFIX=/home/user/ArrayFire .. ``` -------------------------------- ### Display Images and Histograms using af::Window Source: https://arrayfire.org/docs/image_processing_2binary_thresholding_8cpp-example Demonstrates how to create and display various visualizations using the af::Window object, including smoothed histograms and different thresholding techniques applied to images. ```cpp wnd(2, 1).hist(smoothHist, 0, 255, "Smoothed Input Histogram"); wnd(0, 2).image(bt, "Simple Binary threshold"); wnd(1, 2).image(ot, "Otsu's Threshold"); wnd(2, 2).image(otsu(smooth), "Otsu's Threshold on Smoothed Image"); wnd.show(); ``` -------------------------------- ### Initialize and Run ArrayFire Application Source: https://arrayfire.org/docs/computer_vision_2harris_8cpp-example The main function initializes the ArrayFire environment by setting the device and printing system information. It then calls the `harris_demo` function to execute the corner detection process. Exception handling is included to catch and report any ArrayFire-specific errors. ```cpp int main(int argc, char** argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); af::info(); printf("** ArrayFire Harris Corner Detector Demo **\n\n"); harris_demo(console); } catch (af::exception& ae) { fprintf(stderr, "%s\n", ae.what()); throw; } return 0; } ``` -------------------------------- ### Install Linux Graphics Dependencies Source: https://arrayfire.org/docs/installing These commands install necessary dependencies for ArrayFire's graphics support (Forge library) on different Linux distributions. The first command is for Debian/Ubuntu-based systems, and the second is for Fedora/Redhat/CentOS-based systems. These packages provide essential libraries like FreeImage, Fontconfig, and GLU. ```bash apt install build-essential libfreeimage3 libfontconfig1 libglu1-mesa ``` ```bash yum install freeimage fontconfig mesa-libGLU ``` -------------------------------- ### Get Number of Array Elements Source: https://arrayfire.org/docs/benchmarks_2cg_8cpp-example Calculates and returns the total number of elements in an ArrayFire array across all its dimensions. ```c++ dim_t elements() const ``` -------------------------------- ### Initialize ArrayFire Application Source: https://arrayfire.org/docs/image_processing_2pyramids_8cpp-example Sets the target compute device and initializes the ArrayFire environment. Includes basic error handling for ArrayFire exceptions. ```cpp int main(int argc, char** argv) { int device = argc > 1 ? atoi(argv[1]) : 0; try { af::setDevice(device); af::info(); printf("** ArrayFire Image Pyramids Demo **\n\n"); // pyramids_demo(); // Assuming this function is defined elsewhere } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } ``` -------------------------------- ### Initialize ArrayFire and Run Logistic Regression Demo in C++ Source: https://arrayfire.org/docs/machine_learning_2logistic_regression_8cpp-example Sets up the ArrayFire device, prints device information, and executes the main logistic regression demonstration function. Handles potential ArrayFire exceptions. Takes optional command-line arguments for device selection, console output, and data percentage. ```cpp int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int perc = argc > 3 ? atoi(argv[3]) : 60; try { af::setDevice(device); af::info(); return logit_demo(console, perc); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Get Array Dimensions Source: https://arrayfire.org/docs/image_processing_2edge_8cpp-example Retrieves the dimensions of an af::array. This is a fundamental operation for understanding the shape of your data. ```cpp af::array::dims dims() const ``` -------------------------------- ### Get Array Size in Bytes Source: https://arrayfire.org/docs/benchmarks_2cg_8cpp-example Returns the total size of an ArrayFire array in bytes. This can be used to estimate memory usage. ```c++ size_t bytes() const ``` -------------------------------- ### Initialize ArrayFire and Run Template Matching Demo Source: https://arrayfire.org/docs/computer_vision_2matching_8cpp-example This C++ main function initializes the ArrayFire environment, sets the device, and calls the template matching demo function. It includes error handling for ArrayFire exceptions. The function takes optional command-line arguments to specify the device and a console-only mode. ```cpp int main(int argc, char** argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); af::info(); std::cout << "** ArrayFire template matching Demo **" << std::endl << std::endl; templateMatchingDemo(console); } catch (af::exception& ae) { std::cerr << ae.what() << std::endl; throw; } return 0; } ``` -------------------------------- ### Utility Functions Source: https://arrayfire.org/docs/computer_vision_2susan_8cpp-example Documentation for utility functions like `af::info`, `af::setDevice`, and `af_print`. ```APIDOC ## af::info ### Description Prints information about the current ArrayFire setup, including device details and capabilities. ### Method `void` ### Endpoint N/A ### Parameters N/A ### Request Example ```cpp af::info(); ``` ### Response N/A (Prints to console) ## af::setDevice ### Description Sets the active computation device for ArrayFire. ### Method `void` ### Endpoint N/A ### Parameters - **device** (int) - Required - The ID of the device to set as the current device. ### Request Example ```cpp af::setDevice(0); // Set the first available device ``` ### Response N/A ## af_print ### Description A macro used for printing ArrayFire arrays to the console, often with formatting options. ### Method `#define` ### Endpoint N/A ### Parameters - **...** (variadic arguments) - The array(s) to print and optional formatting specifiers. ### Request Example ```cpp array a = randu(5, 5); af_print(a); ``` ### Response N/A (Prints to console) ``` -------------------------------- ### Get Array Dimensions Source: https://arrayfire.org/docs/benchmarks_2cg_8cpp-example Retrieves the dimensions of an ArrayFire array. The dimensions are returned as a `dim4` object, representing the size along each axis. ```c++ dim4 dims() const ``` -------------------------------- ### ArrayFire Array Data Structure Source: https://arrayfire.org/docs/image_processing_2pyramids_8cpp-example Defines the fundamental multi-dimensional data container used in ArrayFire. Supports operations like getting dimensions and deep copying. ```cpp class af::array { public: af::dim4 dims() const; af::array copy() const; }; ``` -------------------------------- ### Get ArrayFire System Information (C++) Source: https://arrayfire.org/docs/image_processing_2gradient_diffusion_8cpp-example Retrieves and prints system information for the ArrayFire library, including details about available devices and their capabilities. This is a utility function. ```cpp af::info ``` -------------------------------- ### Main function for ArrayFire K-Means Demo Source: https://arrayfire.org/docs/machine_learning_2kmeans_8cpp-example Sets up the ArrayFire device, retrieves command-line arguments for device selection, console output, and the number of clusters (k), and then calls the K-Means demo function. Includes error handling for ArrayFire exceptions. ```cpp int main(int argc, char **argv) { int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; int k = argc > 3 ? atoi(argv[3]) : 8; try { af::setDevice(device); af::info(); return kmeans_demo(k, console); } catch (af::exception &ae) { std::cerr << ae.what() << std::endl; } return 0; } ``` -------------------------------- ### Initialize Lattice Boltzmann CFD Simulation (C++) Source: https://arrayfire.org/docs/pde_2boltzmann_cfd_8cpp-example Sets up the initial conditions and parameters for a Lattice Boltzmann CFD simulation. This includes defining grid dimensions, window size for visualization, fluid properties (density, velocity, Reynolds number), and loading initial data for velocity and boundaries from image files. Dependencies include ArrayFire library and a Simulation struct. ```cpp void lattice_boltzmann_cfd_demo() { // Define the lattice for the simulation const size_t len = 128; const size_t grid_width = len; const size_t grid_height = len; // Specify the image scaling displayed float scale = 4.0f; // Forge window initialization int height = static_cast(grid_width * scale); int width = static_cast(grid_height * scale); af::Window window(height, width, "Driven Cavity Flow"); int frame_count = 0; int max_frames = 20000; int simulation_frames = 100; float total_time = 0; float total_time2 = 0; // CFD fluid parameters const float density = 2.7f; const float velocity = 0.35f; const float reynolds = 1e5f; const char* ux_image = ASSETS_DIR "/examples/images/default_ux.bmp"; const char* uy_image = ASSETS_DIR "/examples/images/default_uy.bmp"; const char* set_boundary_image = ASSETS_DIR "/examples/images/default_boundary.bmp"; // Tesla Valve Fluid Simulation - entering from constricted side { // ux_image = ASSETS_DIR "/examples/images/left_tesla_ux.bmp"; // uy_image = ASSETS_DIR "/examples/images/left_tesla_uy.bmp"; // set_boundary_image = ASSETS_DIR // "/examples/images/left_tesla_boundary.bmp"; } // Tesla Valve Fluid Simulation - entering from transfer side { // ux_image = ASSETS_DIR // "/examples/images/right_tesla_ux.bmp"; uy_image = // ASSETS_DIR "/examples/images/right_tesla_uy.bmp"; // set_boundary_image = ASSETS_DIR // "/examples/images/right_tesla_boundary.bmp"; } // Reads the initial values of fluid quantites and simulation parameters Simulation sim = } ``` -------------------------------- ### Get ArrayFire Exception Message Source: https://arrayfire.org/docs/image_processing_2edge_8cpp-example Retrieves the error message from an af::exception object. This is crucial for debugging and understanding issues within ArrayFire operations. ```cpp virtual const char * what() const ``` -------------------------------- ### Initialize ArrayFire and Run Shallow Water Simulation (C++) Source: https://arrayfire.org/docs/pde_2swe_8cpp-example Sets the ArrayFire device, prints system information, and initiates a shallow water equation simulation. Handles potential ArrayFire exceptions. ```cpp int device = argc > 1 ? atoi(argv[1]) : 0; bool console = argc > 2 ? argv[2][0] == '-' : false; try { af::setDevice(device); af::info(); printf("Simulation of shallow water equations\n"); swe(console); } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } return 0; } ``` -------------------------------- ### Get Feature X Locations using af::features::getX Source: https://arrayfire.org/docs/computer_vision_2fast_8cpp-example Retrieves the x-coordinates of detected features as an af::array. This function complements `getY` by providing the horizontal positions. ```cpp af::array getX() const; // Returns an af::array which represents the x locations of a feature. ``` -------------------------------- ### Get Number of Features using af::features::getNumFeatures Source: https://arrayfire.org/docs/computer_vision_2fast_8cpp-example Returns the total count of features represented by an af::features object. This is useful for understanding the scale of detected features. ```cpp size_t getNumFeatures() const; // Returns the number of features represented by this object. ``` -------------------------------- ### Main Function and Initialization Source: https://arrayfire.org/docs/image_processing_2morphing_8cpp-example Details the main function of the ArrayFire demo, including device selection, ArrayFire initialization, and exception handling. ```APIDOC ## Main Application Entry Point ### Description Initializes ArrayFire, sets the compute device, and runs the image morphing demonstration. Includes error handling for ArrayFire exceptions. ### Function - **`main(argc, argv)`**: The entry point of the application. - **`argc`**: Number of command-line arguments. - **`argv`**: Array of command-line argument strings. ### Initialization and Execution - **`af::info()`**: Prints detailed information about the available ArrayFire devices and backend. - **`af::setDevice(device)`**: Sets the active compute device. The device ID is determined by the first command-line argument or defaults to 0. - **`morphing_demo()`**: Calls the function that executes the image morphing demonstration. ### Exception Handling - **`try...catch (af::exception& e)`**: Catches any exceptions thrown by ArrayFire operations. - **`e.what()`**: Retrieves the error message from the caught exception. - **`fprintf(stderr, ...)`**: Prints the error message to standard error. - **`throw;`**: Re-throws the caught exception after logging. ``` -------------------------------- ### Setup Multiview Grid Layout (ArrayFire) Source: https://arrayfire.org/docs/graphics_2field_8cpp-example Configures a grid layout for multiview mode within an ArrayFire window. This allows for displaying multiple plots or views simultaneously in a structured arrangement. ```c++ void af::Window::grid(const int rows, const int cols) { // Implementation to set grid dimensions } ``` -------------------------------- ### Window Management and Image Display Source: https://arrayfire.org/docs/computer_vision_2matching_8cpp-example Demonstrates how to create and manage af::Window objects for displaying af::array data, including images with different colormaps and layouts. ```APIDOC ## af::Window ### Description Represents a window object used for rendering af::arrays, particularly useful for visualizing images and data. ### Method Constructor ### Endpoint N/A (Class constructor) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp af::Window wnd("Window Title"); ``` ### Response #### Success Response (200) N/A (Constructor does not return a value) #### Response Example N/A ## af::Window::close ### Description Checks if the window has been closed by the user. ### Method `bool close() const` ### Endpoint N/A (Member function) ### Parameters None ### Request Example ```cpp if (wnd.close()) { // Handle window close event } ``` ### Response #### Success Response (200) - **bool** - `true` if the window is closed, `false` otherwise. #### Response Example ```json { "is_closed": true } ``` ## af::Window::image ### Description Displays an af::array as an image within a specific grid cell of the window. ### Method `void image(const af::array &img, const char *title="")` ### Endpoint N/A (Member function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp wnd(0, 0).image(my_array, "My Image"); ``` ### Response #### Success Response (200) None (void function) #### Response Example N/A ## af::Window::setColorMap ### Description Sets the colormap for the window. ### Method `void setColorMap(const af::colormap cmap)` ### Endpoint N/A (Member function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp wnd.setColorMap(AF_COLORMAP_HEAT); ``` ### Response #### Success Response (200) None (void function) #### Response Example N/A ## af::Window::grid ### Description Configures the grid layout for the window. ### Method `void grid(int rows, int cols)` ### Endpoint N/A (Member function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp wnd.grid(2, 2); ``` ### Response #### Success Response (200) None (void function) #### Response Example N/A ## af::Window::show ### Description Displays the content of the window. ### Method `void show()` ### Endpoint N/A (Member function) ### Parameters None ### Request Example ```cpp wnd.show(); ``` ### Response #### Success Response (200) None (void function) #### Response Example N/A ``` -------------------------------- ### DBN Demonstration and MNIST Data Loading (C++) Source: https://arrayfire.org/docs/machine_learning_2deep_belief_net_8cpp-example Sets up and runs a demonstration of the DBN class using the MNIST dataset. It includes data loading, reshaping, network initialization, training, and performance benchmarking. ```cpp int dbn_demo(bool console, int perc) { printf("** ArrayFire DBN Demo **\n\n"); array train_images, test_images; array train_target, test_target; int num_classes, num_train, num_test; // Load mnist data float frac = (float)(perc) / 100.0; setup_mnist(&num_classes, &num_train, &num_test, train_images, test_images, train_target, test_target, frac); int feature_size = train_images.elements() / num_train; // Reshape images into feature vectors array train_feats = moddims(train_images, feature_size, num_train).T(); array test_feats = moddims(test_images, feature_size, num_test).T(); train_target = train_target.T(); test_target = test_target.T(); // Network parameters vector layers; layers.push_back(100); layers.push_back(50); // Create network dbn network(train_feats.dims(1), num_classes, layers); // Train network timer::start(); network.train(train_feats, train_target, 0.2, // rbm learning rate 4.0, // nn learning rate 15, // rbm epochs 250, // nn epochs 100, // batch_size 0.5, // max error true); // verbose af::sync(); double train_time = timer::stop(); // Run the trained network and test accuracy. array train_output = network.predict(train_feats); array test_output = network.predict(test_feats); // Benchmark prediction af::sync(); timer::start(); for (int i = 0; i < 100; i++) { network.predict(test_feats); } af::sync(); double test_time = timer::stop() / 100; printf("\nTraining set:\n"); printf("Accuracy on training data: %2.2f\n", accuracy(train_output, train_target)); printf("\nTest set:\n"); printf("Accuracy on testing data: %2.2f\n", accuracy(test_output, test_target)); printf("\nTraining time: %4.4lf s\n", train_time); printf("Prediction time: %4.4lf s\n\n", test_time); if (!console) { // Get 20 random test images. test_output = test_output.T(); ``` -------------------------------- ### ArrayFire Timer: Multiple Timers Example (C++) Source: https://arrayfire.org/docs/timing Illustrates how to use multiple timers concurrently with ArrayFire's timer functions. This example shows starting two separate timers, running code segments, and stopping each timer individually to measure their respective elapsed times. It also highlights the importance of eval and sync. ```cpp // start timers // - be sure to use the eval and sync functions so that previous code // does not get timed as part of the execution segment being measured timer start1 = timer::start(); timer start2 = timer::start(); // run a code segment // - be sure to use the eval and sync functions to ensure the code // segment operations have been completed // stop timer1 printf("elapsed seconds: %g\n", timer::stop(start1)); // run another code segment // - be sure to use the eval and sync functions to ensure the code // segment operations have been completed // stop timer2 printf("elapsed seconds: %g\n", timer::stop(start2)); ``` -------------------------------- ### Get ArrayFire Information Source: https://arrayfire.org/docs/image_processing_2deconvolution_8cpp-example The `af::info()` function retrieves and prints information about the available devices and the ArrayFire build. It does not take any arguments and has no return value. This is useful for understanding the environment ArrayFire is running in. ```cpp void info(); ``` -------------------------------- ### Get Array Offset in C++ Source: https://arrayfire.org/docs/internal_8h Retrieves the offset of an ArrayFire array from its data buffer. The offset indicates the starting position of the array's data within a larger memory block. ```cpp #include #include AFAPI dim_t getOffset (const array &in); ``` -------------------------------- ### Test ArrayFire Backends (C++) Source: https://arrayfire.org/docs/unified_2basic_8cpp-example This example demonstrates how to test and switch between different ArrayFire compute backends (CPU, CUDA, OpenCL). It initializes an array with random data, creates another array with a constant value, and prints them using the af_print macro. Error handling for backend switching is included. ```cpp #include #include #include #include using namespace af; std::vector input(100); // Generate a random number between 0 and 1 // return a uniform number in [0,1]. double unifRand() { return rand() / double(RAND_MAX); } void testBackend() { af::info(); af::dim4 dims(10, 10, 1, 1); af::array A(dims, &input.front()); af_print(A); af::array B = af::constant(0.5, dims, f32); af_print(B); } int main(int, char**) { std::generate(input.begin(), input.end(), unifRand); try { printf("Trying CPU Backend\n"); af::setBackend(AF_BACKEND_CPU); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying CPU backend\n"); fprintf(stderr, "%s\n", e.what()); } try { printf("Trying CUDA Backend\n"); af::setBackend(AF_BACKEND_CUDA); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying CUDA backend\n"); fprintf(stderr, "%s\n", e.what()); } try { printf("Trying OpenCL Backend\n"); af::setBackend(AF_BACKEND_OPENCL); testBackend(); } catch (af::exception& e) { printf("Caught exception when trying OpenCL backend\n"); fprintf(stderr, "%s\n", e.what()); } return 0; } ``` -------------------------------- ### Get Scalar Element with scalar() Source: https://arrayfire.org/docs/classaf_1_1array The scalar() method retrieves the first element of the array as a scalar value. It is recommended for debugging purposes, as frequent calls can impact performance. Examples include image processing and machine learning. ```cpp T scalar() const; ``` -------------------------------- ### Get Feature Y Locations using af::features::getY Source: https://arrayfire.org/docs/computer_vision_2fast_8cpp-example Retrieves the y-coordinates of detected features as an af::array. This function is part of the af::features class, which represents features detected by feature detection algorithms. ```cpp af::array getY() const; // Returns an af::array which represents the y locations of a feature. ``` -------------------------------- ### Initialize and Run Lattice Boltzmann CFD Simulation (C++) Source: https://arrayfire.org/docs/pde_2boltzmann_cfd_8cpp-example This snippet initializes and runs the main loop of a Lattice Boltzmann CFD simulation. It sets up the simulation environment, including device selection and information display. The simulation proceeds frame by frame, updating particle distributions, velocity, and density fields. It also includes timing mechanisms to measure the performance of each simulation step and periodically displays the computed frame. ```C++ int main(int argc, char** argv) { int device = argc > 1 ? std::atoi(argv[1]) : 0; try { af::setDevice(device); af::info(); std::cout << "** ArrayFire CFD Simulation Demo\n\n"; lattice_boltzmann_cfd_demo(); } catch (const af::exception& e) { std::cerr << e.what() << std::endl; return -1; } return 0; } void lattice_boltzmann_cfd_demo() { // Placeholder for simulation initialization parameters // create_simulation(grid_width, grid_height, density, velocity, reynolds, // ux_image, uy_image, set_boundary_image); // Initializes the simulation quantites // initialize(sim); // Placeholder for simulation variables // auto sim = ...; // int frame_count = 0; // int max_frames = ...; // int simulation_frames = ...; // double total_time = 0; // double total_time2 = 0; // af::Window window; // int width = ...; // int height = ...; while (!window.close() && frame_count != max_frames) { af::sync(); auto begin = std::chrono::high_resolution_clock::now(); // Computes the new particle distribution functions for the new // simulation frame // collide_stream(sim); // Updates the velocity, density, and stress fields // update(sim); af::sync(); auto end = std::chrono::high_resolution_clock::now(); // Calculate computation time of 1 simulation frame auto duration = std::chrono::duration_cast(end - begin).count(); // Used for computing the distribution of frame computation time total_time += duration; total_time2 += duration * duration; // Every number of `simulation_frames` display the last computed frame // to the screen if (frame_count % simulation_frames == 0) { // auto image = generate_image(width, height, sim); // Display colored image // window.image(image); float avg_time = total_time / (float)simulation_frames; float stdv_time = std::sqrt(total_time2 * simulation_frames - total_time * total_time) / (float)simulation_frames; std::cout << "Average Simulation Step Time: (" << avg_time << " +/- " << stdv_time << ") us; Total simulation time: " << total_time << " us; Simulation Frames: " << simulation_frames << std::endl; total_time = 0; total_time2 = 0; } frame_count++; } } ``` -------------------------------- ### Initialize Galaxy Particle Conditions in C++ Source: https://arrayfire.org/docs/graphics_2gravity_sim_8cpp-example Sets up initial conditions for particles to simulate a galaxy, using pre-defined constants for mass, position, and velocity. This function allows for more structured and realistic initial states for simulations. ```cpp void initial_conditions_galaxy(af::array &mass, vector &pos, vector &vels, vector &forces) { af::array initial_cond_consts(af::dim4(7, total_particles), hbd); initial_cond_consts = initial_cond_consts.T(); for (int i = 0; i < (int)pos.size(); ++i) { pos[i] = af::randn(total_particles) * width + width; vels[i] = 0 * (af::randu(total_particles) - 0.5); forces[i] = af::constant(0, total_particles); } mass = initial_cond_consts(span, 0); pos[0] = (initial_cond_consts(span, 1) / 32 + 0.6) * width; pos[1] = (initial_cond_consts(span, 2) / 32 + 0.3) * height; pos[2] = (initial_cond_consts(span, 3) / 32 + 0.5) * depth; vels[0] = (initial_cond_consts(span, 4) / 32) * width; vels[1] = (initial_cond_consts(span, 5) / 32) * height; vels[2] = (initial_cond_consts(span, 6) / 32) * depth; pos[0](seq(0, pos[0].dims(0) - 1, 2)) -= 0.4 * width; pos[1](seq(0, pos[0].dims(0) - 1, 2)) += 0.4 * height; vels[0](seq(0, pos[0].dims(0) - 1, 2)) += 4; min_mass = min(mass); mass_range = max(mass) - min(mass); } ```