### Enter Nix dev shell and install pyoperon Source: https://github.com/heal-research/pyoperon/blob/main/README.md Enters the Nix development shell and installs pyoperon into a virtual environment using scikit-build-core. ```bash nix develop .#pyenv virtualenv --system-site-packages .venv source .venv/bin/activate pip install scikit-build-core pip install --no-build-isolation . ``` -------------------------------- ### Install rules and developer mode for pyoperon Source: https://github.com/heal-research/pyoperon/blob/main/CMakeLists.txt Includes install rules unless skipped, and sets up developer mode with a warning when not top-level. ```cmake # ---- Install rules ---- if(NOT CMAKE_SKIP_INSTALL_RULES) include(cmake/install-rules.cmake) endif() # ---- Developer mode ---- if(NOT pyoperon_DEVELOPER_MODE) return() elseif(NOT PROJECT_IS_TOP_LEVEL) message( AUTHOR_WARNING "Developer mode is intended for developers of pyoperon" ) endif() include(cmake/dev-mode.cmake) ``` -------------------------------- ### Build C++ dependencies and install pyoperon with Conda/Mamba Source: https://github.com/heal-research/pyoperon/blob/main/README.md Sets compiler environment variables, builds C++ dependencies, and installs pyoperon without build isolation. ```bash export CC=clang export CXX=clang++ python script/dependencies.py pip install . --no-build-isolation ``` -------------------------------- ### Run pyoperon tests with Nix Source: https://github.com/heal-research/pyoperon/blob/main/README.md Installs the test dependencies and runs the test suite with pytest. ```bash pip install --no-build-isolation '.[test]' pytest tests/ -v ``` -------------------------------- ### CMake project setup and dependencies for pyoperon Source: https://github.com/heal-research/pyoperon/blob/main/CMakeLists.txt Configures the pyoperon project with version 0.6.1, C++23 standard, and finds required dependencies: Python, nanobind, unordered_dense, and xxHash (with fallback to pkg-config). ```cmake cmake_minimum_required(VERSION 3.20) include(cmake/prelude.cmake) project( pyoperon VERSION 0.6.1 DESCRIPTION "Scikit-learn module and python bindings and for the Operon library" HOMEPAGE_URL "https://operongp.readthedocs.io/en/latest/" LANGUAGES CXX ) set(CMAKE_CXX_STANDARD 23) set(CMAKE_CXX_STANDARD_REQUIRED True) docs_early_return() include(cmake/project-is-top-level.cmake) include(cmake/variables.cmake) # ---- Find dependencies ---- find_package(Python COMPONENTS Interpreter Development.Module REQUIRED) # Detect the installed nanobind package and import it into CMake execute_process( COMMAND "${Python_EXECUTABLE}" -m nanobind --cmake_dir OUTPUT_STRIP_TRAILING_WHITESPACE OUTPUT_VARIABLE nanobind_ROOT) find_package(nanobind CONFIG REQUIRED) find_package(unordered_dense REQUIRED) find_package(xxHash) if(NOT xxHash_FOUND) find_package(PkgConfig REQUIRED) pkg_check_modules(xxhash IMPORTED_TARGET xxhash) if (NOT xxhash_FOUND) pkg_check_modules(xxhash IMPORTED_TARGET libxxhash) endif() endif() ``` -------------------------------- ### Configure, build, and test on Windows Source: https://github.com/heal-research/pyoperon/blob/main/HACKING.md Commands to configure, build, and test the project on Windows. Use the dev preset, build with Release config, and run ctest with -C Release. ```sh cmake --preset=dev cmake --build build/dev --config Release cd build/dev && ctest -C Release ``` -------------------------------- ### Import libraries and list PMLB regression datasets Source: https://github.com/heal-research/pyoperon/blob/main/example/operon-sklearn.ipynb Imports pandas, numpy, scikit-learn modules, pyoperon components, and pmlb. Prints the list of available regression dataset names from PMLB. ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split, cross_val_score from sklearn.metrics import r2_score, make_scorer, mean_squared_error from sklearn.ensemble import RandomForestRegressor from pyoperon.sklearn import SymbolicRegressor from pyoperon import R2, MSE, InfixFormatter, FitLeastSquares, Interpreter from pmlb import regression_dataset_names, fetch_data print(regression_dataset_names) ``` -------------------------------- ### Clone and enter pyoperon repository Source: https://github.com/heal-research/pyoperon/blob/main/README.md Commands to clone the pyoperon repository and change into its directory. Used as the first step for building from source with Conda/Mamba or Nix. ```bash git clone https://github.com/heal-research/pyoperon.git cd pyoperon ``` -------------------------------- ### Create CMakeUserPresets.json with dev preset Source: https://github.com/heal-research/pyoperon/blob/main/HACKING.md Create a CMakeUserPresets.json file at the project root to enable developer mode. Replace with win64 or unix based on your operating system. This file is the recommended place to pass additional configure options. ```json { "version": 1, "cmakeMinimumRequired": { "major": 3, "minor": 14, "patch": 0 }, "configurePresets": [ { "name": "dev", "binaryDir": "${sourceDir}/build/dev", "inherits": ["dev-mode", "ci-"] } ] } ``` -------------------------------- ### Configure, build, and test on Unix Source: https://github.com/heal-research/pyoperon/blob/main/HACKING.md Commands to configure, build, and test the project on Unix-based systems (Linux, macOS). Use the dev preset and run ctest without specifying a config. ```sh cmake --preset=dev cmake --build build/dev cd build/dev && ctest ``` -------------------------------- ### Create and activate Conda/Mamba environment Source: https://github.com/heal-research/pyoperon/blob/main/README.md Creates a conda environment from environment.yml and activates it. Replace micromamba with your package manager if needed. ```bash micromamba env create -f environment.yml micromamba activate pyoperon ``` -------------------------------- ### Use SymbolicRegressor with EarlyStopping callback Source: https://github.com/heal-research/pyoperon/blob/main/README.md Demonstrates creating a SymbolicRegressor with a population size of 1000, 1000 generations, and an EarlyStopping callback with patience 20, then fitting it to data X and y. The callbacks argument enables monitoring or early stopping during fit(). ```python from pyoperon.sklearn import SymbolicRegressor from pyoperon import EarlyStopping reg = SymbolicRegressor( population_size=1000, generations=1000, callbacks=[EarlyStopping(patience=20)], ) reg.fit(X, y) ``` -------------------------------- ### Declare nanobind module and link operon Source: https://github.com/heal-research/pyoperon/blob/main/CMakeLists.txt Declares the pyoperon_pyoperon nanobind module with all source files, creates an alias target, finds the operon package, generates an export header, sets target properties, and links against operon::operon. ```cmake # ---- Declare library ---- nanobind_add_module( pyoperon_pyoperon MODULE NB_SUPPRESS_WARNINGS source/algorithm.cpp source/benchmark.cpp source/creator.cpp source/crossover.cpp source/dataset.cpp source/evaluator.cpp source/generator.cpp source/initializer.cpp source/mutation.cpp source/node.cpp source/non_dominated_sorter.cpp source/optimizer.cpp source/problem.cpp source/pset.cpp source/pyoperon.cpp source/reinserter.cpp source/selection.cpp source/tree.cpp ) add_library(pyoperon::pyoperon ALIAS pyoperon_pyoperon) find_package(operon CONFIG REQUIRED) include(GenerateExportHeader) generate_export_header( pyoperon_pyoperon BASE_NAME pyoperon EXPORT_FILE_NAME export/pyoperon/pyoperon_export.hpp CUSTOM_CONTENT_FROM_VARIABLE pragma_suppress_c4251 ) set_target_properties( pyoperon_pyoperon PROPERTIES CXX_VISIBILITY_PRESET hidden VISIBILITY_INLINES_HIDDEN YES VERSION "${PROJECT_VERSION}" SOVERSION "${PROJECT_VERSION_MAJOR}" EXPORT_NAME pyoperon OUTPUT_NAME pyoperon ) target_include_directories( pyoperon_pyoperon ${pyoperon_warning_guard} PUBLIC "$" ) target_include_directories( pyoperon_pyoperon SYSTEM PUBLIC "$" ) target_compile_features(pyoperon_pyoperon PUBLIC cxx_std_23) # this will link in operon's public dependencies: fmt, ceres, etc. target_link_libraries(pyoperon_pyoperon PRIVATE operon::operon) if (MSVC) target_compile_options(pyoperon_pyoperon PRIVATE "/std:c++latest") endif() if (APPLE) set_target_properties(pyoperon_pyoperon PROPERTIES VERSION "") endif() ``` -------------------------------- ### CMake configuration for pyoperon tests Source: https://github.com/heal-research/pyoperon/blob/main/test/CMakeLists.txt Configures the test project, finds the pyoperon package when top-level, and creates the test executable with C++17 support. ```cmake cmake_minimum_required(VERSION 3.14) project(pyoperonTests LANGUAGES CXX) include(../cmake/project-is-top-level.cmake) include(../cmake/windows-set-path.cmake) if(PROJECT_IS_TOP_LEVEL) find_package(pyoperon REQUIRED) enable_testing() endif() add_executable(pyoperon_test source/pyoperon_test.cpp) target_link_libraries(pyoperon_test PRIVATE pyoperon::pyoperon) target_compile_features(pyoperon_test PRIVATE cxx_std_17) add_test(NAME pyoperon_test COMMAND pyoperon_test) windows_set_path(pyoperon_test pyoperon::pyoperon) ``` -------------------------------- ### Import SymbolicRegressor from pyoperon.sklearn Source: https://github.com/heal-research/pyoperon/blob/main/README.md Shows how to import the scikit-learn compatible regressor from the pyoperon.sklearn module. ```python from pyoperon.sklearn import SymbolicRegressor ``` -------------------------------- ### Fit SymbolicRegressor with sample_weight Source: https://github.com/heal-research/pyoperon/blob/main/README.md Shows how to pass sample_weight to fit() for training on non-uniformly sampled data, following the scikit-learn convention. ```python reg.fit(X, y, sample_weight=sample_weight) ``` -------------------------------- ### Fetch PMLB dataset '1027_ESL' Source: https://github.com/heal-research/pyoperon/blob/main/example/operon-sklearn.ipynb Loads the '1027_ESL' regression dataset from PMLB, returning features X and target y, with a local cache directory './datasets'. ```python X, y = fetch_data('1027_ESL', return_X_y=True, local_cache_dir='./datasets') ``` -------------------------------- ### Constructor binding with keep_alive for stored dependencies Source: https://github.com/heal-research/pyoperon/blob/main/docs/binding-lifetime.md Use nb::keep_alive<1, N>() for each stored argument in a constructor that takes pointers/references. 1 is self for constructor bindings, N is the 1-based Python argument index. Add one keep_alive per independently stored dependency. ```cpp nb::class_(m, "Foo") .def(nb::init(), nb::keep_alive<1, 2>(), nb::keep_alive<1, 3>()); ``` -------------------------------- ### Train SymbolicRegressor with Pareto front objectives Source: https://github.com/heal-research/pyoperon/blob/main/example/operon-sklearn.ipynb Splits the data into train/test sets and fits a SymbolicRegressor with objectives 'poisson' and 'length', collecting objective values from the Pareto front. Uses 8 threads, max 1e6 evaluations, and a tournament size of 3. ```python reps = 1 values = [] for _ in range(reps): X_train, X_test, y_train, y_test = train_test_split(X, y, train_size=0.75, test_size=0.25, shuffle=True) reg = SymbolicRegressor( allowed_symbols='add,sub,mul,aq,sin,constant,variable', offspring_generator='basic', optimizer_iterations=10, max_length=50, initialization_method='btc', n_threads=8, objectives = ['poisson', 'length'], epsilon = 0, random_state=None, reinserter='keep-best', max_evaluations=int(1e6), symbolic_mode=False, tournament_size=3 ) reg.fit(X_train, y_train) values += [t['objective_values'] for t in reg.pareto_front_] ``` -------------------------------- ### Returning ndarray view into internal memory with owner Source: https://github.com/heal-research/pyoperon/blob/main/docs/binding-lifetime.md Any nb::ndarray that points to memory owned by a C++ object must carry that owner using nb::find(self). Do not use nb::handle() (null owner) for internal memory views. Use a nb::capsule owner only when memory is heap-allocated specifically for the return value. ```cpp return nb::ndarray( ptr, ndim, shape, nb::find(self), strides ); ``` -------------------------------- ### Method binding with keep_alive for stored non-owning input Source: https://github.com/heal-research/pyoperon/blob/main/docs/binding-lifetime.md If a method stores a pointer/reference/span to its argument, tie lifetime with keep_alive. For container inputs, prefer bound container types and add .noconvert() where needed to avoid temporary materialization. ```cpp .def("SetDependency", &Foo::SetDependency, nb::keep_alive<1, 2>()) ``` -------------------------------- ### Plot Pareto front with seaborn scatterplot Source: https://github.com/heal-research/pyoperon/blob/main/example/operon-sklearn.ipynb Creates a scatter plot of the Pareto front objectives: tree length (x-axis) vs. -R2 (y-axis). Includes grid and axis labels. May produce FutureWarnings from seaborn's internal categorical dtype check. ```python import matplotlib.pyplot as plt import seaborn as sns values = np.array(values) fig, ax = plt.subplots(figsize=(18,8)) ax.grid(True, linestyle='dotted') ax.set(xlabel='Obj 1 (Tree length)', ylabel='Obj 2 (-R2)') sns.scatterplot(ax=ax, x=values[:,1], y=values[:,0]) ```