### Configure and Use Linear Programming Solvers (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Shows how to configure the linear programming solver used by the polytope package. It covers checking installed solvers, changing the default solver, and using a specific solver for projection and direct LP solving. ```python from polytope import solvers import polytope as pc import numpy as np # Check installed solvers print(f"Installed solvers: {solvers.installed_solvers}") # Check current default print(f"Default solver: {solvers.default_solver}") # Change default solver solvers.default_solver = 'scipy' # Use specific solver for operations poly = pc.box2poly([[0, 1], [0, 1]]) projected = poly.project([1], solver='scipy') # Direct LP solving (internal use) c = np.array([1, 0]) # Minimize x G = np.array([[1, 0], [0, 1], [-1, 0], [0, -1]]) h = np.array([1, 1, 0, 0]) result = solvers.lpsolve(c, G, h, solver='scipy') print(f"Status: {result['status']}") # 0 = optimal print(f"Optimal x: {result['x']}") print(f"Optimal value: {result['fun']}") ``` -------------------------------- ### Iterate and Access Polytopes in a Region Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Demonstrates iterating through the polytopes contained within a Region object 'r' and accessing individual polytopes by index. ```python for polytope in r: print(polytope) # Accessing the i-th polytope Region[i] # Getting the number of polytopes len(r) ``` -------------------------------- ### Perform Partition Operations with MetricPartition (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Illustrates how to work with partitions of space using the `Partition` and `MetricPartition` classes from the polytope library. It includes creating regions, forming a `MetricPartition`, finding adjacent regions, and inspecting partition properties. ```python import numpy as np import polytope as pc from polytope.prop2partition import MetricPartition, find_adjacent_regions # Create a domain and partition it domain = pc.box2poly([[0, 4], [0, 4]]) # Create partition regions regions = [ pc.box2poly([[0, 2], [0, 2]]), pc.box2poly([[2, 4], [0, 2]]), pc.box2poly([[0, 2], [2, 4]]), pc.box2poly([[2, 4], [2, 4]]) ] # Create a MetricPartition partition = MetricPartition(domain=domain) partition.regions = regions partition.domain = domain # Find adjacent regions adjacency = find_adjacent_regions(partition) print(f"Adjacency matrix:\n{adjacency.toarray()}") # Check partition properties print(f"Number of regions: {len(partition)}") # Iterate over regions for i, region in enumerate(partition): print(f"Region {i}: volume = {region.volume}") ``` -------------------------------- ### Import Polytope Package Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Imports the polytope package for use in Python scripts. This is the first step before utilizing any of its functionalities. ```python import polytope as pc ``` -------------------------------- ### Define Polytope using box2poly convenience function Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Creates a convex polytope aligned with coordinate axes using the box2poly convenience function. It takes a list of lists defining the bounds for each dimension. ```python p = pc.box2poly([[0, 2], [0, 1]]) ``` -------------------------------- ### Create Polytope and Box from Half-Spaces (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Demonstrates creating a 2D polytope from a matrix A and vector b representing half-space inequalities (Ax <= b). It also shows convenience methods for creating box shapes and accessing polytope properties like dimension, volume, and bounding box. ```python import numpy as np import polytope as pc # Create a 2D polytope from half-space inequalities A x <= b # This defines a rectangle: 0 <= x <= 2, 0 <= y <= 1 A = np.array([ [1.0, 0.0], # x <= 2 [0.0, 1.0], # y <= 1 [-1.0, 0.0], # -x <= 0 (i.e., x >= 0) [0.0, -1.0] # -y <= 0 (i.e., y >= 0) ]) b = np.array([2.0, 1.0, 0.0, 0.0]) p = pc.Polytope(A, b) print(p) # Convenience method: create box from intervals [[x_min, x_max], [y_min, y_max], ...] box = pc.box2poly([[0, 2], [0, 1]]) print(box == p) # True # Alternative: class method for boxes box2 = pc.Polytope.from_box([[0, 2], [0, 1]]) # Access properties print(f"Dimension: {p.dim}") # 2 print(f"Volume: {p.volume}") # ~2.0 (computed via sampling) print(f"Chebyshev radius: {p.chebR}") # 0.5 print(f"Chebyshev center: {p.chebXc}") # [1.0, 0.5] print(f"Bounding box: {p.bounding_box}") ``` -------------------------------- ### Polytope Additional Operations Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Performs additional operations on a polytope, such as projection onto a lower dimension or scaling the polytope's inequalities. ```python p1.project(dim) p1.scale(10) # b := 10 * b ``` -------------------------------- ### Access Polytope Attributes Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Retrieves various characteristics of a polytope 'p' through its attributes. Some attributes are computed on demand due to potential computational expense. ```python p.dim # number of dimensions of ambient Euclidean space p.volume # measure in ambient space p.chebR # Chebyshev ball radius p.chebXc # Chebyshev ball center p.cheby p.bounding_box ``` -------------------------------- ### Create Region from Polytopes Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Creates a Region object, which is a container for one or more Polytope objects. Polytopes can be non-convex or disconnected. Polytopes are passed as an iterable during instantiation. ```python p1 = pc.box2poly([[0,2], [0,1]]) p2 = pc.box2poly([[2,3], [0,2]]) r = pc.Region([p1, p2]) ``` -------------------------------- ### Polytope Set Operations Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Performs set operations (union, difference, intersection) between two polytopes, p1 and p2. These operations return new Polytope objects representing the result. ```python p1.union(p2) p1.diff(p2) p1.intersect(p2) ``` -------------------------------- ### Define Polytope using H-representation Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Defines a convex polytope using its H-representation (Ax <= b). Requires numpy arrays for A and b. The resulting polytope 'p' is an instance of the Polytope class. ```python import numpy as np A = np.array([[1.0, 0.0], [0.0, 1.0], [-1.0, -0.0], [-0.0, -1.0]]) b = np.array([2.0, 1.0, 0.0, 0.0]) p = pc.Polytope(A, b) ``` -------------------------------- ### Region Set Operations Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Performs set operations (union, difference, intersection) between two Region objects, r1 and r2. These operations return new Region objects. ```python r1 + r2 # set union r1 - r2 # set difference r1 & r2 # intersection ``` -------------------------------- ### Visualize Polytope with Text Annotations and Custom Appearance (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Demonstrates how to add text annotations to a polytope visualization and customize its appearance using matplotlib and the polytope library. It involves plotting a triangle with specific colors, line styles, and hatching. ```python import numpy as np import matplotlib.pyplot as plt import polytope as pc # Add text annotation at Chebyshev center p1.text("P1", ax=ax, color='white') p2.text("P2", ax=ax, color='white') # Customize appearance triangle = pc.qhull(np.array([[0, 0], [1, 0], [0.5, 1]])) triangle.plot( color='green', alpha=0.7, hatch='///', linestyle='solid', linewidth=2, edgecolor='black' ) plt.title("Polytope Visualization") plt.xlabel("x") plt.ylabel("y") plt.show() ``` -------------------------------- ### Create Non-Convex Regions (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Illustrates the use of the `Region` class to represent non-convex or disconnected shapes by combining multiple `Polytope` objects. It shows how to create a region from a list of polytopes and access its properties and constituent polytopes. ```python import polytope as pc # Create two non-overlapping boxes p1 = pc.box2poly([[0, 2], [0, 1]]) p2 = pc.box2poly([[2, 3], [0, 2]]) # Combine into a non-convex region region = pc.Region([p1, p2]) # Iterate over polytopes in the region for i, poly in enumerate(region): print(f"Polytope {i}: volume = {poly.volume}") # Access by index first_poly = region[0] num_polytopes = len(region) # Region properties print(f"Total volume: {region.volume}") print(f"Dimension: {region.dim}") print(f"Bounding box: {region.bounding_box}") # Display the region print(region) ``` -------------------------------- ### Projecting Polytopes to Lower Dimensions (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Project polytopes onto lower-dimensional subspaces using various available algorithms. The 'project' method takes a list of dimensions to keep. Requires numpy. ```python import polytope as pc import numpy as np # Create a 3D box box_3d = pc.box2poly([[0, 1], [0, 2], [0, 3]]) print(f"Original dimension: {box_3d.dim}") # 3 # Project onto first two dimensions (x, y plane) # dim specifies which dimensions to KEEP (1-indexed) projected_xy = box_3d.project([1, 2]) print(f"Projected dimension: {projected_xy.dim}") # 2 print(f"Projected polytope:\n{projected_xy}") # Project onto x-z plane projected_xz = box_3d.project([1, 3]) # Project onto single dimension projected_x = box_3d.project([1]) # Specify solver explicitly # Available: 'fm' (Fourier-Motzkin), 'exthull' (vertex), 'iterhull' (iterative hull), 'esp' (equality set) projected = box_3d.project([1, 2], solver='fm') # Or use the function form projected = pc.projection(box_3d, [1, 2], solver='exthull') ``` -------------------------------- ### Geometric Transformations for Polytopes (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Apply translation, rotation, and scaling to polytopes. These transformations return new polytope objects, leaving the originals unchanged. Requires numpy and math libraries. ```python import numpy as np import polytope as pc import math # Create a unit square centered at origin square = pc.box2poly([[-0.5, 0.5], [-0.5, 0.5]]) # Translation d = np.array([2.0, 1.0]) translated = square.translation(d) print(f"Original center: {square.chebXc}") # [0, 0] print(f"Translated center: {translated.chebXc}") # [2, 1] # Rotation theta = math.pi / 4 rotated = square.rotation(i=0, j=1, theta=theta) print(f"Rotated polytope vertices: {pc.extreme(rotated)}") # Scaling (in-place) scaled = square.copy() scaled.scale(2.0) print(f"Original volume: {square.volume}") print(f"Scaled volume: {scaled.volume}") # 4x the original # Chained transformations transformed = square.rotation(i=0, j=1, theta=theta).translation(d) ``` -------------------------------- ### Set Operations on Polytopes (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Demonstrates performing set algebra operations such as union and intersection on `Polytope` and `Region` objects. The union operation returns a `Region` to handle potentially non-convex results, while intersection typically returns a `Polytope` if the result is convex. ```python import polytope as pc # Create two overlapping rectangles p1 = pc.box2poly([[0, 2], [0, 1]]) p2 = pc.box2poly([[1, 3], [0, 1]]) # Union - returns Region union_result = p1.union(p2) # Or using function: union_result = pc.union(p1, p2) # Or using + operator (includes convexity check): union_result = p1 + p2 print(f"Union volume: {union_result.volume}") # ~3.0 # Intersection - returns Polytope (convex) intersection = p1.intersect(p2) # Or using function: intersection = pc.intersect(p1, p2) ``` -------------------------------- ### Computing Extreme Points and Convex Hull (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Compute the vertices (extreme points) of a bounded polytope or construct a polytope from a set of points using convex hull computation. Requires numpy. ```python import numpy as np import polytope as pc # Create a polytope triangle_A = np.array([ [1, 1], [-1, 0], [0, -1] ]) triangle_b = np.array([1, 0, 0]) triangle = pc.Polytope(triangle_A, triangle_b) # Get extreme points (vertices) vertices = pc.extreme(triangle) print(f"Triangle vertices:\n{vertices}") # Expected: [[0, 0], [1, 0], [0, 1]] # Create polytope from vertices using convex hull random_points = np.random.rand(10, 2) # 10 random 2D points hull = pc.qhull(random_points) print(f"Convex hull:\n{hull}") # Get vertices of the hull hull_vertices = pc.extreme(hull) print(f"Number of original points: {len(random_points)}") print(f"Number of hull vertices: {len(hull_vertices)}") ``` -------------------------------- ### Test Point Containment in Polytopes (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Shows how to test if points are inside a `Polytope` or `Region` using the `in` operator for single points and the `contains()` method for multiple points. The `contains()` method accepts points as a d x n NumPy array and can optionally exclude boundary points. ```python import numpy as np import polytope as pc # Create a unit square square = pc.box2poly([[0, 1], [0, 1]]) # Single point test with 'in' operator point = [0.5, 0.5] print(f"Point {point} in square: {point in square}") # True outside_point = [1.5, 0.5] print(f"Point {outside_point} in square: {outside_point in square}") # False # Boundary points are included boundary_point = [1.0, 0.5] print(f"Boundary point in square: {boundary_point in square}") # True # Test multiple points efficiently with contains() # Points should be column vectors (d x n array for n points in d dimensions) points = np.array([ [0.5, 1.5, 0.0, 0.5], # x coordinates [0.5, 0.5, 0.0, 1.5] # y coordinates ]) inside = square.contains(points) print(f"Containment results: {inside}") # [True, False, True, False] # Exclude boundary with abs_tol=0 inside_strict = square.contains(points, abs_tol=0) ``` -------------------------------- ### Generate Grid within Polytope Source: https://context7.com/tulip-control/polytope/llms.txt Generates a regular grid of points within a polytope. This is useful for sampling, numerical integration, and visualization. The function can accept a custom resolution for the grid and works with both single polytopes and non-convex regions. ```python import numpy as np import polytope as pc # Create a polytope poly = pc.box2poly([[0, 2], [0, 1]]) # Generate grid with default resolution grid_points, resolution = pc.grid_region(poly) print(f"Grid shape: {grid_points.shape}") print(f"Resolution used: {resolution}") # Specify custom resolution [nx, ny, ...] grid_points, _ = pc.grid_region(poly, res=[10, 5]) print(f"Custom grid points: {grid_points.shape[1]}") # Grid works with non-convex regions too region = pc.Region([ pc.box2poly([[0, 1], [0, 1]]), pc.box2poly([[1, 2], [0, 1]]) ]) grid_points, _ = pc.grid_region(region, res=[20, 10]) print(f"Region grid points: {grid_points.shape[1]}") ``` -------------------------------- ### Plot 2D Polytopes with Matplotlib Source: https://context7.com/tulip-control/polytope/llms.txt Visualizes 2D polytopes and regions using matplotlib integration. Users can customize the appearance with colors, hatching, and transparency. The `plot` method can be called on a Polytope object or a Region object. ```python import numpy as np import polytope as pc import matplotlib.pyplot as plt # Create polytopes p1 = pc.box2poly([[0, 1], [0, 1]]) p2 = pc.box2poly([[0.5, 1.5], [0.5, 1.5]]) # Basic plot ax = p1.plot(color='blue', alpha=0.5) p2.plot(ax=ax, color='red', alpha=0.5) # Set axis limits based on bounding box combined = pc.Region([p1, p2]) l, u = combined.bounding_box ax.set_xlim(l[0, 0] - 0.1, u[0, 0] + 0.1) ax.set_ylim(l[1, 0] - 0.1, u[1, 0] + 0.1) # plt.show() # Uncomment to display the plot ``` -------------------------------- ### Reduce Polytope Constraints Source: https://context7.com/tulip-control/polytope/llms.txt Reduces a polytope to its minimal representation by removing redundant constraints. It takes a Polytope object as input and returns a new Polytope object with only essential constraints. This is useful for simplifying geometric representations and improving computational efficiency. ```python import numpy as np import polytope as pc # Create a polytope with redundant constraints A = np.array([ [1, 0], # x <= 1 [-1, 0], # -x <= 0 [0, 1], # y <= 1 [0, -1], # -y <= 0 [1, 1] # x + y <= 10 (redundant) ]) b = np.array([1, 0, 1, 0, 10]) poly = pc.Polytope(A, b) print(f"Original constraints: {poly.A.shape[0]}") # 5 # Reduce to minimal representation reduced = pc.reduce(poly) print(f"Reduced constraints: {reduced.A.shape[0]}") # 4 print(f"Reduced polytope:\n{reduced}") # Check if minimal representation is achieved print(f"Is minimal: {reduced.minrep}") # True ``` -------------------------------- ### Compute Polytope Volume Source: https://context7.com/tulip-control/polytope/llms.txt Computes the approximate volume of polytopes and regions using Monte Carlo sampling. The computation can be customized with the number of samples (`nsamples`) and a random seed (`seed`) for reproducibility. This is useful for estimating the size of complex shapes. ```python import polytope as pc # Create polytopes unit_square = pc.box2poly([[0, 1], [0, 1]]) unit_cube = pc.box2poly([[0, 1], [0, 1], [0, 1]]) # Basic volume computation print(f"Square volume: {pc.volume(unit_square)}") # ~1.0 print(f"Cube volume: {pc.volume(unit_cube)}") # ~1.0 # Access via property print(f"Volume property: {unit_square.volume}") # Control accuracy with number of samples vol_precise = pc.volume(unit_cube, nsamples=50000) print(f"Volume with more samples: {vol_precise}") # Reproducible computation with seed vol1 = pc.volume(unit_cube, nsamples=10000, seed=42) vol2 = pc.volume(unit_cube, nsamples=10000, seed=42) print(f"Same seed produces same result: {vol1 == vol2}") # True # Volume of non-convex region region = pc.Region([ pc.box2poly([[0, 1], [0, 1]]), pc.box2poly([[1, 2], [0, 1]]) ]) print(f"Region volume: {region.volume}") # ~2.0 ``` -------------------------------- ### Check Point Membership in Polytope Source: https://github.com/tulip-control/polytope/blob/main/doc/tutorial.md Checks if a given point (represented as a list or numpy array) is contained within a polytope 'p'. Returns a boolean value. ```python [0.5, 0.5] in p ``` -------------------------------- ### Polytope Set Operations (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Perform set operations like intersection, difference, and subset checks on polytopes. These operations can be performed using dedicated methods or overloaded operators. ```python import polytope as pc # Create two polytopes (e.g., boxes) p1 = pc.box2poly([[0, 2], [0, 1]]) p2 = pc.box2poly([[1, 3], [0.5, 1.5]]) # Intersection intersection = p1 & p2 print(f"Intersection volume: {intersection.volume}") # ~1.0 # Set difference diff = p1.diff(p2) # Or using operator: diff = p1 - p2 print(f"Difference volume: {diff.volume}") # ~1.0 # Check subset relationship p_small = pc.box2poly([[0.5, 1.5], [0.25, 0.75]]) print(f"p_small <= p1: {p_small <= p1}") # True print(f"p1 <= p_small: {p1 <= p_small}") # False # Check equality p1_copy = pc.box2poly([[0, 2], [0, 1]]) print(f"p1 == p1_copy: {p1 == p1_copy}") # True ``` -------------------------------- ### Enumerate Integral Points in Polytope Source: https://context7.com/tulip-control/polytope/llms.txt Finds all points with integer coordinates that lie within a polytope. This function is useful for applications in integer programming and discrete geometry. It returns a NumPy array where each column represents an integral point. ```python import numpy as np import polytope as pc # Create a polytope containing some integer points poly = pc.box2poly([[0.5, 3.5], [0.5, 2.5]]) # Enumerate all integral points inside int_points = pc.enumerate_integral_points(poly) print(f"Integral points shape: {int_points.shape}") # (2, n) for n points print(f"Points:\n{int_points}") # Expected: [[1, 2, 3, 1, 2, 3], [1, 1, 1, 2, 2, 2]] # Works for higher dimensions cube = pc.box2poly([[0, 2], [0, 2], [0, 2]]) int_points_3d = pc.enumerate_integral_points(cube) print(f"3D integral points: {int_points_3d.shape[1]} points") ``` -------------------------------- ### Chebyshev Ball and Bounding Box Computation (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Calculate the largest inscribed ball (Chebyshev ball) and the smallest enclosing axis-aligned bounding box for a polytope. Useful for collision detection and sampling. Requires numpy. ```python import polytope as pc import numpy as np # Create an irregular polygon A = np.array([ [1, 0], [-1, 0], [0, 1], [0, -1], [1, 1], [-1, -1] ]) b = np.array([2, 1, 1, 1, 2, 1]) poly = pc.Polytope(A, b) # Get Chebyshev ball (largest inscribed ball) radius, center = pc.cheby_ball(poly) print(f"Chebyshev radius: {radius}") print(f"Chebyshev center: {center}") # Alternative: access as properties print(f"Radius via property: {poly.chebR}") print(f"Center via property: {poly.chebXc}") # Get bounding box lower, upper = pc.bounding_box(poly) print(f"Lower bounds: {lower.flatten()}") print(f"Upper bounds: {upper.flatten()}") # Alternative: access as property lower, upper = poly.bounding_box # Check if polytope is full-dimensional is_full = pc.is_fulldim(poly) print(f"Is full-dimensional: {is_full}") # Check if polytope is empty is_empty = pc.is_empty(poly) print(f"Is empty: {is_empty}") ``` -------------------------------- ### Check Polytope Adjacency and Convexity Source: https://context7.com/tulip-control/polytope/llms.txt Determines spatial relationships between polytopes, including adjacency (sharing a facet) and convexity checking for regions. It uses functions like `is_adjacent`, `is_interior`, and `is_convex`. This is useful for analyzing the connectivity and shape of geometric spaces. ```python import polytope as pc # Create adjacent boxes (sharing an edge) box1 = pc.box2poly([[0, 1], [0, 1]]) box2 = pc.box2poly([[1, 2], [0, 1]]) # Non-adjacent box box3 = pc.box2poly([[3, 4], [0, 1]]) # Check adjacency print(f"box1 adjacent to box2: {pc.is_adjacent(box1, box2)}") # True print(f"box1 adjacent to box3: {pc.is_adjacent(box1, box3)}") # False # Check if one polytope is strictly inside another inner = pc.box2poly([[0.25, 0.75], [0.25, 0.75]]) print(f"inner inside box1: {pc.is_interior(box1, inner)}") # Check if a region is convex region = pc.Region([box1, box2]) is_convex, envelope = pc.is_convex(region) print(f"Region is convex: {is_convex}") if is_convex: print(f"Envelope: {envelope}") # Separate a region into connected components disconnected = pc.Region([box1, box3]) components = pc.separate(disconnected) print(f"Number of connected components: {len(components)}") ``` -------------------------------- ### Reducing Polytope Representation (Python) Source: https://context7.com/tulip-control/polytope/llms.txt Simplify the H-representation of a polytope by removing redundant inequalities. This is useful after set operations or when dealing with over-specified polytopes. Requires numpy. ```python import numpy as np import polytope as pc # Example: Create a polytope with redundant inequalities A = np.array([ [1, 0], [-1, 0], [0, 1], [0, -1], [2, 0], [-2, 0], [0, 2], [0, -2] # Redundant constraints ]) b = np.array([1, 1, 1, 1, 1, 1, 1, 1]) poly_redundant = pc.Polytope(A, b) # Reduce the representation poly_minimal = pc.reduce(poly_redundant) print(f"Original number of inequalities: {poly_redundant.A.shape[0]}") print(f"Minimal number of inequalities: {poly_minimal.A.shape[0]}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.