### Run AOCL-DA Examples Info Module Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Execute the AOCL-DA examples info module from your command prompt to get information about available examples. ```bash python -m aoclda.examples.info ``` -------------------------------- ### Radius Neighbors Example Setup Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/nearest_neighbors/nearest_neighbors.md This section outlines the setup for a radius neighbors example. It includes standard redistribution and disclaimer notices common in open-source software. ```Python # Copyright (C) 2025-2026 Advanced Micro Devices, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, # OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. ``` -------------------------------- ### Install Python Package Files Source: https://github.com/amd/aocl-data-analytics/blob/main/python_interface/CMakeLists.txt Installs the main Python package directory, including setup scripts and documentation. It conditionally excludes Fortran-dependent examples if Fortran support is disabled. ```cmake if(BUILD_FORTRAN) install(DIRECTORY python_package/aoclda DESTINATION python_package) else() # Exclude those Python examples that rely on Fortran code install( DIRECTORY python_package/aoclda DESTINATION python_package PATTERN "nlls_*.py" EXCLUDE) endif() install(FILES python_package/setup.py python_package/pyproject.toml python_package/README.rst ${CMAKE_SOURCE_DIR}/License DESTINATION python_package) ``` -------------------------------- ### Get AOCL-DA Examples Path Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Use this snippet to find the installation path of AOCL-DA example scripts within your Python environment. ```python >>> from aoclda.examples import info >>> info.examples_path() >>> info.examples_list() ``` -------------------------------- ### Configure CMake to Build Examples and Google Test Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Example CMake configuration to enable building examples and Google Test for AOCL-DA. These are enabled by default. ```bash cmake -DBUILD_EXAMPLES=On -DBUILD_GTEST=On ``` -------------------------------- ### Configure CMake for Installation Prefix Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Example CMake configuration to specify the installation path for the AOCL-DA library. ```bash cmake -DCMAKE_INSTALL_PREFIX= ``` -------------------------------- ### Loop Through Examples for Linking and Definitions Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/examples/CMakeLists.txt Iterates through a list of example targets to link common libraries and define build flags. This avoids repetitive configuration for each example. ```cmake foreach(target ${EXAMPLE_EXES}) target_link_libraries(${target} PRIVATE aocl-da) if(BUILD_SMP) target_link_libraries(${target} PRIVATE OpenMP::OpenMP_CXX) endif() # Define -DAOCL_ILP64 when ILP64 libraries are built. For LP64, this is an # empty string. This is what AOCL-DA users will need to do explicitly to get # the correct symbols, otherwise they will get linking errors or aborts. target_compile_definitions(${target} PRIVATE ${AOCLDA_ILP64}) target_link_directories(${target} PRIVATE ${IFORT_LIBS}) target_link_directories(${target} PRIVATE ${FLANG_LIBS}) target_link_libraries(${target} PRIVATE ${FORTRAN_RUNTIME}) endforeach() ``` -------------------------------- ### Install Documentation Requirements Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/doc/Readme.md Installs the necessary Python packages for building the documentation. Ensure you are in the project root directory. ```bash python -m pip install libRALFit/doc/requirements.txt ``` -------------------------------- ### Run a Specific Example Script Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Execute a specific AOCL-DA example script, such as pca_ex.py, from your command prompt. ```bash python path/to/examples/pca_ex.py ``` -------------------------------- ### Inspect and Run Example from Python Interpreter Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Inspect the source code of an example like pca_ex and then run its example function from a Python interpreter. ```python >>> from aoclda.examples import pca_ex >>> import inspect >>> print(''.join(inspect.getsourcelines(pca_ex)[0])) >>> pca_ex.pca_example() ``` -------------------------------- ### Python PCA Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/factorization/factorization.md Demonstrates Principal Component Analysis using the aoclda library. This snippet shows how to initialize PCA, fit it to data, transform new data, and verify the results against expected values. Ensure the aoclda library is installed. ```python #!/usr/bin/env python # -*- coding: utf-8 -*- # # Principal component analysis example Python script import sys import numpy as np from aoclda.factorization import PCA def pca_example(): """ Principal component analysis example """ # Define data arrays a = np.array([[2., 2., 3., 2., 4.], [2., 5., 4., 8., 3.], [3., 2., 4., 4., 1.], [4., 8., 3., 6., 4.], [4., 3., 2., 9., 2.], [3., 2., 1., 5., 2.]]) x = np.array([[7., 4., 2., 9., 3.], [3., 2., 5., 6., 4.], [3., 3., 2., 4., 1.]]) print("\nPrincipal component analysis for a 6x5 data matrix\n") try: pca = PCA(n_components=3, store_U=True) pca.fit(a) x_transform = pca.transform(x) except RuntimeError: sys.exit(1) # Print results print("\nPrincipal components of a:\n") print(pca.principal_components) print("\nx_transform:\n") print(x_transform) # Check against expected results expected_components = np.array([[-0.14907884486130418, -0.6612054163818867, -0.031706610956396264, -0.7289116905829763, -0.09091387966203135], [-0.07220367025708045, 0.623738867070505, 0.20952521660694667, -0.6138062400926413, 0.4302063910917139], [-0.38718653977350936, -0.06907631947413592, 0.8854125206703791, 0.1296593407398653, -0.21106437194645863]]) expected_x_transform = np.array([[-3.250305270939447, -2.1581247424555086, -1.9477723543266676], [0.6691223004872521, -0.21658703437771865, 1.7953216115607247], [1.833601737126601, -0.2844305102179128, -0.5561178355649032]]) norm_components = np.linalg.norm( pca.principal_components - expected_components) norm_x_transform = np.linalg.norm(x_transform - expected_x_transform) tol = 1.0e-12 if norm_components > tol or norm_x_transform > tol: print("\nSolution is not within expected tolerance\n") sys.exit(1) print("\nPCA successfully computed\n") if __name__ == "__main__": pca_example() ``` -------------------------------- ### Python Metrics Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/metrics/metrics.md This Python code snippet is part of the installation and demonstrates the usage of distance metrics. It includes copyright and license information. ```Python # Copyright (C) 2024-2025 Advanced Micro Devices, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # ``` -------------------------------- ### Python PCA Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/factorization/factorization.md This Python code snippet is part of the installation and demonstrates PCA usage. It includes copyright and redistribution information. ```Python # Copyright (C) 2024-2025 Advanced Micro Devices, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. ``` -------------------------------- ### Configure, Build, Install, and Validate in One Step Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Executes the entire workflow of configuring, building, installing, and validating the library using a single CMake preset command. This streamlines the development process. ```bash cmake --workflow --preset linux-gcc-mt-lp64-static-release-dynamic ``` -------------------------------- ### Build C Example with Box Constraint Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/example/C/CMakeLists.txt Adds an executable for a C example demonstrating box constraints and links it with the ral_nlls library. ```cmake add_executable (nlls_c_example_box nlls_example_box.c) target_link_libraries(nlls_c_example_box ral_nlls -lm) ``` -------------------------------- ### Conditionally Build Examples Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/CMakeLists.txt Includes the 'examples' subdirectory in the build if the BUILD_EXAMPLES variable is set to true. ```cmake if(BUILD_EXAMPLES) add_subdirectory(examples) endif() ``` -------------------------------- ### Install AOCL-DA from a wheel file Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Install AOCL-DA by providing the path to a downloaded wheel file. Replace '*' with the specific version and system identifier from the filename. ```bash pip install aoclda-*.whl ``` -------------------------------- ### Build and Install AOCL-DA from Source Directory using Preset Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Builds and installs the library from the source directory using a specified CMake preset. The installation will be in a directory named 'install-linux-gcc-dynamic-release'. ```bash cmake --build --preset linux-gcc-mt-lp64-static-release-dynamic-install ``` -------------------------------- ### Install Header Files Source: https://github.com/amd/aocl-data-analytics/blob/main/source/CMakeLists.txt Installs header files from the 'include/' directory to the destination 'include/${INT_LIB}'. It specifically matches files with .h and .hpp extensions. ```cmake install( DIRECTORY include/ DESTINATION include/${INT_LIB} FILES_MATCHING PATTERN "*.h" PATTERN "*.hpp") ``` -------------------------------- ### k-NN Regression Example in C++ Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/nearest_neighbors/nearest_neighbors.md This C++ code demonstrates a k-nearest neighbors regression for a small data matrix. It includes setup, training, and computation of neighbors and distances. ```C++ #include "aoclda.h" #include #include /* * Basic k-nearest neighbors (k-NN) example * * This example computes k-nearest neighbors regression for a small data matrix. */ int main() { std::cout << "-----------------------------------------------------------" << std::endl; std::cout << "k-Nearest Neighbors model for regression (double precision)" << std::endl; std::cout << "-----------------------------------------------------------" << std::endl; std::cout << std::fixed; std::cout.precision(5); da_status status; bool pass = true; // Input data da_int n_features = 3; da_int n_samples = 6; da_int n_queries = 3; da_int n_neigh = 3; std::vector X_train{-1, -2, -3, 1, 2, 3, -1, -1, -2, 3, 5, -1, 2, 3, -1, 1, 1, 2}; std::vector y_train{1, 2, 0, 1, 2, 2}; // Set up and train the kNN da_handle knn_handle = nullptr; pass = da_handle_init_d(&knn_handle, da_handle_nn) == da_status_success; // Set options pass &= da_options_set_int(knn_handle, "number of neighbors", n_neigh) == da_status_success; pass &= da_options_set_string(knn_handle, "metric", "euclidean") == da_status_success; pass &= da_options_set_string(knn_handle, "weights", "uniform") == da_status_success; pass &= da_options_set_string(knn_handle, "algorithm", "auto") == da_status_success; if (!pass) { std::cout << "Failure while setting up the optional parameters.\n"; da_handle_print_error_message(knn_handle); return 1; } status = da_nn_set_data_d(knn_handle, n_samples, n_features, X_train.data(), n_samples); if (status != da_status_success) { std::cout << "Failure while setting up the knn data.\n"; da_handle_print_error_message(knn_handle); return 1; } std::vector X_test{-2, -1, 2, 2, -2, 1, 3, -1, -3}; // Compute the k-nearest neighbors and return the distances std::vector k_dist(n_neigh * n_queries); std::vector k_ind(n_neigh * n_queries); status = da_nn_kneighbors_d(knn_handle, n_queries, n_features, X_test.data(), n_queries, k_ind.data(), k_dist.data(), n_neigh, 1); if (status != da_status_success) { std::cout << "Failure while computing the neighbors.\n"; da_handle_print_error_message(knn_handle); return 1; } std::cout << "The indices of neighbors\n"; for (da_int i = 0; i < n_queries; i++) { for (da_int j = 0; j < n_neigh; j++) { std::cout << k_ind[i + j * n_queries] << " "; } std::cout << std::endl; } std::cout << std::endl; std::cout << "\n\nThe corresponding distances\n"; for (da_int i = 0; i < n_queries; i++) { for (da_int j = 0; j < n_neigh; j++) { std::cout << k_dist[i + j * n_queries] << " "; } std::cout << std::endl; } std::cout << std::endl; status = da_nn_set_targets_d(knn_handle, n_samples, y_train.data()); if (status != da_status_success) { std::cout << "Failure while setting up the targets.\n"; da_handle_print_error_message(knn_handle); return 1; } ``` -------------------------------- ### Build C Tracks Example Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/example/C/CMakeLists.txt Adds an executable for a C example related to tracks and links it with the ral_nlls library. ```cmake add_executable (tracks tracks.c) target_link_libraries(tracks ral_nlls -lm) ``` -------------------------------- ### Install Documentation Dependencies Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/doc_utilities/index.md Installs Sphinx and other required extensions for building AOCL-DA documentation within a virtual Python environment. ```bash cd ~/DA-projects/aocl-da python3 -m venv ~/DA-projects/doc-3 source ~/DA-projects/doc-3/bin/activate pip install -r doc/requirements.txt ``` -------------------------------- ### Compile AOCL-DA Examples on Windows with cl Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/examples/README.txt Compile AOCL-DA C++ examples on Windows using the 'cl' compiler. Ensure INT_LIB is set correctly and the Fortran runtime libraries are sourced. Update the Windows PATH to include library folders. ```bash cl .cpp /I \\include\ /EHsc /MD \\aocl-da\lib\\aocl-da.lib \\amd-sparse\lib\\aoclsparse.lib \\amd-libflame\lib\\AOCL-LibFlame-Win-MT-dll.lib \\amd-blis\lib\\AOCL-LibBlis-Win-MT-dll.lib \\amd-utils\lib\libaoclutils.lib /openmp:llvm ``` -------------------------------- ### Define List of Example Executables Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/examples/CMakeLists.txt Creates a CMake list variable containing the names of all example executables to be built. This simplifies subsequent loop operations. ```cmake set(EXAMPLE_EXES linear_model linmod_diabetes basic_statistics train_test_split pca pca_cancer kmeans dbscan datastore decision_tree decision_forest metrics model_persistence_decision_tree model_persistence_pca knn_classification knn_regression radius_neighbors radius_neighbors_classification radius_neighbors_regression svc nusvr kernel_functions ann cubic_spline) ``` -------------------------------- ### Tests and Examples Inclusion Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/CMakeLists.txt Includes subdirectories for tests and various language examples (C, Fortran, Python). ```cmake add_subdirectory (test) add_subdirectory (example/C) add_subdirectory (example/Fortran) add_subdirectory (example/Python) ``` -------------------------------- ### Build C Examples with Single Precision Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/example/C/CMakeLists.txt Adds an executable for a single-precision C example and links it with the ral_nlls library. This is used when the SINGLE_PRECISION flag is enabled. ```cmake if (SINGLE_PRECISION) add_executable (nlls_c_example2 nlls_example2.c) target_link_libraries(nlls_c_example2 ral_nlls -lm) else() add_executable (nlls_c_example nlls_example.c) target_link_libraries(nlls_c_example ral_nlls -lm) add_executable (nlls_c_example_fd nlls_example_fd.c) target_link_libraries(nlls_c_example_fd ral_nlls -lm) add_executable (nlls_c_example_chk nlls_example_chk.c) target_link_libraries(nlls_c_example_chk ral_nlls -lm) endif() ``` -------------------------------- ### Set up Python Virtual Environment Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/README.md Create and activate a virtual environment for building the Python interface. ```bash python3 -mvenv p3 . p3/bin/activate ``` -------------------------------- ### jacobian_setup Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/doc/Fortran/howtouse.rst Sets up a handle and allocates workspace for finite-difference derivative approximation. This must be called before any approximations are made. ```APIDOC ## jacobian_setup ### Description Sets up a handle and allocates required workspace for performing finite-difference derivative approximations. This subroutine needs to be called prior to performing any approximations. ### Method Fortran Subroutine ### Interface `jacobian_setup(status, handle, n, m, x, eval_r, params, lower, upper, f_storage)` ### Parameters #### Input/Output Parameters - **status** (Integer, out): Exit status, zero on success. - **handle** (Type(jacobian_handle), Inout): Handle object. - **n** (Integer, in): Dimension of the problem. - **m** (Integer, in): Dimension of the residual vector. - **x** (Real(n), in): Current iterate point. - **eval_r** (Procedure): The user-provided procedure to evaluate the residual vector. - **params** (params_base_type, in): User-defined parameters. #### Optional Input Parameters - **lower** (Real(n), optional, in): Lower bounds for the variables. - **upper** (Real(n), optional, in): Upper bounds for the variables. - **f_storage** (Logical, optional, in): Boolean flag to indicate if the matrix is stored in Fortran format. ``` -------------------------------- ### k-NN Classification Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/nearest_neighbors/nearest_neighbors.md This Python code snippet demonstrates a k-NN classification setup. It includes standard license and disclaimer information. ```Python # Copyright (C) 2024-2026 Advanced Micro Devices, Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ``` -------------------------------- ### Configure CMake for AOCL Root Path Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Example CMake configuration to specify the installation path for AOCL libraries, overriding the environment variable. ```bash cmake -DCMAKE_AOCL_ROOT= ``` -------------------------------- ### Include Boost Download in CMake Build Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Example of how to include a Boost download within your CMake build of AOCL-DA. This is useful if Boost is not installed on your system path. ```bash cmake -DBoost_ROOT=${BASE_DIR}/DA-projects/aocl-da/external/boost-1.86.0 -DBoost_NO_BOOST_CMAKE=ON ``` -------------------------------- ### Configure and Build RALFit (Standard) Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/README.md Navigate to the library directory, configure the build using CMake, and then build the library with Make. The --parallel option speeds up the build process. ```bash cd RALFit/libRALFit cmake -S . -B build cmake --build build --parallel 4 ``` -------------------------------- ### Fortran Jacobian Setup Source: https://github.com/amd/aocl-data-analytics/blob/main/external/RALFit/libRALFit/doc/Fortran/howtouse.rst Sets up a handle for finite-difference derivative calculations. Must be called before approximating derivatives. ```Fortran subroutine jacobian_setup(status, handle, n, m, x, eval_r, params, lower, upper, f_storage) ! Input/Output arguments integer, intent(out) :: status type(jacobian_handle), intent(inout) :: handle integer, intent(in) :: n, m real, intent(in) :: x(n) procedure(eval_r_desc), intent(in) :: eval_r params_base_type, intent(in) :: params real, optional, intent(in) :: lower(n), upper(n) logical, optional, intent(in) :: f_storage ``` -------------------------------- ### DBSCAN Clustering Example in Python Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/clustering/clustering.md This script performs DBSCAN clustering on a predefined NumPy array. It prints the resulting labels and core sample indices, and verifies them against expected outputs. Ensure the 'aoclda' library is installed. ```python import sys import numpy as np from aoclda.clustering import DBSCAN def dbscan_example(): """ DBSCAN clustering example """ # Define data arrays a = np.array([[2., 1.], [-1., -2.], [3., 2.], [2., 3.], [-3., -2.], [-2., -1.], [-2., -3.], [1., 2.], [2., 2.], [-2., -2.]]) print("\nDBSCAN clustering for a small data matrix\n") try: db = DBSCAN(eps=1.1, min_samples=4) db.fit(a) except RuntimeError: sys.exit(1) # Print results print("\nLabels:\n") print(db.labels) print("\nCore sample indices:\n") print(db.core_sample_indices) # Check against expected results expected_labels = np.array([0, 1, 0, 0, 1, 1, 1, 0, 0, 1]) expected_core_sample_indices = np.array([8, 9]) incorrect_results = np.any(expected_labels - db.labels) or np.any( expected_core_sample_indices - db.core_sample_indices) tol = 1.0e-12 if incorrect_results: print("\nThe expected solution was not obtained\n") sys.exit(1) print("\nDBSCAN clusters successfully computed\n") if __name__ == "__main__": dbscan_example() ``` -------------------------------- ### Python Basic Statistics Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/basic_statistics/basic_stats.md This script calculates and prints row means, column harmonic means, overall variance, row medians, covariance matrix, and standardized matrix for a given dataset. Ensure the aoclda library and numpy are installed. ```python # Basic statistics example python script from aoclda.basic_stats import harmonic_mean, mean, variance, quantile, covariance_matrix, standardize import numpy as np import sys def basic_stats_example(): """ Basic statistics examples """ a = np.array([[1.1, 2.213, 3.3], [4, 5.013, 6]], dtype=np.float32, order='F') print("Dataset:\n") print(a) means = mean(a, axis="row") print(f"\nRow means: {means}") harmonic_means = harmonic_mean(a, axis="col") print(f"\nColumn harmonic means: {harmonic_means}") var = variance(a, axis="all") print(f"\nOverall data variance: {var}") medians = quantile(a, 0.5, axis="row") print(f"\nRow medians: {medians}") covar = covariance_matrix(a) print(f"\nCovariance matrix:\n{covar}") standardized = standardize(a) print(f"\nStandardized matrix:\n{standardized}") print("\nBasic statistics calculations successful") print("---------------------------") if __name__ == "__main__": try: basic_stats_example() except RuntimeError: sys.exit(1) ``` -------------------------------- ### Radius Neighbors Regression Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/nearest_neighbors/nearest_neighbors.md This Python script demonstrates how to use the `nearest_neighbors` function for radius neighbors regression. It includes defining training and testing data, fitting the model, predicting targets, and validating the results against expected values. Ensure numpy and aoclda.neighbors are installed. ```python import sys import numpy as np from aoclda.neighbors import nearest_neighbors def radius_neighbors_regressor_example(): """ Radius Neighbors regression """ # Define data arrays x_train = np.array([[-1, -1, 2], [-2, -1, 3], [-3, -2, -1], [1, 3, 1], [2, 5, 1], [3, -1, 2]], dtype=np.float64) y_train = np.array([1.5, 2.3, 0.6, 1, 2.8, 5.2], dtype=np.float64) x_test = np.array([[-2, 2, 3], [-1, -2, -1], [2, 1, -3]], dtype=np.float64) print("\nradius neighbors for a small data matrix\n") rnn = nearest_neighbors(radius=3.0, outlier_handling=-1.0) rnn.fit(x_train, y_train) print(x_train) r_dist, r_ind = rnn.radius_neighbors( x_test, radius=2.0, return_distance=True, sort_results=False) y_test = rnn.regressor_predict(x_test, search_mode='radius_neighbors') # Print results print("\nIndices of the nearest neighbors:\n") print(r_ind) print("\nCorresponding distances of the nearest neighbors:\n") print(r_dist) print("\nPredicted targets for the test data matrix:\n") print(y_test) # Check against expected results expected_r_dist = [np.array([]), np.array([2.]), np.array([])] expected_r_ind = [np.array([]), np.array([2]), np.array([])] expected_targets = np.array([2.3, 0.6, -1.]) incorrect_targets = np.linalg.norm(y_test - expected_targets) tol = 1.0e-8 # Test radius neighbors radius_errors = False # Check radius neighbors results with simplified validation try: # Check distances - will raise if shapes don't match dist_diff = np.linalg.norm( np.concatenate(r_dist) - np.concatenate(expected_r_dist)) if dist_diff > tol: print("\nRadius neighbors: distances not within tolerance\n") print("Norm difference: ", dist_diff) radius_errors = True # Check indices - will raise if shapes don't match for i, expected_indices in enumerate(expected_r_ind): if not np.array_equal(r_ind[i], expected_indices): print("\nRadius neighbors query ", i, ": incorrect indices") print("Got: ", r_ind[i]) print("Expected: ", expected_indices) radius_errors = True except (ValueError, IndexError) as e: print("\nRadius neighbors: incorrect structure or size mismatch") print("Got ", len(r_dist), " distance arrays, expected ", len(expected_r_dist)) print("Got ", len(r_ind), " index arrays, expected ", len(expected_r_ind)) print("Error: ", e) radius_errors = True if radius_errors or incorrect_targets > tol: print("\nRadius neighbors solution is not within expected tolerance\n") print("incorrect_targets = ", incorrect_targets) sys.exit(1) print("\nradius neighbors regression successfully computed\n") if __name__ == "__main__": try: radius_neighbors_regressor_example() except RuntimeError: sys.exit(1) ``` -------------------------------- ### Adding an Options Table Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/doc_utilities/index.md Illustrates the syntax for creating an options table, which is updated by the build system. ```rst .. update options using table _opts_linearmodels .. csv-table:: :strong:`Example table of options for linear models`. :escape: ~ :header: "Option name", "Type", "Default", "Description", "Constraints" "print options", "string", ":math:`s=` `no`", "Print options.", ":math:`s=` `no`, or `yes`." ``` -------------------------------- ### Install AOCL-DA using pip Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Python/python_intro.md Use this command to install the AOCL-DA Python package via pip. Ensure you have pip installed and updated. ```bash pip install aoclda ``` -------------------------------- ### Configure Preset with Additional CMake Options Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Demonstrates how to append standard CMake options to a preset configuration. This example enables code coverage in addition to the settings defined by the 'linux-gcc-mt-lp64-static-release-dynamic' preset. ```bash cmake --preset linux-gcc-mt-lp64-static-release-dynamic -DCOVERAGE=ON ``` -------------------------------- ### Add Examples to CTest Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/examples/CMakeLists.txt Adds all defined example executables as tests to CTest. This allows the examples to be run as part of the automated testing suite. ```cmake foreach(EX_NAME ${EXAMPLE_EXES}) string(CONCAT TNAME ${EX_NAME} "_ex") add_test(${TNAME} ${EX_NAME}) endforeach() ``` -------------------------------- ### k-means Clustering Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/clustering/clustering.md This C++ code demonstrates the usage of a k-means clustering algorithm. It initializes data, performs clustering, and verifies the results against expected values. Ensure the necessary data structures and libraries are included. ```C++ #include #include #include #include #include "../include/daal.h" using namespace daal; using namespace daal::algorithms; int main(int argc, char const *argv[]) { // Initialize DAAL data structures da_handle handle; da_handle_create(&handle); // Input data dimensions da_int n_samples = 8; da_int n_features = 2; da_int n_clusters = 2; da_int cluster_centres_dim = n_features * n_clusters; da_int labels_dim = n_samples; da_int m_samples = 2; // Input data double X_data[16] = {1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0, 3.0, 3.0, 3.0, 3.0, 4.0, 4.0, 4.0, 4.0, 5.0}; double cluster_centres_init[4] = {1.0, 1.0, 5.0, 5.0}; // Allocate memory for results double *cluster_centres = new double[cluster_centres_dim]; da_int *labels = new da_int[labels_dim]; double *X_transform = new double[m_samples * n_clusters]; da_int *X_labels = new da_int[m_samples]; da_int exit_code = 0; // Perform k-means clustering da_status status = daal_kmeans_clustering(handle, n_samples, n_features, n_clusters, X_data, cluster_centres_init, cluster_centres, labels, X_transform, X_labels); if (status == DAAL_SUCCESS) { std::cout << "Cluster Centres:" << std::endl; for (da_int i = 0; i < cluster_centres_dim; i++) { std::cout << cluster_centres[i] << " "; if ((i + 1) % n_features == 0) { std::cout << std::endl; } } std::cout << std::endl; std::cout << "Labels:" << std::endl; for (da_int i = 0; i < n_samples; i++) { std::cout << labels[i] << " "; } std::cout << std::endl; // Check against expected results double cluster_centres_exp[4] = {2.0, -2.0, 2.0, -2.0}; da_int labels_exp[8] = {0, 1, 0, 0, 1, 1, 1, 0}; double X_transform_exp[4] = {2.23606797749979, 3.605551275463989, 3.605551275463989, 2.23606797749979}; da_int X_labels_exp[2] = {0, 1}; double tol = 1.0e-14; double err = 0.0; for (da_int i = 0; i < cluster_centres_dim; i++) err = std::max(err, std::abs(cluster_centres[i] - cluster_centres_exp[i])); bool incorrect_labels = false; for (da_int i = 0; i < labels_dim; i++) { if (labels[i] != labels_exp[i]) { incorrect_labels = true; break; } } for (da_int i = 0; i < m_samples * n_clusters; i++) { err = std::max(err, std::abs(X_transform[i] - X_transform_exp[i])); std::cout << X_transform[i] << " " << X_transform_exp[i] << std::endl; } for (da_int i = 0; i < m_samples; i++) { if (X_labels[i] != X_labels_exp[i]) { incorrect_labels = true; break; } } if (err > tol || incorrect_labels) { std::cout << "Solution is not within the expected tolerance: " << err << std::endl; exit_code = 1; } } else { exit_code = 1; } // Clean up da_handle_destroy(&handle); delete[] cluster_centres; delete[] labels; delete[] X_transform; delete[] X_labels; std::cout << "-----------------------------------------------------------------------" << std::endl; return exit_code; } ``` -------------------------------- ### List Available CMake Presets Source: https://github.com/amd/aocl-data-analytics/blob/main/README.md Use this command to view all predefined CMake presets for the project. This helps in understanding the available configuration and build options. ```bash cmake --list-presets ``` -------------------------------- ### Elastic Net Regression Example Source: https://github.com/amd/aocl-data-analytics/blob/main/doc/Algorithms/linear_models/linear_models.md Demonstrates initializing and computing an Elastic Net regression model using a data analytics library. It includes setting model parameters, defining features, fitting the model, and verifying the computed coefficients against expected values. ```cpp #include #include #include #include // Assuming da_handle, da_status, da_int, etc. are defined elsewhere // For demonstration purposes, we'll use placeholder types and functions. enum da_status { da_status_success, da_status_error }; struct da_handle {}; using da_int = int; // Placeholder functions (replace with actual library functions) da_status da_handle_init_d(da_handle** handle, int type) { return da_status_success; } da_status da_linmod_select_model_d(da_handle* handle, int model) { return da_status_success; } da_status da_options_set_string(da_handle* handle, const char* name, const char* value) { return da_status_success; } da_status da_options_set_real_d(da_handle* handle, const char* name, double value) { return da_status_success; } da_status da_options_set_int(da_handle* handle, const char* name, int value) { return da_status_success; } da_status da_linmod_define_features_d(da_handle* handle, int m, int n, const double* features, int m2, const double* rhs) { return da_status_success; } da_status da_linmod_fit_start_d(da_handle* handle, int n, const double* x) { return da_status_success; } void da_handle_get_result_d(da_handle* handle, int result_type, da_int* nx, double* data) {} void da_handle_print_error_message(da_handle* handle) {} void da_handle_destroy(da_handle** handle) {} int main() { // Example parameters (replace with actual data) const int m = 10; const int n = 5; std::vector features(m * n); std::vector rhs(m); std::vector x(n + 1); // Coefficients + intercept std::vector x_ref = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0}; // Example reference coefficients // Initialize data (replace with actual data loading/generation) for (int i = 0; i < m * n; ++i) features[i] = i * 0.1; for (int i = 0; i < m; ++i) rhs[i] = i * 0.5; // Model types const int linmod_model_mse = 0; // Result types const int da_linmod_coef = 0; bool pass = true; da_int nx = 0; da_handle* handle = nullptr; da_status status; pass = pass && da_handle_init_d(&handle, 0) == da_status_success; // Assuming 0 is a valid type for linmod pass = pass && da_linmod_select_model_d(handle, linmod_model_mse) == da_status_success; pass = pass && da_options_set_string(handle, "scaling", "standardise") == da_status_success; pass = pass && da_options_set_real_d(handle, "alpha", 1) == da_status_success; pass = pass && da_options_set_real_d(handle, "lambda", 4) == da_status_success; pass = pass && da_options_set_string(handle, "print options", "yes") == da_status_success; pass = pass && da_options_set_int(handle, "intercept", 0) == da_status_success; pass = pass && da_options_set_int(handle, "print level", 1) == da_status_success; pass = pass && da_linmod_define_features_d(handle, m, n, features.data(), m, rhs.data()) == da_status_success; if (!pass) { std::cout << "Unexpected error in the model definition.\n"; da_handle_destroy(&handle); return 1; } // Compute regression status = da_linmod_fit_start_d(handle, n + 1, x.data()); bool ok = false; if (status == da_status_success) { std::cout << "Regression computed" << std::endl; // Query the amount of coefficient in the model (n+intercept) da_handle_get_result_d(handle, da_linmod_coef, &nx, x.data()); x.resize(nx); da_handle_get_result_d(handle, da_linmod_coef, &nx, x.data()); std::cout << "Coefficients: " << std::endl; std::cout.precision(3); bool oki; ok = !ok; for (da_int i = 0; i < nx; i++) { oki = std::abs(x[i] - x_ref[i]) <= 1.0e-3; std::cout << " x[" << std::setw(2) << i << "] = " << std::setw(9) << x[i] << " expecting " << std::setw(9) << x_ref[i] << (oki ? " (OK)" : " [WRONG]") << std::endl; ok &= oki; } } else { std::cout << "Unexpected error:" << std::endl; da_handle_print_error_message(handle); } std::cout << "----------------------------------------" << std::endl; da_handle_destroy(&handle); return ok ? 0 : 7; } ``` -------------------------------- ### Exclude gtest and gmock from installation Source: https://github.com/amd/aocl-data-analytics/blob/main/tests/unit_tests/CMakeLists.txt This snippet sets CMake variables to prevent Google Test and Google Mock from being installed with the project. ```cmake set(INSTALL_GTEST OFF) set(INSTALL_GMOCK OFF) ```