### Configure and Install kep3 and pykep from Source Source: https://github.com/esa/pykep/blob/master/README.md These commands configure the build process using CMake, specifying installation paths and enabling Python bindings, then build and install the libraries. This is recommended for v3 development. ```bash cmake -S . -B build -G Ninja \ -DCMAKE_EXPORT_COMPILE_COMMANDS=1 \ -DCMAKE_INSTALL_PREFIX="$CONDA_PREFIX" \ -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" \ -Dkep3_BUILD_PYTHON_BINDINGS=ON cmake --build build --target install --parallel ``` -------------------------------- ### Setup CMake Package Configuration File Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Configures and installs the CMake package configuration file for 'kep3', enabling proper package discovery by other projects. ```cmake include(CMakePackageConfigHelpers) configure_package_config_file( "${CMAKE_CURRENT_SOURCE_DIR}/kep3-config.cmake.in" "${CMAKE_CURRENT_BINARY_DIR}/kep3-config.cmake" INSTALL_DESTINATION "${kep3_INSTALL_LIBDIR}/cmake/kep3") install(FILES "${CMAKE_CURRENT_BINARY_DIR}/kep3-config.cmake" DESTINATION "${kep3_INSTALL_LIBDIR}/cmake/kep3") install( EXPORT kep3_export NAMESPACE kep3:: DESTINATION "${kep3_INSTALL_LIBDIR}/cmake/kep3") write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/kep3-config-version.cmake" COMPATIBILITY SameMinorVersion) install(FILES "${CMAKE_CURRENT_BINARY_DIR}/kep3-config-version.cmake" DESTINATION "${kep3_INSTALL_LIBDIR}/cmake/kep3") ``` -------------------------------- ### Full CMake Configure Command Example Source: https://github.com/esa/pykep/blob/master/README.md This example demonstrates a complete configure command including core and common optional targets for building pykep with Ninja. ```bash cmake -S . -B build -G Ninja \ -DCMAKE_EXPORT_COMPILE_COMMANDS=1 \ -DCMAKE_INSTALL_PREFIX="$CONDA_PREFIX" \ -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" \ -Dkep3_BUILD_PYTHON_BINDINGS=ON \ -Dkep3_BUILD_TESTS=ON \ -Dkep3_BUILD_BENCHMARKS=ON ``` -------------------------------- ### Configure and Install Header Files Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Configures the 'config.hpp' file using a template and installs header files to the appropriate destinations. ```cmake configure_file("${CMAKE_CURRENT_SOURCE_DIR}/config.hpp.in" "${CMAKE_CURRENT_SOURCE_DIR}/include/kep3/config.hpp" @ONLY) install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/include/kep3" DESTINATION include) install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/include/kep3/config.hpp" DESTINATION include/kep3) ``` -------------------------------- ### Install Shared Library Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Installs the 'kep3' shared library, archive, and runtime components to specified destinations. ```cmake install( TARGETS kep3 EXPORT kep3_export LIBRARY DESTINATION "${kep3_INSTALL_LIBDIR}" ARCHIVE DESTINATION "${kep3_INSTALL_LIBDIR}" RUNTIME DESTINATION bin) ``` -------------------------------- ### Install Core Module Source: https://github.com/esa/pykep/blob/master/pykep/CMakeLists.txt Installs the 'core' target (runtime and library files) to the determined pykep installation directory. ```cmake install(TARGETS core RUNTIME DESTINATION ${_PYKEP_INSTALL_DIR} LIBRARY DESTINATION ${_PYKEP_INSTALL_DIR} ) ``` -------------------------------- ### Install Python Files Source: https://github.com/esa/pykep/blob/master/pykep/CMakeLists.txt Installs all Python files listed in PYKEP_PYTHON_FILES to the pykep installation directory. ```cmake install(FILES ${PYKEP_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}) ``` -------------------------------- ### Configure Wheel Setup Files Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Configures setup.py and optionally setup.cfg for building Python wheels. The setup.cfg is Linux-specific. ```cmake message(STATUS "Creating the files for the generation of a binary wheel.") set(PYKEP_VERSION ${kep3_VERSION}) file(MAKE_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/wheel") configure_file("${CMAKE_SOURCE_DIR}/tools/wheel_setup.py" "${CMAKE_CURRENT_BINARY_DIR}/wheel/setup.py" @ONLY) if(${CMAKE_SYSTEM_NAME} MATCHES "Linux") # NOTE: keep this Linux-only to mirror ppnf wheel generation. configure_file("${CMAKE_SOURCE_DIR}/tools/wheel_setup.cfg" "${CMAKE_CURRENT_BINARY_DIR}/wheel/setup.cfg" @ONLY) endif() ``` -------------------------------- ### Install Pykep using Pip Source: https://github.com/esa/pykep/blob/master/README.md Use this command to install pykep via PyPI. Currently, only v1 is available on PyPI. ```bash pip install pykep ``` -------------------------------- ### Install Pykep Leg Python Files Source: https://github.com/esa/pykep/blob/master/pykep/leg/CMakeLists.txt Installs the Python files defined for the Pykep leg module to the specified installation directory. This ensures the module is available after installation. ```cmake install(FILES ${PYKEP_LEG_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}/leg) ``` -------------------------------- ### Install Pykep Data Files Source: https://github.com/esa/pykep/blob/master/pykep/data/CMakeLists.txt Installs specified data files into the Pykep installation directory. These files are essential for ephemeris calculations and time conversions. ```cmake set(PYKEP_DATA_PYTHON_FILES de440s.bsp tle.txt naif0012.tls) install(FILES ${PYKEP_DATA_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}/data) ``` -------------------------------- ### Verify pykep Installation Source: https://github.com/esa/pykep/blob/master/doc/installation.rst Confirms the pykep installation by importing the library and printing its version number using Python. ```console $ python -c "import pykep; print(pykep.__version__)" ``` -------------------------------- ### Configure and Build pykep from Source Source: https://github.com/esa/pykep/blob/master/doc/installation.rst Configures the build using CMake with specified flags for installation prefix, dependency resolution, and Python bindings, then builds the project using Ninja. ```console $ cmake -S . -B build -G Ninja \ -DCMAKE_EXPORT_COMPILE_COMMANDS=1 \ -DCMAKE_INSTALL_PREFIX="$CONDA_PREFIX" \ -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" \ -D kep3_BUILD_PYTHON_BINDINGS=ON $ cmake --build build --target install --parallel ``` -------------------------------- ### Include Directories Configuration Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Configures include directories for the 'kep3' target, specifying build, binary, and installation paths. ```cmake target_include_directories( kep3 PUBLIC $ $ $) ``` -------------------------------- ### Set Library Installation Directory Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Configures the library installation directory, using GNUInstallDirs on Unix-like systems (excluding macOS) to determine the correct path. Defaults to 'lib' otherwise. The 'kep3_INSTALL_LIBDIR' variable can be overridden by the user. ```cmake if(UNIX AND NOT APPLE) include(GNUInstallDirs) set(_kep3_INSTALL_LIBDIR_DEFAULT "${CMAKE_INSTALL_LIBDIR}") else() set(_kep3_INSTALL_LIBDIR_DEFAULT "lib") endif() if(NOT kep3_INSTALL_LIBDIR) set(kep3_INSTALL_LIBDIR "${_kep3_INSTALL_LIBDIR_DEFAULT}" CACHE STRING "Library installation directory." FORCE) endif() mark_as_advanced(kep3_INSTALL_LIBDIR) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/esa/pykep/blob/master/doc/notebooks/anomalies.ipynb Imports the pykep, numpy, time, and matplotlib libraries for use in the examples. ```python import pykep as pk import numpy as np import time from matplotlib import pyplot as plt ``` -------------------------------- ### Install Pykep Plot Python Files Source: https://github.com/esa/pykep/blob/master/pykep/plot/CMakeLists.txt Installs the Python files defined in PYKEP_PLOT_PYTHON_FILES to the specified installation directory. ```cmake install(FILES ${PYKEP_PLOT_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}/plot) ``` -------------------------------- ### Testcase Setup for Single Shooting Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Sets up a test case for solving a transfer problem using single shooting in pykep. Includes defining source and target planets, time of flight guess, gravitational parameter, and initial spacecraft properties. ```python # Testcase 1 source=pk.planet(pk.udpla.jpl_lp("earth")) target=pk.planet(pk.udpla.jpl_lp("mars")) tof_guess = 250 mu = pk.MU_SUN olds = 1e-5 T_max = 6. Isp = 3000 m0 = 1500 n_rev=0 ``` -------------------------------- ### Install pykep using Pip Source: https://github.com/esa/pykep/blob/master/doc/installation.rst Installs pykep using pip. Prebuilt binary wheels are available for Linux (x86-64 and arm64). Note potential conflicts with other packages bundling C++ libraries. ```console $ pip install pykep ``` -------------------------------- ### Create and Activate Development Environment Source: https://github.com/esa/pykep/blob/master/doc/installation.rst Sets up a dedicated conda environment for development, installing all mandatory C++ and Python dependencies for pykep. ```console $ conda env create -f kep3_devel.yml $ conda activate kep3_devel ``` -------------------------------- ### Validate Pykep Installation Source: https://github.com/esa/pykep/blob/master/README.md Run this Python command to verify that pykep has been installed correctly and to check its version. ```python python -c "import pykep; print(pykep.__version__)" ``` -------------------------------- ### Single Shooting Test Case Setup (Heliocentric Transfer) Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_mass.ipynb Sets up initial and final position/velocity states, time of flight, and gravitational parameter for a direct TPBVP solve at a small epsilon, suitable for well-conditioned transfers. ```python # Test case 1: direct solve at small epsilon (no continuation) posvel0 = [ [34110913367.783306, -139910016918.87585, -14037825669.025244], [29090.9902134693, 10000.390168313803, 1003.3858682643288], ] posvelf = [ [-159018773159.22266, -18832495968.945133, 15781467087.350443], [2781.182556622003, -28898.40730995848, -483.4533989771214], ] tof = 250 mu = pk.MU_SUN ``` -------------------------------- ### Install Python Files for Pykep TA Source: https://github.com/esa/pykep/blob/master/pykep/ta/CMakeLists.txt Installs the Python files for the pykep/ta module to the specified destination directory. ```cmake set(PYKEP_TA_PYTHON_FILES __init__.py _zoh_kep.py _zoh_eq.py _zoh_cr3bp.py _zoh_ss.py) install(FILES ${PYKEP_TA_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}/ta) ``` -------------------------------- ### Basic Imports for Pykep and Pygmo Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_sf_point2point.ipynb Imports necessary libraries for trajectory optimization, including pykep, numpy, time, and pygmo. Ensure pykep and pygmo are installed. ```python import pykep as pk import numpy as np import time import pygmo as pg import pygmo_plugins_nonfree as ppnf import time from matplotlib import pyplot as plt ``` -------------------------------- ### CR3BP and BCP Initial State Setup and Integration Source: https://github.com/esa/pykep/blob/master/doc/notebooks/ta_cr3bp_bcp.ipynb Sets the initial state for CR3BP and BCP models, calculates the Jacobi constant, and propagates trajectories over a defined time grid. Ensure `ta_cr3bp`, `ta_bcp`, `jacobi_C`, `CR3BP_MU`, and `np.linspace` are properly initialized and imported. ```python ta_cr3bp.time = 0.0 ta_cr3bp.state[:] = [x, 0, 0, 0.0, vy-2.705, 0.0] ta_bcp.time = 0.0 ta_bcp.state[:] = ta_cr3bp.state C = jacobi_C(ta_cr3bp.state, pars=[CR3BP_MU]) t_grid = np.linspace(0, 4*np.pi, 1000) sol_cr3bp = ta_cr3bp.propagate_grid(t_grid) sol_bcp = ta_bcp.propagate_grid(t_grid) print("Value of the Jacobi constant C:", C) ``` -------------------------------- ### Run Multi-Start with IPOPT Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Executes the multi-start optimization strategy using the configured IPOPT algorithm for 10 trials. ```python pop = multistart(ipopt, n_trials=10) ``` -------------------------------- ### Run Multistart with MINPACK (with gradient) Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_mass.ipynb Applies the multistart strategy using the configured MINPACK solver (with gradient computation) for 40 trials. ```python pop = multistart(minpack_g, 40) ``` -------------------------------- ### Import Libraries and Set Up Environment Source: https://github.com/esa/pykep/blob/master/doc/notebooks/primer_vector.ipynb Imports necessary libraries for Pykep and numerical operations. Sets the print options for NumPy arrays. ```python import pykep as pk import numpy as np np.set_printoptions(legacy="1.25") import matplotlib.pyplot as plt ``` -------------------------------- ### Install Python Files for Pykep UDPLA Source: https://github.com/esa/pykep/blob/master/pykep/udpla/CMakeLists.txt Installs a list of Python files to the specified destination directory within the pykep installation. This is typically used in a CMake build system to ensure Python modules are correctly placed. ```cmake set(PYKEP_UDPLA_PYTHON_FILES __init__.py _tle.py _spice.py _cr3bp.py) install(FILES ${PYKEP_UDPLA_PYTHON_FILES} DESTINATION ${_PYKEP_INSTALL_DIR}/udpla) ``` -------------------------------- ### Initialize Homotopy Parameters Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_mass.ipynb Sets up initial parameters for an exponential homotopy optimization. Includes importing necessary modules like `time`, `deepcopy`, and `clear_output`. Initializes `epsilon` and `decrease_factor` for the homotopy process. ```python import time from copy import deepcopy from IPython.display import clear_output # No initial guess first = True epsilon = 1e-1 decrease_factor = 0.85 ``` -------------------------------- ### Initialization Parameters for Homotopy Continuation Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_mass.ipynb Sets up initial parameters for the homotopy continuation solver, including the `first` iteration flag, the initial `epsilon` value, and the `decrease_factor` for epsilon. ```python import time from copy import deepcopy from IPython.display import clear_output # No initial guess first = True epsilon = 1e-1 decrease_factor = 0.75 ``` -------------------------------- ### Initialize UDP with Taylor-Adaptive Integrators Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_zoh_pl2pl.ipynb Sets up nominal and variational dynamics integrators and prints their state dimensions. The pars[4] attribute is set based on veff_nd. ```python ta.pars[4] = 1.0 / veff_nd ta_var.pars[4] = 1.0 / veff_nd print(f"Nominal integrator state dimension: {len(ta.state)}") print(f"Variational integrator state dimension: {len(ta_var.state)}") ``` -------------------------------- ### Find Installed kep3 Library Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Locates an installed 'kep3' library using its version. If not found, it displays a fatal error message. ```cmake find_package(kep3 ${PROJECT_VERSION} CONFIG) if(NOT kep3_FOUND) message( FATAL_ERROR "kep3 C++ library (version ${PROJECT_VERSION}) was not found. " "Either install it first, or set kep3_BUILD_CPP_LIBRARY=ON to build it from source." ) endif() ``` -------------------------------- ### Run Multi-Start with MINPACK (Gradient) Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Executes the multi-start optimization strategy using the MINPACK solver with gradient calculation enabled for 10 trials. ```python pop = multistart(minpack_g, n_trials=10) ``` -------------------------------- ### Initialize TOPS Two-Body Moving-Boundary Benchmark Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_zoh_pl2pl.ipynb Builds a wrapped UDP instance for a specific TOPS benchmark case ('P0') with a given number of segments and time encoding. Prints extra information about the selected benchmark. ```python # 1) Select a TOPS benchmark case and build the wrapped UDP prob_name = "P0" udp = pk.trajopt.gym.tops_twobody_mb(prob_name, nseg=10, time_encoding="uniform") print(udp.extra_info) ``` -------------------------------- ### Install Pykep using Conda Source: https://github.com/esa/pykep/blob/master/README.md Use this command to install pykep via conda-forge. Note that v3 packages will be published once the API is stabilized. ```bash conda install -c conda-forge pykep ``` -------------------------------- ### Run Multistart with IPOPT Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_mass.ipynb Applies the multistart strategy using the configured IPOPT algorithm for 40 trials to solve the Pontryagin Cartesian Mass problem. ```python pop = multistart(ipopt, 40) ``` -------------------------------- ### Determine pykep Installation Directory Source: https://github.com/esa/pykep/blob/master/pykep/CMakeLists.txt Determines the installation directory for pykep. It defaults to Python's site-packages directory if PYKEP_INSTALL_PATH is not set, otherwise uses the custom path. ```cmake if(PYKEP_INSTALL_PATH STREQUAL "") message(VERBOSE "pykep install location (default): ${Python3_SITEARCH}") set(_PYKEP_INSTALL_DIR "${Python3_SITEARCH}/pykep") else() message(VERBOSE "pykep install location (custom): ${PYKEP_INSTALL_PATH}") set(_PYKEP_INSTALL_DIR "${PYKEP_INSTALL_PATH}/pykep") endif() ``` -------------------------------- ### Configure IPOPT Solver Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Sets up the IPOPT (Interior Point Optimizer) algorithm from pygmo with specific numeric and integer options for trajectory optimization. This includes setting convergence tolerance, maximum iterations, and suppressing console output. ```python ip = pg.ipopt() ip.set_numeric_option("tol", 1e-9) # Relative convergence tolerance ip.set_integer_option("max_iter", 50) # Maximum iterations ip.set_integer_option("print_level", 0) # Suppress IPOPT console output ip.set_string_option("sb", "yes") ip.set_string_option("nlp_scaling_method", "none") # Disable IPOPT automatic scaling ip.set_string_option("mu_strategy", "adaptive") # Adaptive barrier update strategy ipopt = pg.algorithm(ip) ``` -------------------------------- ### Pykep Pre-assembled Integrators and Evaluators Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_mass.ipynb Demonstrates the use of Pykep's pre-assembled components for obtaining the Taylor integrator, variational integrator, Hamiltonian, switching function, and throttle magnitude, which are preferred for robust workflows. ```python # The Taylor integrator ta = _pk.ta.get_peq(1e-16, _pk.optimality_type.MASS) # The Variational Taylor integrator ta = _pk.ta.get_peq_var(1e-16, _pk.optimality_type.MASS) # The Hamiltonian H_func = _pk.ta.get_peq_H_cfunc(_pk.optimality_type.MASS) # The switching function SF_func = _pk.ta.get_peq_SF_cfunc(_pk.optimality_type.MASS) # The magnitude of the throttle u_func = _pk.ta.get_peq_u_cfunc(_pk.optimality_type.MASS) ``` -------------------------------- ### Initialize CR3BP Propagation with Initial Conditions Source: https://github.com/esa/pykep/blob/master/doc/notebooks/leg_zoh.ipynb Sets up the CR3BP propagation using `taylor_adaptive` with specific physical parameters and an initial condition for a known periodic orbit. Ensure `veff_nd` and `mu` are defined before use. ```python mu = 0.01215058560962404 ic = np.array([5.5643551520142581e-02, 9.2420772211102929e-27, 1.3616512785913887e-31, 2.6173746491479341e-12, 5.2390814115699671e+00, 5.3268092625591314e-30, 1000/MASS]) period = 6.301205688481844 ta_cr3bp.pars[4] = 1./veff_nd ta_cr3bp.pars[5] = mu ta_cr3bp_var.pars[4] = 1./veff_nd ta_cr3bp_var.pars[5] = mu ``` -------------------------------- ### Get Thrust Direction Function Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Retrieve the function defining the thrust direction for time-optimal control. ```python i_vers_func = pk.ta.get_pc_i_vers_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Define System and Sailcraft Parameters Source: https://github.com/esa/pykep/blob/master/doc/notebooks/ta_zoh_ss.ipynb Sets up physical constants and sail characteristics for the Altaira system and sailcraft. ```python # We define our units MU = 139348062043.343e9 # this is the MU of the ALTAIRA star L = 149597870.691e3 # this is the reference radius (1AU) where th Altaira flux is given V = np.sqrt(MU / L) TIME = L / V ACC = V / TIME MASS = 500 # These are the sail physical characteristics SAIL_C = 5.4026e-6 # in N/m^2 SAIL_A = 15000 # in m^2 SAIL_MASS = 500 # in kg ``` -------------------------------- ### Get Current Epoch Source: https://github.com/esa/pykep/blob/master/doc/notebooks/epochs.ipynb Creates an epoch object representing the current time (UTC style). ```python ep = pk.epoch.now() print(ep) ``` -------------------------------- ### Get Throttle Magnitude Function Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Retrieve the function for the magnitude of the throttle, which is always 1 for time-optimal control. ```python u_func = pk.ta.get_pc_u_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Configure IPOPT Optimizer Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Sets up the IPOPT optimizer with specific integer and string options for solving the optimization problem. Adjusts maximum iterations, print level, and scaling methods. ```python ip = pg.ipopt() #ip.set_numeric_option("tol", 1e-1) # Change the relative convergence tolerance ip.set_integer_option("max_iter", 200) # Change the maximum iterations ip.set_integer_option("print_level", 0) # Makes Ipopt unverbose ip.set_string_option( "sb", "yes" ) ip.set_string_option( "nlp_scaling_method", "none" # Removes any scaling made in auto mode ) ip.set_string_option( "mu_strategy", "adaptive" # Alternative is to tune the initial mu value ) ipopt200 = pg.algorithm(ip) ip.set_integer_option("max_iter", 20) # Change the maximum iterations ipopt20 = pg.algorithm(ip) ``` -------------------------------- ### Get Dynamics Function Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Retrieve the dynamics function for time-optimal control problems using the Pontryagin Cartesian method. ```python dyn_func = pk.ta.get_pc_dyn_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Import necessary libraries Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_mga.ipynb Import pykep, pygmo, and matplotlib for trajectory optimization and plotting. ```python import pykep as pk import pygmo as pg import matplotlib.pyplot as plt ``` -------------------------------- ### Get Switching Function Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Retrieve the switching function for time-optimal control. This function is always negative for time-optimal cases. ```python SF_func = pk.ta.get_pc_SF_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Get Hamiltonian Function Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Retrieve the Hamiltonian function for time-optimal control problems using the Pontryagin Cartesian method. ```python H_func = pk.ta.get_pc_H_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Add Subdirectory for pykep Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Adds the pykep subdirectory to the build. This is typically done after configuring wheel setup files. ```cmake add_subdirectory("${CMAKE_SOURCE_DIR}/pykep") ``` -------------------------------- ### Use Pre-built CR3BP UDPLA Source: https://github.com/esa/pykep/blob/master/doc/notebooks/planet.ipynb This snippet shows how to use the convenience function `pk.udpla.cr3bp` which is already provided by pykep. This function simplifies the creation of CR3BP UDPLAs, eliminating the need to define a custom class for common scenarios. ```python # The above udpla is actually provided for your convenience already in pykep as pk.udpla.cr3bp station = pk.udpla.cr3bp( 0.0, [1.0809931218390707, 0.0, -0.20235953267405354, 0.0, -0.19895001215078018, 0.0], pk.CR3BP_MU_EARTH_MOON, L=384400000, TIME=375000, tol=1e-16, ) ``` -------------------------------- ### Instantiate Taylor Integrator Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Get the Pontryagin Cartesian Taylor integrator for time-optimal control. The first argument is the desired precision. ```python ta = pk.ta.get_pc(1e-16, pk.optimality_type.TIME) ``` -------------------------------- ### Define pykep Python Files Source: https://github.com/esa/pykep/blob/master/pykep/CMakeLists.txt Sets a list of all Python files belonging to the pykep package. This list is used for installation purposes. ```cmake set(PYKEP_PYTHON_FILES __init__.py _patch_planet.py _patch_epoch.py _version.py test.py test_ta.py test_trajopt.py test_utils.py test_leg_sims_flanagan.py test_leg_zoh.py test_core.py test_udplas.py) ``` -------------------------------- ### Define Python Files for Pykep Leg Source: https://github.com/esa/pykep/blob/master/pykep/leg/CMakeLists.txt Specifies the Python files that belong to the Pykep leg module. These files are used for installation. ```cmake set(PYKEP_LEG_PYTHON_FILES __init__.py _zoh.py) ``` -------------------------------- ### Problem and Population Initialization for Optimization Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_sf_point2point.ipynb Creates pygmo problem instances for both UDPs (with and without gradient) and initializes a population for the gradient-enabled problem. Sets constraint tolerances. ```python prob_nog = pg.problem(udp_nog) prob_nog.c_tol = 1e-6 prob_g = pg.problem(udp_g) prob_g.c_tol = 1e-6 pop_g = pg.population(prob_g, 1) pop_g = algo.evolve(pop_g) print(prob_g.feasibility_f(pop_g.champion_f)) ``` -------------------------------- ### Initialize CR3BP and BCP Integrators Source: https://github.com/esa/pykep/blob/master/doc/notebooks/ta_cr3bp_bcp.ipynb Initializes Taylor adaptive integrators for CR3BP and BCP, sets their parameters, and configures them for the Earth-Moon system. ```python # We get the Taylor adaptive integrator for the Circular Restricted 3-body Problem ta_cr3bp = pk.ta.get_cr3bp(tol=1e-16) # We get the Taylor adaptive integrator for the Bi-Circular Problem ta_bcp = pk.ta.get_bcp(tol=1e-16) # We set the parameters for the CR3BP (Earth-Moon) CR3BP_MU = pk.CR3BP_MU_EARTH_MOON ta_cr3bp.pars[:] = [CR3BP_MU] # We set the parameters for the Bi-Circular Problem (Earth-Moon-Sun) ta_bcp.pars[:] = [CR3BP_MU, pk.BCP_MU_S, pk.BCP_RHO_S, pk.BCP_OMEGA_S] ``` -------------------------------- ### Control C++ Library Build Source: https://github.com/esa/pykep/blob/master/README.md Set to OFF to build only Python bindings, tests, or benchmarks against an already installed kep3 library. Defaults to ON. ```cmake -Dkep3_BUILD_CPP_LIBRARY=OFF ``` -------------------------------- ### SF Point-to-Point UDP Initialization (No Gradient) Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_sf_point2point.ipynb Initializes the `sf_point2point` User Defined Problem (UDP) for trajectory optimization without gradient information. Specifies initial/final states, physical constants, thrust limits, and trajectory segment parameters. ```python # Throttles and tof nseg = 4 throttles = np.random.uniform(-1, 1, size=(nseg * 3)) tof = 2 * np.pi * np.sqrt(pk.AU**3 / pk.MU_SUN) / 4 udp_nog = pk.trajopt.sf_point2point( rvs=[rs, vs], rvf=[rf, vf], ms = 1000, mu=pk.MU_SUN, max_thrust=0.22, veff=3000*pk.G0, tof_bounds=[200, 500], mf_bounds=[200.0, 1000.0], nseg=nseg, cut=0.6, with_gradient=False, ) ``` -------------------------------- ### Instantiate Variational Taylor Integrator Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_cartesian_time.ipynb Get the Pontryagin Cartesian Variational Taylor integrator. 8 digits of precision are generally sufficient. ```python ta_var = pk.ta.get_pc_var(1e-8, pk.optimality_type.TIME) ``` -------------------------------- ### Set Initial Conditions for CR3BP Orbit Source: https://github.com/esa/pykep/blob/master/doc/notebooks/ta_cr3bp_bcp.ipynb Defines the initial conditions for generating an orbit in the Earth-Moon CR3BP, starting from a circular LEO. ```python EARTH_MOON_DISTANCE = 384400000 # Let us set the initial conditions in the Earth-Moon system. An equatorial LEO at an altitude of ~1700 km r = 8000000 / EARTH_MOON_DISTANCE # In the reference frame of the CR3BP, the initial coordinate is thus: x = -CR3BP_MU-r # The initial velocity is obtained from the circular velocity at the distance r from the center of mass. vy = -np.sqrt((1-CR3BP_MU)/r)+x ``` -------------------------------- ### Import Libraries for pykep and MEE Operations Source: https://github.com/esa/pykep/blob/master/doc/notebooks/equinoctial_elements.ipynb Import necessary libraries including heyoka for symbolic expressions, numpy for numerical operations, and pykep for orbital mechanics calculations. ```python import heyoka as hy import numpy as np import pykep as pk ``` -------------------------------- ### Summary of SPICE and SpiceyPy Benchmark Results Source: https://github.com/esa/pykep/blob/master/benchmark/notebooks/benchmarkudplaiface.ipynb Prints a summary of the calculated real-time performance for SPICE ephemeris calculations using pykep and SpiceyPy, comparing vectorized and non-vectorized methods. ```python # Summary print(f"udpla.eph -> {udplaeph:.5f}") print(f"pla.eph -> {plaeph:.5f}") print(f"eph_v.eph -> {plaephv:.5f}") print(f"spice -> {spicep:.5f}") print(f"spice_v -> {spicepv:.5f}") ``` -------------------------------- ### Visualize Trajectory Source: https://github.com/esa/pykep/blob/master/doc/notebooks/primer_vector.ipynb Generates a 3D plot of the computed trajectory, marking the start and impulse points, and overlays the orbits of the involved planets. ```python ax = pk.plot.make_3Daxis() ax.plot( [item[0][0] for item in posvels], [item[0][1] for item in posvels], [item[0][2] for item in posvels], ) ax.scatter3D( posvels[0][0][0], posvels[0][0][1], posvels[0][0][2], "ko", c="k", alpha=0.5 ) ax.scatter3D( posvels[103][0][0], posvels[103][0][1], posvels[103][0][2], "ko", c="k", alpha=0.5 ) ax.scatter3D( posvels[153][0][0], posvels[153][0][1], posvels[153][0][2], "ko", c="k", alpha=0.5 ) ax.scatter3D( posvels[175][0][0], posvels[175][0][1], posvels[175][0][2], "ko", c="k", alpha=0.5 ) pk.plot.add_planet_orbit(ax, start, units=1.0, alpha=0.3) pk.plot.add_planet_orbit(ax, target, units=1.0, alpha=0.3) ax.axis("off") ax.view_init(90, 0) ``` -------------------------------- ### Get pykep TPBVP Components Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Instantiates various pre-assembled components for the Two-Body Problem (TPBVP) using pykep. These are preferred for robust workflows. ```python # The Taylor integrator ta = pk.ta.get_peq(1e-16, pk.optimality_type.TIME) # The Variational Taylor integrator ta_var = pk.ta.get_peq_var(1e-16, pk.optimality_type.TIME) # The Hamiltonian H_func = pk.ta.get_peq_H_cfunc(pk.optimality_type.TIME) # The switching function SF_func = pk.ta.get_peq_SF_cfunc(pk.optimality_type.TIME) # The magnitude of the throttle u_func = pk.ta.get_peq_u_cfunc(pk.optimality_type.TIME) # The thrust direction i_vers_func = pk.ta.get_peq_i_vers_cfunc(pk.optimality_type.TIME) # The dynamics cfunc dyn_func = pk.ta.get_peq_dyn_cfunc(pk.optimality_type.TIME) ``` -------------------------------- ### Define Constants and Solver Parameters for Testcase 1 Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_mass.ipynb Configures the simulation parameters including time of flight, gravitational parameter, error tolerance, maximum thrust, specific impulse, initial mass, and number of revolutions. ```python tof = 250 mu = _pk.MU_SUN eps = 1e-5 T_max = 0.6 Isp = 3000 m0 = 1500 n_rev=0 ``` -------------------------------- ### Get Zero-Order Hold Solar Sail Integrator Source: https://github.com/esa/pykep/blob/master/doc/notebooks/ta_zoh_ss.ipynb Retrieves the zero-order hold integrator for simple solar sail dynamics with a specified tolerance. ```python # We get the Taylor adaptive integrator for the simple sail (zero-hold) dynamics ta = pk.ta.get_zoh_ss(tol=1e-16) ``` -------------------------------- ### Display Configuration Summary Source: https://github.com/esa/pykep/blob/master/CMakeLists.txt Outputs a summary of the current CMake configuration, including version, system details, compiler, build type, and enabled features. ```cmake message( STATUS "Config summary: kep3 ${kep3_VERSION} on ${CMAKE_SYSTEM_NAME}/${CMAKE_SYSTEM_PROCESSOR} with ${CMAKE_CXX_COMPILER_ID} ${CMAKE_CXX_COMPILER_VERSION}" ) message( STATUS "Config summary: build type=${CMAKE_BUILD_TYPE}, build_kep3=${kep3_BUILD_CPP_LIBRARY}, tests=${kep3_BUILD_TESTS}, benchmarks=${kep3_BUILD_BENCHMARKS}, python=${kep3_BUILD_PYTHON_BINDINGS}, verbose=${KEP3_VERBOSE_CONFIGURE}" ) message( STATUS "Config summary: install libdir=${kep3_INSTALL_LIBDIR}, deps Boost>=${_kep3_MIN_BOOST_VERSION}, fmt>=${_kep3_MIN_FMT_VERSION}, heyoka>=${_kep3_MIN_HEYOKA_VERSION}" ) ``` -------------------------------- ### Propagate Trajectory Segments Source: https://github.com/esa/pykep/blob/master/doc/notebooks/primer_vector.ipynb Propagates each segment of the trajectory using `propagate_lagrangian_grid`, applying delta-v at the start of each segment and handling state transfer between segments. ```python # First segment retval0 = pk.propagate_lagrangian_grid([r0, v0 + DV0], tgrid0, mu=pk.MU_SUN, stm=True) # Second segment retval1 = pk.propagate_lagrangian_grid( [retval0[-1][0][0], retval0[-1][0][1] + DV1], tgrid1, mu=pk.MU_SUN, stm=True ) # Third segment retval2 = pk.propagate_lagrangian_grid( [retval1[-1][0][0], retval1[-1][0][1] + DV2], tgrid2, mu=pk.MU_SUN, stm=True ) # We assemble all the trajectory in the same grid (these are the extra manipulations) stms = [item[1] for item in retval0] posvels = [item[0] for item in retval0] Mn0 = retval0[-1][1] Mmn = retval1[-1][1] retval1.pop(0) retval2.pop(0) for item in retval1: stms.append(item[1] @ Mn0) posvels.append(item[0]) for item in retval2: stms.append(item[1] @ Mmn @ Mn0) posvels.append(item[0]) #posvels[-1][1] = [a + b for a, b in zip(posvels[-1][1], DV3)] ``` -------------------------------- ### Load SPICE Kernel and Initialize SPICE Ephemeris Source: https://github.com/esa/pykep/blob/master/benchmark/notebooks/benchmarkudplaiface.ipynb Loads a SPICE kernel file and initializes a pykep planet object using SPICE data for Jupiter Barycenter. This sets up the system for SPICE-based ephemeris calculations. ```python pk.utils.load_spice_kernels("../../pykep/data/de440s.bsp") udpla = pk.udpla.spice("JUPITER BARYCENTER", "ECLIPJ2000", "SSB") pla = pk.planet(udpla) ``` -------------------------------- ### SNOPT7 Optimizer Configuration Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_sf_point2point.ipynb Configures the SNOPT7 optimizer with specific library path and iteration limits. This setup is required for running the optimization with gradient information. ```python snopt72 = "/Users/dario.izzo/opt/libsnopt7_c.dylib" uda = ppnf.snopt7(library=snopt72, minor_version=2, screen_output=False) uda.set_integer_option("Major iterations limit", 2000) uda.set_integer_option("Iterations limit", 20000) uda.set_numeric_option("Major optimality tolerance", 1e-3) uda.set_numeric_option("Major feasibility tolerance", 1e-12) # uda = pg.nlopt("slsqp") algo = pg.algorithm(uda) ``` -------------------------------- ### Instantiate Pontryagin Equinoctial Mass UDP Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_mass.ipynb Initializes the trajectory optimization UDP for Pontryagin's Minimum Principle with equinoctial states and mass optimization. Requires initial and final states, time of flight, gravitational parameter, and other mission-specific parameters. ```python udp = _pk.trajopt.pontryagin_equinoctial_mass( posvel0=posvel0, posvelf=posvelf, tof=tof, mu=mu, eps=eps, lambda0 = None, # use 0.3 in case no normalization is seeked. T_max=T_max, Isp=Isp, m0=m0, n_rev = n_rev, L=_pk.AU, MU=mu, MASS=m0, with_gradient=True, taylor_tolerance=1e-10, # lower tolerances with multiple rev can be an issue taylor_tolerance_var=1e-4, ) prob = pg.problem(udp) prob.c_tol = 1e-6 ``` -------------------------------- ### Create and Activate Development Environment Source: https://github.com/esa/pykep/blob/master/README.md This command creates a new conda environment using the specified YAML file and then activates it. This is part of the build-from-source installation process. ```bash conda env create -f kep3_devel.yml conda activate kep3_devel ``` -------------------------------- ### Get PMP Thrust Direction and Dynamics Functions Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_mass.ipynb Retrieves the thrust direction and dynamics functions for mass-optimal transfers using Pontryagin's Maximum Principle. ```python i_vers_func = _pk.ta.get_peq_i_vers_cfunc(_pk.optimality_type.MASS) dyn_func = _pk.ta.get_peq_dyn_cfunc(_pk.optimality_type.MASS) ``` -------------------------------- ### Load and Configure Solar-Sail UDP Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_zoh_point2point.ipynb Loads a TOPS solar-sail benchmark using pykep's trajopt gym. This UDP is based on the zoh_ss_point2point leg. 'nseg' defines the number of trajectory segments, and 'time_encoding' specifies the time representation. ```python # 1) Load a TOPS solar-sail benchmark prob_name = "P1" udp = pk.trajopt.gym.tops_ss(prob_name, nseg=10, time_encoding="uniform") print(udp.extra_info) # 2) Build pygmo wrapper prob = pg.problem(udp) prob.c_tol = 1e-7 # This affects pagmo feasibility checks, not IPOPT's internal tol ``` -------------------------------- ### Verify Gradients for Two-Body MEE Problem Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_zoh_point2point.ipynb Checks the consistency of analytical gradients against finite-difference approximations for the MEE dynamics. This step is essential for validating the optimization setup. ```python # Gradient consistency check for the MEE benchmark pop = pg.population(prob, 1) grad_err = pg.estimate_gradient_h(udp.fitness, pop.champion_x, dx=1e-8) - udp.gradient(pop.champion_x) grad_err.max(), grad_err.min() ``` -------------------------------- ### Get Ephemerides for a Specific Epoch Source: https://github.com/esa/pykep/blob/master/doc/notebooks/planet.ipynb Calculates and returns the position and velocity vectors for a planet at a given epoch. The epoch is specified using pykep's epoch object. ```python epoch = pk.epoch("2026-10-22 00:00:00:00") pla.eph(epoch) ``` -------------------------------- ### Define problem data and states Source: https://github.com/esa/pykep/blob/master/doc/notebooks/leg_sims_flanagan.ipynb Set up the gravitational parameter, maximum thrust, specific impulse, and initial/final spacecraft states (position, velocity, mass). ```python # Problem data mu = pk.MU_SUN max_thrust = 0.12 isp = 3000 # Initial state ms = 1500.0 rs = np.array([1, 0.1, -0.1]) * pk.AU vs = np.array([0.2, 1, -0.2]) * pk.EARTH_VELOCITY # Final state mf = 1300.0 rf = np.array([-1.2, -0.1, 0.1]) * pk.AU vf = np.array([0.2, -1.023, 0.44]) * pk.EARTH_VELOCITY # Throttles and tof nseg = 10 throttles = np.random.uniform(-1,1,size=(nseg*3)) tof = 324.0 * pk.DAY2SEC ``` -------------------------------- ### SF Point-to-Point UDP Initialization (With Gradient) Source: https://github.com/esa/pykep/blob/master/doc/notebooks/udp_sf_point2point.ipynb Initializes the `sf_point2point` User Defined Problem (UDP) for trajectory optimization with gradient information enabled. This version is intended for use with gradient-aware optimizers. ```python udp_g = pk.trajopt.sf_point2point( rvs=[rs, vs], rvf=[rf, vf], ms = 1000, mu=pk.MU_SUN, max_thrust=0.22, veff=3000*pk.G0, tof_bounds=[200, 500], mf_bounds=[200.0, 1000.0], nseg=nseg, cut=0.6, with_gradient=True, ) ``` -------------------------------- ### Get Rotation Matrix Between Frames Source: https://github.com/esa/pykep/blob/master/doc/notebooks/interface_to_spice.ipynb Obtain a rotation matrix to transform coordinates between two specified reference frames. This is useful when you need to manually convert positions or velocities. ```python R = pk.utils.rotation_matrix("ECLIPJ2000", "J2000") ``` -------------------------------- ### Core CMake Flags for Pykep Build Source: https://github.com/esa/pykep/blob/master/README.md These flags are essential for configuring the build. They control compilation database generation, installation paths, dependency resolution, and Python binding enablement. ```cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_INSTALL_PREFIX="$CONDA_PREFIX" -DCMAKE_PREFIX_PATH="$CONDA_PREFIX" -Dkep3_BUILD_PYTHON_BINDINGS=ON ``` -------------------------------- ### Compare Epochs Source: https://github.com/esa/pykep/blob/master/doc/notebooks/epochs.ipynb Demonstrates basic comparison operators for epoch objects. ```python print(ep < ep + 4) print(ep == ep + datetime.timedelta(days=32) - 32) ``` -------------------------------- ### Multi-Start Optimization Strategy Source: https://github.com/esa/pykep/blob/master/doc/notebooks/pontryagin_equinoctial_time.ipynb Implements a multi-start strategy to run a given algorithm multiple times and collect successful results. This is useful for indirect shooting methods sensitive to initialization. ```python def multistart(algo, n_trials=50): masses = [] xs = [] total_time = 0.0 success=0 for i in range(n_trials): pop = pg.population(prob,1) time_start = time.time() pop = algo.evolve(pop) time_end = time.time() total_time += time_end - time_start if prob.feasibility_f(pop.champion_f): print(".", end="") udp.fitness(pop.champion_x) xs.append(pop.champion_x) masses.append(udp.ta.state[6]) success+=1 else: print("x", end="") if masses: print(f"\nFinal mass is: {masses[0]*udp.MASS}") print(f"Total time to success: {total_time:.3f} seconds") print(f"Number of successes: {success} over {n_trials} trials ({success/n_trials*100:.1f} %)") else: print("\nNo success") return pop ``` -------------------------------- ### Get DE440s Kernel File Path Source: https://github.com/esa/pykep/blob/master/doc/notebooks/interface_to_spice.ipynb Retrieves the file path for the DE440 ephemerides kernel, which is included with pykep for convenience. This kernel contains ephemeris data for various solar system bodies. ```python de440s_kernel = pk.udpla.de440s.kernel_file() print(de440s_kernel) ```