CGAL intersection of line<circular_kernel> and circle<circular_kernel> with circle extremal point processing circular arcs expand - intersection

I'm new to using CGAL library and
trying to get the intersection of line<circular_kernel> and circle<circular_kernel>
The circular_kernel is Exact_circular_kernel
In the general case, intersection is just fine
But there did not have any intersection point if the line is intersect with the extremal points of the circle
My purpose is to expand a circular arcs. So, I use the center of arcs to construct concentric circles with new radius(arc.radius + CONSTANT C) and do intersect with two lines to get the new start point and new end point of this new arcs
Here's example of this situation
#include <CGAL/Exact_circular_kernel_2.h>
#include <CGAL/Line_2.h>
#include <CGAL/Circle_2.h>
#include <CGAL/Circular_kernel_intersections.h>
#include <vector>
#include <iterator>
typedef CGAL::Exact_circular_kernel_2 CK;
typedef CK::Point_2 Point
typedef CK::Circle_2 Circle;
typedef CK::Line_2 Line;
typedef CK::FT FT;
int main()
{
// both lines intersect with the circle in extremal point
Line l1(FT(0), FT(1), FT(-0.3532));
Line l2(FT(-1), FT(0), FT(2.1838));
Circle c(Point(FT(2.0138), FT(0.5232)), CGAL::square(0.17));
/*My circle construction is like this
double radius = CGAL::sqrt(to_double(CGAL::squared_distance(PointOnArc, c.center())));
Circle c(ArcCenter, CGAL::squared_distance(radius + EXPAND_GAP));
*/
typedef typename CGAL::CK2_Intersection_traits<CK, Line, Circle>::type Intersection_result;
std::vector<Intersection_result> res;
CGAL::intersection(l1, c, std::back_inserter(res));
CGAL::intersection(l2, c, std::back_inserter(res));
std::cout << res.size() << '\n'; // should be 2 but it is 0
}
Is this caused by precision?
Any suggestion is appreciated, Thanks!
Edit:
The example above is extracted for represeting this problem
The size of res is 2 but it seems that only the intersection of l1 and circle get the intersection point(but duplicate once, so the res.size() is 2)
The correct size of res should be 2 and one for l1 and circle, one for l2 and circle)
And l1 is horizontal line, and l2 is vertical line
After testing, the problem seems to happen if the line is vertical line i.e. no intersection point between vertical line and circle

Related

Function for Creating Spiral Stripes with Orientation 45 Degrees to Radial?

I am trying to reconstruct the spiral pattern in the depicted image for a neuroscience experiment. Basically, the pattern has the properties that:
1) Every part of the spiral has local orientation 45 degrees to radial
2) The thickness of each arm of the spiral increases in direct proportion with the radius.
Ideally I would like to be able to parametrically vary the number of arms of the spiral as needed. You can ignore the blank circle in the middle and the circular boundaries, those are very easy to add.
Does anybody know if there is a function in terms of the number of spiral arms and local orientation that would be able to reconstruct this spiral pattern? For what it's worth I'm coding in Matlab, although if someone has the mathematical formula I can implement it myself no problem.
Your spiral image does not satisfy your property 1, as can be seen by overlaying the spiral with a flipped copy (the angles at the outer edge are more perpendicular to the radial direction than 45deg, and more parallel at the inner edge):
As I commented, a logarithmic spiral can satisfy both properties. I implemented it in GLSL using Fragmentarium, here is the code:
#include "Progressive2D.frag"
#group Spiral
uniform int Stripes; slider[1,20,100]
const float pi = 3.141592653589793;
vec2 cLog(vec2 z)
{
return vec2(log(length(z)), atan(z.y, z.x));
}
vec3 color(vec2 p)
{
float t = radians(45.0);
float c = cos(t);
float s = sin(t);
mat2 m = mat2(c, -s, s, c);
vec2 q = m * cLog(p);
return vec3(float
( mod(float(Stripes) * q.y / (sqrt(2.0) * pi), 1.0) < 0.5
|| length(p) < 0.125
|| length(p) > 0.875
));
}
And the output:

GSL Fast-Fourier Transform - Non-zero Imaginary for Transformed Gaussian?

As an extension to this question that I asked. The Fourier transform of a real Gaussian is a real Gaussian. Now of course a DFT of a set of points that only resemble a Gaussian will not always be a perfect Gaussian, but it should certainly be close. In the code below I'm taking this [discrete] Fourier transform using GSL. Aside from the issue of the returned/transformed real components (outlined in linked question), I'm getting a weird result for the imaginary component (which should be identically zero). Granted, it's very small in magnitude, but its still weird. What is the cause for this asymmetric & funky output?
#include <gsl/gsl_fft_complex.h>
#include <gsl/gsl_errno.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#define REAL(z,i) ((z)[2*(i)]) //complex arrays stored as [Re(z0),Im(z0),Re(z1),Im(z1),...]
#define IMAG(z,i) ((z)[2*(i)+1])
#define MODU(z,i) ((z)[2*(i)])*((z)[2*(i)])+((z)[2*(i)+1])*((z)[2*(i)+1])
#define PI 3.14159265359
using namespace std;
int main(){
int n = pow(2,9);
double data[2*n];
double N = (double) n;
ofstream file_out("out.txt");
double xmin=-10.;
double xmax=10.;
double dx=(xmax-xmin)/N;
double x=xmin;
for (int i=0; i<n; ++i){
REAL(data,i)=exp(-100.*x*x);
IMAG(data,i)=0.;
x+=dx;
}
gsl_fft_complex_radix2_forward(data, 1, n);
for (int i=0; i<n; ++i){
file_out<<(i-n/2)<<" "<<IMAG(data,((i+n/2)%n))<<'\n';
}
file_out.close();
}
Your result for the imaginary part is correct and expected.
The difference to zero (10^-15) is less than accuracy that you give to pi (12 digits, pi is used in the FFT, but I'm can't know whether you are overriding the pi inside the routine).
The FFT of a real function is not in general a real function. When you do the math analytically you integrate over the following expression:
f(t) e^{i w t} = f(t) cos wt + i f(t) sin wt,
so only if the function f(t) is real and even will the imaginary part (which is otherwise odd) vanish during integration. This has little meaning though, since the real part and imaginary part have physical meaning only in special cases.
Direct physical meaning is in the abs value (magnitude spectrum), the abs. value squared (intensity spectrum) and the phase or angle (phase spectrum).
A more significant offset from zero in the imaginary part would happen if it wasn't centered at the center of your time vector. Try shifting the x vector by some fraction of dx.
See below how the shift of the input by dx/2 (right column) affects the imaginary part, but not the magnitude (example written in Python, Numpy).
from __future__ import division
import numpy as np
import matplotlib.pyplot as p
%matplotlib inline
n=512 # number of samples 2**9
x0,x1=-10,10
dx=(x1-x0)/n
x= np.arange(-10,10,dx) # even number, asymmetric range [-10, 10-dx]
#make signal
s1= np.exp(-100*x**2)
s2= np.exp(-100*(x+dx/2 )**2)
#make ffts
f1=np.fft.fftshift(np.fft.fft(s1))
f2=np.fft.fftshift(np.fft.fft(s2))
#plots
p.figure(figsize=(16,12))
p.subplot(421)
p.title('gaussian (just ctr shown)')
p.plot(s1[250:262])
p.subplot(422)
p.title('same, shifted by dx/2')
p.plot(s2[250:262])
p.subplot(423)
p.plot(np.imag(f1))
p.title('imaginary part of FFT')
p.subplot(424)
p.plot(np.imag(f2))
p.subplot(425)
p.plot(np.real(f1))
p.title('real part of FFT')
p.subplot(426)
p.plot(np.real(f2))
p.subplot(427)
p.plot(np.abs(f1))
p.title('abs. value of FFT')
p.subplot(428)
p.plot(np.abs(f2))

Parallel Anti diagonal 'for' loop?

I have an N x N square matrix of integers (which is stored in the device as a 1-d array for convenience).
I'm implementing an algorithm which requires the following to be performed:
There are 2N anti diagonals in this square. (anti - diagonals are parallel lines from top edge to left edge and right edge to bottom edge)
I need a for loop with 2N iterations with each iteration computing one anti-diagonal starting from the top left and ending at bottom right.
In each iteration, all the elements in that anti-diagonal must run parallelly.
Each anti-diagonal is calculated based on the values of the previous anti-diagonal.
So, how do I index the threads with this requirement in CUDA?
As long as I understand, you want something like
Parallelizing the Smith-Waterman Local Alignment Algorithm using CUDA A
At each iteration, the kernel is launched with a different number of threads.
Perhaps the code in Parallel Anti diagonal 'for' loop could be modified as
int iDivUp(const int a, const int b) { return (a % b != 0) ? (a / b + 1) : (a / b); };
#define BLOCKSIZE 32
__global__ antiparallel(float* d_A, int step, int N) {
int i = threadIdx.x + blockIdx.x* blockDim.x;
int j = step-i;
/* do work on d_A[i*N+j] */
}
for (int step = 0; step < 2*N-1; step++) {
dim3 dimBlock(BLOCKSIZE);
dim3 dimGrid(iDivUp(step,dimBlock.x));
antiparallel<<<dimGrid.x,dimBlock.x>>>(d_A,step,N);
}
This code is untested and is just a sketch of a possible solution (provided that I have not misunderstood your question). Furthermore, I do not know how efficient would be a solution like that since you will have kernels launched with very few threads.

Is there a way to convert "QRST-code" to longitude/latitude?

I did a lot of research for that topic - but it seems not enough, so I'm here asking for help :-)
Google Maps could use QRST-code for specifing a location. I've got a line like that:
trtqtqsss...
and so on. In some other forums I've found out that GM once used that in an URL-Syntax. But now it seems it doesn't work anymore - or at least I don't know how.
Here is an example of the link that won't work anymore:
kh0.google.com/kh?n=404&v=8&t=tq
kh1.google.com/kh?n=404&v=8&t=tr
In this URL, the quadrants are specified with the string after t=.
Is there a converter or something like that?
Thank you in advance!
Partial answer:
From what I gather, the long string of trtqtqss indicates, in essence, a binary search for the location. It roughly translates like this:
Start with the letter t. This gives you "the sholw world"
Look for your point on the map. If it's in the top left quadrant, add a q. If top right, add r. Bottom right, add s. Bottom left, add t.
Zoom in on the new quadrant. Repeat.
Every time you add a letter you halve the size of the tile, and find a new bottom left corner. If we think of the world map as a rectangle of width and height = 1, we can find a new corner for each character added. This is the essence of the algorithm you linked in your comment.
With that, plus the "Rosetta stone" (again from your link) of a known string-to-satellite image translation, I give you the following code. This will give you the Longitude/Latitude of a point based on your string. Compile it, then pass the string as argument to the executable:
#include <stdio.h>
#include <string.h>
#include <math.h>
double NormalToMercator(double y) {
double pi;
pi = 2 * asin(1);
y -= 0.5;
y *= 2 * pi;
y = exp( 2 * y );
y = ( y - 1 ) / ( y + 1 );
y = -asin( y );
return -y * 180 / pi;
}
int main(int argc, char* argv[]) {
double x=0, y=0, scale=1;
char buf[100]={' '};
int ii;
buf[0]=argv[1][0];
for(ii = 1; ii < strlen(argv[1]); ii++) {
buf[ii-1]=argv[1][ii];
scale *= 0.5;
switch (tolower(argv[1][ii])) {
case 'q':
y+=scale;
break;
case 'r':
y+=scale;
x+=scale;
break;
case 's':
x+=scale;
break;
case 't':
break;
default:
break;
}
printf("the string %s gets you to (x,y): %.9lf, %.9lf\n", \
buf, x, y);
}
printf("the final lat/long is %.5lf, %.5lf\n", 360.0 * (x - 0.5), NormalToMercator(y));
}
The intermediate printf statement is there to show you how the algorithm is slowly making its way to the right location. I tested this with the string from the link in your comment (tsrrtrsqsqqqrqrtsst), and got the coordinates 153.39935ºE 28.32372ºS (note - a negative number for longitude means "W", and a negative number for latitude means "S". I got 153.39935, -28.32372). When I entered those in Google maps, I got the picture of the hospital that you get when entering the link from blog post.

CUDA: Getting max value and its index in an array

I have several blocks were each block executes on separate part of an integer array. As an example: block one from array[0] to array[9] and block two from array[10] to array[20].
What is the best way i can get the index of the max value of the array for each block?
Example block one a[0] to a[10] have the following values:
5 10 2 3 4 34 56 3 9 10
So 56 is the largest value at index 6.
I cannot use the shared memory because the size of the array may be very big. Therefore it won't fit. Are there any libraries that allows me to do so fast?
I know about the reduction algorithm, but i think my case is different because i want to get the index of the largest element.
If I understood exactly what you want is : Get the index for the array A of the max value inside it.
If that is true then I would suggest you to use the thrust library:
Here is how you would do it:
#include <thrust/device_vector.h>
#include <thrust/tuple.h>
#include <thrust/reduce.h>
#include <thrust/fill.h>
#include <thrust/generate.h>
#include <thrust/sort.h>
#include <thrust/sequence.h>
#include <thrust/copy.h>
#include <cstdlib>
#include <time.h>
using namespace thrust;
// return the biggest of two tuples
template <class T>
struct bigger_tuple {
__device__ __host__
tuple<T,int> operator()(const tuple<T,int> &a, const tuple<T,int> &b)
{
if (a > b) return a;
else return b;
}
};
template <class T>
int max_index(device_vector<T>& vec) {
// create implicit index sequence [0, 1, 2, ... )
counting_iterator<int> begin(0); counting_iterator<int> end(vec.size());
tuple<T,int> init(vec[0],0);
tuple<T,int> smallest;
smallest = reduce(make_zip_iterator(make_tuple(vec.begin(), begin)), make_zip_iterator(make_tuple(vec.end(), end)),
init, bigger_tuple<T>());
return get<1>(smallest);
}
int main(){
thrust::host_vector<int> h_vec(1024);
thrust::sequence(h_vec.begin(), h_vec.end()); // values = indices
// transfer data to the device
thrust::device_vector<int> d_vec = h_vec;
int index = max_index(d_vec);
std::cout << "Max index is:" << index <<std::endl;
std::cout << "Value is: " << h_vec[index] <<std::endl;
return 0;
}
This will not benefit the original poster but for those who came to this page looking for an answer I would second the recommendation to use thrust that already has a function thrust::max_element that does exactly that - returns an index of the largest element. min_element and minmax_element functions are also provided. See thrust documentation for details here.
As well as the suggestion to use Thrust, you could also use the CUBLAS cublasIsamax function.
The size of your array in comparison to shared memory is almost irrelevant, since the number of threads in each block is the limiting factor rather than the size of the array. One solution is to have each thread block work on a size of the array the same size as the thread block. That is, if you have 512 threads, then block n will be looking at array[ n ] thru array[ n + 511 ]. Each block does a reduction to find the highest member in that portion of the array. Then you bring the max of each section back to the host and do a simple linear search to locate the highest value in the overall array. Each reduction no the GPU reduces the linear search by a factor of 512. Depending on the size of the array, you might want to do more reductions before you bring the data back. (If your array is 3*512^10 in size, you might want to do 10 reductions on the gpu, and have the host search through the 3 remaining data points.)
One thing to watch out for when doing a max value plus index reduction is that if there is more than one identical valued maximum element in your array, i.e. in your example if there were 2 or more values equal to 56, then the index which is returned would not be unique and possibly be different on every run of the code because the timing of the thread ordering over the GPU is not deterministic.
To get around this kind of problem you can use a unique ordering index such as threadid + threadsperblock * blockid, or else the element index location if that is unique. Then the max test is along these lines:
if(a>max_so_far || a==max_so_far && order_a>order_max_so_far)
{
max_so_far = a;
index_max_so_far = index_a;
order_max_so_far = order_a;
}
(index and order can be the same variable, depending on the application.)