Rectangle.Intersects(Rectangle)-Code - intersection

I think you know all the Rectangle.Intersects(Rectangle)-Method (returns boolean) in C# for example. Because I switched to plattform that doesn't has something like that, I try to make somwhink like that manually by creating my own Rectangle-Class. But I have really no idea of how to get if two rectangles intersect.
Thanks for your help!

Let the rectangles be defined by r1 = ((x11, y11), (x12, y12)) and r2 = ((x21, y21), (x22, y22)), then the problem can be solved in one dimension at a time:
The interval [x11, x12] must overlap [x21, x22]. The same goes for the y coordinates.
Overlapping intervals can be tested lime this:
x11 <= x21 < x12 or x21 < x12 <= x22

Related

Solving a steady flow in a subdomain of a mesh using FiPy

I'm fairly new to FiPy and I'm currently facing an issue of which I am sure can be solved easily: I want to solve a 3D steady flow of the form:
eq = ( DiffusionTerm(var=u) == -(1/mu) * dP + g_acc * (rho/mu) * ymax )
Where velocity u is in the y-direction and where du/dy = 0.
I would like to let the PDE solve within a subdomain of the entire 3D mesh, meaning that:
0 <= X < Boundary_1, u=0.
Boundary_1 <= X < Boundary_2, u = PDE solution
Boundary_2 <= X < Lx, u = 0.
Currently I have tried the following:
mesh = Grid3D(dx=dx, dy=dy, dz=dz, Lx=(Lx-0), Ly =(ymax-ymin), Lz=(zmax-zmin))
u = CellVariable(name = "velocity", mesh = mesh)
X, Y, Z = mesh.cellCenters
LeftWall = (X <= xBoundary_left)
RightWall = (X > xBoundary_right)
FrontWall = (mesh.facesFront)
BackWall = (mesh.facesBack)
u.constrain(0., where=LeftWall)
u.constrain(0., where=RightWall)
u.constrain(0., where=FrontWall)
u.constrain(0., where=BackWall)
Which leads to a solution of image 1 (see attached image). The boundary conditions for the X variable are not taken into account as I would like, as you can see in the example in image 2, where only the PDE domain is shown.
What I am looking for is a way to define the boundary conditions at the faces of the subdomain in such a way that it does not 'crop' the solution, but rather only solves the PDE for that subdomain. If it is possible to 'stitch' meshes together that include a Cellvariable u that has value 0 for two meshes and the value of the solved PDE for one mesh, that would be great as well!
I have tried working with inner boundary conditions in the form of an Implicit source, but that ended up in different errors.
Any help would be much appreciated!
FiPy constraints do not work on internal faces.
In our own work, rather than only solving an equation in a subdomain, we modify the coefficients to cause different behaviors to dominate in different subdomains. Conservation of momentum and conservation of mass don't suddenly stop being true; rather different conditions lead to, e.g., different Reynolds numbers.
It is possible to solve different equations on different meshes and communicate between them. See, e.g.,
https://www.mail-archive.com/search?q=how+to+set+up+data+transfer+between+two+adjacent+nonuniform+meshs&l=fipy%40nist.gov
How to extract a plane from a 3D variable in FiPy (3D to 2D)
https://www.mail-archive.com/search?l=fipy%40nist.gov&q=How+to+combine+scipy.interpolate.interp2d+with+fipy+variables&x=0&y=0
https://www.mail-archive.com/search?l=fipy%40nist.gov&q=Spline+interpolation+and+fipy+variable&x=18&y=9

Can I use functions as min(y,0) in ZIMPL with y being a variable?

I am using SCIP with ZIMPL to solve an optimization problem where I want to "punish" a solution for which variable x < k, with k being a parameter.
I do not want to exclude all solutions where this is the case. Therefore, I introduced variable y= x-k and want to add a penalty term to my objective value, but only if y is negative, as I don't want to punish a solution if x>k.
Adding -(min(y,0)) should do the trick, but I got the feeling that all functions and operations in ZIMPL such as the min - function (listed in Table 2 and 3 on p. 7 of the ZIMPL documentation) can only be aplied to parameters.
Can someone confirm that? And if yes, does anyone maybe have an idea how I can implement a kind of penalty term that only punishes the negative part of variable y in ZIMPL?
PS: Sorry for the misleading tag #scip, as it is a clear ZIMPL related problem. But unfortunatelly there was no existing tag #zimpl.
Yes, you can't use this kind of operators with variables (it wouldn't be a MILP anymore). However, why don't you model it like y1 - y2 = x-k with y1 >= 0 and y2 >= 0 and then put y2 into the objective function?

Solve equation with logarithms

I want to solve the following equation: log(log(y))=1/(x**2), and I want to get y as a function of x. How can I make a program in phyton in order to to this?
Thank you in advance!
By rearrangement, y = exp(exp(x ** -2)) will do it.
Note that this is a very strong function of x. Are you sure your starting equation is correct? (The log10 log10 of the number of particles in the universe is less than 2).

Face coloring in Matlab revisited

Using Mathematica I was able to create the following plot
Now I would like to switch to Matlab - which I am just starting to learn. I was able to create the triangulation with FL.vertices and FL.faces matrix and the patch function, that looks like this
faces=FV.faces;
facecolor = [.7 .7 .7];
patch('faces',faces,'vertices',FV.vertices,...
'facecolor',facecolor,'facealpha',0.8,'edgecolor',[.8.8.8]);
camlight('headlight','infinite');
daspect([1 1 1]); axis vis3d; axis off
material dull;
It produces a dull image:
Now, I have a function J that takes the matrix FL.vertices and returns a matrix of positive values. I would like to color the faces according to the values of J on vertices. Possibly interpolate along the faces. Edges can be, for now, as they are - to deal with later. After reading the documentation it is not clear to me how to accomplish this task. Do I need to find min and max of J manually? Or can Matlab do it automatically? It is OK for now to use one of Matlab's preset coloring schemes, something like a "temperature map" would do. At which point should I call my function J? How exactly it should be used with the patch command? I looked through the previous answers to a similar question, but still I am not able to figure out how to deal with my case. Any helping suggestion will be appreciated.
P.S.
OK. I think I did it with simple
FV.Cdata=sphere_jacobian(FV.vertices,1,1,0,1);
figure
Hp = patch('faces',FV.faces,'vertices',FV.vertices,...
'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
But I am not sure if min and max have been automatically computed and interpolated.
Here is what I believe to be the answer given by the poster, I will put it here so the question does not remain open.
OK. I think I did it with simple
FV.Cdata=sphere_jacobian(FV.vertices,1,1,0,1);
figure
Hp = patch('faces',FV.faces,'vertices',FV.vertices,...
'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
But I am not sure if min and max have been automatically computed and interpolated.
I did
colormap(hsv(3200));
and normalized my function:
jac = sphere_jacobian(FV.vertices,m);
minj = min(jac);
maxj = max(jac);
jac1 = (jac-minj*ones(size(jac)))/(maxj-minj);FV.Cdata=jac1;
figure Hp = patch('faces',FV.faces,'vertices',FV.vertices,... 'FaceVertexCData',FV.Cdata,'facecolor','interp','edgecolor',[.8 .8 .8]);
The result can be seen here.

Multivariate Bisection Method

I need an algorithm to perform a 2D bisection method for solving a 2x2 non-linear problem. Example: two equations f(x,y)=0 and g(x,y)=0 which I want to solve simultaneously. I am very familiar with the 1D bisection ( as well as other numerical methods ). Assume I already know the solution lies between the bounds x1 < x < x2 and y1 < y < y2.
In a grid the starting bounds are:
^
| C D
y2 -+ o-------o
| | |
| | |
| | |
y1 -+ o-------o
| A B
o--+------+---->
x1 x2
and I know the values f(A), f(B), f(C) and f(D) as well as g(A), g(B), g(C) and g(D). To start the bisection I guess we need to divide the points out along the edges as well as the middle.
^
| C F D
y2 -+ o---o---o
| | |
|G o o M o H
| | |
y1 -+ o---o---o
| A E B
o--+------+---->
x1 x2
Now considering the possibilities of combinations such as checking if f(G)*f(M)<0 AND g(G)*g(M)<0 seems overwhelming. Maybe I am making this a little too complicated, but I think there should be a multidimensional version of the Bisection, just as Newton-Raphson can be easily be multidimed using gradient operators.
Any clues, comments, or links are welcomed.
Sorry, while bisection works in 1-d, it fails in higher dimensions. You simply cannot break a 2-d region into subregions using only information about the function at the corners of the region and a point in the interior. In the words of Mick Jagger, "You can't always get what you want".
I just stumbled upon the answer to this from geometrictools.com and C++ code.
edit: the code is now on github.
I would split the area along a single dimension only, alternating dimensions. The condition you have for existence of zero of a single function would be "you have two points of different sign on the boundary of the region", so I'd just check that fro the two functions. However, I don't think it would work well, since zeros of both functions in a particular region don't guarantee a common zero (this might even exist in a different region that doesn't meet the criterion).
For example, look at this image:
There is no way you can distinguish the squares ABED and EFIH given only f() and g()'s behaviour on their boundary. However, ABED doesn't contain a common zero and EFIH does.
This would be similar to region queries using eg. kD-trees, if you could positively identify that a region doesn't contain zero of eg. f. Still, this can be slow under some circumstances.
If you can assume (per your comment to woodchips) that f(x,y)=0 defines a continuous monotone function y=f2(x), i.e. for each x1<=x<=x2 there is a unique solution for y (you just can't express it analytically due to the messy form of f), and similarly y=g2(x) is a continuous monotone function, then there is a way to find the joint solution.
If you could calculate f2 and g2, then you could use a 1-d bisection method on [x1,x2] to solve f2(x)-g2(x)=0. And you can do that by using 1-d bisection on [y1,y2] again for solving f(x,y)=0 for y for any given fixed x that you need to consider (x1, x2, (x1+x2)/2, etc) - that's where the continuous monotonicity is helpful -and similarly for g. You have to make sure to update x1-x2 and y1-y2 after each step.
This approach might not be efficient, but should work. Of course, lots of two-variable functions don't intersect the z-plane as continuous monotone functions.
I'm not much experient on optimization, but I built a solution to this problem with a bisection algorithm like the question describes. I think is necessary to fix a bug in my solution because it compute tow times a root in some cases, but i think it's simple and will try it later.
EDIT: I seem the comment of jpalecek, and now I anderstand that some premises I assumed are wrong, but the methods still works on most cases. More especificaly, the zero is garanteed only if the two functions variate the signals at oposite direction, but is need to handle the cases of zero at the vertices. I think is possible to build a justificated and satisfatory heuristic to that, but it is a little complicated and now I consider more promising get the function given by f_abs = abs(f, g) and build a heuristic to find the local minimuns, looking to the gradient direction on the points of the middle of edges.
Introduction
Consider the configuration in the question:
^
| C D
y2 -+ o-------o
| | |
| | |
| | |
y1 -+ o-------o
| A B
o--+------+---->
x1 x2
There are many ways to do that, but I chose to use only the corner points (A, B, C, D) and not middle or center points liky the question sugests. Assume I have tow function f(x,y) and g(x,y) as you describe. In truth it's generaly a function (x,y) -> (f(x,y), g(x,y)).
The steps are the following, and there is a resume (with a Python code) at the end.
Step by step explanation
Calculate the product each scalar function (f and g) by them self at adjacent points. Compute the minimum product for each one for each direction of variation (axis, x and y).
Fx = min(f(C)*f(B), f(D)*f(A))
Fy = min(f(A)*f(B), f(D)*f(C))
Gx = min(g(C)*g(B), g(D)*g(A))
Gy = min(g(A)*g(B), g(D)*g(C))
It looks to the product through tow oposite sides of the rectangle and computes the minimum of them, whats represents the existence of a changing of signal if its negative. It's a bit of redundance but work's well. Alternativaly you can try other configuration like use the points (E, F, G and H show in the question), but I think make sense to use the corner points because it consider better the whole area of the rectangle, but it is only a impression.
Compute the minimum of the tow axis for each function.
F = min(Fx, Fy)
G = min(Gx, Gy)
It of this values represents the existence of a zero for each function, f and g, within the rectangle.
Compute the maximum of them:
max(F, G)
If max(F, G) < 0, then there is a root inside the rectangle. Additionaly, if f(C) = 0 and g(C) = 0, there is a root too and we do the same, but if the root is in other corner we ignore him, because other rectangle will compute it (I want to avoid double computation of roots). The statement bellow resumes:
guaranteed_contain_zeros = max(F, G) < 0 or (f(C) == 0 and g(C) == 0)
In this case we have to proceed breaking the region recursively ultil the rectangles are as small as we want.
Else, may still exist a root inside the rectangle. Because of that, we have to use some criterion to break this regions ultil the we have a minimum granularity. The criterion I used is to assert the largest dimension of the current rectangle is smaller than the smallest dimension of the original rectangle (delta in the code sample bellow).
Resume
This Python code resume:
def balance_points(x_min, x_max, y_min, y_max, delta, eps=2e-32):
width = x_max - x_min
height = y_max - y_min
x_middle = (x_min + x_max)/2
y_middle = (y_min + y_max)/2
Fx = min(f(C)*f(B), f(D)*f(A))
Fy = min(f(A)*f(B), f(D)*f(C))
Gx = min(g(C)*g(B), g(D)*g(A))
Gy = min(g(A)*g(B), g(D)*g(C))
F = min(Fx, Fy)
G = min(Gx, Gy)
largest_dim = max(width, height)
guaranteed_contain_zeros = max(F, G) < 0 or (f(C) == 0 and g(C) == 0)
if guaranteed_contain_zeros and largest_dim <= eps:
return [(x_middle, y_middle)]
elif guaranteed_contain_zeros or largest_dim > delta:
if width >= height:
return balance_points(x_min, x_middle, y_min, y_max, delta) + balance_points(x_middle, x_max, y_min, y_max, delta)
else:
return balance_points(x_min, x_max, y_min, y_middle, delta) + balance_points(x_min, x_max, y_middle, y_max, delta)
else:
return []
Results
I have used a similar code similar in a personal project (GitHub here) and it draw the rectangles of the algorithm and the root (the system have a balance point at the origin):
Rectangles
It works well.
Improvements
In some cases the algorithm compute tow times the same zero. I thinh it can have tow reasons:
I the case the functions gives exatly zero at neighbour rectangles (because of an numerical truncation). In this case the remedy is to incrise eps (increase the rectangles). I chose eps=2e-32, because 32 bits is a half of the precision (on 64 bits archtecture), then is problable that the function don't gives a zero... but it was more like a guess, I don't now if is the better. But, if we decrease much the eps, it extrapolates the recursion limit of Python interpreter.
The case in witch the f(A), f(B), etc, are near to zero and the product is truncated to zero. I think it can be reduced if we use the product of the signals of f and g in place of the product of the functions.
I think is possible improve the criterion to discard a rectangle. It can be made considering how much the functions are variating in the region of the rectangle and how distante the function is of zero. Perhaps a simple relation between the average and variance of the function values on the corners. In another way (and more complicated) we can use a stack to store the values on each recursion instance and garantee that this values are convergent to stop recursion.
This is a similar problem to finding critical points in vector fields (see http://alglobus.net/NASAwork/topology/Papers/alsVugraphs93.ps).
If you have the values of f(x,y) and g(x,y) at the vertexes of your quadrilateral and you are in a discrete problem (such that you don't have an analytical expression for f(x,y) and g(x,y) nor the values at other locations inside the quadrilateral), then you can use bilinear interpolation to get two equations (for f and g). For the 2D case the analytical solution will be a quadratic equation which, according to the solution (1 root, 2 real roots, 2 imaginary roots) you may have 1 solution, 2 solutions, no solutions, solutions inside or outside your quadrilateral.
If instead you have analytic functions of f(x,y) and g(x,y) and want to use them, this is not useful. Instead you could divide your quadrilateral recursively, however as it was already pointed out by jpalecek (2nd post), you would need a way to stop your divisions by figuring out a test that would assure you would have no zeros inside a quadrilateral.
Let f_1(x,y), f_2(x,y) be two functions which are continuous and monotonic with respect to x and y. The problem is to solve the system f_1(x,y) = 0, f_2(x,y) = 0.
The alternating-direction algorithm is illustrated below. Here, the lines depict sets {f_1 = 0} and {f_2 = 0}. It is easy to see that the direction of movement of the algorithm (right-down or left-up) depends on the order of solving the equations f_i(x,y) = 0 (e.g., solve f_1(x,y) = 0 w.r.t. x then solve f_2(x,y) = 0 w.r.t. y OR first solve f_1(x,y) = 0 w.r.t. y and then solve f_2(x,y) = 0 w.r.t. x).
Given the initial guess, we don't know where the root is. So, in order to find all roots of the system, we have to move in both directions.