### SpheriCart CMake Configuration Options Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Lists available CMake configuration options for building the SpheriCart C/C++/CUDA library. These options control the inclusion of PyTorch bindings, tests, examples, OpenMP, CUDA, and the installation prefix. ```cmake -DSPHERICART_BUILD_TORCH=ON/OFF -DSPHERICART_BUILD_TESTS=ON/OFF -DSPHERICART_BUILD_EXAMPLES=ON/OFF -DSPHERICART_OPENMP=ON/OFF -DSPHERICART_CUDA=ON/OFF -DCMAKE_INSTALL_PREFIX=where/you/want/to/install ``` -------------------------------- ### Build SpheriCart from Source (with PyTorch and JAX) Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Builds the SpheriCart library from source for optimal performance, GPU support, and JAX integration. Requires cloning the repository and installing dependencies. ```bash git clone https://github.com/lab-cosmo/sphericart pip install . # if you also want the torch bindings (CPU and GPU) pip install .[torch] # if you also want the jax bindings pip install .[jax] # torch bindings (CPU-only) pip install --extra-index-url https://download.pytorch.org/whl/cpu .[torch] ``` -------------------------------- ### Install SpheriCart Python Package with PyTorch Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Installs the SpheriCart Python package with PyTorch bindings. This pre-built version may have performance limitations and lacks GPU support. ```bash pip install sphericart[torch] ``` -------------------------------- ### Build SpheriCart C/C++/CUDA Library Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Builds the C/C++/CUDA library from source using CMake. This process involves cloning the repository, creating a build directory, and configuring the build with specific options. ```bash git clone https://github.com/lab-cosmo/sphericart cd sphericart/ mkdir build cd build/ cmake .. # possibly include cmake configuration options here make install ``` -------------------------------- ### Install SpheriCart Julia Package Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Installs the native SpheriCart Julia package. This is done within the Julia REPL using the package manager. ```julia ] add SpheriCart ``` -------------------------------- ### Sphericart C Example Build Source: https://github.com/lab-cosmo/sphericart/blob/main/examples/CMakeLists.txt Build configuration for the C example executable. It links against the sphericart library. ```cmake cmake_minimum_required(VERSION 3.10) project(sphericart_examples LANGUAGES C CXX) add_executable(example_c c/example.c) target_link_libraries(example_c sphericart) add_test(NAME example_c COMMAND ./example_c) ``` -------------------------------- ### Install SpheriCart Python Package Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/installation.rst Installs the basic SpheriCart Python package using pip. This version relies on NumPy and does not include GPU support or advanced features. ```bash pip install sphericart ``` -------------------------------- ### Sphericart Initialization and Calculation Examples Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/examples.rst Demonstrates the general process of initializing sphericart calculators and computing spherical harmonics and their derivatives for Cartesian coordinates. This includes examples for C++, C, CUDA, Python, PyTorch, and JAX, often comparing 32-bit and 64-bit floating-point precision. ```cpp // C++ examples would typically involve initializing a SphericalHarmonics object // and then calling methods to compute harmonics for given Cartesian coordinates. // Example: // SphericalHarmonics sh(lmax, nthreads); // sh.compute(x, y, z, l, m, derivatives); ``` ```c // C examples would involve similar initialization and computation steps, // likely using a C-style API for the SphericalHarmonics structure. // Example: // SphericalHarmonics* sh = sph_init(lmax, nthreads); // sph_compute(sh, x, y, z, l, m, derivatives); // sph_free(sh); ``` ```cuda // CUDA examples would focus on GPU-accelerated computation, potentially // involving kernel launches for the harmonic calculations. // Example: // SphericalHarmonics* sh = sph_init_cuda(lmax, nthreads); // sph_compute_cuda(sh, d_x, d_y, d_z, d_l, d_m, d_derivatives); // sph_free_cuda(sh); ``` ```python import sphericart import numpy as np # Initialize calculator lmax = 10 calculator = sphericart.SphericalHarmonics(lmax=lmax, dtype=np.float64) # Generate random Cartesian coordinates n_points = 1000 x = np.random.rand(n_points) y = np.random.rand(n_points) z = np.random.rand(n_points) # Compute spherical harmonics and derivatives # The compute method typically returns a tuple or dictionary of harmonic values harmonics = calculator.compute(x, y, z) ``` ```pytorch import sphericart.torch import torch # Initialize calculator lmax = 10 calculator = sphericart.torch.SphericalHarmonics(lmax=lmax, dtype=torch.float64) # Generate random Cartesian coordinates on the desired device device = 'cuda' if torch.cuda.is_available() else 'cpu' x = torch.rand(1000, device=device) y = torch.rand(1000, device=device) z = torch.rand(1000, device=device) # Compute spherical harmonics and derivatives harmonics = calculator.compute(x, y, z) ``` ```jax import sphericart.jax import jax.numpy as jnp # Initialize calculator lmax = 10 calculator = sphericart.jax.SphericalHarmonics(lmax=lmax, dtype=jnp.float64) # Generate random Cartesian coordinates x = jnp.asarray(np.random.rand(1000)) y = jnp.asarray(np.random.rand(1000)) z = jnp.asarray(np.random.rand(1000)) # Compute spherical harmonics and derivatives harmonics = calculator.compute(x, y, z) ``` -------------------------------- ### Sphericart C++ Example Build Source: https://github.com/lab-cosmo/sphericart/blob/main/examples/CMakeLists.txt Build configuration for the C++ example executable. It links against the sphericart library and requires C++14. ```cmake cmake_minimum_required(VERSION 3.10) project(sphericart_examples LANGUAGES C CXX) add_executable(example_cpp cpp/example.cpp) target_link_libraries(example_cpp sphericart) add_test(NAME example_cpp COMMAND ./example_cpp) target_compile_features(example_cpp PRIVATE cxx_std_14) ``` -------------------------------- ### Benchmark Setup with CMake Source: https://github.com/lab-cosmo/sphericart/blob/main/benchmarks/CMakeLists.txt This snippet demonstrates how to define a benchmark executable in CMake. It adds the benchmark source file, links it against the sphericart library, registers it as a test, and specifies the required C++ standard. ```cmake add_executable(benchmark_cpp cpp/benchmark.cpp) target_link_libraries(benchmark_cpp sphericart) add_test(benchmark benchmark_cpp COMMAND ./benchmark_cpp) target_compile_features(benchmark_cpp PRIVATE cxx_std_17) ``` -------------------------------- ### Sphericart CMake Installation Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/CMakeLists.txt Configures the installation of the sphericart target, including libraries, archives, and runtime components. It also sets up export targets and installs generated configuration files. ```cmake configure_file( "${CMAKE_CURRENT_SOURCE_DIR}/cmake/sphericart-config-version.in.cmake" "${CMAKE_CURRENT_BINARY_DIR}/sphericart-config-version.cmake" @ONLY ) install(TARGETS sphericart EXPORT sphericart-targets LIBRARY DESTINATION ${LIB_INSTALL_DIR} ARCHIVE DESTINATION ${LIB_INSTALL_DIR} RUNTIME DESTINATION ${BIN_INSTALL_DIR} ) include(CMakePackageConfigHelpers) configure_package_config_file( "${PROJECT_SOURCE_DIR}/cmake/sphericart-config.in.cmake" "${PROJECT_BINARY_DIR}/sphericart-config.cmake" INSTALL_DESTINATION ${LIB_INSTALL_DIR}/cmake/sphericart ) install(EXPORT sphericart-targets DESTINATION ${LIB_INSTALL_DIR}/cmake/sphericart) install(FILES "${PROJECT_BINARY_DIR}/sphericart-config-version.cmake" "${PROJECT_BINARY_DIR}/sphericart-config.cmake" DESTINATION ${LIB_INSTALL_DIR}/cmake/sphericart) install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/ DESTINATION ${INCLUDE_INSTALL_DIR}) install(DIRECTORY ${PROJECT_BINARY_DIR}/include/ DESTINATION ${INCLUDE_INSTALL_DIR}) ``` -------------------------------- ### Sphericart CUDA Example Build Source: https://github.com/lab-cosmo/sphericart/blob/main/examples/CMakeLists.txt Build configuration for the CUDA example executable. This is enabled only if a CUDA compiler is found and SPHERICART_ENABLE_CUDA is set. It links against the sphericart library. ```cmake if (CMAKE_CUDA_COMPILER AND SPHERICART_ENABLE_CUDA) project(sphericart_examples LANGUAGES C CXX CUDA) if(SPHERICART_ARCH_NATIVE) set(CMAKE_CUDA_ARCHITECTURES native) endif() add_executable(example_cuda cuda/example.cu) target_link_libraries(example_cuda sphericart) add_test(NAME example_cuda COMMAND ./example_cuda) endif() ``` -------------------------------- ### Sphericart Installation Targets Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-torch/CMakeLists.txt Specifies the installation targets for the Sphericart libraries and Python build helper files. Libraries are installed into the 'lib' directory, and a Python build version file is installed if the Python build is enabled. ```cmake install(TARGETS sphericart_torch LIBRARY DESTINATION "lib" ) install(TARGETS sphericart_torch_cuda_stream LIBRARY DESTINATION "lib" ) if (SPHERICART_TORCH_BUILD_FOR_PYTHON) install( FILES ${CMAKE_CURRENT_BINARY_DIR}/_build_torch_version.py DESTINATION "." ) endif() ``` -------------------------------- ### CMake Configuration Options (C/C++) Source: https://github.com/lab-cosmo/sphericart/blob/main/README.md Lists available CMake configuration options for building the sphericart C/C++ library. These options control the inclusion of Torch bindings, tests, examples, OpenMP, and the installation directory. ```cmake -DSPHERICART_BUILD_TORCH=ON/OFF: build the torch bindings in addition to the main library -DSPHERICART_BUILD_TESTS=ON/OFF: build C++ unit tests -DSPHERICART_BUILD_EXAMPLES=ON/OFF: build C++ examples and benchmarks -DSPHERICART_OPENMP=ON/OFF: enable OpenMP parallelism -DCMAKE_INSTALL_PREFIX=: set the root path for installation ``` -------------------------------- ### Installation Directory Configuration Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/CMakeLists.txt Sets cache variables for installation directories, allowing users to customize where libraries, binaries, and headers are installed relative to the CMAKE_INSTALL_PREFIX. ```cmake set(LIB_INSTALL_DIR "lib" CACHE PATH "Path relative to CMAKE_INSTALL_PREFIX where to install libraries") set(BIN_INSTALL_DIR "bin" CACHE PATH "Path relative to CMAKE_INSTALL_PREFIX where to install DLL/binaries") set(INCLUDE_INSTALL_DIR "include" CACHE PATH "Path relative to CMAKE_INSTALL_PREFIX where to install headers") ``` -------------------------------- ### PyTorch Sphericart Example Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/pytorch-examples.rst This example demonstrates the usage of Sphericart's PyTorch implementation, showcasing backpropagation for gradient calculation and TorchScript compilation. ```python import torch import sphericart.torch # Initialize SphericalHarmonics sh = sphericart.torch.SphericalHarmonics( lmax=2, normalized=True, sampling_mode="mu_sigma", legendre_normalization="4pi", ) # Create dummy input data coords = torch.tensor([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0]], dtype=torch.float64) # Compute Spherical Harmonics # requires_grad=True is needed to compute gradients spherical_harmonics = sh(coords, requires_grad=True) print("Spherical Harmonics:") print(spherical_harmonics) # Compute gradients with respect to input coordinates # We need to sum the output before calling backward() if the output is not a scalar spherical_harmonics.sum().backward() print("Gradients:") print(coords.grad) # Example of TorchScript compilation traced_sh = torch.jit.trace(sh, (coords,)) print("TorchScript traced model:") print(traced_sh.code) # Using the traced model print("Output from traced model:") print(traced_sh(coords)) # Initialize SolidHarmonics solh = sphericart.torch.SolidHarmonics( lmax=2, normalized=True, sampling_mode="mu_sigma", legendre_normalization="4pi", ) solid_harmonics = solh(coords) print("Solid Harmonics:") print(solid_harmonics) # TorchScript compilation for SolidHarmonics traced_solh = torch.jit.trace(solh, (coords,)) print("TorchScript traced SolidHarmonics model:") print(traced_solh.code) print("Output from traced SolidHarmonics model:") print(traced_solh(coords)) ``` -------------------------------- ### SphericalHarmonics Class Usage (CUDA C++) Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/cuda-examples.rst Demonstrates the usage of the sphericart::cuda::SphericalHarmonics class in CUDA C++. This class handles internal initialization of pre-factors and buffers, offering a unified function for computing values, gradients, and Hessians of spherical harmonics. The example provided is intended to guide users getting started with the API. ```cuda #include int main() { // Example usage of SphericalHarmonics class // Initialization, computation of values, gradients, and Hessians // ... (actual code from example.cu would go here) return 0; } ``` -------------------------------- ### Build sphericart from Source (C/C++) Source: https://github.com/lab-cosmo/sphericart/blob/main/README.md Builds the sphericart library from source for C/C++ using CMake. Allows configuration of Torch bindings, tests, examples, OpenMP parallelism, and installation prefix. ```bash git clone https://github.com/lab-cosmo/sphericart cd sphericart mkdir build && cd build cmake .. cmake --build . --target install ``` -------------------------------- ### Uploading Wheels to PyPI Source: https://github.com/lab-cosmo/sphericart/wiki/Release-process This command uploads the built Python wheels and source distributions to the Python Package Index (PyPI) using the twine utility. Ensure you have twine installed and are logged into your PyPI account. ```bash twine upload ``` -------------------------------- ### Sphericart CMake Configuration Source: https://github.com/lab-cosmo/sphericart/blob/main/CMakeLists.txt Main CMakeLists.txt for the Sphericart project. It sets the minimum CMake version, project name, enables testing, configures the default build type, includes subdirectories for core library, examples, benchmarks, and optional Torch bindings. ```cmake cmake_minimum_required(VERSION 3.27) project(sphericart_meta) enable_testing() # Set a default build type if none was specified if (${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) if("${CMAKE_BUILD_TYPE}" STREQUAL "" AND "${CMAKE_CONFIGURATION_TYPES}" STREQUAL "") message(STATUS "Setting build type to 'release' as none was specified.") set(CMAKE_BUILD_TYPE "release" CACHE STRING "Choose the type of build, options are: none(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) debug relwithdebinfo minsizerel." FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS release debug relwithdebinfo minsizerel none) endif() endif() add_subdirectory(sphericart) OPTION(SPHERICART_BUILD_TORCH "Build the torch bindings" OFF) OPTION(SPHERICART_BUILD_EXAMPLES "Build and run examples and benchmarks for Sphericart" OFF) if (SPHERICART_BUILD_EXAMPLES) add_subdirectory(examples) add_subdirectory(benchmarks) endif() if (SPHERICART_BUILD_TORCH) add_subdirectory(sphericart-torch) endif() ``` -------------------------------- ### Install SpheriCart (Julia) Source: https://github.com/lab-cosmo/sphericart/blob/main/README.md Installs the native Julia implementation of sphericart, named SpheriCart. Instructions are provided for adding the package via the Julia REPL. ```julia ] add SpheriCart ``` -------------------------------- ### Install sphericart (Python) Source: https://github.com/lab-cosmo/sphericart/blob/main/README.md Installs the sphericart library for Python, with options for NumPy, PyTorch, and JAX bindings. Pre-built packages are available on PyPI. ```bash pip install sphericart # numpy version pip install sphericart[torch] # including also the torch bindings pip install sphericart[jax] # JAX bindings (CPU-only) ``` -------------------------------- ### Sphericart JAX CPU Module Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-jax/CMakeLists.txt This snippet defines the C++ source file for the CPU operations of the Sphericart JAX module and uses pybind11 to create the module. It links against the 'sphericart' target and sets C++17 as a compile feature. Include directories are configured for build and installation. ```cmake # CPU op library set(CPU_SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/sphericart_jax_cpu.cpp) pybind11_add_module(sphericart_jax_cpu ${CPU_SOURCES}) target_link_libraries(sphericart_jax_cpu PUBLIC sphericart) target_compile_features(sphericart_jax_cpu PUBLIC cxx_std_17) target_include_directories(sphericart_jax_cpu PUBLIC $ $ ) install(TARGETS sphericart_jax_cpu LIBRARY DESTINATION "lib" ) ``` -------------------------------- ### Sphericart Metatensor Example Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/metatensor-examples.rst Computes spherical harmonics, gradients, and Hessians using sphericart with metatensor. This example showcases the integration for handling metadata and performing complex calculations in a unified manner. ```python import metatensor import sphericart # Example usage (assuming necessary setup and data) # This is a placeholder for the actual code from the literalinclude directive. # The actual code would involve creating metatensor objects, # initializing sphericart calculators, and performing computations. # Placeholder for actual code: print("Sphericart with Metatensor Example") # Example: # calculator = sphericart.SphericalHarmonics( # max_degree=2, # dtype=sphericart.Dtype.Float64, # calculation_mode=sphericart.CalculationMode.SphericalHarmonics # ) # # # Assume 'tensor' is a metatensor object with input data # # result = calculator.compute(tensor) # # print(result) ``` -------------------------------- ### Basic Usage of SpheriCart for Solid Harmonics Source: https://github.com/lab-cosmo/sphericart/blob/main/julia/README.md Demonstrates how to initialize a SpheriCart basis for solid harmonics and compute their values and gradients for single and multiple inputs. Includes examples for both single vector and array inputs, as well as in-place computation. ```julia using SpheriCart, StaticArrays # generate the basis object L = 5 basis = SolidHarmonics(L) # Replace this with # basis = SphericalHarmonics(L) # to evaluate the spherical instead of solid harmonics # evaluate for a single input 𝐫 = @SVector randn(3) # Z : SVector of length (L+1)² Z = basis(𝐫) Z = compute(basis, 𝐫) # ∇Z : SVector of length (L+1)², each ∇Z[i] is an SVector{3, T} Z, ∇Z = compute_with_gradients(basis, 𝐫) # evaluate for many inputs nX = 32 Rs = [ @SVector randn(3) for _ = 1:nX ] # Z : Matrix of size nX × (L+1)² of scalar # dZ : Matrix of size nX × (L+1)² of SVector{3, T} Z = basis(Rs) Z = compute(basis, Rs) Z, ∇Z = compute_with_gradients(basis, Rs) # in-place evaluation to avoid the allocation compute!(Z, basis, Rs) compute_with_gradients!(Z, ∇Z, basis, Rs) ``` -------------------------------- ### Sphericart JAX CUDA Module Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-jax/CMakeLists.txt This snippet configures the CUDA module for Sphericart JAX, provided CUDA is enabled and a compiler is found. It defines the CUDA source file, creates the pybind11 module, links to 'sphericart', sets C++17 compile features, and configures include directories including CUDA toolkit paths. It also handles installation. ```cmake if(CMAKE_CUDA_COMPILER AND SPHERICART_ENABLE_CUDA) set(CUDA_SOURCES ${CMAKE_CURRENT_LIST_DIR}/src/sphericart_jax_cuda.cpp) pybind11_add_module(sphericart_jax_cuda ${CUDA_SOURCES}) target_link_libraries(sphericart_jax_cuda PUBLIC sphericart) target_compile_features(sphericart_jax_cuda PUBLIC cxx_std_17) target_include_directories(sphericart_jax_cuda PUBLIC $ $ ${CMAKE_CUDA_TOOLKIT_INCLUDE_DIRECTORIES} ) install(TARGETS sphericart_jax_cuda LIBRARY DESTINATION "lib" ) endif() ``` -------------------------------- ### Sphericart PyTorch Build Configuration Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-torch/CMakeLists.txt Handles the configuration for building the sphericart_torch extension for Python. It includes checks for the root project, disables recursive builds, finds the PyTorch installation path, and configures CuDNN. ```cmake option(SPHERICART_TORCH_BUILD_FOR_PYTHON "Are we building sphericart_torch for usage from Python?" OFF) mark_as_advanced(SPHERICART_TORCH_BUILD_FOR_PYTHON) if (SPHERICART_TORCH_BUILD_FOR_PYTHON) if (NOT ${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) message(FATAL_ERROR "SPHERICART_TORCH_BUILD_FOR_PYTHON can only be set when this project is the root project") endif() # prevent recursive build: we are including sphericart/CMakeLists.txt, which can # include this file (in sphericart/torch/CMakeLists.txt) if SPHERICART_BUILD_TORCH=ON. set(SPHERICART_BUILD_TORCH OFF CACHE BOOL "" FORCE) set(BUILD_SHARED_LIBS OFF CACHE BOOL "" FORCE) mark_as_advanced(SPHERICART_BUILD_TORCH) add_subdirectory(sphericart EXCLUDE_FROM_ALL) # add path to the cmake configuration of the version of libtorch used # by the Python torch module. PYTHON_EXECUTABLE is provided by skbuild execute_process( COMMAND ${PYTHON_EXECUTABLE} -c "import torch.utils; print(torch.utils.cmake_prefix_path)" RESULT_VARIABLE TORCH_CMAKE_PATH_RESULT OUTPUT_VARIABLE TORCH_CMAKE_PATH_OUTPUT ERROR_VARIABLE TORCH_CMAKE_PATH_ERROR ) if (NOT ${TORCH_CMAKE_PATH_RESULT} EQUAL 0) message(FATAL_ERROR "failed to find your pytorch installation\n${TORCH_CMAKE_PATH_ERROR}") endif() string(STRIP ${TORCH_CMAKE_PATH_OUTPUT} TORCH_CMAKE_PATH_OUTPUT) set(CMAKE_PREFIX_PATH "${CMAKE_PREFIX_PATH};${TORCH_CMAKE_PATH_OUTPUT}") # ============================= Handle CUDNN ============================= # # The FindCUDNN.cmake distributed with PyTorch is a bit broken, so we have a # fixed version in `cmake/FindCUDNN.cmake`, and we set the right variables # for it below to point the code to the right `libcudnn.do`/`cudnn.h` set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake;${CMAKE_MODULE_PATH}") # First try using the `nvidia.cudnn` package (dependency of torch on PyPI) execute_process( COMMAND ${PYTHON_EXECUTABLE} -c "import nvidia.cudnn, os; print(os.path.dirname(nvidia.cudnn.__file__))" RESULT_VARIABLE CUDNN_CMAKE_PATH_RESULT OUTPUT_VARIABLE CUDNN_CMAKE_PATH_OUTPUT ERROR_VARIABLE CUDNN_CMAKE_PATH_ERROR ) if (${CUDNN_CMAKE_PATH_RESULT} EQUAL 0) string(STRIP ${CUDNN_CMAKE_PATH_OUTPUT} CUDNN_CMAKE_PATH_OUTPUT) set(CUDNN_ROOT ${CUDNN_CMAKE_PATH_OUTPUT}) else() # Otherwise try to find CuDNN inside PyTorch itself set(CUDNN_ROOT ${TORCH_CMAKE_PATH_OUTPUT}/../..) if (NOT EXISTS ${CUDNN_ROOT}/include/cudnn_version.h) # HACK: create a minimal cudnn_version.h (with a made-up version), # because it is not bundled together with the CuDNN shared library # in PyTorch: https://github.com/pytorch/pytorch/issues/47743 file(WRITE ${CUDNN_ROOT}/include/cudnn_version.h "#define CUDNN_MAJOR 8\n#define CUDNN_MINOR 5\n#define CUDNN_PATCHLEVEL 0\n") endif() endif() set(CUDNN_INCLUDE_DIR ${CUDNN_ROOT}/include CACHE PATH "" FORCE) set(CUDNN_LIBRARY ${CUDNN_ROOT}/lib CACHE PATH "" FORCE) unset(CUDNN_ROOT) mark_as_advanced(CUDNN_INCLUDE_DIR CUDNN_LIBRARY) else() if (NOT TARGET sphericart) message(FATAL_ERROR "missing sphericart target, you should build sphericart_torch as a sub-project of sphericart") endif() endif() find_package(Torch 2.1 REQUIRED) file(WRITE ${CMAKE_CURRENT_BINARY_DIR}/_build_torch_version.py "BUILD_TORCH_VERSION = '${Torch_VERSION}'") add_library(sphericart_torch SHARED "include/sphericart/torch_cuda_wrapper.hpp" "include/sphericart/torch.hpp" "include/sphericart/autograd.hpp" "src/autograd.cpp" "src/torch.cpp" ) if (CMAKE_CUDA_COMPILER AND SPHERICART_ENABLE_CUDA) target_sources(sphericart_torch PUBLIC "src/torch_cuda_wrapper.cpp") else() target_sources(sphericart_torch PUBLIC "src/torch_cuda_wrapper_stub.cpp") endif() target_link_libraries(sphericart_torch PUBLIC sphericart) # only link to `torch_cpu_library` instead of `torch`, which could also include ``` -------------------------------- ### Sphericart C API Example Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/c-examples.rst This example demonstrates how to use the C API of the Sphericart library to compute spherical harmonics and their derivatives. It utilizes the opaque `sphericart_calculator_t` type to interact with the underlying C++ implementation. ```c #include #include #include int main() { // Example usage (replace with actual Sphericart API calls) printf("Sphericart C API Example\n"); // Placeholder for calculator initialization sphericart_calculator_t* calculator = NULL; // Replace with actual initialization // Placeholder for computation // sphericart_compute_harmonics(calculator, ...); // Placeholder for cleanup // sphericart_destroy_calculator(calculator); return 0; } ``` -------------------------------- ### Running Tests with tox Source: https://github.com/lab-cosmo/sphericart/blob/main/README.md Executes tests and builds documentation locally using tox. Demonstrates how to run tests in a CPU-only environment by setting the PIP_EXTRA_INDEX_URL environment variable. ```bash tox # Example for CPU-only documentation build: PIP_EXTRA_INDEX_URL=https://download.pytorch.org/whl/cpu tox -e docs ``` -------------------------------- ### Tagging and Pushing a New Version Source: https://github.com/lab-cosmo/sphericart/wiki/Release-process This snippet demonstrates how to tag the repository with a new version number and push the tag to the remote repository. This action triggers documentation updates on Read the Docs and initiates CI builds. ```git git tag v0.42.1 git push --tags ``` -------------------------------- ### Sphericart Core and Language Interfaces Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/api.rst The sphericart library's core is built with C++ and CUDA. It provides interfaces for multiple programming languages and frameworks, including C, Python, PyTorch, JAX, and Metatensor. Links to detailed documentation for each interface are provided. ```APIDOC Sphericart Core and Interfaces: Core Implementation: - Written in C++ and CUDA. Available Interfaces: - C API: Documentation available in cpp-api. - C API: Documentation available in c-api. - CUDA API: Documentation available in cuda-api. - Python API: Documentation available in python-api. - PyTorch API: Documentation available in pytorch-api. - JAX API: Documentation available in jax-api. - Metatensor API: Documentation available in metatensor-api. Julia API: - Basic usage examples available at: https://github.com/lab-cosmo/sphericart/blob/main/julia/README.md ``` -------------------------------- ### Compute Complex Spherical Harmonics Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/spherical-complex.rst This example illustrates the computation of complex spherical harmonics using the sphericart library. It is useful for applications that require complex-valued harmonic representations. The correctness can be verified against other implementations like SciPy. ```python import sphericart import numpy as np # Example usage: # Assume you have Cartesian coordinates (x, y, z) # For simplicity, let's use dummy data x = np.array([1.0, 0.0, 0.0]) y = np.array([0.0, 1.0, 0.0]) z = np.array([0.0, 0.0, 1.0]) # Create a SphericalHarmonics object for complex harmonics calculator = sphericart.SphericalHarmonics(lmax=2, mmax=2, normalization='complex', dtype=np.complex128) # Compute the complex spherical harmonics # The output 'coeffs' will be a numpy array with shape (n_samples, n_harmonics) coeffs = calculator.compute_complex_harmonics(x, y, z) print(coeffs) ``` -------------------------------- ### Sphericart CMake Configuration Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-torch/CMakeLists.txt Sets up the minimum CMake version, project name, compiler flags, and checks for CUDA support. It includes policies for source path handling and conditionally adds CUDA language support. ```cmake cmake_minimum_required(VERSION 3.27) if (POLICY CMP0076) # target_sources() converts relative paths to absolute cmake_policy(SET CMP0076 NEW) endif() project(sphericart_torch CXX) if(COMPILER_SUPPORTS_WPRAGMAS) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unknown-pragmas") endif() include(CheckLanguage) check_language(CUDA) if(CMAKE_CUDA_COMPILER) enable_language(CUDA) set(CUDA_USE_STATIC_CUDA_RUNTIME OFF CACHE BOOL "" FORCE) else() message(STATUS "Could not find a CUDA compiler") endif() ``` -------------------------------- ### Compute Spherical Harmonics from Spherical Coordinates Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/spherical-complex.rst This example demonstrates how to compute spherical harmonics using spherical input coordinates. It serves as a basic adaptor for cases where Cartesian coordinates are not directly available. The implementation is consistent with Wikipedia's definitions. ```python import sphericart import numpy as np # Example usage: # Assume you have spherical coordinates (radius, theta, phi) # For simplicity, let's use dummy data r = np.array([1.0, 1.0, 1.0]) theta = np.array([0.0, np.pi/2, np.pi]) phi = np.array([0.0, np.pi/2, np.pi]) # Create a SphericalHarmonics object # The 'lmax' parameter specifies the maximum degree of the harmonics to compute # The 'mmax' parameter specifies the maximum order of the harmonics to compute # The 'normalization' parameter can be 'real' or 'complex' # The 'dtype' parameter specifies the data type for calculations calculator = sphericart.SphericalHarmonics(lmax=2, mmax=2, normalization='real', dtype=np.float64) # Compute the spherical harmonics # The output 'coeffs' will be a numpy array with shape (n_samples, n_harmonics) coeffs = calculator.compute_real_harmonics(r, theta, phi) print(coeffs) ``` -------------------------------- ### Compute Complex Spherical Harmonics from Spherical Coordinates Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/spherical-complex.rst This example shows how to compute complex spherical harmonics directly from spherical coordinates (radius, theta, phi). This adaptor is convenient when input data is naturally in spherical form. Its accuracy can be cross-checked with SciPy's spherical harmonic implementations. ```python import sphericart import numpy as np # Example usage: # Assume you have spherical coordinates (radius, theta, phi) # For simplicity, let's use dummy data r = np.array([1.0, 1.0, 1.0]) theta = np.array([0.0, np.pi/2, np.pi]) phi = np.array([0.0, np.pi/2, np.pi]) # Create a SphericalHarmonics object for complex harmonics from spherical coordinates calculator = sphericart.SphericalHarmonics(lmax=2, mmax=2, normalization='complex', dtype=np.complex128) # Compute the complex spherical harmonics from spherical coordinates # The output 'coeffs' will be a numpy array with shape (n_samples, n_harmonics) coeffs = calculator.compute_complex_harmonics_from_spherical(r, theta, phi) print(coeffs) ``` -------------------------------- ### CMake Configuration for Sphericart Tests Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/tests/CMakeLists.txt This snippet details the CMake commands used to build and link test executables for the Sphericart library. It specifies the source files, the library dependencies, and the required C++ compilation features. ```cmake add_executable(test_hardcoding test_hardcoding.cpp) target_link_libraries(test_hardcoding sphericart) target_compile_features(test_hardcoding PRIVATE cxx_std_17) add_executable(test_samples test_samples.cpp) target_link_libraries(test_samples sphericart) target_compile_features(test_samples PRIVATE cxx_std_17) add_executable(test_derivatives test_derivatives.cpp) target_link_libraries(test_derivatives sphericart) target_compile_features(test_derivatives PRIVATE cxx_std_17) add_test(NAME test_hardcoding COMMAND ./test_hardcoding) add_test(NAME test_samples COMMAND ./test_samples) add_test(NAME test_derivatives COMMAND ./test_derivatives) ``` -------------------------------- ### Sphericart Torch Library Configuration Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-torch/CMakeLists.txt Configures the main Sphericart PyTorch library, linking against PyTorch CPU, setting include directories, and defining compile flags. It also handles OpenMP linking and C++ standard requirements. ```cmake target_link_libraries(sphericart_torch PUBLIC torch_cpu_library) target_include_directories(sphericart_torch PUBLIC "${TORCH_INCLUDE_DIRS}") target_compile_definitions(sphericart_torch PUBLIC "${TORCH_CXX_FLAGS}") if(OpenMP_CXX_FOUND) target_link_libraries(sphericart_torch PUBLIC OpenMP::OpenMP_CXX) endif() target_compile_features(sphericart_torch PUBLIC cxx_std_17) target_include_directories(sphericart_torch PUBLIC $ $ ) if (LINUX) # so dlopen can find libsphericart_torch_cuda_stream.so set_target_properties(sphericart_torch PROPERTIES INSTALL_RPATH "$ORIGIN") endif() ``` -------------------------------- ### JAX CPU Dependency Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/requirements.txt Specifies the JAX library with CPU support, crucial for numerical computations within the project. The `[cpu]` extra ensures that only the CPU version is installed, avoiding potential conflicts or unnecessary GPU dependencies. Version 0.4.18 or higher is recommended. ```python jax[cpu] >= 0.4.18 ``` -------------------------------- ### Sphinx Documentation Dependencies Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/requirements.txt These packages are required for building the project's documentation using Sphinx. It includes the core Sphinx library, a popular theme (sphinx_rtd_theme, furo), and Breathe for integrating C/C++ documentation generated by Doxygen. ```python sphinx sphinx_rtd_theme breathe >=4.33 furo ``` -------------------------------- ### Includeable String Wrapper Function Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/CMakeLists.txt This CMake function reads a file, formats its content as a C++ raw string literal, and writes it to an output file. This allows source code to be statically initialized as a string, useful for embedding code directly into executables. ```cmake function(make_includeable INPUT_FILE OUTPUT_FILE) if(NOT EXISTS ${INPUT_FILE}) message(FATAL_ERROR "Error: The input file '${INPUT_FILE}' does not exist.") endif() file(READ ${INPUT_FILE} content) # Format the content to be included as a raw string in C++ set(content "R\"======(\n${content}\n)======"") # Write the formatted content to the output file file(WRITE ${OUTPUT_FILE} "${content}") endfunction() ``` -------------------------------- ### Compute Spherical Harmonics with JAX Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/jax-examples.rst Demonstrates how to compute spherical harmonics using the `sphericart.jax.spherical_harmonics` function. It also shows how to apply standard JAX transformations such as `vmap`, `grad`, and `jit` to the function for vectorized, differentiable, and optimized computations. ```python import jax import jax.numpy as jnp from sphericart.jax import spherical_harmonics # Example usage: # Assume you have input data `x`, `y`, `z` and coefficients `coeffs` # x, y, z = jnp.array([...]) # coeffs = jnp.array([...]) # Compute spherical harmonics # result = spherical_harmonics(x, y, z, coeffs) # Example with JAX transformations: # Vectorized computation # vmap_spherical_harmonics = jax.vmap(spherical_harmonics, in_axes=(0, 0, 0, None)) # vectorized_result = vmap_spherical_harmonics(x_batch, y_batch, z_batch, coeffs) # Differentiable computation # grad_spherical_harmonics = jax.grad(spherical_harmonics, argnums=3) # gradient = grad_spherical_harmonics(x, y, z, coeffs) # Just-In-Time compilation # jit_spherical_harmonics = jax.jit(spherical_harmonics) # compiled_result = jit_spherical_harmonics(x, y, z, coeffs) ``` -------------------------------- ### Sphericart PyTorch Library Creation Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart-torch/CMakeLists.txt Defines the `sphericart_torch` shared library, specifying its header and source files. It conditionally includes CUDA wrapper sources based on the CUDA compiler and `SPHERICART_ENABLE_CUDA` flag. ```cmake add_library(sphericart_torch SHARED "include/sphericart/torch_cuda_wrapper.hpp" "include/sphericart/torch.hpp" "include/sphericart/autograd.hpp" "src/autograd.cpp" "src/torch.cpp" ) if (CMAKE_CUDA_COMPILER AND SPHERICART_ENABLE_CUDA) target_sources(sphericart_torch PUBLIC "src/torch_cuda_wrapper.cpp") else() target_sources(sphericart_torch PUBLIC "src/torch_cuda_wrapper_stub.cpp") endif() target_link_libraries(sphericart_torch PUBLIC sphericart) ``` -------------------------------- ### Sphericart Torch Metatensor API Reference Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/metatensor-api.rst Provides the API reference for the `sphericart.torch.metatensor` module, including the `SphericalHarmonics` and `SolidHarmonics` classes and their members. This enables the use of Sphericart with metatensor within PyTorch. ```APIDOC sphericart.torch.metatensor.SphericalHarmonics :members: sphericart.torch.metatensor.SolidHarmonics :members: ``` -------------------------------- ### Sphericart Build Options Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/CMakeLists.txt Defines CMake options for configuring the Sphericart build. Users can enable/disable building shared libraries, enabling tests, using OpenMP, utilizing native architecture optimizations, and enabling the CUDA backend. ```cmake OPTION(BUILD_SHARED_LIBS "Build shared libraries instead of static ones" OFF) OPTION(SPHERICART_BUILD_TESTS "Build and run tests for Sphericart" OFF) OPTION(SPHERICART_OPENMP "Try to use OpenMP when compiling Sphericart" ON) OPTION(SPHERICART_ARCH_NATIVE "Try to use -march=native when compiling Sphericart" ON) OPTION(SPHERICART_ENABLE_CUDA "Are we building the CUDA backend of Sphericart?" ON) ``` -------------------------------- ### Sphericart Metatensor API Reference Source: https://github.com/lab-cosmo/sphericart/blob/main/docs/src/metatensor-api.rst Provides the API reference for the `sphericart.metatensor` module, including the `SphericalHarmonics` and `SolidHarmonics` classes and their members. This allows for the integration of Sphericart with metatensor for metadata handling. ```APIDOC sphericart.metatensor.SphericalHarmonics :members: sphericart.metatensor.SolidHarmonics :members: ``` -------------------------------- ### Default Build Type Setting Source: https://github.com/lab-cosmo/sphericart/blob/main/sphericart/CMakeLists.txt Configures a default build type (relwithdebinfo) if none is specified by the user. This ensures a reasonable build configuration is used when the user does not explicitly set CMAKE_BUILD_TYPE. ```cmake if (${CMAKE_CURRENT_SOURCE_DIR} STREQUAL ${CMAKE_SOURCE_DIR}) if("${CMAKE_BUILD_TYPE}" STREQUAL "" AND "${CMAKE_CONFIGURATION_TYPES}" STREQUAL "") message(STATUS "Setting build type to 'relwithdebinfo' as none was specified.") set(CMAKE_BUILD_TYPE "relwithdebinfo" CACHE STRING "Choose the type of build, options are: none(CMAKE_CXX_FLAGS or CMAKE_C_FLAGS used) debug release relwithdebinfo minsizerel." FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS release debug relwithdebinfo minsizerel none) endif() endif() ```