What is the best way to ask for a coloring of a grid where no sub-rectangle has all of the same colors? - combinatorics

I have an m by n rectangular grid with c possible colors for each gridpoint. I want to use OR-Tools to find a valid coloring. What is the best way to do it?
I was thinking that it might be adding an OnlyEnforceIf clause for each pair of columns per row (based on color assignment equality), and then asserting that if an aligned pair in two different rows are also equal, then the two pairs cannot have the same color.
However, this seems very verbose, and introduces a lot of new variables.

Just create
color[x, y, c] a boolean var that is true of point (x, y) has color c.
then add the constraints:
Each point has exactly one color
for each (x, y):
sum over c color[x, y, c] == 1
Any rectangle is not uni color:
for each x1, y1, x2, y2, c: # (x2 > x1, y2 > y1)
BoolOr(color[x1, y1, c].Not(),
color[x1, y2, c].Not(),
color[x2, y1, c].Not(),
color[x2, y2, c].Not())

Related

Find coordinates for arrowhead [duplicate]

This question already has answers here:
Find coordinates to draw arrow head (isoscele triangle) at the end of a line
(2 answers)
Closed 17 days ago.
I have drawn a line (x1, y1), (x2, y2) and would now like to draw 2 more lines that would form an arrowhead at point (x2, y2). How do I determine the 2 points to which I need to draw the arrowheads from point (x2, y2)? I know that I need to find 2 points on a circle with center at point (x2, y2) that are equidistant from line (x1, y1), (x2, y2) but I do not know how to find this. Geometry is not my forte.
Your line is vector from (x1,y1) to (x2,y2), its components are
D = (dx, dy) = (x2-x1, y2-y1)
Length of vector (perhaps you have Hypot function in math library):
Norm = Sqrt(dx * dx + dy * dy)
Normalized (unit length) vector:
uD = (udx, udy) = (dx/Norm, dy/Norm)
(again - math library might contain a function for normalized vector to replace two last formulas)
Unit perpendicular vector:
uP = (upx, upy) = (-udy, udx)
Now make two points at distance L along line from line end, and with perpendicular distance W from the line:
ax = x2 - udx * L + W * upx
ay = y2 - udy * L + W * upy
bx = x2 - udx * L - W * upx
by = y2 - udy * L - W * upy
At last draw lines A-P2 and B-P2
P.S. If you want to define arrow angle, tg(alpha) = W/L, also you can look at calculations here

Matlab- graphing and subplots [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I tried to do my homework and i'm not sure if I did it right. I'm not entirely sure how linspace works and was hoping for some input on my code! I'll attach the assignment it's based on. [enter link description here][1]
[enter image description here][2]
clc
clear all
figure(1);
figure(1);
x = 0:0.1:10
y1 = exp(-0.5*x).*sin(2*x)
y2 = exp(-0.5*x).*cos(2*x)
plot(x,y1,'-b',x,y2,'--r')
legend('y1','y2');
grid on
xlabel('\bfx axis');
ylabel('\bfy axis');
title('Sin and Cos Functions')
figure(2);
subplot(2,2,1)
plot(x,y1,'-b');
legend('y1','Location','northeast');
grid on
xlabel('\bfx')
ylabel('\bfy1')
title('Subplot of x and y1')
figure(3)
subplot(2,2,2)
plot(x,y2,'--r');
legend('y2','Location','northeast');
grid on
xlabel('\bfx')
ylabel('\bfy2')
title('Subplot of x and y2')
figure(4)
x = linspace(-2,8,200);
fun=(x.^2-6*x+5)./(x-3)
plot(x,fun,'b-','LineWidth',2)
axis([-2 8 -10 10]);
hold on;
title('Plot of f(x)')
xlabel('\bfx')
ylabel('\bfy')
(50 Points) Plot the function y(x) = (e^-0.5x)(Sin2x) for 100 values of x between 0 and 10. Use solid blue line for this function. Then plot the function y(x) = (e^-0.5x)(Cos2x)on the same axis. Use dashed red line for this function. Be sure to include a legend, title, axis labels and grid on the plots. Re-graph the two functions using subplot.
(50 Points) Plot the function Plot the function f(x)= ((X^2)-6x-5)/(x-3) using 200 points over the range −2 ≤ x ≤ 8. Note that there is an asymptote at x = 3, so the function will tent to infinity near to that point. In order to see the rest of the plot properly, you will need to limit the y-axis to the range -10 to 10.
linspace takes 3 arguments: a starting value, an ending value, and n = the number of points you want to generate in between those two numbers. It outputs an array of n evenly spaced numbers between your starting and ending values. For example linspace(0, 10, 5) returns an array of 5 evenly spaced numbers starting with 0 and ending with 10.
Here's the code for figure 1
x = linspace(0, 10, 100);
y1 = exp(-0.5*x).*sin(2*x);
y2 = exp(-0.5*x).*cos(2*x);
figure(1)
plot(x, y1, '-b', x, y2, '--r')
title('This is the title')
legend('This is Y1', 'This is Y2')
xlabel('These are the X values')
ylabel('These are the Y values')
grid on
Figure 2. Both subplots can be under one figure handle (i.e. figure(2)).
figure(2)
subplot(2, 1, 1)
plot(x, y1, '-b')
title('This is the first subplot')
xlabel('X axis')
ylabel('Y axis')
grid on
subplot(2, 1, 2)
plot(x, y2, '--r')
title('This is the second subplot')
xlabel('Another X axis')
ylabel('Another Y axis')
grid on
Figure 3. Your code looks right. Here's a similar solution:
x2 = linspace(-2, 8, 200);
y3 = ((x2.^2)-6.*x2-5)./(x2-3);
figure(3)
plot(x2, y3, '-g')
title('The third figure')
grid on
ylim([-10 10])
xlabel('Another axis')
ylabel('The last axis')

Inverted pixel coordinates of segmentation mask

The following is an image of a segmentation mask (it appears yellow). Overlaid onto this mask are the pixels/coordinates of the very same segmentation mask (appears blue).
My question is: why are these pixels/coordinates inverted, transparent and split at the diagonal? Why are they not plotted as a complete "fill", such as the mask itself?
My goal is for these coordinates to appear in "normal" (x,y) linear order. Code:
from matplotlib import patches
import numpy as np
# create mask
mask = np.zeros((350, 525), dtype=np.uint8)
# populate region of mask
mask[2:222,42:521] = 1
# get coordinates of populated region
y, x = np.where(mask == 1)
pts = np.column_stack([x, y])
# define figure, axes, title
fig = plt.figure()
ax = fig.add_axes([0,0,1,1])
ax.set_title('Segmentation mask pixel coordinates')
# show mask
plt.imshow(mask, interpolation='none')
# add mask points
poly = patches.Polygon(pts)
ax.add_patch(poly)
plt.show()
In your example len(pts) gives 105380 because pts contains all the points of the mask in row-based order. So poly has a snake-like shape with length=105380 and width=1. The snake starts in the upper left corner and ends in the lower right - that's why you have diagonal line.
To correct the plot you may do the following modification:
# borders
(x1, y1), (x2, y2) = pts.min(axis=0), pts.max(axis=0)
# corners
pts_for_poly = list(zip((x1, x2, x2, x1), (y1, y1, y2, y2)))
# rectangle polygon
poly = patches.Polygon(pts_for_poly)
I hope now it looks kinda like expected or close to that.

How to visualize feasible region for linear programming (with arbitrary inequalities) in Numpy/MatplotLib?

I need to implement a solver for linear programming problems. All of the restrictions are <= ones such as
5x + 10y <= 10
There can be an arbitrary amount of these restrictions. Also , x>=0 y>=0 implicitly.
I need to find the optimal solutions(max) and show the feasible region in matplotlib. I've found the optimal solution by implementing the simplex method but I can't figure out how to draw the graph.
Some approaches I've found:
This link finds the minimum of the y points from each function and uses plt.fillBetween() to draw the region. But it doesn't work when I change the order of the equations. I'm not sure which y values to minimize(). So I can't use it for arbitrary restrictions.
Find solution for every pair of restrictions and draw a polygon. Not efficient.
An easier approach might be to have matplotlib compute the feasible region on its own (with you only providing the constraints) and then simply overlay the "constraint" lines on top.
# plot the feasible region
d = np.linspace(-2,16,300)
x,y = np.meshgrid(d,d)
plt.imshow( ((y>=2) & (2*y<=25-x) & (4*y>=2*x-8) & (y<=2*x-5)).astype(int) ,
extent=(x.min(),x.max(),y.min(),y.max()),origin="lower", cmap="Greys", alpha = 0.3);
# plot the lines defining the constraints
x = np.linspace(0, 16, 2000)
# y >= 2
y1 = (x*0) + 2
# 2y <= 25 - x
y2 = (25-x)/2.0
# 4y >= 2x - 8
y3 = (2*x-8)/4.0
# y <= 2x - 5
y4 = 2 * x -5
# Make plot
plt.plot(x, 2*np.ones_like(y1))
plt.plot(x, y2, label=r'$2y\leq25-x$')
plt.plot(x, y3, label=r'$4y\geq 2x - 8$')
plt.plot(x, y4, label=r'$y\leq 2x-5$')
plt.xlim(0,16)
plt.ylim(0,11)
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
This is a vertex enumeration problem. You can use the function lineqs which visualizes the system of inequalities A x >= b for any number of lines. The function will also display the vertices on which the graph was plotted.
The last 2 lines mean that x,y >=0
from intvalpy import lineqs
import numpy as np
A = -np.array([[5, 10],
[-1, 0],
[0, -1]])
b = -np.array([10, 0, 0])
lineqs(A, b, title='Solution', color='gray', alpha=0.5, s=10, size=(15,15), save=False, show=True)
Visual Solution Link

Calculate the Z of a line intersection given the XY coordinates?

I'm intersecting a line in 2D and I calculate the X,Y coordinates of the intersection point. What I need is the Z of the intersection point given the X,Y,Z of the line points, and the X,Y of the intersection. From what I understand of equations it should be a one-liner but I don't know enough math to get there.
Your question is rather vague, but I will try to answer.
So take following equation:
Let's note it as Fx(X) = Fy(Y) = Fz(Z) and take a part of it:
Fx(X) = Fz(Z)
Then you said you know x, y and z for two points, put it to x1, x2, z1, z2 accordingly. Then put x of intersection to x. Now you have a linear equation with one variable z. Here it is:
z = (x - x1) / (x2 - x1) * (z2 - z1) + z1

Resources