Monday, January 30, 2023

Plotting Region defined by Inequality Constraints in Python (Part 1)

plot

Plotting Region defined by Inequality Constraints in Python (Part 1)

Author: Tran Thu Le & Chat GPT
Date: 30/1/2023

In this tutorial, we will use Python to visualize the regions defined by a set of inequality constraints of the form Ax <= b. The code provided below will plot a region on a 2D plane defined by a set of inequalities Ax <= b, where A is a matrix and b is a vector.

Prerequisites

Before we start, you will need to install the following packages:

  • numpy
  • matplotlib

In terminal, you can install these packages using the following command:

pip install numpy matplotlib

Code

Here is the code that plots the region defined by the inequality constraints AxbAx \leq b:

import numpy as np
import matplotlib.pyplot as plt

def  draw_regions(A, b, xlim, ylim):
	"""
	Draw a 2D region defined by Ax <= b
	"""
	# setup parameters
	nx, ny = 400, 500
	x = np.linspace(xlim[0], xlim[1], nx)
	y = np.linspace(ylim[0], ylim[1], ny)
	X, Y = np.meshgrid(x, y)
	gx, gy = X.reshape(-1), Y.reshape(-1)
	points = np.vstack([gx, gy])

	# find the active/feasible region
	active = (b.reshape(-1, 1) - A @ points >= 0)
	active = active.all(axis=0)
	active = active.reshape(ny, nx)

	# plot region
	fig, ax = plt.subplots(figsize=(8, 8))
	ax.contourf(X, Y, active)
	ax.set_xlim(*xlim)
	ax.set_ylim(*ylim)
	plt.show()

Example

Here’s an example of how to use the code to draw a region defined by the following inequality constraints:

1x+2y21x1y21x+1y21x1y1 \begin{aligned} 1x + 2y & \leq 2\\ 1x - 1y & \leq 2\\ -1x + 1y & \leq 2\\ -1x - 1y & \leq 1 \end{aligned}

A = np.array([[1, 2], [1, -1], [-1, 1], [-1, -1]])
b = np.array([2, 2, 2, 1])
xlim = [-3, 3]
ylim = [-3, 3]
draw_regions(A, b, xlim, ylim)

This will generate a plot with the region defined by the inequality constraints. The region will be shaded and the limits of the plot can be adjusted by changing the values of xlim and ylim.

Conclusion

In this tutorial, we learned how to use Python to visualize the regions defined by a set of inequality constraints. The code provided is a useful tool for visualizing these regions and can be used for a variety of applications.

Popular Posts