### Install pycvxset Source: https://context7.com/merlresearch/pycvxset/llms.txt Install the pycvxset package using pip. ```bash pip install pycvxset ``` -------------------------------- ### Install PyCvxset with Docs and Test Dependencies Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Installs pycvxset along with all dependencies needed for documentation generation and testing. ```bash pip install -e ".[with_docs_and_tests]" ``` -------------------------------- ### Install PyCvxset with Test Dependencies Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Installs pycvxset along with additional dependencies required for running tests. ```bash pip install -e ".[with_tests]" ``` -------------------------------- ### Install pycddlib on Ubuntu Source: https://github.com/merlresearch/pycvxset/blob/main/docs/source/index.md Installs gmp and cddlib development libraries required for pycddlib on Ubuntu. ```bash $ sudo apt-get install libgmp-dev libcdd-dev python3-dev ``` -------------------------------- ### Install pycddlib on MacOS Source: https://github.com/merlresearch/pycvxset/blob/main/docs/source/index.md Installs gmp and cddlib using Homebrew, upgrades pip, and installs pycddlib with specific compiler flags. ```bash % brew install gmp cddlib % python3 -m pip install --upgrade pip % env "CFLAGS=-I$(brew --prefix)/include -L$(brew --prefix)/lib" python -m pip install pycddlib==3.0.0 ``` -------------------------------- ### Serve Local Documentation Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Starts a local HTTP server to view the generated HTML documentation, including API docs, tutorials, and code coverage reports. ```bash python -m http.server --directory ./docs/build/ ``` -------------------------------- ### Scaling and Transformation of Polytope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Illustrates scaling and transformation of a polytope. The example shows a polytope growing in the x-direction and shrinking in the y-direction, visualized with different colors. ```python patch_args_old = { "facecolor": OLD_POLYTOPE_COLOR_1, "label": "Original polytope", } patch_args_new = { "facecolor": NEW_POLYTOPE_COLOR, "label": "Affine transformed polytope", } P = Polytope(V=spread_points_on_a_unit_sphere(2, 7)[0]) new_P = [[2, 0], [0, 0.5]] @ P ax, _, _ = P.plot(patch_args=patch_args_old) new_P.plot(ax=ax, patch_args=dict(patch_args_new, **{"alpha": 0.5})) ax.legend(loc="lower right", bbox_to_anchor=(1, 0)) ax.grid() ax.set_xlabel("x") ax.set_ylabel("y") ax.set_title("Grow in x, but shrink in y") ``` -------------------------------- ### Physical Example: Reachable Set Computation Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Application_Reachability.ipynb Applies the backward robust reachable set computation to a physical example, analyzing different disturbance scalings and set representations (Polytope and ConstrainedZonotope). It measures computation time and set area. ```python k_backward_robust_reachable_set = 20 DISTURBANCE_SCALING_LIST = [0, 0.2, 0.4, 0.8] # Define the terminal set and input set (Polytope) terminal_set_polytope = Polytope(c=[0, 0], h=[0.75, 0.25]) input_set_polytope = Polytope(lb=-1, ub=1) # Define the terminal set and input set (Constrained zonotope) terminal_set_constrained_zonotope = ConstrainedZonotope( c=[0, 0], h=[0.75, 0.25] ) input_set_constrained_zonotope = ConstrainedZonotope(lb=-1, ub=1) # Recursion list_of_backward_robust_reachable_sets_dict = [None] * 2 elapsed_time = np.zeros((len(DISTURBANCE_SCALING_LIST), 2)) area_of_sets = np.zeros((len(DISTURBANCE_SCALING_LIST), 2)) for index, [input_set, terminal_set] in enumerate( [ [input_set_polytope, terminal_set_polytope], [ input_set_constrained_zonotope, terminal_set_constrained_zonotope, ], ] ): list_of_backward_robust_reachable_sets_dict[index] = {} for disturbance_index, disturbance_scaling in enumerate( DISTURBANCE_SCALING_LIST ): start_time = time.time() disturbance_set = disturbance_scaling * input_set list_of_backward_robust_reachable_sets_dict[index][ disturbance_scaling ] = compute_backward_robust_reachable_set( terminal_set, k_backward_robust_reachable_set, input_set, disturbance_set, ) elapsed_time[disturbance_index, index] = time.time() - start_time if index == 0: area_of_sets[disturbance_index, index] = ( list_of_backward_robust_reachable_sets_dict[index][ disturbance_scaling ][0].volume() ) else: area_of_sets[disturbance_index, index] = ( approximate_volume_from_grid( list_of_backward_robust_reachable_sets_dict[index][ disturbance_scaling ][0], 0.5, ) ) ``` -------------------------------- ### 3D Plotting and Projection of Constrained Zonotopes Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Visualizes ConstrainedZonotopes in 3D and their 2D projections. This example requires `matplotlib` and `numpy` for plotting and array manipulation. ```python L1_norm_ball_polytope = Polytope(V=np.vstack((np.eye(3), -np.eye(3)))) L1_norm_ball = ConstrainedZonotope(polytope=L1_norm_ball_polytope) simplex_in_R_pos_polytope = Polytope(V=np.vstack((np.eye(3), [0, 0, 0]))) simplex_in_R_pos = ConstrainedZonotope(polytope=simplex_in_R_pos_polytope) constrained_zonotope_list = [ L1_norm_ball, simplex_in_R_pos, simplex_in_R_pos, ] view_dict = [ {"elev": 21, "azim": -120}, {"elev": 21, "azim": -35}, {"elev": 21, "azim": -35}, ] facecolor_3d_list = ["lightblue", "lightblue", None] for C, view_dict, facecolor_3d in zip( constrained_zonotope_list, view_dict, facecolor_3d_list ): fig = plt.figure() ax = fig.add_subplot(1, 2, 1, projection="3d") ax.view_init(**view_dict) C.plot( ax=ax, direction_vectors=dir_vectors, patch_args={"facecolor": facecolor_3d}, ) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") ax.set_aspect("equal") ax.set_title("3D constrained zonotope") P_projection = C.projection(project_away_dims=2) ax2d = fig.add_subplot(1, 2, 2) P_projection.plot(ax=ax2d) ax2d.set_xlabel("x") ax2d.set_ylabel("y") ax2d.set_aspect("equal") ax2d.set_title("Projection on x-y") plt.subplots_adjust(wspace=1) ``` -------------------------------- ### Create ConstrainedZonotope Instances Source: https://context7.com/merlresearch/pycvxset/llms.txt Demonstrates different ways to initialize a ConstrainedZonotope, including from generators and offsets, equality constraints, bounds, polytopes, single points, and empty sets. ```python import numpy as np from pycvxset import ConstrainedZonotope, Polytope # Zonotope (G, c): {G ξ + c | ||ξ||∞ ≤ 1} G = np.array([[1.0, 0.0], [0.0, 0.5]]) c = np.array([1.0, 2.0]) CZ_zono = ConstrainedZonotope(G=G, c=c) # Constrained zonotope (G, c, Ae, be) Ae = np.array([[1.0, -1.0]]) be = np.array([0.0]) CZ = ConstrainedZonotope(G=G, c=c, Ae=Ae, be=be) # From bounds (creates a zonotope equivalent to a box) CZ_box = ConstrainedZonotope(lb=[-1, -1], ub=[1, 1]) CZ_centered = ConstrainedZonotope(c=[0, 0], h=1.0) # From a Polytope P = Polytope(V=[[1, 0], [0, 1], [-1, 0], [0, -1]]) CZ_from_P = ConstrainedZonotope(polytope=P) # Singleton CZ_pt = ConstrainedZonotope(G=None, c=[1.0, 2.0]) # Empty CZ_empty = ConstrainedZonotope(dim=2) print(CZ_box.is_zonotope) # True print(CZ.is_zonotope) # False (has equality constraints) print(CZ_pt.is_singleton) # True ``` -------------------------------- ### Defining and Checking Empty Polytope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Demonstrates how to define an empty polytope and check its properties like V-rep, H-rep, and emptiness. Assumes 'Polytope' class is imported. ```python empty_polytope = Polytope(dim=3) print(empty_polytope) print("Is empty_polytope in V-Rep?", empty_polytope.in_V_rep) print("Is empty_polytope in H-Rep?", empty_polytope.in_H_rep) print("Is empty_polytope empty?", empty_polytope.is_empty) ``` -------------------------------- ### ConstrainedZonotope.plot Source: https://context7.com/merlresearch/pycvxset/llms.txt Plots the constrained zonotope via a polytopic approximation. This method requires matplotlib to be installed. ```APIDOC ## ConstrainedZonotope.plot ### Description Plots the constrained zonotope via a polytopic approximation. ### Method `plot(ax, method='inner', n_vertices=32, patch_args={})` ### Parameters #### Path Parameters - **ax** (matplotlib.axes.Axes) - Required - The axes object to plot on. - **method** (str) - Optional - The approximation method to use ('inner' or 'outer'). Defaults to 'inner'. - **n_vertices** (int) - Optional - The number of vertices to use for the polytopic approximation. Defaults to 32. - **patch_args** (dict) - Optional - Arguments to pass to matplotlib.patches.Polygon. ### Request Example ```python import matplotlib.pyplot as plt from pycvxset import ConstrainedZonotope import numpy as np G = np.array([[1.0, 0.5], [0.0, 1.0]]) CZ = ConstrainedZonotope(G=G, c=[0.0, 0.0]) fig, ax = plt.subplots() CZ.plot(ax=ax, method="inner", n_vertices=32, patch_args={"facecolor": "green", "alpha": 0.4, "edgecolor": "darkgreen"}) ax.set_aspect("equal") plt.show() ``` ### Response This method does not return a value but displays a plot. ``` -------------------------------- ### Create and Print Polytope Representations Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ACC2025_code_snippets.ipynb Demonstrates creating a polytope from vertices (V-Rep) and from inequalities (H-Rep), then printing its representation and vertices. ```python import numpy as np from pycvxset import Polytope V = [[-1, 0.5], [-1, 1], [1, 1], [1, -1], [0.5, -1]] P1 = Polytope(V=V) print("P1 is a", repr(P1)) A, b = -np.eye(3), np.zeros((3,))) Ae, be = [1, 1, 1], 1 P2 = Polytope(A=A, b=b, Ae=Ae, be=be) print("P2 is a", P2) print("Vertices of P2 are:\n", P2.V) print("P2 is a", P2) ``` -------------------------------- ### Generate Sphinx PDF Documentation Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Builds the MANUAL.pdf documentation using Sphinx, assuming a LaTeX environment is properly set up. ```bash $ ./scripts/run_sphinx_pdf.sh ``` -------------------------------- ### Intersection with Affine Set in Python Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Intersects a 3D constrained zonotope with an affine set defined by Ax=b. Requires plotting setup and direction vectors. ```python ax, _, _ = C_3D.plot( direction_vectors=dir_vectors, patch_args={"label": "C_3D"} ) C_3D.intersection_with_affine_set(Ae=[1, 1, 1], be=0).plot( ax=ax, direction_vectors=dir_vectors, patch_args={"facecolor": "yellow", "label": "C_3D after intersection"}, ) ax.legend() ax.view_init(elev=15, azim=-24) ax.set_title("Intersection with affine set") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z"); ``` -------------------------------- ### Default CVXPY Arguments Source: https://github.com/merlresearch/pycvxset/blob/main/docs/source/pycvxset.common.constants.md Sets up default arguments for CVXPY, including the solver to be used. Note that 'reoptimize': True should be used when employing the GUROBI solver. ```python # CVXPY args used by default (use "reoptimize": True when using GUROBI) DEFAULT_CVXPY_ARGS_LP = {"solver": DEFAULT_LP_SOLVER_STR} DEFAULT_CVXPY_ARGS_SOCP = {"solver": DEFAULT_SOCP_SOLVER_STR} DEFAULT_CVXPY_ARGS_SDP = {"solver": DEFAULT_SDP_SOLVER_STR} ``` -------------------------------- ### Slicing a Constrained Zonotope in Python Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Slices a 3D constrained zonotope along a specified dimension with a given constant value. Requires plotting setup and direction vectors. ```python ax, _, _ = C_3D.plot( direction_vectors=dir_vectors, patch_args={"label": "C_3D"} ) C_3D.slice(dims=2, constants=0.5).plot( ax=ax, direction_vectors=dir_vectors, patch_args={"facecolor": "yellow", "label": "C_3D after slicing"}, ) ax.legend() ax.view_init(elev=15, azim=-24) ax.set_title("Slicing") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z"); ``` -------------------------------- ### Define Initial and Input Sets for Reachability Analysis Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Application_Reachability.ipynb Sets up the initial state set (hypercube) and the control input set for the robot's forward reachability analysis. Supports both Polytope and ConstrainedZonotope representations. ```python # Parameters n_time_steps_for_forward_reach_computation = 5 FACECOLOR_LIST = [ "black", "gray", "lightgray", "lightblue", "lightgreen", "white", ] # Define the initial and input sets (Polytope) initial_set_polytope = Polytope(c=[0, 0], h=0.5) input_set_polytope = Polytope(lb=-1, ub=1) # Define the initial and input sets (Constrained zonotopes) initial_set_constrained_zonotope = ConstrainedZonotope(c=[0, 0], h=0.5) input_set_constrained_zonotope = ConstrainedZonotope(lb=-1, ub=1) ``` -------------------------------- ### Create and Check Empty Constrained Zonotope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Demonstrates creating an empty constrained zonotope and checking its emptiness status. It also verifies the emptiness of previously defined zonotopes. ```python empty_constrained_zonotope = ConstrainedZonotope(dim=3) print(empty_constrained_zonotope) print( "Is empty_constrained_zonotope empty?", empty_constrained_zonotope.is_empty, ) print("Was C_3D empty?", C_3D.is_empty) print( "Was axis_aligned_cuboid_from_bounds empty?", axis_aligned_cuboid_from_bounds.is_empty, ) print( "Was axis_aligned_cuboid_from_center_and_sides empty?", axis_aligned_cuboid_from_center_and_sides.is_empty, ) ``` -------------------------------- ### Get CVXPY Constraints for ConstrainedZonotope Source: https://context7.com/merlresearch/pycvxset/llms.txt Returns CVXPY constraints for embedding a ConstrainedZonotope into custom optimization problems. This is useful for solving problems involving these sets within a CVXPY framework. ```python import cvxpy as cp import numpy as np from pycvxset import ConstrainedZonotope CZ = ConstrainedZonotope(lb=[-2, -2], ub=[2, 2]) x = cp.Variable((2,)) constraints, xi = CZ.containment_constraints(x) # Find the point in CZ closest to [3, 1] target = np.array([3.0, 1.0]) prob = cp.Problem(cp.Minimize(cp.sum_squares(x - target)), constraints) prob.solve() print(x.value) # [2. 1.] — closest feasible point ``` -------------------------------- ### Import pycvxset classes Source: https://context7.com/merlresearch/pycvxset/llms.txt Import the main set classes from the pycvxset library. ```python from pycvxset import Polytope, Ellipsoid, ConstrainedZonotope ``` -------------------------------- ### Plotting Backward Robust Reachable Sets Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Application_Reachability.ipynb This code generates plots comparing backward robust reachable sets for Polytope and Constrained Zonotope representations. It iterates through different set types, plots the reachable sets, and visualizes example trajectories from initial states. ```python disturbance_scaling = 0.2 direction_list = [ [1, 1], [1, -1], [-1, 1], [-1, -1], [-0.01, -1], [0.01, 1], ] plt.figure() for index, [input_set, terminal_set, title] in enumerate( [ [input_set_polytope, terminal_set_polytope, "Polytope"], [ input_set_constrained_zonotope, terminal_set_constrained_zonotope, "Constrained zonotope", ], ] ): ax = plt.subplot(120 + index + 1) plot_backward_reachable_sets( ax, terminal_set, list_of_backward_robust_reachable_sets_dict[index], disturbance_scaling, title, plot_all=False, ) backward_robust_reachable_sets_list = ( list_of_backward_robust_reachable_sets_dict[index][ disturbance_scaling ] ) for direction in direction_list: initial_state = backward_robust_reachable_sets_list[0].extreme( direction )[0] ax.scatter( *initial_state, 50, label=f"Initial state ({initial_state[0]:1.2f}, {initial_state[1]:1.2f})", ) state_trajectory = generate_approximate_worst_case_trajectory( backward_robust_reachable_sets_list, initial_state, input_set, terminal_set, disturbance_scaling, ) ax.plot( state_trajectory[0, :], state_trajectory[1, :], "kx-", label=f"Trajectory from ({initial_state[0]:1.2f}, {initial_state[1]:1.2f})", ) plt.subplots_adjust(left=0.1, wspace=0.5) plt.suptitle( f"Backward robust reach set ($\\mathcal{{W}}={disturbance_scaling:1.1f} \\mathcal{{U}}$)" ) ax.legend(bbox_to_anchor=(1.25, 1.2), ncols=2); ``` -------------------------------- ### Build Sphinx HTML Documentation Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Generates the HTML API documentation without rendering notebooks or coverage results. This is a faster option for API docs. ```bash $ ./scripts/run_sphinx_html.sh ``` -------------------------------- ### Run Tests and Update Documentation Source: https://github.com/merlresearch/pycvxset/blob/main/README.md Executes the test suite and updates documentation, typically used for development and CI/CD pipelines. ```bash $ ./scripts/run_tests_and_update_docs.sh ``` -------------------------------- ### Slicing 3D Polytope with Equality Constraints Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Demonstrates slicing a 3D polytope using equality constraints and visualizes both the original and constrained polytopes. Assumes 'Polytope' class and 'P_hrep_3D' are defined. ```python # Slicing a 3D polytope print("Is P_hrep_3D full-dimensional?", P_hrep_3D.is_full_dimensional) equality_constrained_P_hrep_3D = Polytope( A=P_hrep_3D.A, b=P_hrep_3D.b, Ae=[0.03, 0, 0.2], be=[0] ) print( "What is equality_constrained_P_hrep_3D's dimension?", equality_constrained_P_hrep_3D.dim, ) print( "Is equality_constrained_P_hrep_3D full-dimensional?", equality_constrained_P_hrep_3D.is_full_dimensional, ) ax, _, _ = P_hrep_3D.plot( patch_args={ "alpha": 0.4, "facecolor": "lightblue", "label": "Original", } ) equality_constrained_P_hrep_3D.plot( ax=ax, patch_args={ "facecolor": "lightgreen", "label": "Equality constrained", }, ) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") ax.legend(loc="best", bbox_to_anchor=(1.5, 1)) ax.set_title("Polytope with equality constraints"); ``` -------------------------------- ### Create Constrained Zonotopes from Polytope and Box Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ACC2025_code_snippets.ipynb Shows how to create constrained zonotopes, one from an existing polytope and another from lower and upper bounds defining a box. ```python from pycvxset import ConstrainedZonotope C1 = ConstrainedZonotope(polytope=P1) print("C1 is a", repr(C1)) print("P1 is a", repr(P1)) C2 = ConstrainedZonotope(lb=[-1, -1], ub=[1, 1]) print("C2 is a", repr(C2)) ``` -------------------------------- ### Default Solver Configurations Source: https://github.com/merlresearch/pycvxset/blob/main/docs/source/pycvxset.common.constants.md Specifies the default solvers for Linear Programming (LP), Second-Order Cone Programming (SOCP), and Semidefinite Programming (SDP). These constants define the string names of the solvers to be used. ```python # Solvers used by default DEFAULT_LP_SOLVER_STR = "CLARABEL" # CLARABEL, MOSEK, CVXOPT, SCS, ECOS, GUROBI, OSQP DEFAULT_SOCP_SOLVER_STR = "CLARABEL" # CLARABEL, MOSEK, CVXOPT, SCS, ECOS, GUROBI DEFAULT_SDP_SOLVER_STR = "SCS" # CLARABEL, MOSEK, CVXOPT, SCS ``` -------------------------------- ### Affine Transformation of Polytope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Demonstrates affine transformation of a polytope using both operator overloading and explicit method calls. It verifies that both methods yield the same resulting polytope. ```python OLD_POLYTOPE_COLOR_1 = "skyblue" NEW_POLYTOPE_COLOR = "lightgray" OLD_POLYTOPE_1 = Polytope(V=[[0, 0], [0, 1], [2, 0]]) rotation_degree = 45 rotation_radians = np.deg2rad(rotation_degree) rotation_matrix = np.array( [ [np.cos(rotation_radians), -np.sin(rotation_radians)], [np.sin(rotation_radians), np.cos(rotation_radians)], ] ) translation = np.array([[2, -2]]).T # Computation via operator overloading new_polytope_from_affine_transformation = ( rotation_matrix @ OLD_POLYTOPE_1 + translation ) patch_args_old = { "facecolor": OLD_POLYTOPE_COLOR_1, "label": "Original polytope", } patch_args_new = { "facecolor": NEW_POLYTOPE_COLOR, "label": "Affine transformed polytope", } ax, _, _ = OLD_POLYTOPE_1.plot(patch_args=patch_args_old) new_polytope_from_affine_transformation.plot( ax=ax, patch_args=patch_args_new ) ax.legend() ax.set_title("Affine transformation") # Explicit computation via methods new_polytope_from_affine_transformation_explicit = ( OLD_POLYTOPE_1.affine_map(rotation_matrix).plus(translation) ) print( "Are polytopes obtained from these methods the same?", new_polytope_from_affine_transformation == new_polytope_from_affine_transformation_explicit, ) ``` -------------------------------- ### Inverse Affine Transformation with Polytope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Demonstrates how to undo an affine transformation on a polytope using overloaded operators or explicit methods. It verifies the correctness of the inverse transformation by comparing the results. ```python old_polytope_from_new_polytope = ( new_polytope_from_affine_transformation - translation ) @ rotation_matrix old_polytope_from_new_polytope_explicit = ( new_polytope_from_affine_transformation.minus( translation ).inverse_affine_map_under_invertible_matrix(rotation_matrix) ) print( "Are polytopes obtained from these methods the same?", old_polytope_from_new_polytope_explicit == old_polytope_from_new_polytope, ) print( "Did we get the old polytope back?", old_polytope_from_new_polytope_explicit == OLD_POLYTOPE_1, ) patch_args_new = { "facecolor": OLD_POLYTOPE_COLOR_1, "label": "Affine transformed polytope", } patch_args_new_undo = { "facecolor": NEW_POLYTOPE_COLOR, "label": "Undo the affine transformation", } ax, _, _ = new_polytope_from_affine_transformation.plot( patch_args=patch_args_new ) old_polytope_from_new_polytope_explicit.plot( ax=ax, patch_args=patch_args_new_undo ) ax.legend() ax.set_title("Inverse affine transformation"); ``` -------------------------------- ### Construct Polytope from V-rep Source: https://context7.com/merlresearch/pycvxset/llms.txt Create a Polytope using its vertex representation (V-rep) by providing the convex hull of vertices. ```python from pycvxset import Polytope # V-rep: convex hull of vertices P_vrep = Polytope(V=[[1, 0], [0, 1], [-1, 0], [0, -1]]) ``` -------------------------------- ### Import necessary packages Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Imports the required libraries for polytope operations, numerical computations, and plotting. ```python from pycvxset import Polytope, Ellipsoid, spread_points_on_a_unit_sphere import numpy as np import matplotlib.pyplot as plt ``` -------------------------------- ### Create a Polytope from V-Rep Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Defines a polytope using its Vertex representation. It then prints its representation and confirms its available representations. ```python theta_vec = np.arange(0, stop=2 * np.pi, step=2 * np.pi / 5) P_vrep = Polytope( V=[[np.cos(theta), np.sin(theta)] for theta in theta_vec] ) print(repr(P_vrep)) print("Is P_vrep in V-Rep?", P_vrep.in_V_rep) print("Is P_vrep in H-Rep?", P_vrep.in_H_rep) ``` -------------------------------- ### Create Ellipsoids Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ACC2025_code_snippets.ipynb Illustrates the creation of two ellipsoids: one defined by its center and quadratic form (Q), and another by its center and generator matrix (G). ```python from pycvxset import Ellipsoid E1 = Ellipsoid(c=[2, -1], Q=np.diag([1, 4])) print("E1 is an", E1) E2 = Ellipsoid(c=[0, 1, 0], G=np.diag([1, 2, 3])) print("E2 is an", E2) ``` -------------------------------- ### Define and Manipulate Convex Sets with PyCvxset Source: https://github.com/merlresearch/pycvxset/blob/main/docs/source/index.md Demonstrates defining a polytope, applying affine transformations (rotation and translation), projecting it onto the XY plane, and computing inscribed and circumscribing ellipsoids. ```python # Copyright (C) 2020-2026 Mitsubishi Electric Research Laboratories (MERL) import numpy as np from pycvxset import Ellipsoid, Polytope from scipy.spatial.transform import Rotation # Define P as the intersection of a box with different sides and a halfspace box_with_different_sides = Polytope(c=[0, 0, 0], h=[1, 0.5, 0.1]) P = box_with_different_sides.intersection_with_halfspaces([1, -0.5, 0], 0.25) # Affine transformation (Rotate and translate P) rotate_angle = np.pi / 4 R = Rotation.from_rotvec(rotate_angle * np.array([0, 0, 1])).as_matrix() shift_vec = [5, 4, 3] transformed_P = R @ P + shift_vec # Projection (Compute its shadow on to the xy space) project_transformed_P_to_XY = transformed_P.projection(project_away_dims=2) # Centering ellipsoids ellipsoid_inside_projection = Ellipsoid.deflate(project_transformed_P_to_XY) ellipsoid_outside_projection = Ellipsoid.inflate(project_transformed_P_to_XY) ``` -------------------------------- ### Construct Polytope with Equality Constraints Source: https://context7.com/merlresearch/pycvxset/llms.txt Create a Polytope that includes equality constraints (Ae x = be) in addition to inequality constraints. ```python from pycvxset import Polytope # H-rep with equality constraints: {x | Ax <= b, Ae x = be} P_eq = Polytope(A=[[1, 0, 0], [-1, 0, 0]], b=[1, 1], Ae=[[0, 0, 1]], be=[0.5]) ``` -------------------------------- ### Plotting Reachable Sets and Optimal Control Trajectories Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Application_Reachability.ipynb Visualizes forward reachable sets and plots optimal control trajectories to terminal states. Use for analyzing system behavior and validating reachability. ```python plt.figure() list_of_terminal_state_list = [None] * 2 for index, [ controlled_forward_reachable_sets, input_set, initial_set, title, ] in enumerate( [ [ controlled_forward_reachable_sets_polytope, input_set_polytope, initial_set_polytope, "Polytope", ], [ controlled_forward_reachable_sets_constrained_zonotope, input_set_constrained_zonotope, initial_set_constrained_zonotope, "Constrained zonotope", ], ] ]: ax = plt.subplot(120 + index + 1) list_of_terminal_state_list[index] = ( plot_forward_reachable_set_and_answer_example_questions( ax, initial_set, controlled_forward_reachable_sets[-1] ) ) ax.set_title(title) for terminal_state in list_of_terminal_state_list[index]: # Use optimal control to obtain trajectories state_trajectory, prob_status = generate_safe_trajectory( initial_set, input_set, terminal_state ) if state_trajectory is not None: # Plot the trajectory ax.plot( state_trajectory[0, :], state_trajectory[1, :], "kx:", label=( f"Min. acceleration trajectory to terminal state " f"({terminal_state[0]:.2f}, {terminal_state[1]:.2f})" ), ) else: ax.scatter( *terminal_state, 100, marker="o", edgecolors="k", facecolor="none", label="Terminal state in Q.5", ) print( f"No trajectory to terminal state ({terminal_state[0]:.2f}, {terminal_state[1]:.2f}). " f"CVXPY status: {prob_status}" ) plt.subplots_adjust(left=0.1, wspace=0.5) plt.suptitle("Validation using optimal control"); ``` -------------------------------- ### Centering and Bounding Sets Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ACC2025_code_snippets.ipynb Illustrates centering and bounding for a polytope P1 and a constrained zonotope C1. Uses `pycvxset` for set operations and `matplotlib` for plotting. ```python from pycvxset import is_polytope for C1_type, plot_sets in zip(["vrep", "hrep"], [False, True]): print(f"Using CZ obtained from {C1_type:s} polytope") if plot_sets: plt.figure() if C1_type == "hrep": C1 = ConstrainedZonotope(polytope=Polytope(A=P1.A, b=P1.b)) elif C1_type == "vrep": C1 = ConstrainedZonotope(polytope=Polytope(V=P1.V)) for index, cset in enumerate([P1, C1]): rect = Polytope.deflate_rectangle(cset) cheby_ball = Ellipsoid.inflate_ball(cset) max_vol_ell = Ellipsoid.inflate(cset) patch_args = { "facecolor": "pink", "linewidth": 3, "linestyle": ":", "label": "Bounding rectangle", } if plot_sets: ax = plt.subplot(121 + index) rect.plot(ax, patch_args=patch_args)[0] cset.plot(ax=ax, patch_args={"label": "Set"})[0] cheby_ball.plot( ax=ax, center_args={"color": "k", "label": "Chebyshev. center"}, patch_args={ "facecolor": "gray", "label": "Chebyshev ball", }, ) max_vol_ell.plot( ax=ax, center_args={"color": "gold", "label": "Ellipsoid center"}, patch_args={ "facecolor": "gold", "alpha": 0.6, "label": "Max. vol. ellipsoid", }, ) if index == 1: handles, labels = ax.get_legend_handles_labels() handles = [handles[1], handles[0], *handles[2:]] labels = [labels[1], labels[0], *labels[2:]] ax.legend(handles, labels, bbox_to_anchor=(1, 1.02)) ax.set_aspect("equal") if is_polytope(cset): ax.set_title("Polytope") else: ax.set_title("Constrained Zonotope") print( f"Set {type(cset).__name__}: Chebyshev radius (in each dim.): " f"{np.array2string(np.diag(cheby_ball.G), formatter={'float_kind':'{:1.2f}'.format}):s}" ) print( f"Set {type(cset).__name__}: MVIE volume: {max_vol_ell.volume():1.2f}" ) plt.subplots_adjust(right=0.6, wspace=0.3) ``` -------------------------------- ### Intersection with a Halfspace Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Demonstrates intersecting a 3D polytope (P_3D) with a halfspace defined by the inequality Ax <= b. The resulting polytope is visualized. ```python ax, _, _ = P_3D.plot(patch_args={\"label\": \"P_3D\"}) P_3D.intersection_with_halfspaces(A=[1, 1, 1], b=0).plot( ax=ax, patch_args={\"facecolor\": \"yellow\", \"label\": \"P_3D after intersection\"}, ) ax.legend() ax.view_init(elev=15, azim=-24) ax.set_title("Intersection with a halfspace") ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z"); ``` -------------------------------- ### Create a 3D Polytope from H-Rep Source: https://github.com/merlresearch/pycvxset/blob/main/examples/Polytope.ipynb Defines a 3D polytope using its Halfspace representation (A, b). It then prints its representation and confirms its dimensionality and available representations. ```python A = np.array( [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1]] ) b = [2, 3, 1, 2, 3, 1] P_hrep_3D = Polytope(A=A, b=b) print(repr(P_hrep_3D)) print("Is P_hrep_3D in V-Rep?", P_hrep_3D.in_V_rep) print("Is P_hrep_3D in H-Rep?", P_hrep_3D.in_H_rep) print(f"The dimension of P_hrep_3D is {P_hrep_3D.dim:d}.") ``` -------------------------------- ### Create and Inspect a 3D Constrained Zonotope Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Initializes a 3D constrained zonotope from a polytope defined in H-representation and prints its properties. This is useful for understanding the structure and characteristics of the zonotope. ```python A = np.array( [[1, 0, 0], [0, 1, 0], [0, 0, 1], [-1, 0, 0], [0, -1, 0], [0, 0, -1]] ) b = [2, 3, 1, 2, 3, 1] P_3D = Polytope(A=A, b=b) C_3D = ConstrainedZonotope(polytope=P_3D) print(repr(C_3D)) print(f"The dimension of C_3D is {C_3D.dim:d}.") print("G", np.array2string(C_3D.G, precision=2, suppress_small=True)) print("c", np.array2string(C_3D.c, precision=2, suppress_small=True)) print("Ae", np.array2string(C_3D.Ae, precision=2, suppress_small=True)) print("be", np.array2string(C_3D.be, precision=2, suppress_small=True)) print("He", np.array2string(C_3D.He, precision=2, suppress_small=True)) print("is_bounded?", C_3D.is_bounded) print("is_full_dimensional?", C_3D.is_full_dimensional) ``` -------------------------------- ### Project Sets for 3D Plotting Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ACC2025_code_snippets.ipynb Projects target set, line of sight cone, and robust controllable set onto specified dimensions for 3D visualization. This step involves polytopic inner approximation and can take time. ```python target_set_3D = [None] * 2 line_of_sight_cone_3D = [None] * 2 brs_3D = [None] * 2 for index, v_index in enumerate([2, 3]): target_set_3D[index] = target_set.projection(v_index) line_of_sight_cone_3D[index] = line_of_sight_cone.projection(v_index) brs_3D[index] = ( brs_list[0] .slice(v_index, 0) .projection(v_index) .polytopic_inner_approximation() ) ``` -------------------------------- ### Inverse Affine Transformation of Constrained Zonotopes Source: https://github.com/merlresearch/pycvxset/blob/main/examples/ConstrainedZonotope.ipynb Demonstrates how to undo an affine transformation on a ConstrainedZonotope using overloaded operators or explicit methods. Verifies the correctness of the inverse transformation. ```python old_constrained_zonotope_from_new_constrained_zonotope = ( new_constrained_zonotope_from_affine_transformation - translation ) @ rotation_matrix old_constrained_zonotope_from_new_constrained_zonotope_explicit = ( new_constrained_zonotope_from_affine_transformation.minus( translation ).inverse_affine_map_under_invertible_matrix(rotation_matrix) ) print( "Are constrained zonotopes obtained from these methods the same?", old_constrained_zonotope_from_new_constrained_zonotope_explicit == old_constrained_zonotope_from_new_constrained_zonotope, ) print( "Did we get the old constrained zonotope back?", old_constrained_zonotope_from_new_constrained_zonotope_explicit == CZ, ) patch_args_new = { "facecolor": OLD_CONSTRAINED_ZONOTOPE_COLOR_1, "label": "Affine transformed constrained zonotope", } patch_args_new_undo = { "facecolor": NEW_CONSTRAINED_ZONOTOPE_COLOR, "label": "Undo the affine transformation", } ax, _, _ = new_constrained_zonotope_from_affine_transformation.plot( patch_args=patch_args_new ) old_constrained_zonotope_from_new_constrained_zonotope_explicit.plot( ax=ax, patch_args=patch_args_new_undo ) ax.legend() ax.set_title("Inverse affine transformation"); ``` -------------------------------- ### Polytope.minimize (CVXPY Integration) Source: https://context7.com/merlresearch/pycvxset/llms.txt Convenience wrapper to minimize a CVXPY objective over the polytope. ```APIDOC ## Polytope.minimize ### Description Convenience wrapper: minimizes a CVXPY objective over the polytope. ### Method `minimize(x, objective_to_minimize, cvxpy_args=None)` ### Parameters #### Path Parameters None #### Query Parameters - **x** (cvxpy.Variable) - The CVXPY variable to minimize. - **objective_to_minimize** (cvxpy.Expression) - The CVXPY objective function to minimize. - **cvxpy_args** (dict, optional) - Additional arguments to pass to the CVXPY solver. ### Request Example ```python import cvxpy as cp import numpy as np from pycvxset import Polytope P = Polytope(c=[0, 0], h=2.0) x = cp.Variable((2,)) target = np.array([3.0, 1.0]) x_opt, obj_val, status = P.minimize( x, objective_to_minimize=cp.norm(x - target, p=2), cvxpy_args={"solver": "CLARABEL"} ) print(x_opt) # [2. 1.] — closest point in P to target print(obj_val) # 1.0 ``` ### Response #### Success Response (200) - **x_opt** (numpy.ndarray) - The optimal value of the variable x. - **obj_val** (float) - The optimal value of the objective function. - **status** (str) - The status of the CVXPY problem solution. ```