Blame view

stim/optics/scalarmie.h 35.9 KB
9339fbad   David Mayerich   implementing mie ...
1
2
  #ifndef STIM_MIE_H
  #define STIM_MIE_H
8309b07a   David Mayerich   fixed some vec3 e...
3
  #include <boost/math/special_functions/bessel.hpp>
9339fbad   David Mayerich   implementing mie ...
4
5
6
  
  #include "scalarwave.h"
  #include "../math/bessel.h"
31262e83   David Mayerich   GPU implementatio...
7
  #include "../cuda/cudatools/devices.h"
9339fbad   David Mayerich   implementing mie ...
8
9
10
11
12
13
14
15
16
17
18
  #include <cmath>
  
  namespace stim{
  
  
  /// Calculate the scattering coefficients for a spherical scatterer
  template<typename T>
  void B_coefficients(stim::complex<T>* B, T a, T k, stim::complex<T> n, int Nl){
  
  	//temporary variables
  	double vm;															//allocate space to store the return values for the bessel function calculation
dd5aab2f   David Mayerich   fixed errors in s...
19
20
21
22
  	double* j_ka = (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* y_ka = (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* dj_ka= (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* dy_ka= (double*) malloc( (Nl + 2) * sizeof(double) );
9339fbad   David Mayerich   implementing mie ...
23
  
dd5aab2f   David Mayerich   fixed errors in s...
24
25
26
27
  	stim::complex<double>* j_kna = (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* y_kna = (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dj_kna= (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dy_kna= (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
9339fbad   David Mayerich   implementing mie ...
28
29
30
31
32
33
34
35
36
37
  
  	double ka = k * a;													//store k*a (argument for spherical bessel and Hankel functions)
  	stim::complex<double> kna = k * n * a;								//store k*n*a (argument for spherical bessel functions and derivatives)
  
  	stim::bessjyv_sph<double>(Nl, ka, vm, j_ka, y_ka, dj_ka, dy_ka);			//calculate bessel functions and derivatives for k*a
  	stim::cbessjyva_sph<double>(Nl, kna, vm, j_kna, y_kna, dj_kna, dy_kna);		//calculate complex bessel functions for k*n*a
  
  	stim::complex<double> h_ka, dh_ka;
  	stim::complex<double> numerator, denominator;
  	stim::complex<double> i(0, 1);
31262e83   David Mayerich   GPU implementatio...
38
  	for(int l = 0; l <= Nl; l++){
9339fbad   David Mayerich   implementing mie ...
39
40
41
42
43
44
45
46
  		h_ka.r = j_ka[l];
  		h_ka.i = y_ka[l];
  		dh_ka.r = dj_ka[l];
  		dh_ka.i = dy_ka[l];
  
  		numerator = j_ka[l] * dj_kna[l] * (stim::complex<double>)n - j_kna[l] * dj_ka[l];
  		denominator = j_kna[l] * dh_ka - h_ka * dj_kna[l] * (stim::complex<double>)n;
  		B[l] = (2 * l + 1) * pow(i, l) * numerator / denominator;
9339fbad   David Mayerich   implementing mie ...
47
  	}
dd5aab2f   David Mayerich   fixed errors in s...
48
49
50
  
  	//free memory
  	free(j_ka); free(y_ka);	free(dj_ka); free(dy_ka); free(j_kna); free(y_kna); free(dj_kna); free(dy_kna);
9339fbad   David Mayerich   implementing mie ...
51
52
53
54
55
56
  }
  
  template<typename T>
  void A_coefficients(stim::complex<T>* A, T a, T k, stim::complex<T> n, int Nl){
  	//temporary variables
  	double vm;															//allocate space to store the return values for the bessel function calculation
dd5aab2f   David Mayerich   fixed errors in s...
57
58
59
60
  	double* j_ka = (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* y_ka = (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* dj_ka= (double*) malloc( (Nl + 2) * sizeof(double) );
  	double* dy_ka= (double*) malloc( (Nl + 2) * sizeof(double) );
9339fbad   David Mayerich   implementing mie ...
61
  
dd5aab2f   David Mayerich   fixed errors in s...
62
63
64
65
  	stim::complex<double>* j_kna = (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* y_kna = (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dj_kna= (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dy_kna= (stim::complex<double>*) malloc( (Nl + 2) * sizeof(stim::complex<double>) );
9339fbad   David Mayerich   implementing mie ...
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
  
  	double ka = k * a;													//store k*a (argument for spherical bessel and Hankel functions)
  	stim::complex<double> kna = k * n * a;								//store k*n*a (argument for spherical bessel functions and derivatives)
  
  	stim::bessjyv_sph<double>(Nl, ka, vm, j_ka, y_ka, dj_ka, dy_ka);			//calculate bessel functions and derivatives for k*a
  	stim::cbessjyva_sph<double>(Nl, kna, vm, j_kna, y_kna, dj_kna, dy_kna);		//calculate complex bessel functions for k*n*a
  
  	stim::complex<double> h_ka, dh_ka;
  	stim::complex<double> numerator, denominator;
  	stim::complex<double> i(0, 1);
  	for(size_t l = 0; l <= Nl; l++){
  		h_ka.r = j_ka[l];
  		h_ka.i = y_ka[l];
  		dh_ka.r = dj_ka[l];
  		dh_ka.i = dy_ka[l];
  
  		numerator = j_ka[l] * dh_ka - dj_ka[l] * h_ka;
  		denominator = j_kna[l] * dh_ka - h_ka * dj_kna[l] * (stim::complex<double>)n;
  		A[l] = (2 * l + 1) * pow(i, l) * numerator / denominator;
  	}
dd5aab2f   David Mayerich   fixed errors in s...
86
87
  	//free memory
  	free(j_ka);	free(y_ka);	free(dj_ka); free(dy_ka); free(j_kna); free(y_kna); free(dj_kna); free(dy_kna);
9339fbad   David Mayerich   implementing mie ...
88
89
  }
  
31262e83   David Mayerich   GPU implementatio...
90
  #define LOCAL_NL	16
9339fbad   David Mayerich   implementing mie ...
91
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
92
  __global__ void cuda_scalar_mie_scatter(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T>* W, size_t nW, T a, stim::complex<T> n, stim::vec3<T> c, stim::complex<T>* hB, T r_min, T dr, size_t N_hB, int Nl){
31262e83   David Mayerich   GPU implementatio...
93
  	extern __shared__ stim::complex<T> shared_hB[];		//declare the list of waves in shared memory
9339fbad   David Mayerich   implementing mie ...
94
95
  
  	size_t i = blockIdx.x * blockDim.x + threadIdx.x;				//get the index into the array
31262e83   David Mayerich   GPU implementatio...
96
  	if(i >= N) return;													//exit if this thread is outside the array
9339fbad   David Mayerich   implementing mie ...
97
98
99
100
  	stim::vec3<T> p;
  	(x == NULL) ? p[0] = 0 : p[0] = x[i];								// test for NULL values and set positions
  	(y == NULL) ? p[1] = 0 : p[1] = y[i];
  	(z == NULL) ? p[2] = 0 : p[2] = z[i];
2a10ecf4   David Mayerich   updated files and...
101
  	p = p - c;
31262e83   David Mayerich   GPU implementatio...
102
103
  	T r = p.len();														//calculate the distance from the sphere
  	if(r < a) return;													//exit if the point is inside the sphere (we only calculate the internal field)
8309b07a   David Mayerich   fixed some vec3 e...
104
  	T fij = (r - r_min)/dr;											//FP index into the spherical bessel LUT
31262e83   David Mayerich   GPU implementatio...
105
106
  	size_t ij = (size_t) fij;											//convert to an integral index
  	T alpha = fij - ij;													//calculate the fractional portion of the index
8309b07a   David Mayerich   fixed some vec3 e...
107
108
  	size_t n0j = ij * (Nl + 1);												//start of the first entry in the LUT
  	size_t n1j = (ij+1) * (Nl + 1);											//start of the second entry in the LUT
9339fbad   David Mayerich   implementing mie ...
109
110
  
  	T cos_phi;	
31262e83   David Mayerich   GPU implementatio...
111
112
113
  	T Pl_2, Pl_1, Pl;														//declare registers to store the previous two Legendre polynomials
  	
  	stim::complex<T> hBl;
9339fbad   David Mayerich   implementing mie ...
114
115
  	stim::complex<T> Ei = 0;											//create a register to store the result
  	int l;
31262e83   David Mayerich   GPU implementatio...
116
  
8309b07a   David Mayerich   fixed some vec3 e...
117
118
  	stim::complex<T> hlBl[LOCAL_NL+1];									//the first LOCAL_NL components are stored in registers for speed
  	int shared_start = threadIdx.x * (Nl - LOCAL_NL);					//wrap up some operations so that they aren't done in the main loops
31262e83   David Mayerich   GPU implementatio...
119
  
8309b07a   David Mayerich   fixed some vec3 e...
120
  	#pragma unroll LOCAL_NL+1											//copy the first LOCAL_NL+1 h_l * B_l components to registers
31262e83   David Mayerich   GPU implementatio...
121
122
123
  	for(l = 0; l <= LOCAL_NL; l++)
  		hlBl[l] = clerp<T>( hB[n0j + l], hB[n1j + l], alpha );
  	
8309b07a   David Mayerich   fixed some vec3 e...
124
  	for(l = LOCAL_NL+1; l <= Nl; l++)									//copy any additional h_l * B_l components to shared memory
31262e83   David Mayerich   GPU implementatio...
125
126
  		shared_hB[shared_start + (l - (LOCAL_NL+1))] = clerp<T>( hB[n0j + l], hB[n1j + l], alpha );
  
2a10ecf4   David Mayerich   updated files and...
127
  	complex<T> e, Ew;
8309b07a   David Mayerich   fixed some vec3 e...
128
  	for(size_t w = 0; w < nW; w++){										//for each plane wave
9339fbad   David Mayerich   implementing mie ...
129
  		cos_phi = p.norm().dot(W[w].kvec().norm());						//calculate the cosine of the angle between the k vector and the direction from the sphere
8309b07a   David Mayerich   fixed some vec3 e...
130
  		Pl_2 = 1;														//the Legendre polynomials will be calculated recursively, initialize the first two steps of the recursive relation
31262e83   David Mayerich   GPU implementatio...
131
  		Pl_1 = cos_phi;
2a10ecf4   David Mayerich   updated files and...
132
133
134
135
  		e = exp(complex<T>(0, W[w].kvec().dot(c)));
  		Ew = W[w].E() * e;
  		Ei += Ew * hlBl[0] * Pl_2;								//unroll the first two orders using the initial steps of the Legendre recursive relation
  		Ei += Ew * hlBl[1] * Pl_1;		
31262e83   David Mayerich   GPU implementatio...
136
  
8309b07a   David Mayerich   fixed some vec3 e...
137
  		#pragma unroll LOCAL_NL-1										//unroll the next LOCAL_NL-1 loops for speed (iterating through the components in the register file)
31262e83   David Mayerich   GPU implementatio...
138
  		for(l = 2; l <= LOCAL_NL; l++){
8309b07a   David Mayerich   fixed some vec3 e...
139
  			Pl = ( (2 * (l-1) + 1) * cos_phi * Pl_1 - (l-1) * Pl_2 ) / (l);	//calculate the next step in the Legendre polynomial recursive relation (this is where most of the computation occurs)
2a10ecf4   David Mayerich   updated files and...
140
  			Ei += Ew * hlBl[l] * Pl;								//calculate and sum the current field order
31262e83   David Mayerich   GPU implementatio...
141
  			Pl_2 = Pl_1;												//shift Pl_1 -> Pl_2 and Pl -> Pl_1
9339fbad   David Mayerich   implementing mie ...
142
  			Pl_1 = Pl;
31262e83   David Mayerich   GPU implementatio...
143
  		}
9339fbad   David Mayerich   implementing mie ...
144
  
8309b07a   David Mayerich   fixed some vec3 e...
145
146
  		for(l = LOCAL_NL+1; l <= Nl; l++){											//do the same as above, except for any additional orders that are stored in shared memory (not registers)
  			Pl = ( (2 * (l-1) + 1) * cos_phi * Pl_1 - (l-1) * Pl_2 ) / (l);				//again, this is where most computation in the kernel occurs
2a10ecf4   David Mayerich   updated files and...
147
  			Ei += Ew * shared_hB[shared_start + l - LOCAL_NL - 1] * Pl;
8309b07a   David Mayerich   fixed some vec3 e...
148
149
  			Pl_2 = Pl_1;															//shift Pl_1 -> Pl_2 and Pl -> Pl_1
  			Pl_1 = Pl;			
9339fbad   David Mayerich   implementing mie ...
150
  		}
9339fbad   David Mayerich   implementing mie ...
151
  	}
31262e83   David Mayerich   GPU implementatio...
152
  	E[i] += Ei;															//copy the result to device memory
9339fbad   David Mayerich   implementing mie ...
153
154
  }
  
2a10ecf4   David Mayerich   updated files and...
155
156
157
158
159
160
161
162
163
164
  ///Calculate the scalar Mie scattered field on the GPU
  /// @param E (GPU) is the N x N destination scalar field
  /// @param N is the number fo elements of the scalar field in each direction
  /// @param x (GPU) is the grid of X coordinates for each point in E
  /// @param y (GPU) is the grid of Y coordinates for each point in E
  /// @param z (GPU) is the grid of Z coordinates for each point in E
  /// @param W (CPU) is an array of coherent scalar plane waves incident on the Mie scatterer
  /// @param a is the radius of the Mie scatterer
  /// @param n is the complex refractive index of the Mie scatterer
  /// @param r_spacing is the minimum distance between r values of the sample points in E (used to calculate look-up tables)
9339fbad   David Mayerich   implementing mie ...
165
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
166
  void gpu_scalar_mie_scatter(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T>* W, size_t nW, T a, stim::complex<T> n, stim::vec3<T> c, stim::complex<T>* hB, T kr_min, T dkr, size_t N_hB, size_t Nl){
31262e83   David Mayerich   GPU implementatio...
167
168
  	
  	size_t max_shared_mem = stim::sharedMemPerBlock();	
8309b07a   David Mayerich   fixed some vec3 e...
169
  	size_t hBl_array = sizeof(stim::complex<T>) * (Nl + 1);
4252d827   David Mayerich   ivote3 fixes and ...
170
171
  	//std::cout<<"hl*Bl array size:  "<<hBl_array<<std::endl;
  	//std::cout<<"shared memory:     "<<max_shared_mem<<std::endl;
8309b07a   David Mayerich   fixed some vec3 e...
172
  	int threads = (int)((max_shared_mem / hBl_array) / 32 * 32);
4252d827   David Mayerich   ivote3 fixes and ...
173
  	//std::cout<<"threads per block: "<<threads<<std::endl;
31262e83   David Mayerich   GPU implementatio...
174
175
176
177
178
  	dim3 blocks((unsigned)(N / threads + 1));										//calculate the optimal number of blocks
  
  	size_t shared_mem;
  	if(Nl <= LOCAL_NL) shared_mem = 0;
  	else shared_mem = threads * sizeof(stim::complex<T>) * (Nl - LOCAL_NL);				//amount of shared memory to allocate
4252d827   David Mayerich   ivote3 fixes and ...
179
  	//std::cout<<"shared memory allocated: "<<shared_mem<<std::endl;
2a10ecf4   David Mayerich   updated files and...
180
  	cuda_scalar_mie_scatter<T><<< blocks, threads, shared_mem >>>(E, N, x, y, z, W, nW, a, n, c, hB, kr_min, dkr, N_hB, (int)Nl);	//call the kernel
31262e83   David Mayerich   GPU implementatio...
181
182
183
  }
  
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
184
  __global__ void cuda_dist(T* r, T* x, T* y, T* z, size_t N, stim::vec3<T> c = stim::vec3<T>(0, 0, 0)){
31262e83   David Mayerich   GPU implementatio...
185
186
187
188
189
190
191
192
  	size_t i = blockIdx.x * blockDim.x + threadIdx.x;				//get the index into the array
  	if(i >= N) return;													//exit if this thread is outside the array
  
  	stim::vec3<T> p;
  	(x == NULL) ? p[0] = 0 : p[0] = x[i];								// test for NULL values and set positions
  	(y == NULL) ? p[1] = 0 : p[1] = y[i];
  	(z == NULL) ? p[2] = 0 : p[2] = z[i];
  
2a10ecf4   David Mayerich   updated files and...
193
  	r[i] = (p - c).len();
9339fbad   David Mayerich   implementing mie ...
194
  }
2a10ecf4   David Mayerich   updated files and...
195
196
197
198
199
200
201
202
203
204
205
  
  ///Calculate the scalar Mie scattered field on the GPU
  /// @param E (GPU) is the N x N destination scalar field
  /// @param N is the number fo elements of the scalar field in each direction
  /// @param x (GPU) is the grid of X coordinates for each point in E
  /// @param y (GPU) is the grid of Y coordinates for each point in E
  /// @param z (GPU) is the grid of Z coordinates for each point in E
  /// @param W (CPU) is an array of coherent scalar plane waves incident on the Mie scatterer
  /// @param a is the radius of the Mie scatterer
  /// @param n is the complex refractive index of the Mie scatterer
  /// @param r_spacing is the minimum distance between r values of the sample points in E (used to calculate look-up tables)
9339fbad   David Mayerich   implementing mie ...
206
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
207
  void gpu_scalar_mie_scatter(stim::complex<T>* E, size_t N, T* x, T* y, T* z, std::vector<stim::scalarwave<T>> W, T a, stim::complex<T> n, stim::vec3<T> c = stim::vec3<T>(0, 0, 0), T r_spacing = 0.1){
4252d827   David Mayerich   ivote3 fixes and ...
208
  	
9339fbad   David Mayerich   implementing mie ...
209
210
211
  	//calculate the necessary number of orders required to represent the scattered field
  	T k = W[0].kmag();
  
31262e83   David Mayerich   GPU implementatio...
212
213
  	int Nl = (int)ceil(k*a + 4 * cbrt( k * a ) + 2);
  	if(Nl < LOCAL_NL) Nl = LOCAL_NL;							//always do at least the minimum number of local operations (kernel optimization)
4252d827   David Mayerich   ivote3 fixes and ...
214
  	//std::cout<<"Nl: "<<Nl<<std::endl;
9339fbad   David Mayerich   implementing mie ...
215
216
217
  
  	//calculate the scattering coefficients for the sphere
  	stim::complex<T>* B = (stim::complex<T>*) malloc( sizeof(stim::complex<T>) * (Nl + 1) );	//allocate space for the scattering coefficients
4252d827   David Mayerich   ivote3 fixes and ...
218
219
  	B_coefficients(B, a, k, n, Nl);	
  	
9339fbad   David Mayerich   implementing mie ...
220
221
222
223
224
  	//	PLANE WAVES
  	stim::scalarwave<T>* dev_W;																//allocate space and copy plane waves
  	HANDLE_ERROR( cudaMalloc(&dev_W, sizeof(stim::scalarwave<T>) * W.size()) );
  	HANDLE_ERROR( cudaMemcpy(dev_W, &W[0], sizeof(stim::scalarwave<T>) * W.size(), cudaMemcpyHostToDevice) );
  
9339fbad   David Mayerich   implementing mie ...
225
  	// BESSEL FUNCTION LOOK-UP TABLE
31262e83   David Mayerich   GPU implementatio...
226
227
228
229
230
231
  	//calculate the distance from the sphere center
  	T* dev_r;
  	HANDLE_ERROR( cudaMalloc(&dev_r, sizeof(T) * N) );
  		
  	int threads = stim::maxThreadsPerBlock();
  	dim3 blocks((unsigned)(N / threads + 1));
2a10ecf4   David Mayerich   updated files and...
232
  	cuda_dist<T> <<< blocks, threads >>>(dev_r, x, y, z, N, c);
31262e83   David Mayerich   GPU implementatio...
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
  
  	//Find the minimum and maximum values of r
      cublasStatus_t stat;
      cublasHandle_t handle;
  
  	stat = cublasCreate(&handle);							//create a cuBLAS handle
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS initialization failed\n");
  		exit(1);
  	}
  
  	int i_min, i_max;
  	stat = cublasIsamin(handle, (int)N, dev_r, 1, &i_min);
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS Error: failed to calculate minimum r value.\n");
  		exit(1);
  	}
  	stat = cublasIsamax(handle, (int)N, dev_r, 1, &i_max);
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS Error: failed to calculate maximum r value.\n");
  		exit(1);
  	}
  
8309b07a   David Mayerich   fixed some vec3 e...
256
257
  	i_min--;				//cuBLAS uses 1-based indexing for Fortran compatibility
  	i_max--;
31262e83   David Mayerich   GPU implementatio...
258
259
260
261
  	T r_min, r_max;											//allocate space to store the minimum and maximum values
  	HANDLE_ERROR( cudaMemcpy(&r_min, dev_r + i_min, sizeof(T), cudaMemcpyDeviceToHost) );		//copy the min and max values from the device to the CPU
  	HANDLE_ERROR( cudaMemcpy(&r_max, dev_r + i_max, sizeof(T), cudaMemcpyDeviceToHost) );
  
8309b07a   David Mayerich   fixed some vec3 e...
262
  	r_min = max(r_min, a);									//if the radius of the sphere is larger than r_min, change r_min to a (the scattered field doesn't exist inside the sphere)
31262e83   David Mayerich   GPU implementatio...
263
  
9339fbad   David Mayerich   implementing mie ...
264
  	//size_t Nlut_j = (size_t)((r_max - r_min) / r_spacing + 1);			//number of values in the look-up table based on the user-specified spacing along r
31262e83   David Mayerich   GPU implementatio...
265
  	size_t N_hB_lut = (size_t)((r_max - r_min) / r_spacing + 1);
9339fbad   David Mayerich   implementing mie ...
266
  
8309b07a   David Mayerich   fixed some vec3 e...
267
268
  	//T kr_min = k * r_min;
  	//T kr_max = k * r_max;
9339fbad   David Mayerich   implementing mie ...
269
270
271
272
273
274
275
276
  
  	//temporary variables
  	double vm;															//allocate space to store the return values for the bessel function calculation
  	double* jv = (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* yv = (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* djv= (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* dyv= (double*) malloc( (Nl + 1) * sizeof(double) );
  
31262e83   David Mayerich   GPU implementatio...
277
278
  	size_t hB_bytes = sizeof(stim::complex<T>) * (Nl+1) * N_hB_lut;
  	stim::complex<T>* hB_lut = (stim::complex<T>*) malloc(hB_bytes);													//pointer to the look-up table
8309b07a   David Mayerich   fixed some vec3 e...
279
  	T dr = (r_max - r_min) / (N_hB_lut-1);												//distance between values in the LUT
4252d827   David Mayerich   ivote3 fixes and ...
280
  	//std::cout<<"LUT jl bytes:  "<<hB_bytes<<std::endl;
31262e83   David Mayerich   GPU implementatio...
281
  	stim::complex<T> hl;
8309b07a   David Mayerich   fixed some vec3 e...
282
283
  	for(size_t ri = 0; ri < N_hB_lut; ri++){													//for each value in the LUT
  		stim::bessjyv_sph<double>(Nl, k * (r_min + ri * dr), vm, jv, yv, djv, dyv);		//compute the list of spherical bessel functions from [0 Nl]
9339fbad   David Mayerich   implementing mie ...
284
  		for(size_t l = 0; l <= Nl; l++){													//for each order
31262e83   David Mayerich   GPU implementatio...
285
286
287
  			hl.r = (T)jv[l];
  			hl.i = (T)yv[l];
  
8309b07a   David Mayerich   fixed some vec3 e...
288
289
  			hB_lut[ri * (Nl + 1) + l] = hl * B[l];										//store the bessel function result
  			//std::cout<<hB_lut[ri * (Nl + 1) + l]<<std::endl;
9339fbad   David Mayerich   implementing mie ...
290
291
  		}
  	}
4252d827   David Mayerich   ivote3 fixes and ...
292
293
294
  	//T* real_lut = (T*) malloc(hB_bytes/2);
  	//stim::real(real_lut, hB_lut, N_hB_lut);
  	//stim::cpu2image<T>(real_lut, "hankel_B.bmp", Nl+1, N_hB_lut, stim::cmBrewer);
9339fbad   David Mayerich   implementing mie ...
295
296
  
  	//Allocate device memory and copy everything to the GPU
31262e83   David Mayerich   GPU implementatio...
297
298
299
  	stim::complex<T>* dev_hB_lut;
  	HANDLE_ERROR( cudaMalloc(&dev_hB_lut, hB_bytes) );
  	HANDLE_ERROR( cudaMemcpy(dev_hB_lut, hB_lut, hB_bytes, cudaMemcpyHostToDevice) );
2a10ecf4   David Mayerich   updated files and...
300
301
302
  	//std::cout << "r_min: " << r_min << std::endl;
  	//std::cout << "dr: " << dr << std::endl;
  	gpu_scalar_mie_scatter<T>(E, N, x, y, z, dev_W, W.size(), a, n, c, dev_hB_lut, r_min, dr, N_hB_lut, Nl);
9339fbad   David Mayerich   implementing mie ...
303
  
2a10ecf4   David Mayerich   updated files and...
304
305
306
307
308
  	HANDLE_ERROR(cudaMemcpy(E, E, N * sizeof(stim::complex<T>), cudaMemcpyDeviceToHost));			//copy the field from device memory
  
  	HANDLE_ERROR(cudaFree(dev_hB_lut));
  	HANDLE_ERROR(cudaFree(dev_r));
  	HANDLE_ERROR(cudaFree(dev_W));
9339fbad   David Mayerich   implementing mie ...
309
  
4252d827   David Mayerich   ivote3 fixes and ...
310
311
312
313
314
315
316
317
318
319
320
321
  }
  /// Calculate the scalar Mie solution for the scattered field produced by a single plane wave
  
  /// @param E is a pointer to the destination field values
  /// @param N is the number of points used to calculate the field
  /// @param x is an array of x coordinates for each point, specified relative to the sphere (x = NULL assumes all zeros)
  /// @param y is an array of y coordinates for each point, specified relative to the sphere (y = NULL assumes all zeros)
  /// @param z is an array of z coordinates for each point, specified relative to the sphere (z = NULL assumes all zeros)
  /// @param W is an array of planewaves that will be scattered
  /// @param a is the radius of the sphere
  /// @param n is the complex refractive index of the sphere
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
322
  void cpu_scalar_mie_scatter(stim::complex<T>* E, size_t N, T* x, T* y, T* z, std::vector<stim::scalarwave<T>> W, T a, stim::complex<T> n, stim::vec3<T> c = stim::vec3<T>(0, 0, 0)){
4252d827   David Mayerich   ivote3 fixes and ...
323
324
  	
  
2a10ecf4   David Mayerich   updated files and...
325
  /*#ifdef CUDA_FOUND
4252d827   David Mayerich   ivote3 fixes and ...
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
  	stim::complex<T>* dev_E;										//allocate space for the field
  	cudaMalloc(&dev_E, N * sizeof(stim::complex<T>));
  	cudaMemcpy(dev_E, E, N * sizeof(stim::complex<T>), cudaMemcpyHostToDevice);
  	//cudaMemset(dev_F, 0, N * sizeof(stim::complex<T>));				//set the field to zero (necessary because a sum is used)
  
  	//	COORDINATES
  	T* dev_x = NULL;												//allocate space and copy the X coordinate (if specified)
  	if(x != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_x, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_x, x, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  	T* dev_y = NULL;												//allocate space and copy the Y coordinate (if specified)
  	if(y != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_y, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_y, y, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  	T* dev_z = NULL;												//allocate space and copy the Z coordinate (if specified)
  	if(z != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_z, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_z, z, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  
2a10ecf4   David Mayerich   updated files and...
348
  	gpu_scalar_mie_scatter(dev_E, N, dev_x, dev_y, dev_z, W, a, n, c, r_spacing);
9339fbad   David Mayerich   implementing mie ...
349
350
351
352
353
354
  
  	if(x != NULL) cudaFree(dev_x);														//free everything
  	if(y != NULL) cudaFree(dev_y);
  	if(z != NULL) cudaFree(dev_z);
  	cudaFree(dev_E);
  #else
2a10ecf4   David Mayerich   updated files and...
355
  */
9339fbad   David Mayerich   implementing mie ...
356
  	
4252d827   David Mayerich   ivote3 fixes and ...
357
358
359
360
361
362
363
364
365
366
  	//calculate the necessary number of orders required to represent the scattered field
  	T k = W[0].kmag();
  
  	int Nl = (int)ceil(k*a + 4 * cbrt( k * a ) + 2);
  	if(Nl < LOCAL_NL) Nl = LOCAL_NL;							//always do at least the minimum number of local operations (kernel optimization)
  	//std::cout<<"Nl: "<<Nl<<std::endl;
  
  	//calculate the scattering coefficients for the sphere
  	stim::complex<T>* B = (stim::complex<T>*) malloc( sizeof(stim::complex<T>) * (Nl + 1) );	//allocate space for the scattering coefficients
  	B_coefficients(B, a, k, n, Nl);
9339fbad   David Mayerich   implementing mie ...
367
368
369
370
371
372
373
374
375
376
377
378
  
  	//allocate space to store the bessel function call results
  	double vm;										
  	double* j_kr = (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* y_kr = (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* dj_kr= (double*) malloc( (Nl + 1) * sizeof(double) );
  	double* dy_kr= (double*) malloc( (Nl + 1) * sizeof(double) );
  
  	T* P = (T*) malloc( (Nl + 1) * sizeof(T) );
  
  	T r, kr, cos_phi;
  	stim::complex<T> h;
2a10ecf4   David Mayerich   updated files and...
379
  	stim::complex<T> Ew;
9339fbad   David Mayerich   implementing mie ...
380
381
382
383
384
385
  	for(size_t i = 0; i < N; i++){
  		stim::vec3<T> p;															//declare a 3D point
  	
  		(x == NULL) ? p[0] = 0 : p[0] = x[i];										// test for NULL values and set positions
  		(y == NULL) ? p[1] = 0 : p[1] = y[i];
  		(z == NULL) ? p[2] = 0 : p[2] = z[i];
2a10ecf4   David Mayerich   updated files and...
386
  		p = p - c;
9339fbad   David Mayerich   implementing mie ...
387
388
389
  		r = p.len();
  		if(r >= a){
  			for(size_t w = 0; w < W.size(); w++){
2a10ecf4   David Mayerich   updated files and...
390
  				Ew = W[w].E() * exp(stim::complex<double>(0, W[w].kvec().dot(c)));
9339fbad   David Mayerich   implementing mie ...
391
392
393
394
395
396
397
398
  				kr = p.len() * W[w].kmag();											//calculate k*r
  				stim::bessjyv_sph<double>(Nl, kr, vm, j_kr, y_kr, dj_kr, dy_kr);
  				cos_phi = p.norm().dot(W[w].kvec().norm());							//calculate the cosine of the angle from the propagating direction
  				stim::legendre<T>(Nl, cos_phi, P);
  
  				for(size_t l = 0; l <= Nl; l++){
  					h.r = j_kr[l];
  					h.i = y_kr[l];
2a10ecf4   David Mayerich   updated files and...
399
  					E[i] += Ew * B[l] * h * P[l];
9339fbad   David Mayerich   implementing mie ...
400
401
402
403
  				}
  			}
  		}
  	}
2a10ecf4   David Mayerich   updated files and...
404
  //#endif
9339fbad   David Mayerich   implementing mie ...
405
406
407
  }
  
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
408
  void cpu_scalar_mie_scatter(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T> w, T a, stim::complex<T> n, stim::vec3<T> c = stim::vec3<T>(0, 0, 0), T r_spacing = 0.1){
9339fbad   David Mayerich   implementing mie ...
409
  	std::vector< stim::scalarwave<T> > W(1, w);
2a10ecf4   David Mayerich   updated files and...
410
  	cpu_scalar_mie_scatter(E, N, x, y, z, W, a, n, c, r_spacing);
8309b07a   David Mayerich   fixed some vec3 e...
411
412
413
414
415
416
417
418
419
420
421
422
423
424
  }
  
  template<typename T>
  __global__ void cuda_scalar_mie_internal(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T>* W, size_t nW, T a, stim::complex<T> n, stim::complex<T>* jA, T r_min, T dr, size_t N_jA, int Nl){
  	extern __shared__ stim::complex<T> shared_jA[];		//declare the list of waves in shared memory
  
  	size_t i = blockIdx.x * blockDim.x + threadIdx.x;				//get the index into the array
  	if(i >= N) return;													//exit if this thread is outside the array
  	stim::vec3<T> p;
  	(x == NULL) ? p[0] = 0 : p[0] = x[i];								// test for NULL values and set positions
  	(y == NULL) ? p[1] = 0 : p[1] = y[i];
  	(z == NULL) ? p[2] = 0 : p[2] = z[i];
  	
  	T r = p.len();														//calculate the distance from the sphere
963d0676   David Mayerich   bug fixes related...
425
  	if(r >= a) return;													//exit if the point is inside the sphere (we only calculate the internal field)
2a10ecf4   David Mayerich   updated files and...
426
  	T fij = (r - r_min)/dr;												//FP index into the spherical bessel LUT
8309b07a   David Mayerich   fixed some vec3 e...
427
428
  	size_t ij = (size_t) fij;											//convert to an integral index
  	T alpha = fij - ij;													//calculate the fractional portion of the index
2a10ecf4   David Mayerich   updated files and...
429
430
  	size_t n0j = ij * (Nl + 1);											//start of the first entry in the LUT
  	size_t n1j = (ij+1) * (Nl + 1);										//start of the second entry in the LUT
8309b07a   David Mayerich   fixed some vec3 e...
431
432
  
  	T cos_phi;	
2a10ecf4   David Mayerich   updated files and...
433
  	T Pl_2, Pl_1, Pl;													//declare registers to store the previous two Legendre polynomials
8309b07a   David Mayerich   fixed some vec3 e...
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
  	
  	stim::complex<T> jAl;
  	stim::complex<T> Ei = 0;											//create a register to store the result
  	int l;
  
  	stim::complex<T> jlAl[LOCAL_NL+1];									//the first LOCAL_NL components are stored in registers for speed
  	int shared_start = threadIdx.x * (Nl - LOCAL_NL);					//wrap up some operations so that they aren't done in the main loops
  
  	#pragma unroll LOCAL_NL+1											//copy the first LOCAL_NL+1 h_l * B_l components to registers
  	for(l = 0; l <= LOCAL_NL; l++)
  		jlAl[l] = clerp<T>( jA[n0j + l], jA[n1j + l], alpha );
  	
  	for(l = LOCAL_NL+1; l <= Nl; l++)									//copy any additional h_l * B_l components to shared memory
  		shared_jA[shared_start + (l - (LOCAL_NL+1))] = clerp<T>( jA[n0j + l], jA[n1j + l], alpha );
  
  	for(size_t w = 0; w < nW; w++){										//for each plane wave
  		if(r == 0) cos_phi = 0;
  		else
2a10ecf4   David Mayerich   updated files and...
452
  			cos_phi = p.norm().dot(W[w].kvec().norm());					//calculate the cosine of the angle between the k vector and the direction from the sphere
8309b07a   David Mayerich   fixed some vec3 e...
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
  		Pl_2 = 1;														//the Legendre polynomials will be calculated recursively, initialize the first two steps of the recursive relation
  		Pl_1 = cos_phi;
  		Ei += W[w].E() * jlAl[0] * Pl_2;								//unroll the first two orders using the initial steps of the Legendre recursive relation
  		Ei += W[w].E() * jlAl[1] * Pl_1;		
  
  		#pragma unroll LOCAL_NL-1										//unroll the next LOCAL_NL-1 loops for speed (iterating through the components in the register file)
  		for(l = 2; l <= LOCAL_NL; l++){
  			Pl = ( (2 * (l-1) + 1) * cos_phi * Pl_1 - (l-1) * Pl_2 ) / (l);	//calculate the next step in the Legendre polynomial recursive relation (this is where most of the computation occurs)
  			Ei += W[w].E() * jlAl[l] * Pl;								//calculate and sum the current field order
  			Pl_2 = Pl_1;												//shift Pl_1 -> Pl_2 and Pl -> Pl_1
  			Pl_1 = Pl;
  		}
  
  		for(l = LOCAL_NL+1; l <= Nl; l++){											//do the same as above, except for any additional orders that are stored in shared memory (not registers)
  			Pl = ( (2 * (l-1) + 1) * cos_phi * Pl_1 - (l-1) * Pl_2 ) / (l);				//again, this is where most computation in the kernel occurs
  			Ei += W[w].E() * shared_jA[shared_start + l - LOCAL_NL - 1] * Pl;
  			Pl_2 = Pl_1;															//shift Pl_1 -> Pl_2 and Pl -> Pl_1
  			Pl_1 = Pl;			
  		}
  	}
  	E[i] = Ei;															//copy the result to device memory
  }
  
  template<typename T>
  void gpu_scalar_mie_internal(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T>* W, size_t nW, T a, stim::complex<T> n, stim::complex<T>* jA, T r_min, T dr, size_t N_jA, size_t Nl){
  	
  	size_t max_shared_mem = stim::sharedMemPerBlock();	
  	size_t hBl_array = sizeof(stim::complex<T>) * (Nl + 1);
4252d827   David Mayerich   ivote3 fixes and ...
481
482
  	//std::cout<<"hl*Bl array size:  "<<hBl_array<<std::endl;
  	//std::cout<<"shared memory:     "<<max_shared_mem<<std::endl;
8309b07a   David Mayerich   fixed some vec3 e...
483
  	int threads = (int)((max_shared_mem / hBl_array) / 32 * 32);
4252d827   David Mayerich   ivote3 fixes and ...
484
  	//std::cout<<"threads per block: "<<threads<<std::endl;
8309b07a   David Mayerich   fixed some vec3 e...
485
486
487
488
489
  	dim3 blocks((unsigned)(N / threads + 1));										//calculate the optimal number of blocks
  
  	size_t shared_mem;
  	if(Nl <= LOCAL_NL) shared_mem = 0;
  	else shared_mem = threads * sizeof(stim::complex<T>) * (Nl - LOCAL_NL);				//amount of shared memory to allocate
4252d827   David Mayerich   ivote3 fixes and ...
490
  	//std::cout<<"shared memory allocated: "<<shared_mem<<std::endl;
8309b07a   David Mayerich   fixed some vec3 e...
491
  	cuda_scalar_mie_internal<T><<< blocks, threads, shared_mem >>>(E, N, x, y, z, W, nW, a, n, jA, r_min, dr, N_jA, (int)Nl);	//call the kernel
9339fbad   David Mayerich   implementing mie ...
492
493
494
495
496
497
498
499
500
501
502
503
504
  }
  
  /// Calculate the scalar Mie solution for the internal field produced by a single plane wave scattered by a sphere
  
  /// @param E is a pointer to the destination field values
  /// @param N is the number of points used to calculate the field
  /// @param x is an array of x coordinates for each point, specified relative to the sphere (x = NULL assumes all zeros)
  /// @param y is an array of y coordinates for each point, specified relative to the sphere (y = NULL assumes all zeros)
  /// @param z is an array of z coordinates for each point, specified relative to the sphere (z = NULL assumes all zeros)
  /// @param w is a planewave that will be scattered
  /// @param a is the radius of the sphere
  /// @param n is the complex refractive index of the sphere
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
505
  void cpu_scalar_mie_internal(stim::complex<T>* E, size_t N, T* x, T* y, T* z, std::vector< stim::scalarwave<T> > W, T a, stim::complex<T> n, stim::vec3<T> c = stim::vec3<T>(0, 0, 0)){
8309b07a   David Mayerich   fixed some vec3 e...
506
  //calculate the necessary number of orders required to represent the scattered field
9339fbad   David Mayerich   implementing mie ...
507
508
  	T k = W[0].kmag();
  
8309b07a   David Mayerich   fixed some vec3 e...
509
510
  	int Nl = (int)ceil(k*a + 4 * cbrt( k * a ) + 2);
  	if(Nl < LOCAL_NL) Nl = LOCAL_NL;							//always do at least the minimum number of local operations (kernel optimization)
4252d827   David Mayerich   ivote3 fixes and ...
511
  	//std::cout<<"Nl: "<<Nl<<std::endl;
9339fbad   David Mayerich   implementing mie ...
512
513
514
515
516
  
  	//calculate the scattering coefficients for the sphere
  	stim::complex<T>* A = (stim::complex<T>*) malloc( sizeof(stim::complex<T>) * (Nl + 1) );	//allocate space for the scattering coefficients
  	A_coefficients(A, a, k, n, Nl);
  
2a10ecf4   David Mayerich   updated files and...
517
  /*#ifdef CUDA_FOUND
8309b07a   David Mayerich   fixed some vec3 e...
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
  	stim::complex<T>* dev_E;										//allocate space for the field
  	cudaMalloc(&dev_E, N * sizeof(stim::complex<T>));
  	cudaMemcpy(dev_E, E, N * sizeof(stim::complex<T>), cudaMemcpyHostToDevice);
  	//cudaMemset(dev_F, 0, N * sizeof(stim::complex<T>));				//set the field to zero (necessary because a sum is used)
  
  	//	COORDINATES
  	T* dev_x = NULL;												//allocate space and copy the X coordinate (if specified)
  	if(x != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_x, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_x, x, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  	T* dev_y = NULL;												//allocate space and copy the Y coordinate (if specified)
  	if(y != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_y, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_y, y, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  	T* dev_z = NULL;												//allocate space and copy the Z coordinate (if specified)
  	if(z != NULL){
  		HANDLE_ERROR(cudaMalloc(&dev_z, N * sizeof(T)));
  		HANDLE_ERROR(cudaMemcpy(dev_z, z, N * sizeof(T), cudaMemcpyHostToDevice));
  	}
  
  	//	PLANE WAVES
  	stim::scalarwave<T>* dev_W;																//allocate space and copy plane waves
  	HANDLE_ERROR( cudaMalloc(&dev_W, sizeof(stim::scalarwave<T>) * W.size()) );
  	HANDLE_ERROR( cudaMemcpy(dev_W, &W[0], sizeof(stim::scalarwave<T>) * W.size(), cudaMemcpyHostToDevice) );
  
  	// BESSEL FUNCTION LOOK-UP TABLE
  	//calculate the distance from the sphere center
  	T* dev_r;
  	HANDLE_ERROR( cudaMalloc(&dev_r, sizeof(T) * N) );
  		
  	int threads = stim::maxThreadsPerBlock();
  	dim3 blocks((unsigned)(N / threads + 1));
  	cuda_dist<T> <<< blocks, threads >>>(dev_r, dev_x, dev_y, dev_z, N);
  
  	//Find the minimum and maximum values of r
      cublasStatus_t stat;
      cublasHandle_t handle;
  
  	stat = cublasCreate(&handle);							//create a cuBLAS handle
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS initialization failed\n");
  		exit(1);
  	}
  
  	int i_min, i_max;
  	stat = cublasIsamin(handle, (int)N, dev_r, 1, &i_min);
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS Error: failed to calculate minimum r value.\n");
  		exit(1);
  	}
  	stat = cublasIsamax(handle, (int)N, dev_r, 1, &i_max);
  	if (stat != CUBLAS_STATUS_SUCCESS){						//test for failure
          printf ("CUBLAS Error: failed to calculate maximum r value.\n");
  		exit(1);
  	}
2a10ecf4   David Mayerich   updated files and...
575
  	cublasDestroy(handle);									//destroy the CUBLAS handle
8309b07a   David Mayerich   fixed some vec3 e...
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
  
  	i_min--;				//cuBLAS uses 1-based indexing for Fortran compatibility
  	i_max--;
  	T r_min, r_max;											//allocate space to store the minimum and maximum values
  	HANDLE_ERROR( cudaMemcpy(&r_min, dev_r + i_min, sizeof(T), cudaMemcpyDeviceToHost) );		//copy the min and max values from the device to the CPU
  	HANDLE_ERROR( cudaMemcpy(&r_max, dev_r + i_max, sizeof(T), cudaMemcpyDeviceToHost) );
  
  	r_max = min(r_max, a);		//the internal field doesn't exist outside of the sphere
  
  	size_t N_jA_lut = (size_t)((r_max - r_min) / r_spacing + 1);
  
  	//temporary variables
  	double vm;															//allocate space to store the return values for the bessel function calculation
  	stim::complex<double>* jv = (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* yv = (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* djv= (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dyv= (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  
  	size_t jA_bytes = sizeof(stim::complex<T>) * (Nl+1) * N_jA_lut;
  	stim::complex<T>* jA_lut = (stim::complex<T>*) malloc(jA_bytes);													//pointer to the look-up table
  	T dr = (r_max - r_min) / (N_jA_lut-1);												//distance between values in the LUT
4252d827   David Mayerich   ivote3 fixes and ...
597
  	//std::cout<<"LUT jl bytes:  "<<jA_bytes<<std::endl;
8309b07a   David Mayerich   fixed some vec3 e...
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
  	stim::complex<T> hl;
  	stim::complex<double> nd = (stim::complex<double>)n;
  	for(size_t ri = 0; ri < N_jA_lut; ri++){													//for each value in the LUT
  		stim::cbessjyva_sph<double>(Nl, nd * k * (r_min + ri * dr), vm, jv, yv, djv, dyv);		//compute the list of spherical bessel functions from [0 Nl]
  		for(size_t l = 0; l <= Nl; l++){													//for each order
  			jA_lut[ri * (Nl + 1) + l] = (stim::complex<T>)(jv[l] * (stim::complex<double>)A[l]);										//store the bessel function result
  		}
  	}
  
  	//Allocate device memory and copy everything to the GPU
  	stim::complex<T>* dev_jA_lut;
  	HANDLE_ERROR( cudaMalloc(&dev_jA_lut, jA_bytes) );
  	HANDLE_ERROR( cudaMemcpy(dev_jA_lut, jA_lut, jA_bytes, cudaMemcpyHostToDevice) );
  
  	gpu_scalar_mie_internal<T>(dev_E, N, dev_x, dev_y, dev_z, dev_W, W.size(), a, n, dev_jA_lut, r_min, dr, N_jA_lut, Nl);
  
  	cudaMemcpy(E, dev_E, N * sizeof(stim::complex<T>), cudaMemcpyDeviceToHost);			//copy the field from device memory
  
  	if(x != NULL) cudaFree(dev_x);														//free everything
  	if(y != NULL) cudaFree(dev_y);
  	if(z != NULL) cudaFree(dev_z);
4252d827   David Mayerich   ivote3 fixes and ...
619
620
621
622
  	HANDLE_ERROR( cudaFree(dev_jA_lut) );
  	HANDLE_ERROR( cudaFree(dev_E) );
  	HANDLE_ERROR( cudaFree(dev_W) );
  	HANDLE_ERROR( cudaFree(dev_r) );
2a10ecf4   David Mayerich   updated files and...
623
  	HANDLE_ERROR( cudaFree(dev_E) );
8309b07a   David Mayerich   fixed some vec3 e...
624
  #else
2a10ecf4   David Mayerich   updated files and...
625
  */
9339fbad   David Mayerich   implementing mie ...
626
627
628
629
630
631
632
633
634
635
636
637
  	//allocate space to store the bessel function call results
  	double vm;										
  	stim::complex<double>* j_knr = (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* y_knr = (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dj_knr= (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  	stim::complex<double>* dy_knr= (stim::complex<double>*) malloc( (Nl + 1) * sizeof(stim::complex<double>) );
  
  	T* P = (T*) malloc( (Nl + 1) * sizeof(T) );
  
  	T r, cos_phi;
  	stim::complex<double> knr;
  	stim::complex<T> h;
2a10ecf4   David Mayerich   updated files and...
638
  	stim::complex<T> Ew;
9339fbad   David Mayerich   implementing mie ...
639
640
641
642
643
644
  	for(size_t i = 0; i < N; i++){
  		stim::vec3<T> p;									//declare a 3D point
  	
  		(x == NULL) ? p[0] = 0 : p[0] = x[i];				// test for NULL values and set positions
  		(y == NULL) ? p[1] = 0 : p[1] = y[i];
  		(z == NULL) ? p[2] = 0 : p[2] = z[i];
2a10ecf4   David Mayerich   updated files and...
645
  		p = p - c;
9339fbad   David Mayerich   implementing mie ...
646
647
648
649
  		r = p.len();
  		if(r < a){
  			E[i] = 0;
  			for(size_t w = 0; w < W.size(); w++){
2a10ecf4   David Mayerich   updated files and...
650
  				Ew = W[w].E() * exp(stim::complex<double>(0, W[w].kvec().dot(c)));
9339fbad   David Mayerich   implementing mie ...
651
652
653
654
655
656
657
658
659
660
  				knr = (stim::complex<double>)n * p.len() * W[w].kmag();							//calculate k*n*r
  
  				stim::cbessjyva_sph<double>(Nl, knr, vm, j_knr, y_knr, dj_knr, dy_knr);
  				if(r == 0)
  					cos_phi = 0;
  				else
  					cos_phi = p.norm().dot(W[w].kvec().norm());				//calculate the cosine of the angle from the propagating direction
  				stim::legendre<T>(Nl, cos_phi, P);
  								
  				for(size_t l = 0; l <= Nl; l++){
2a10ecf4   David Mayerich   updated files and...
661
  					E[i] += Ew * A[l] * (stim::complex<T>)j_knr[l] * P[l];
9339fbad   David Mayerich   implementing mie ...
662
663
664
665
  				}
  			}
  		}
  	}
2a10ecf4   David Mayerich   updated files and...
666
  //#endif
9339fbad   David Mayerich   implementing mie ...
667
668
669
  }
  
  template<typename T>
2a10ecf4   David Mayerich   updated files and...
670
  void cpu_scalar_mie_internal(stim::complex<T>* E, size_t N, T* x, T* y, T* z, stim::scalarwave<T> w, T a, stim::complex<T> n, stim::vec3<T> c = stim::vec3<T>(0, 0, 0)){
9339fbad   David Mayerich   implementing mie ...
671
  	std::vector< stim::scalarwave<T> > W(1, w);
2a10ecf4   David Mayerich   updated files and...
672
  	cpu_scalar_mie_internal(E, N, x, y, z, W, a, n, c);
9339fbad   David Mayerich   implementing mie ...
673
674
  }
  
963d0676   David Mayerich   bug fixes related...
675
676
677
678
679
  
  /// Class stim::scalarmie represents a scalar Mie scattering model that can be used to calculate the fields produced by a scattering sphere.
  template<typename T>
  class scalarmie
  {
2a10ecf4   David Mayerich   updated files and...
680
  public:
963d0676   David Mayerich   bug fixes related...
681
682
  	T radius;					//radius of the scattering sphere
  	stim::complex<T> n;			//refractive index of the scattering sphere
2a10ecf4   David Mayerich   updated files and...
683
  	vec3<T> c;					//position of the sphere in space
963d0676   David Mayerich   bug fixes related...
684
685
686
  	
  public:
  
2a10ecf4   David Mayerich   updated files and...
687
688
689
690
691
692
693
  	scalarmie() {				//default constructor
  		radius = 0.5;
  		n = stim::complex<T>(1.4, 0.0);
  		c = stim::vec3<T>(0, 0, 0);
  	}
  
  	scalarmie(T r, stim::complex<T> ri, stim::vec3<T> center = stim::vec3<T>(0, 0, 0)){
963d0676   David Mayerich   bug fixes related...
694
695
  		radius = r;
  		n = ri;
2a10ecf4   David Mayerich   updated files and...
696
697
  		c = center;
  		//c = stim::vec3<T>(2, 1, 0);
963d0676   David Mayerich   bug fixes related...
698
699
  	}
  
2a10ecf4   David Mayerich   updated files and...
700
701
702
703
  	//void sum_scat(stim::scalarfield<T>& E, T* X, T* Y, T* Z, stim::scalarbeam<T> b, int samples = 1000){
  	//	std::vector< stim::scalarwave<float> > wave_array = b.mc(samples);			//decompose the beam into an array of plane waves
  	//	stim::cpu_scalar_mie_scatter<float>(E.ptr(), E.size(), X, Y, Z, wave_array, radius, n, E.spacing());
  	//}
4252d827   David Mayerich   ivote3 fixes and ...
704
  
2a10ecf4   David Mayerich   updated files and...
705
706
707
708
  	//void sum_intern(stim::scalarfield<T>& E, T* X, T* Y, T* Z, stim::scalarbeam<T> b, int samples = 1000){
  	//	std::vector< stim::scalarwave<float> > wave_array = b.mc(samples);			//decompose the beam into an array of plane waves
  	//	stim::cpu_scalar_mie_internal<float>(E.ptr(), E.size(), X, Y, Z, wave_array, radius, n, E.spacing());
  	//}
4252d827   David Mayerich   ivote3 fixes and ...
709
  
2a10ecf4   David Mayerich   updated files and...
710
711
712
713
714
715
  	//void eval(stim::scalarfield<T>& E, T* X, T* Y, T* Z, stim::scalarbeam<T> b, int order = 500, int samples = 1000){
  	//	b.eval(E, X, Y, Z, order);													//evaluate the incident field using a plane wave expansion
  	//	std::vector< stim::scalarwave<float> > wave_array = b.mc(samples);			//decompose the beam into an array of plane waves		
  	//	sum_scat(E, X, Y, Z, b, samples);
  	//	sum_intern(E, X, Y, Z, b, samples);
  	//}
4252d827   David Mayerich   ivote3 fixes and ...
716
  
963d0676   David Mayerich   bug fixes related...
717
718
  	void eval(stim::scalarfield<T>& E, stim::scalarbeam<T> b, int order = 500, int samples = 1000){
  
4252d827   David Mayerich   ivote3 fixes and ...
719
720
  		E.meshgrid();
  		b.eval(E, order);
963d0676   David Mayerich   bug fixes related...
721
722
  
  		std::vector< stim::scalarwave<float> > wave_array = b.mc(samples);			//decompose the beam into an array of plane waves
4252d827   David Mayerich   ivote3 fixes and ...
723
724
  
  		if(E.gpu()){
2a10ecf4   David Mayerich   updated files and...
725
  			stim::gpu_scalar_mie_scatter<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, c, E.spacing());
4252d827   David Mayerich   ivote3 fixes and ...
726
727
728
729
730
  		}
  		else{
  			stim::cpu_scalar_mie_scatter<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, E.spacing());
  			stim::cpu_scalar_mie_internal<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, E.spacing());
  		}
963d0676   David Mayerich   bug fixes related...
731
732
733
734
  	}
  
  };			//end stim::scalarmie
  
2a10ecf4   David Mayerich   updated files and...
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
  template<typename T>
  class scalarcluster : public std::vector< scalarmie<T> > {
  public:
  
  	void eval(stim::scalarfield<T>& E, stim::scalarbeam<T> b, int order = 500, int samples = 1000) {
  		E.meshgrid();
  		b.eval(E, order);
  
  		std::vector< stim::scalarwave<float> > wave_array = b.mc(samples);			//decompose the beam into an array of plane waves
  
  		T radius;
  		stim::complex<T> n;
  		stim::vec3<T> c;
  		for (size_t si = 0; si < size(); si++) {									//for each sphere in the cluster
  			radius = at(si).radius;
  			n = at(si).n;
  			c = at(si).c;
  			if (E.gpu()) {
  				stim::gpu_scalar_mie_scatter<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, c, E.spacing());
  			}
  			else {
  				stim::cpu_scalar_mie_scatter<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, c);
  				stim::cpu_scalar_mie_internal<float>(E.ptr(), E.size(), E.x(), E.y(), E.z(), wave_array, radius, n, c);
  			}
  		}
  	}
  };
  
963d0676   David Mayerich   bug fixes related...
763
  }			//end namespace stim
9339fbad   David Mayerich   implementing mie ...
764
765
  
  #endif