nmie.cc 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301
  1. ///
  2. /// @file nmie.cc
  3. /// @author Ladutenko Konstantin <kostyfisik at gmail (.) com>
  4. /// @date Tue Sep 3 00:38:27 2013
  5. /// @copyright 2013 Ladutenko Konstantin
  6. ///
  7. /// nmie is free software: you can redistribute it and/or modify
  8. /// it under the terms of the GNU General Public License as published by
  9. /// the Free Software Foundation, either version 3 of the License, or
  10. /// (at your option) any later version.
  11. ///
  12. /// nmie-wrapper is distributed in the hope that it will be useful,
  13. /// but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. /// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. /// GNU General Public License for more details.
  16. ///
  17. /// You should have received a copy of the GNU General Public License
  18. /// along with nmie-wrapper. If not, see <http://www.gnu.org/licenses/>.
  19. ///
  20. /// nmie uses nmie.c from scattnlay by Ovidio Pena
  21. /// <ovidio@bytesfall.com> . He has an additional condition to
  22. /// his library:
  23. // The only additional condition is that we expect that all publications //
  24. // describing work using this software , or all commercial products //
  25. // using it, cite the following reference: //
  26. // [1] O. Pena and U. Pal, "Scattering of electromagnetic radiation by //
  27. // a multilayered sphere," Computer Physics Communications, //
  28. // vol. 180, Nov. 2009, pp. 2348-2354. //
  29. ///
  30. /// @brief Wrapper class around nMie function for ease of use
  31. ///
  32. #include "nmie.h"
  33. #include <array>
  34. #include <algorithm>
  35. #include <cstdio>
  36. #include <cstdlib>
  37. #include <stdexcept>
  38. #include <vector>
  39. namespace nmie {
  40. //helpers
  41. template<class T> inline T pow2(const T value) {return value*value;}
  42. //#define round(x) ((x) >= 0 ? (int)((x) + 0.5):(int)((x) - 0.5))
  43. int round(double x) {
  44. return x >= 0 ? (int)(x + 0.5):(int)(x - 0.5);
  45. }
  46. // ********************************************************************** //
  47. // ********************************************************************** //
  48. // ********************************************************************** //
  49. //emulate C call.
  50. int nMie_wrapper(int L, const std::vector<double>& x, const std::vector<std::complex<double> >& m,
  51. int nTheta, const std::vector<double>& Theta,
  52. double *Qext, double *Qsca, double *Qabs, double *Qbk, double *Qpr, double *g, double *Albedo,
  53. std::vector<std::complex<double> >& S1, std::vector<std::complex<double> >& S2) {
  54. if (x.size() != L || m.size() != L)
  55. throw std::invalid_argument("Declared number of layers do not fit x and m!");
  56. if (Theta.size() != nTheta)
  57. throw std::invalid_argument("Declared number of sample for Theta is not correct!");
  58. try {
  59. MultiLayerMie multi_layer_mie;
  60. multi_layer_mie.SetWidthSP(x);
  61. multi_layer_mie.SetIndexSP(m);
  62. multi_layer_mie.SetAngles(Theta);
  63. multi_layer_mie.RunMieCalculations();
  64. *Qext = multi_layer_mie.GetQext();
  65. *Qsca = multi_layer_mie.GetQsca();
  66. *Qabs = multi_layer_mie.GetQabs();
  67. *Qbk = multi_layer_mie.GetQbk();
  68. *Qpr = multi_layer_mie.GetQpr();
  69. *g = multi_layer_mie.GetAsymmetryFactor();
  70. *Albedo = multi_layer_mie.GetAlbedo();
  71. S1 = multi_layer_mie.GetS1();
  72. S2 = multi_layer_mie.GetS2();
  73. multi_layer_mie.GetFailed();
  74. } catch( const std::invalid_argument& ia ) {
  75. // Will catch if multi_layer_mie fails or other errors.
  76. std::cerr << "Invalid argument: " << ia.what() << std::endl;
  77. throw std::invalid_argument(ia);
  78. return -1;
  79. }
  80. return 0;
  81. }
  82. // ********************************************************************** //
  83. // ********************************************************************** //
  84. // ********************************************************************** //
  85. void MultiLayerMie::GetFailed() {
  86. double faild_x = 9.42477796076938;
  87. //double faild_x = 9.42477796076937;
  88. std::complex<double> z(faild_x, 0.0);
  89. std::vector<int> nmax_local_array = {20, 100, 500, 2500};
  90. for (auto nmax_local : nmax_local_array) {
  91. std::vector<std::complex<double> > D1_failed(nmax_local +1);
  92. // Downward recurrence for D1 - equations (16a) and (16b)
  93. D1_failed[nmax_local] = std::complex<double>(0.0, 0.0);
  94. const std::complex<double> zinv = std::complex<double>(1.0, 0.0)/z;
  95. for (int n = nmax_local; n > 0; n--) {
  96. D1_failed[n - 1] = double(n)*zinv - 1.0/(D1_failed[n] + double(n)*zinv);
  97. }
  98. printf("Faild D1[0] from reccurence (z = %16.14f, nmax = %d): %g\n",
  99. faild_x, nmax_local, D1_failed[0].real());
  100. }
  101. printf("Faild D1[0] from continued fraction (z = %16.14f): %g\n", faild_x,
  102. calcD1confra(0,z).real());
  103. //D1[nmax_] = calcD1confra(nmax_, z);
  104. }
  105. // ********************************************************************** //
  106. // ********************************************************************** //
  107. // ********************************************************************** //
  108. double MultiLayerMie::GetQext() {
  109. if (!isMieCalculated_)
  110. throw std::invalid_argument("You should run calculations before result reques!");
  111. return Qext_;
  112. }
  113. // ********************************************************************** //
  114. // ********************************************************************** //
  115. // ********************************************************************** //
  116. double MultiLayerMie::GetQabs() {
  117. if (!isMieCalculated_)
  118. throw std::invalid_argument("You should run calculations before result reques!");
  119. return Qabs_;
  120. }
  121. // ********************************************************************** //
  122. // ********************************************************************** //
  123. // ********************************************************************** //
  124. double MultiLayerMie::GetQsca() {
  125. if (!isMieCalculated_)
  126. throw std::invalid_argument("You should run calculations before result reques!");
  127. return Qsca_;
  128. }
  129. // ********************************************************************** //
  130. // ********************************************************************** //
  131. // ********************************************************************** //
  132. double MultiLayerMie::GetQbk() {
  133. if (!isMieCalculated_)
  134. throw std::invalid_argument("You should run calculations before result reques!");
  135. return Qbk_;
  136. }
  137. // ********************************************************************** //
  138. // ********************************************************************** //
  139. // ********************************************************************** //
  140. double MultiLayerMie::GetQpr() {
  141. if (!isMieCalculated_)
  142. throw std::invalid_argument("You should run calculations before result reques!");
  143. return Qpr_;
  144. }
  145. // ********************************************************************** //
  146. // ********************************************************************** //
  147. // ********************************************************************** //
  148. double MultiLayerMie::GetAsymmetryFactor() {
  149. if (!isMieCalculated_)
  150. throw std::invalid_argument("You should run calculations before result reques!");
  151. return asymmetry_factor_;
  152. }
  153. // ********************************************************************** //
  154. // ********************************************************************** //
  155. // ********************************************************************** //
  156. double MultiLayerMie::GetAlbedo() {
  157. if (!isMieCalculated_)
  158. throw std::invalid_argument("You should run calculations before result reques!");
  159. return albedo_;
  160. }
  161. // ********************************************************************** //
  162. // ********************************************************************** //
  163. // ********************************************************************** //
  164. std::vector<std::complex<double> > MultiLayerMie::GetS1() {
  165. return S1_;
  166. }
  167. // ********************************************************************** //
  168. // ********************************************************************** //
  169. // ********************************************************************** //
  170. std::vector<std::complex<double> > MultiLayerMie::GetS2() {
  171. return S2_;
  172. }
  173. // ********************************************************************** //
  174. // ********************************************************************** //
  175. // ********************************************************************** //
  176. void MultiLayerMie::AddTargetLayer(double width, std::complex<double> layer_index) {
  177. if (width <= 0)
  178. throw std::invalid_argument("Layer width should be positive!");
  179. target_width_.push_back(width);
  180. target_index_.push_back(layer_index);
  181. } // end of void MultiLayerMie::AddTargetLayer(...)
  182. // ********************************************************************** //
  183. // ********************************************************************** //
  184. // ********************************************************************** //
  185. void MultiLayerMie::SetTargetPEC(double radius) {
  186. if (target_width_.size() != 0 || target_index_.size() != 0)
  187. throw std::invalid_argument("Error! Define PEC target radius before any other layers!");
  188. // Add layer of any index...
  189. AddTargetLayer(radius, std::complex<double>(0.0, 0.0));
  190. // ... and mark it as PEC
  191. SetPEC(0.0);
  192. }
  193. // ********************************************************************** //
  194. // ********************************************************************** //
  195. // ********************************************************************** //
  196. void MultiLayerMie::SetCoatingIndex(std::vector<std::complex<double> > index) {
  197. coating_index_.clear();
  198. for (auto value : index) coating_index_.push_back(value);
  199. } // end of void MultiLayerMie::SetCoatingIndex(std::vector<complex> index);
  200. // ********************************************************************** //
  201. // ********************************************************************** //
  202. // ********************************************************************** //
  203. void MultiLayerMie::SetAngles(const std::vector<double>& angles) {
  204. isMieCalculated_ = false;
  205. theta_ = angles;
  206. // theta_.clear();
  207. // for (auto value : angles) theta_.push_back(value);
  208. } // end of SetAngles()
  209. // ********************************************************************** //
  210. // ********************************************************************** //
  211. // ********************************************************************** //
  212. void MultiLayerMie::SetCoatingWidth(std::vector<double> width) {
  213. coating_width_.clear();
  214. for (auto w : width)
  215. if (w <= 0)
  216. throw std::invalid_argument("Coating width should be positive!");
  217. else coating_width_.push_back(w);
  218. }
  219. // end of void MultiLayerMie::SetCoatingWidth(...);
  220. // ********************************************************************** //
  221. // ********************************************************************** //
  222. // ********************************************************************** //
  223. void MultiLayerMie::SetWidthSP(const std::vector<double>& size_parameter) {
  224. isMieCalculated_ = false;
  225. size_parameter_.clear();
  226. double prev_size_parameter = 0.0;
  227. for (auto layer_size_parameter : size_parameter) {
  228. if (layer_size_parameter <= 0.0)
  229. throw std::invalid_argument("Size parameter should be positive!");
  230. if (prev_size_parameter > layer_size_parameter)
  231. throw std::invalid_argument
  232. ("Size parameter for next layer should be larger than the previous one!");
  233. prev_size_parameter = layer_size_parameter;
  234. size_parameter_.push_back(layer_size_parameter);
  235. }
  236. }
  237. // end of void MultiLayerMie::SetWidthSP(...);
  238. // ********************************************************************** //
  239. // ********************************************************************** //
  240. // ********************************************************************** //
  241. void MultiLayerMie::SetIndexSP(const std::vector< std::complex<double> >& index) {
  242. isMieCalculated_ = false;
  243. //index_.clear();
  244. index_ = index;
  245. // for (auto value : index) index_.push_back(value);
  246. } // end of void MultiLayerMie::SetIndexSP(...);
  247. // ********************************************************************** //
  248. // ********************************************************************** //
  249. // ********************************************************************** //
  250. void MultiLayerMie::SetPEC(int layer_position) {
  251. if (layer_position < 0)
  252. throw std::invalid_argument("Error! Layers are numbered from 0!");
  253. PEC_layer_position_ = layer_position;
  254. }
  255. // ********************************************************************** //
  256. // ********************************************************************** //
  257. // ********************************************************************** //
  258. void MultiLayerMie::SetMaxTermsNumber(int nmax) {
  259. nmax_preset_ = nmax;
  260. //debug
  261. printf("Setting max terms: %d\n", nmax_preset_);
  262. }
  263. // ********************************************************************** //
  264. // ********************************************************************** //
  265. // ********************************************************************** //
  266. void MultiLayerMie::GenerateSizeParameter() {
  267. size_parameter_.clear();
  268. double radius = 0.0;
  269. for (auto width : target_width_) {
  270. radius += width;
  271. size_parameter_.push_back(2*PI*radius / wavelength_);
  272. }
  273. for (auto width : coating_width_) {
  274. radius += width;
  275. size_parameter_.push_back(2*PI*radius / wavelength_);
  276. }
  277. total_radius_ = radius;
  278. } // end of void MultiLayerMie::GenerateSizeParameter();
  279. // ********************************************************************** //
  280. // ********************************************************************** //
  281. // ********************************************************************** //
  282. void MultiLayerMie::GenerateIndex() {
  283. index_.clear();
  284. for (auto index : target_index_) index_.push_back(index);
  285. for (auto index : coating_index_) index_.push_back(index);
  286. } // end of void MultiLayerMie::GenerateIndex();
  287. // ********************************************************************** //
  288. // ********************************************************************** //
  289. // ********************************************************************** //
  290. double MultiLayerMie::GetTotalRadius() {
  291. if (total_radius_ == 0) GenerateSizeParameter();
  292. return total_radius_;
  293. } // end of double MultiLayerMie::GetTotalRadius();
  294. // ********************************************************************** //
  295. // ********************************************************************** //
  296. // ********************************************************************** //
  297. std::vector< std::vector<double> >
  298. MultiLayerMie::GetSpectra(double from_WL, double to_WL, int samples) {
  299. std::vector< std::vector<double> > spectra;
  300. double step_WL = (to_WL - from_WL)/ static_cast<double>(samples);
  301. double wavelength_backup = wavelength_;
  302. long fails = 0;
  303. for (double WL = from_WL; WL < to_WL; WL += step_WL) {
  304. wavelength_ = WL;
  305. try {
  306. RunMieCalculations();
  307. } catch( const std::invalid_argument& ia ) {
  308. fails++;
  309. continue;
  310. }
  311. //printf("%3.1f ",WL);
  312. spectra.push_back(std::vector<double>({wavelength_, Qext_, Qsca_, Qabs_, Qbk_}));
  313. } // end of for each WL in spectra
  314. printf("Spectrum has %li fails\n",fails);
  315. wavelength_ = wavelength_backup;
  316. return spectra;
  317. }
  318. // ********************************************************************** //
  319. // ********************************************************************** //
  320. // ********************************************************************** //
  321. void MultiLayerMie::ClearTarget() {
  322. target_width_.clear();
  323. target_index_.clear();
  324. }
  325. // ********************************************************************** //
  326. // ********************************************************************** //
  327. // ********************************************************************** //
  328. void MultiLayerMie::ClearCoating() {
  329. coating_width_.clear();
  330. coating_index_.clear();
  331. }
  332. // ********************************************************************** //
  333. // ********************************************************************** //
  334. // ********************************************************************** //
  335. void MultiLayerMie::ClearLayers() {
  336. ClearTarget();
  337. ClearCoating();
  338. }
  339. // ********************************************************************** //
  340. // ********************************************************************** //
  341. // ********************************************************************** //
  342. void MultiLayerMie::ClearAllDesign() {
  343. ClearLayers();
  344. size_parameter_.clear();
  345. index_.clear();
  346. }
  347. // ********************************************************************** //
  348. // ********************************************************************** //
  349. // ********************************************************************** //
  350. // Computational core
  351. // ********************************************************************** //
  352. // ********************************************************************** //
  353. // ********************************************************************** //
  354. // Calculate Nstop - equation (17)
  355. //
  356. void MultiLayerMie::Nstop() {
  357. const double& xL = size_parameter_.back();
  358. if (xL <= 8) {
  359. nmax_ = round(xL + 4.0*pow(xL, 1.0/3.0) + 1);
  360. } else if (xL <= 4200) {
  361. nmax_ = round(xL + 4.05*pow(xL, 1.0/3.0) + 2);
  362. } else {
  363. nmax_ = round(xL + 4.0*pow(xL, 1.0/3.0) + 2);
  364. }
  365. }
  366. // ********************************************************************** //
  367. // ********************************************************************** //
  368. // ********************************************************************** //
  369. void MultiLayerMie::Nmax(int first_layer) {
  370. int ri, riM1;
  371. const std::vector<double>& x = size_parameter_;
  372. const std::vector<std::complex<double> >& m = index_;
  373. Nstop(); // Set initial nmax_ value
  374. for (int i = first_layer; i < x.size(); i++) {
  375. if (i > PEC_layer_position_)
  376. ri = round(std::abs(x[i]*m[i]));
  377. else
  378. ri = 0;
  379. nmax_ = std::max(nmax_, ri);
  380. // first layer is pec, if pec is present
  381. if ((i > first_layer) && ((i - 1) > PEC_layer_position_))
  382. riM1 = round(std::abs(x[i - 1]* m[i]));
  383. else
  384. riM1 = 0;
  385. nmax_ = std::max(nmax_, riM1);
  386. }
  387. nmax_ += 15; // Final nmax_ value
  388. }
  389. //**********************************************************************************//
  390. // This function calculates the spherical Bessel (jn) and Hankel (h1n) functions //
  391. // and their derivatives for a given complex value z. See pag. 87 B&H. //
  392. // //
  393. // Input parameters: //
  394. // z: Real argument to evaluate jn and h1n //
  395. // nmax_: Maximum number of terms to calculate jn and h1n //
  396. // //
  397. // Output parameters: //
  398. // jn, h1n: Spherical Bessel and Hankel functions //
  399. // jnp, h1np: Derivatives of the spherical Bessel and Hankel functions //
  400. // //
  401. // The implementation follows the algorithm by I.J. Thompson and A.R. Barnett, //
  402. // Comp. Phys. Comm. 47 (1987) 245-257. //
  403. // //
  404. // Complex spherical Bessel functions from n=0..nmax_-1 for z in the upper half //
  405. // plane (Im(z) > -3). //
  406. // //
  407. // j[n] = j/n(z) Regular solution: j[0]=sin(z)/z //
  408. // j'[n] = d[j/n(z)]/dz //
  409. // h1[n] = h[0]/n(z) Irregular Hankel function: //
  410. // h1'[n] = d[h[0]/n(z)]/dz h1[0] = j0(z) + i*y0(z) //
  411. // = (sin(z)-i*cos(z))/z //
  412. // = -i*exp(i*z)/z //
  413. // Using complex CF1, and trigonometric forms for n=0 solutions. //
  414. //**********************************************************************************//
  415. void MultiLayerMie::sbesjh(std::complex<double> z,
  416. std::vector<std::complex<double> >& jn,
  417. std::vector<std::complex<double> >& jnp,
  418. std::vector<std::complex<double> >& h1n,
  419. std::vector<std::complex<double> >& h1np) {
  420. const int limit = 20000;
  421. const double accur = 1.0e-12;
  422. const double tm30 = 1e-30;
  423. double absc;
  424. std::complex<double> zi, w;
  425. std::complex<double> pl, f, b, d, c, del, jn0, jndb, h1nldb, h1nbdb;
  426. absc = std::abs(std::real(z)) + std::abs(std::imag(z));
  427. if ((absc < accur) || (std::imag(z) < -3.0)) {
  428. throw std::invalid_argument("TODO add error description for condition if ((absc < accur) || (std::imag(z) < -3.0))");
  429. }
  430. zi = 1.0/z;
  431. w = zi + zi;
  432. pl = double(nmax_)*zi;
  433. f = pl + zi;
  434. b = f + f + zi;
  435. d = 0.0;
  436. c = f;
  437. for (int n = 0; n < limit; n++) {
  438. d = b - d;
  439. c = b - 1.0/c;
  440. absc = std::abs(std::real(d)) + std::abs(std::imag(d));
  441. if (absc < tm30) {
  442. d = tm30;
  443. }
  444. absc = std::abs(std::real(c)) + std::abs(std::imag(c));
  445. if (absc < tm30) {
  446. c = tm30;
  447. }
  448. d = 1.0/d;
  449. del = d*c;
  450. f = f*del;
  451. b += w;
  452. absc = std::abs(std::real(del - 1.0)) + std::abs(std::imag(del - 1.0));
  453. if (absc < accur) {
  454. // We have obtained the desired accuracy
  455. break;
  456. }
  457. }
  458. if (absc > accur) {
  459. throw std::invalid_argument("We were not able to obtain the desired accuracy");
  460. }
  461. jn[nmax_ - 1] = tm30;
  462. jnp[nmax_ - 1] = f*jn[nmax_ - 1];
  463. // Downward recursion to n=0 (N.B. Coulomb Functions)
  464. for (int n = nmax_ - 2; n >= 0; n--) {
  465. jn[n] = pl*jn[n + 1] + jnp[n + 1];
  466. jnp[n] = pl*jn[n] - jn[n + 1];
  467. pl = pl - zi;
  468. }
  469. // Calculate the n=0 Bessel Functions
  470. jn0 = zi*std::sin(z);
  471. h1n[0] = std::exp(std::complex<double>(0.0, 1.0)*z)*zi*(-std::complex<double>(0.0, 1.0));
  472. h1np[0] = h1n[0]*(std::complex<double>(0.0, 1.0) - zi);
  473. // Rescale j[n], j'[n], converting to spherical Bessel functions.
  474. // Recur h1[n], h1'[n] as spherical Bessel functions.
  475. w = 1.0/jn[0];
  476. pl = zi;
  477. for (int n = 0; n < nmax_; n++) {
  478. jn[n] = jn0*(w*jn[n]);
  479. jnp[n] = jn0*(w*jnp[n]) - zi*jn[n];
  480. if (n != 0) {
  481. h1n[n] = (pl - zi)*h1n[n - 1] - h1np[n - 1];
  482. // check if hankel is increasing (upward stable)
  483. if (std::abs(h1n[n]) < std::abs(h1n[n - 1])) {
  484. jndb = z;
  485. h1nldb = h1n[n];
  486. h1nbdb = h1n[n - 1];
  487. }
  488. pl += zi;
  489. h1np[n] = -(pl*h1n[n]) + h1n[n - 1];
  490. }
  491. }
  492. }
  493. //**********************************************************************************//
  494. // This function calculates the spherical Bessel functions (bj and by) and the //
  495. // logarithmic derivative (bd) for a given complex value z. See pag. 87 B&H. //
  496. // //
  497. // Input parameters: //
  498. // z: Complex argument to evaluate bj, by and bd //
  499. // nmax_: Maximum number of terms to calculate bj, by and bd //
  500. // //
  501. // Output parameters: //
  502. // bj, by: Spherical Bessel functions //
  503. // bd: Logarithmic derivative //
  504. //**********************************************************************************//
  505. void MultiLayerMie::sphericalBessel(std::complex<double> z,
  506. std::vector<std::complex<double> >& bj,
  507. std::vector<std::complex<double> >& by,
  508. std::vector<std::complex<double> >& bd) {
  509. std::vector<std::complex<double> > jn(nmax_), jnp(nmax_), h1n(nmax_), h1np(nmax_);
  510. sbesjh(z, jn, jnp, h1n, h1np);
  511. for (int n = 0; n < nmax_; n++) {
  512. bj[n] = jn[n];
  513. by[n] = (h1n[n] - jn[n])/std::complex<double>(0.0, 1.0);
  514. bd[n] = jnp[n]/jn[n] + 1.0/z;
  515. }
  516. }
  517. // ********************************************************************** //
  518. // ********************************************************************** //
  519. // ********************************************************************** //
  520. // Calculate an - equation (5)
  521. std::complex<double> MultiLayerMie::calc_an(int n, double XL, std::complex<double> Ha, std::complex<double> mL,
  522. std::complex<double> PsiXL, std::complex<double> ZetaXL,
  523. std::complex<double> PsiXLM1, std::complex<double> ZetaXLM1) {
  524. std::complex<double> Num = (Ha/mL + n/XL)*PsiXL - PsiXLM1;
  525. std::complex<double> Denom = (Ha/mL + n/XL)*ZetaXL - ZetaXLM1;
  526. return Num/Denom;
  527. }
  528. // ********************************************************************** //
  529. // ********************************************************************** //
  530. // ********************************************************************** //
  531. // Calculate bn - equation (6)
  532. std::complex<double> MultiLayerMie::calc_bn(int n, double XL, std::complex<double> Hb, std::complex<double> mL,
  533. std::complex<double> PsiXL, std::complex<double> ZetaXL,
  534. std::complex<double> PsiXLM1, std::complex<double> ZetaXLM1) {
  535. std::complex<double> Num = (mL*Hb + n/XL)*PsiXL - PsiXLM1;
  536. std::complex<double> Denom = (mL*Hb + n/XL)*ZetaXL - ZetaXLM1;
  537. return Num/Denom;
  538. }
  539. // ********************************************************************** //
  540. // ********************************************************************** //
  541. // ********************************************************************** //
  542. // Calculates S1 - equation (25a)
  543. std::complex<double> MultiLayerMie::calc_S1(int n, std::complex<double> an, std::complex<double> bn,
  544. double Pi, double Tau) {
  545. return double(n + n + 1)*(Pi*an + Tau*bn)/double(n*n + n);
  546. }
  547. // ********************************************************************** //
  548. // ********************************************************************** //
  549. // ********************************************************************** //
  550. // Calculates S2 - equation (25b) (it's the same as (25a), just switches Pi and Tau)
  551. std::complex<double> MultiLayerMie::calc_S2(int n, std::complex<double> an, std::complex<double> bn,
  552. double Pi, double Tau) {
  553. return calc_S1(n, an, bn, Tau, Pi);
  554. }
  555. //**********************************************************************************//
  556. // This function calculates the Riccati-Bessel functions (Psi and Zeta) for a //
  557. // real argument (x). //
  558. // Equations (20a) - (21b) //
  559. // //
  560. // Input parameters: //
  561. // x: Real argument to evaluate Psi and Zeta //
  562. // nmax: Maximum number of terms to calculate Psi and Zeta //
  563. // //
  564. // Output parameters: //
  565. // Psi, Zeta: Riccati-Bessel functions //
  566. //**********************************************************************************//
  567. void MultiLayerMie::calcPsiZeta(double x,
  568. std::vector<std::complex<double> > D1,
  569. std::vector<std::complex<double> > D3,
  570. std::vector<std::complex<double> >& Psi,
  571. std::vector<std::complex<double> >& Zeta) {
  572. //Upward recurrence for Psi and Zeta - equations (20a) - (21b)
  573. Psi[0] = std::complex<double>(sin(x), 0);
  574. Zeta[0] = std::complex<double>(sin(x), -cos(x));
  575. for (int n = 1; n <= nmax_; n++) {
  576. Psi[n] = Psi[n - 1]*(n/x - D1[n - 1]);
  577. Zeta[n] = Zeta[n - 1]*(n/x - D3[n - 1]);
  578. }
  579. }
  580. //**********************************************************************************//
  581. // Function CONFRA ported from MIEV0.f (Wiscombe,1979)
  582. // Ref. to NCAR Technical Notes, Wiscombe, 1979
  583. /*
  584. c Compute Bessel function ratio A-sub-N from its
  585. c continued fraction using Lentz method
  586. c ZINV = Reciprocal of argument of A
  587. c I N T E R N A L V A R I A B L E S
  588. c ------------------------------------
  589. c CAK Term in continued fraction expansion of A (Eq. R25)
  590. c a_k
  591. c CAPT Factor used in Lentz iteration for A (Eq. R27)
  592. c T_k
  593. c CNUMER Numerator in capT ( Eq. R28A )
  594. c N_k
  595. c CDENOM Denominator in capT ( Eq. R28B )
  596. c D_k
  597. c CDTD Product of two successive denominators of capT factors
  598. c ( Eq. R34C )
  599. c xi_1
  600. c CNTN Product of two successive numerators of capT factors
  601. c ( Eq. R34B )
  602. c xi_2
  603. c EPS1 Ill-conditioning criterion
  604. c EPS2 Convergence criterion
  605. c KK Subscript k of cAk ( Eq. R25B )
  606. c k
  607. c KOUNT Iteration counter ( used to prevent infinite looping )
  608. c MAXIT Max. allowed no. of iterations
  609. c MM + 1 and - 1, alternately
  610. */
  611. std::complex<double> MultiLayerMie::calcD1confra(const int N, const std::complex<double> z) {
  612. // NTMR -> nmax_ -1 \\TODO nmax_ ?
  613. //int N = nmax_ - 1;
  614. int KK, KOUNT, MAXIT = 10000, MM;
  615. // double EPS1=1.0e-2;
  616. double EPS2=1.0e-8;
  617. std::complex<double> CAK, CAPT, CDENOM, CDTD, CNTN, CNUMER;
  618. std::complex<double> one = std::complex<double>(1.0,0.0);
  619. std::complex<double> ZINV = one/z;
  620. // c ** Eq. R25a
  621. std::complex<double> CONFRA = static_cast<std::complex<double> >(N+1)*ZINV; //debug ZINV
  622. MM = -1;
  623. KK = 2*N +3; //debug 3
  624. // c ** Eq. R25b, k=2
  625. CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; //debug -3 ZINV
  626. CDENOM = CAK;
  627. CNUMER = CDENOM + one / CONFRA; //-3zinv+z
  628. KOUNT = 1;
  629. //10 CONTINUE
  630. do { ++KOUNT;
  631. if (KOUNT > MAXIT) {
  632. printf("re(%g):im(%g)\t\n", CONFRA.real(), CONFRA.imag());
  633. throw std::invalid_argument("ConFra--Iteration failed to converge!\n");
  634. }
  635. MM *= -1; KK += 2; //debug mm=1 kk=5
  636. CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; // ** Eq. R25b //debug 5zinv
  637. // //c ** Eq. R32 Ill-conditioned case -- stride two terms instead of one
  638. // if (std::abs( CNUMER / CAK ) >= EPS1 || std::abs( CDENOM / CAK ) >= EPS1) {
  639. // //c ** Eq. R34
  640. // CNTN = CAK * CNUMER + 1.0;
  641. // CDTD = CAK * CDENOM + 1.0;
  642. // CONFRA = ( CNTN / CDTD ) * CONFRA; // ** Eq. R33
  643. // MM *= -1; KK += 2;
  644. // CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; // ** Eq. R25b
  645. // //c ** Eq. R35
  646. // CNUMER = CAK + CNUMER / CNTN;
  647. // CDENOM = CAK + CDENOM / CDTD;
  648. // ++KOUNT;
  649. // //GO TO 10
  650. // continue;
  651. // } else { //c *** Well-conditioned case
  652. {
  653. CAPT = CNUMER / CDENOM; // ** Eq. R27 //debug (-3zinv + z)/(-3zinv)
  654. // printf("re(%g):im(%g)**\t", CAPT.real(), CAPT.imag());
  655. CONFRA = CAPT * CONFRA; // ** Eq. R26
  656. //if (N == 0) {output=true;printf(" re:");prn(CONFRA.real());printf(" im:"); prn(CONFRA.imag());output=false;};
  657. //c ** Check for convergence; Eq. R31
  658. if ( std::abs(CAPT.real() - 1.0) >= EPS2 || std::abs(CAPT.imag()) >= EPS2 ) {
  659. //c ** Eq. R30
  660. CNUMER = CAK + one/CNUMER;
  661. CDENOM = CAK + one/CDENOM;
  662. continue;
  663. //GO TO 10
  664. } // end of if < eps2
  665. }
  666. break;
  667. } while(1);
  668. //if (N == 0) printf(" return confra for z=(%g,%g)\n", ZINV.real(), ZINV.imag());
  669. return CONFRA;
  670. }
  671. //**********************************************************************************//
  672. // This function calculates the logarithmic derivatives of the Riccati-Bessel //
  673. // functions (D1 and D3) for a complex argument (z). //
  674. // Equations (16a), (16b) and (18a) - (18d) //
  675. // //
  676. // Input parameters: //
  677. // z: Complex argument to evaluate D1 and D3 //
  678. // nmax_: Maximum number of terms to calculate D1 and D3 //
  679. // //
  680. // Output parameters: //
  681. // D1, D3: Logarithmic derivatives of the Riccati-Bessel functions //
  682. //**********************************************************************************//
  683. void MultiLayerMie::calcD1D3(const std::complex<double> z,
  684. std::vector<std::complex<double> >& D1,
  685. std::vector<std::complex<double> >& D3) {
  686. // Downward recurrence for D1 - equations (16a) and (16b)
  687. D1[nmax_] = std::complex<double>(0.0, 0.0);
  688. //D1[nmax_] = calcD1confra(nmax_, z);
  689. const std::complex<double> zinv = std::complex<double>(1.0, 0.0)/z;
  690. // printf(" D:");prn((D1[nmax_]).real()); printf("\t diff:");
  691. // prn((D1[nmax_] + double(nmax_)*zinv).real());
  692. for (int n = nmax_; n > 0; n--) {
  693. D1[n - 1] = double(n)*zinv - 1.0/(D1[n] + double(n)*zinv);
  694. //D1[n-1] = calcD1confra(n-1, z);
  695. // printf(" D:");prn((D1[n-1]).real()); printf("\t diff:");
  696. // prn((D1[n] + double(n)*zinv).real());
  697. }
  698. // printf("\n\n"); iformat=0;
  699. if (std::abs(D1[0]) > 1000.0 )
  700. throw std::invalid_argument
  701. ("Unstable D1! Please, try to change input parameters!\n");
  702. // Upward recurrence for PsiZeta and D3 - equations (18a) - (18d)
  703. PsiZeta_[0] = 0.5*(1.0 - std::complex<double>(cos(2.0*z.real()), sin(2.0*z.real()))
  704. *exp(-2.0*z.imag()));
  705. D3[0] = std::complex<double>(0.0, 1.0);
  706. for (int n = 1; n <= nmax_; n++) {
  707. PsiZeta_[n] = PsiZeta_[n - 1]*(static_cast<double>(n)*zinv - D1[n - 1])
  708. *(static_cast<double>(n)*zinv- D3[n - 1]);
  709. D3[n] = D1[n] + std::complex<double>(0.0, 1.0)/PsiZeta_[n];
  710. }
  711. }
  712. //**********************************************************************************//
  713. // This function calculates Pi and Tau for all values of Theta. //
  714. // Equations (26a) - (26c) //
  715. // //
  716. // Input parameters: //
  717. // nmax_: Maximum number of terms to calculate Pi and Tau //
  718. // nTheta: Number of scattering angles //
  719. // Theta: Array containing all the scattering angles where the scattering //
  720. // amplitudes will be calculated //
  721. // //
  722. // Output parameters: //
  723. // Pi, Tau: Angular functions Pi and Tau, as defined in equations (26a) - (26c) //
  724. //**********************************************************************************//
  725. void MultiLayerMie::calcPiTau(std::vector< std::vector<double> >& Pi,
  726. std::vector< std::vector<double> >& Tau) {
  727. //****************************************************//
  728. // Equations (26a) - (26c) //
  729. //****************************************************//
  730. std::vector<double> costheta(theta_.size(), 0.0);
  731. for (int t = 0; t < theta_.size(); t++) {
  732. costheta[t] = cos(theta_[t]);
  733. }
  734. for (int n = 0; n < nmax_; n++) {
  735. for (int t = 0; t < theta_.size(); t++) {
  736. if (n == 0) {
  737. // Initialize Pi and Tau
  738. Pi[n][t] = 1.0;
  739. Tau[n][t] = (n + 1)*costheta[t];
  740. } else {
  741. // Calculate the actual values
  742. Pi[n][t] = ((n == 1) ? ((n + n + 1)*costheta[t]*Pi[n - 1][t]/n)
  743. : (((n + n + 1)*costheta[t]*Pi[n - 1][t]
  744. - (n + 1)*Pi[n - 2][t])/n));
  745. Tau[n][t] = (n + 1)*costheta[t]*Pi[n][t] - (n + 2)*Pi[n - 1][t];
  746. }
  747. }
  748. }
  749. }
  750. //**********************************************************************************//
  751. // This function calculates the scattering coefficients required to calculate //
  752. // both the near- and far-field parameters. //
  753. // //
  754. // Input parameters: //
  755. // L: Number of layers //
  756. // pl: Index of PEC layer. If there is none just send -1 //
  757. // x: Array containing the size parameters of the layers [0..L-1] //
  758. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  759. // nmax: Maximum number of multipolar expansion terms to be used for the //
  760. // calculations. Only use it if you know what you are doing, otherwise //
  761. // set this parameter to -1 and the function will calculate it. //
  762. // //
  763. // Output parameters: //
  764. // an, bn: Complex scattering amplitudes //
  765. // //
  766. // Return value: //
  767. // Number of multipolar expansion terms used for the calculations //
  768. //**********************************************************************************//
  769. void MultiLayerMie::ScattCoeffs(std::vector<std::complex<double> >& an,
  770. std::vector<std::complex<double> >& bn) {
  771. const std::vector<double>& x = size_parameter_;
  772. const std::vector<std::complex<double> >& m = index_;
  773. const int& pl = PEC_layer_position_;
  774. const int L = index_.size();
  775. //************************************************************************//
  776. // Calculate the index of the first layer. It can be either 0
  777. // (default) // or the index of the outermost PEC layer. In the
  778. // latter case all layers // below the PEC are discarded. //
  779. // ************************************************************************//
  780. // TODO, is it possible for PEC to have a zero index? If yes than
  781. // is should be:
  782. // int fl = (pl > -1) ? pl : 0;
  783. // This will give the same result, however, it corresponds the
  784. // logic - if there is PEC, than first layer is PEC.
  785. int fl = (pl > 0) ? pl : 0;
  786. if (nmax_ <= 0) Nmax(fl);
  787. std::complex<double> z1, z2;
  788. //**************************************************************************//
  789. // Note that since Fri, Nov 14, 2014 all arrays start from 0 (zero), which //
  790. // means that index = layer number - 1 or index = n - 1. The only exception //
  791. // are the arrays for representing D1, D3 and Q because they need a value //
  792. // for the index 0 (zero), hence it is important to consider this shift //
  793. // between different arrays. The change was done to optimize memory usage. //
  794. //**************************************************************************//
  795. // Allocate memory to the arrays
  796. std::vector<std::complex<double> > D1_mlxl(nmax_ + 1), D1_mlxlM1(nmax_ + 1),
  797. D3_mlxl(nmax_ + 1), D3_mlxlM1(nmax_ + 1);
  798. std::vector<std::vector<std::complex<double> > > Q(L), Ha(L), Hb(L);
  799. for (int l = 0; l < L; l++) {
  800. // D1_mlxl[l].resize(nmax_ + 1);
  801. // D1_mlxlM1[l].resize(nmax_ + 1);
  802. // D3_mlxl[l].resize(nmax_ + 1);
  803. // D3_mlxlM1[l].resize(nmax_ + 1);
  804. Q[l].resize(nmax_ + 1);
  805. Ha[l].resize(nmax_);
  806. Hb[l].resize(nmax_);
  807. }
  808. an.resize(nmax_);
  809. bn.resize(nmax_);
  810. PsiZeta_.resize(nmax_ + 1);
  811. std::vector<std::complex<double> > D1XL(nmax_ + 1), D3XL(nmax_ + 1),
  812. PsiXL(nmax_ + 1), ZetaXL(nmax_ + 1);
  813. //*************************************************//
  814. // Calculate D1 and D3 for z1 in the first layer //
  815. //*************************************************//
  816. if (fl == pl) { // PEC layer
  817. for (int n = 0; n <= nmax_; n++) {
  818. D1_mlxl[n] = std::complex<double>(0.0, -1.0);
  819. D3_mlxl[n] = std::complex<double>(0.0, 1.0);
  820. }
  821. } else { // Regular layer
  822. z1 = x[fl]* m[fl];
  823. // Calculate D1 and D3
  824. calcD1D3(z1, D1_mlxl, D3_mlxl);
  825. }
  826. // do { \
  827. // ++iformat;\
  828. // if (iformat%5 == 0) printf("%24.16e",z1.real()); \
  829. // } while (false);
  830. //******************************************************************//
  831. // Calculate Ha and Hb in the first layer - equations (7a) and (8a) //
  832. //******************************************************************//
  833. for (int n = 0; n < nmax_; n++) {
  834. Ha[fl][n] = D1_mlxl[n + 1];
  835. Hb[fl][n] = D1_mlxl[n + 1];
  836. }
  837. //*****************************************************//
  838. // Iteration from the second layer to the last one (L) //
  839. //*****************************************************//
  840. std::complex<double> Temp, Num, Denom;
  841. std::complex<double> G1, G2;
  842. for (int l = fl + 1; l < L; l++) {
  843. //************************************************************//
  844. //Calculate D1 and D3 for z1 and z2 in the layers fl+1..L //
  845. //************************************************************//
  846. z1 = x[l]*m[l];
  847. z2 = x[l - 1]*m[l];
  848. //Calculate D1 and D3 for z1
  849. calcD1D3(z1, D1_mlxl, D3_mlxl);
  850. //Calculate D1 and D3 for z2
  851. calcD1D3(z2, D1_mlxlM1, D3_mlxlM1);
  852. // prn(z1.real());
  853. // for ( auto i : D1_mlxl) { prn(i.real());
  854. // // prn(i.imag());
  855. // } printf("\n");
  856. //*********************************************//
  857. //Calculate Q, Ha and Hb in the layers fl+1..L //
  858. //*********************************************//
  859. // Upward recurrence for Q - equations (19a) and (19b)
  860. Num = exp(-2.0*(z1.imag() - z2.imag()))
  861. * std::complex<double>(cos(-2.0*z2.real()) - exp(-2.0*z2.imag()), sin(-2.0*z2.real()));
  862. Denom = std::complex<double>(cos(-2.0*z1.real()) - exp(-2.0*z1.imag()), sin(-2.0*z1.real()));
  863. Q[l][0] = Num/Denom;
  864. for (int n = 1; n <= nmax_; n++) {
  865. Num = (z1*D1_mlxl[n] + double(n))*(double(n) - z1*D3_mlxl[n - 1]);
  866. Denom = (z2*D1_mlxlM1[n] + double(n))*(double(n) - z2*D3_mlxlM1[n - 1]);
  867. Q[l][n] = ((pow2(x[l - 1]/x[l])* Q[l][n - 1])*Num)/Denom;
  868. }
  869. // Upward recurrence for Ha and Hb - equations (7b), (8b) and (12) - (15)
  870. for (int n = 1; n <= nmax_; n++) {
  871. //Ha
  872. if ((l - 1) == pl) { // The layer below the current one is a PEC layer
  873. G1 = -D1_mlxlM1[n];
  874. G2 = -D3_mlxlM1[n];
  875. } else {
  876. G1 = (m[l]*Ha[l - 1][n - 1]) - (m[l - 1]*D1_mlxlM1[n]);
  877. G2 = (m[l]*Ha[l - 1][n - 1]) - (m[l - 1]*D3_mlxlM1[n]);
  878. } // end of if PEC
  879. Temp = Q[l][n]*G1;
  880. Num = (G2*D1_mlxl[n]) - (Temp*D3_mlxl[n]);
  881. Denom = G2 - Temp;
  882. Ha[l][n - 1] = Num/Denom;
  883. //Hb
  884. if ((l - 1) == pl) { // The layer below the current one is a PEC layer
  885. G1 = Hb[l - 1][n - 1];
  886. G2 = Hb[l - 1][n - 1];
  887. } else {
  888. G1 = (m[l - 1]*Hb[l - 1][n - 1]) - (m[l]*D1_mlxlM1[n]);
  889. G2 = (m[l - 1]*Hb[l - 1][n - 1]) - (m[l]*D3_mlxlM1[n]);
  890. } // end of if PEC
  891. Temp = Q[l][n]*G1;
  892. Num = (G2*D1_mlxl[n]) - (Temp* D3_mlxl[n]);
  893. Denom = (G2- Temp);
  894. Hb[l][n - 1] = (Num/ Denom);
  895. } // end of for Ha and Hb terms
  896. } // end of for layers iteration
  897. //**************************************//
  898. //Calculate D1, D3, Psi and Zeta for XL //
  899. //**************************************//
  900. // Calculate D1XL and D3XL
  901. calcD1D3(x[L - 1], D1XL, D3XL);
  902. //printf("%5.20f\n",Ha[L-1][0].real());
  903. // Calculate PsiXL and ZetaXL
  904. calcPsiZeta(x[L - 1], D1XL, D3XL, PsiXL, ZetaXL);
  905. //*********************************************************************//
  906. // Finally, we calculate the scattering coefficients (an and bn) and //
  907. // the angular functions (Pi and Tau). Note that for these arrays the //
  908. // first layer is 0 (zero), in future versions all arrays will follow //
  909. // this convention to save memory. (13 Nov, 2014) //
  910. //*********************************************************************//
  911. for (int n = 0; n < nmax_; n++) {
  912. //********************************************************************//
  913. //Expressions for calculating an and bn coefficients are not valid if //
  914. //there is only one PEC layer (ie, for a simple PEC sphere). //
  915. //********************************************************************//
  916. if (pl < (L - 1)) {
  917. an[n] = calc_an(n + 1, x[L - 1], Ha[L - 1][n], m[L - 1], PsiXL[n + 1], ZetaXL[n + 1], PsiXL[n], ZetaXL[n]);
  918. bn[n] = calc_bn(n + 1, x[L - 1], Hb[L - 1][n], m[L - 1], PsiXL[n + 1], ZetaXL[n + 1], PsiXL[n], ZetaXL[n]);
  919. } else {
  920. an[n] = calc_an(n + 1, x[L - 1], std::complex<double>(0.0, 0.0), std::complex<double>(1.0, 0.0), PsiXL[n + 1], ZetaXL[n + 1], PsiXL[n], ZetaXL[n]);
  921. bn[n] = PsiXL[n + 1]/ZetaXL[n + 1];
  922. }
  923. } // end of for an and bn terms
  924. } // end of void MultiLayerMie::ScattCoeffs(...)
  925. // ********************************************************************** //
  926. // ********************************************************************** //
  927. // ********************************************************************** //
  928. void MultiLayerMie::InitMieCalculations() {
  929. // Initialize the scattering parameters
  930. Qext_ = 0;
  931. Qsca_ = 0;
  932. Qabs_ = 0;
  933. Qbk_ = 0;
  934. Qpr_ = 0;
  935. asymmetry_factor_ = 0;
  936. albedo_ = 0;
  937. Qsca_ch_.clear();
  938. Qext_ch_.clear();
  939. Qabs_ch_.clear();
  940. Qbk_ch_.clear();
  941. Qpr_ch_.clear();
  942. Qsca_ch_.resize(nmax_-1);
  943. Qext_ch_.resize(nmax_-1);
  944. Qabs_ch_.resize(nmax_-1);
  945. Qbk_ch_.resize(nmax_-1);
  946. Qpr_ch_.resize(nmax_-1);
  947. // Initialize the scattering amplitudes
  948. std::vector<std::complex<double> > tmp1(theta_.size(),std::complex<double>(0.0, 0.0));
  949. S1_.swap(tmp1);
  950. S2_ = S1_;
  951. }
  952. // ********************************************************************** //
  953. // ********************************************************************** //
  954. // ********************************************************************** //
  955. void MultiLayerMie::ConvertToSP() {
  956. if (target_width_.size() + coating_width_.size() == 0)
  957. return; // Nothing to convert, we suppose that SP was set directly
  958. GenerateSizeParameter();
  959. GenerateIndex();
  960. if (size_parameter_.size() != index_.size())
  961. throw std::invalid_argument("Ivalid conversion of width to size parameter units!/n");
  962. }
  963. // ********************************************************************** //
  964. // ********************************************************************** //
  965. // ********************************************************************** //
  966. //**********************************************************************************//
  967. // This function calculates the actual scattering parameters and amplitudes //
  968. // //
  969. // Input parameters: //
  970. // L: Number of layers //
  971. // pl: Index of PEC layer. If there is none just send -1 //
  972. // x: Array containing the size parameters of the layers [0..L-1] //
  973. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  974. // nTheta: Number of scattering angles //
  975. // Theta: Array containing all the scattering angles where the scattering //
  976. // amplitudes will be calculated //
  977. // nmax_: Maximum number of multipolar expansion terms to be used for the //
  978. // calculations. Only use it if you know what you are doing, otherwise //
  979. // set this parameter to -1 and the function will calculate it //
  980. // //
  981. // Output parameters: //
  982. // Qext: Efficiency factor for extinction //
  983. // Qsca: Efficiency factor for scattering //
  984. // Qabs: Efficiency factor for absorption (Qabs = Qext - Qsca) //
  985. // Qbk: Efficiency factor for backscattering //
  986. // Qpr: Efficiency factor for the radiation pressure //
  987. // g: Asymmetry factor (g = (Qext-Qpr)/Qsca) //
  988. // Albedo: Single scattering albedo (Albedo = Qsca/Qext) //
  989. // S1, S2: Complex scattering amplitudes //
  990. // //
  991. // Return value: //
  992. // Number of multipolar expansion terms used for the calculations //
  993. //**********************************************************************************//
  994. void MultiLayerMie::RunMieCalculations() {
  995. ConvertToSP();
  996. nmax_ = nmax_preset_;
  997. if (size_parameter_.size() != index_.size())
  998. throw std::invalid_argument("Each size parameter should have only one index!");
  999. if (size_parameter_.size() == 0)
  1000. throw std::invalid_argument("Initialize model first!");
  1001. std::vector<std::complex<double> > an, bn;
  1002. const std::vector<double>& x = size_parameter_;
  1003. // Calculate scattering coefficients
  1004. ScattCoeffs(an, bn);
  1005. // std::vector< std::vector<double> > Pi(nmax_), Tau(nmax_);
  1006. std::vector< std::vector<double> > Pi, Tau;
  1007. Pi.resize(nmax_);
  1008. Tau.resize(nmax_);
  1009. for (int i =0; i< nmax_; ++i) {
  1010. Pi[i].resize(theta_.size());
  1011. Tau[i].resize(theta_.size());
  1012. }
  1013. calcPiTau(Pi, Tau);
  1014. InitMieCalculations(); //
  1015. std::complex<double> Qbktmp(0.0, 0.0);
  1016. std::vector< std::complex<double> > Qbktmp_ch(nmax_ - 1, Qbktmp);
  1017. // By using downward recurrence we avoid loss of precision due to float rounding errors
  1018. // See: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
  1019. // http://en.wikipedia.org/wiki/Loss_of_significance
  1020. for (int i = nmax_ - 2; i >= 0; i--) {
  1021. const int n = i + 1;
  1022. // Equation (27)
  1023. Qext_ch_[i] = (n + n + 1)*(an[i].real() + bn[i].real());
  1024. Qext_ += Qext_ch_[i];
  1025. // Equation (28)
  1026. Qsca_ch_[i] += (n + n + 1)*(an[i].real()*an[i].real() + an[i].imag()*an[i].imag()
  1027. + bn[i].real()*bn[i].real() + bn[i].imag()*bn[i].imag());
  1028. Qsca_ += Qsca_ch_[i];
  1029. // Equation (29) TODO We must check carefully this equation. If we
  1030. // remove the typecast to double then the result changes. Which is
  1031. // the correct one??? Ovidio (2014/12/10) With cast ratio will
  1032. // give double, without cast (n + n + 1)/(n*(n + 1)) will be
  1033. // rounded to integer. Tig (2015/02/24)
  1034. Qpr_ch_[i]=((n*(n + 2)/(n + 1))*((an[i]*std::conj(an[n]) + bn[i]*std::conj(bn[n])).real())
  1035. + ((double)(n + n + 1)/(n*(n + 1)))*(an[i]*std::conj(bn[i])).real());
  1036. Qpr_ += Qpr_ch_[i];
  1037. // Equation (33)
  1038. Qbktmp_ch[i] = (double)(n + n + 1)*(1 - 2*(n % 2))*(an[i]- bn[i]);
  1039. Qbktmp += Qbktmp_ch[i];
  1040. // Calculate the scattering amplitudes (S1 and S2) //
  1041. // Equations (25a) - (25b) //
  1042. for (int t = 0; t < theta_.size(); t++) {
  1043. S1_[t] += calc_S1(n, an[i], bn[i], Pi[i][t], Tau[i][t]);
  1044. S2_[t] += calc_S2(n, an[i], bn[i], Pi[i][t], Tau[i][t]);
  1045. }
  1046. }
  1047. double x2 = pow2(x.back());
  1048. Qext_ = 2.0*(Qext_)/x2; // Equation (27)
  1049. for (double& Q : Qext_ch_) Q = 2.0*Q/x2;
  1050. Qsca_ = 2.0*(Qsca_)/x2; // Equation (28)
  1051. for (double& Q : Qsca_ch_) Q = 2.0*Q/x2;
  1052. Qpr_ = Qext_ - 4.0*(Qpr_)/x2; // Equation (29)
  1053. for (int i = 0; i < nmax_ - 1; ++i) Qpr_ch_[i] = Qext_ch_[i] - 4.0*Qpr_ch_[i]/x2;
  1054. Qabs_ = Qext_ - Qsca_; // Equation (30)
  1055. for (int i = 0; i < nmax_ - 1; ++i) Qabs_ch_[i] = Qext_ch_[i] - Qsca_ch_[i];
  1056. albedo_ = Qsca_ / Qext_; // Equation (31)
  1057. asymmetry_factor_ = (Qext_ - Qpr_) / Qsca_; // Equation (32)
  1058. Qbk_ = (Qbktmp.real()*Qbktmp.real() + Qbktmp.imag()*Qbktmp.imag())/x2; // Equation (33)
  1059. isMieCalculated_ = true;
  1060. nmax_used_ = nmax_;
  1061. //return nmax;
  1062. }
  1063. // ********************************************************************** //
  1064. // ********************************************************************** //
  1065. // ********************************************************************** //
  1066. // external scattering field = incident + scattered
  1067. // BH p.92 (4.37), 94 (4.45), 95 (4.50)
  1068. // assume: medium is non-absorbing; refim = 0; Uabs = 0
  1069. void MultiLayerMie::fieldExt(double Rho, double Phi, double Theta, std::vector<double> Pi, std::vector<double> Tau,
  1070. std::vector<std::complex<double> > an, std::vector<std::complex<double> > bn,
  1071. std::vector<std::complex<double> >& E, std::vector<std::complex<double> >& H) {
  1072. double rn = 0.0;
  1073. std::complex<double> zn, xxip, encap;
  1074. std::vector<std::complex<double> > vm3o1n, vm3e1n, vn3o1n, vn3e1n;
  1075. vm3o1n.resize(3);
  1076. vm3e1n.resize(3);
  1077. vn3o1n.resize(3);
  1078. vn3e1n.resize(3);
  1079. std::vector<std::complex<double> > Ei, Hi, Es, Hs;
  1080. Ei.resize(3);
  1081. Hi.resize(3);
  1082. Es.resize(3);
  1083. Hs.resize(3);
  1084. for (int i = 0; i < 3; i++) {
  1085. Ei[i] = std::complex<double>(0.0, 0.0);
  1086. Hi[i] = std::complex<double>(0.0, 0.0);
  1087. Es[i] = std::complex<double>(0.0, 0.0);
  1088. Hs[i] = std::complex<double>(0.0, 0.0);
  1089. }
  1090. std::vector<std::complex<double> > bj, by, bd;
  1091. bj.resize(nmax_);
  1092. by.resize(nmax_);
  1093. bd.resize(nmax_);
  1094. // Calculate spherical Bessel and Hankel functions
  1095. sphericalBessel(Rho, bj, by, bd);
  1096. for (int n = 0; n < nmax_; n++) {
  1097. rn = double(n + 1);
  1098. zn = bj[n] + std::complex<double>(0.0, 1.0)*by[n];
  1099. xxip = Rho*(bj[n] + std::complex<double>(0.0, 1.0)*by[n]) - rn*zn;
  1100. vm3o1n[0] = std::complex<double>(0.0, 0.0);
  1101. vm3o1n[1] = std::cos(Phi)*Pi[n]*zn;
  1102. vm3o1n[2] = -(std::sin(Phi)*Tau[n]*zn);
  1103. vm3e1n[0] = std::complex<double>(0.0, 0.0);
  1104. vm3e1n[1] = -(std::sin(Phi)*Pi[n]*zn);
  1105. vm3e1n[2] = -(std::cos(Phi)*Tau[n]*zn);
  1106. vn3o1n[0] = std::sin(Phi)*rn*(rn + 1.0)*std::sin(Theta)*Pi[n]*zn/Rho;
  1107. vn3o1n[1] = std::sin(Phi)*Tau[n]*xxip/Rho;
  1108. vn3o1n[2] = std::cos(Phi)*Pi[n]*xxip/Rho;
  1109. vn3e1n[0] = std::cos(Phi)*rn*(rn + 1.0)*std::sin(Theta)*Pi[n]*zn/Rho;
  1110. vn3e1n[1] = std::cos(Phi)*Tau[n]*xxip/Rho;
  1111. vn3e1n[2] = -(std::sin(Phi)*Pi[n]*xxip/Rho);
  1112. // scattered field: BH p.94 (4.45)
  1113. encap = std::pow(std::complex<double>(0.0, 1.0), rn)*(2.0*rn + 1.0)/(rn*(rn + 1.0));
  1114. for (int i = 0; i < 3; i++) {
  1115. Es[i] = Es[i] + encap*(std::complex<double>(0.0, 1.0)*an[n]*vn3e1n[i] - bn[n]*vm3o1n[i]);
  1116. Hs[i] = Hs[i] + encap*(std::complex<double>(0.0, 1.0)*bn[n]*vn3o1n[i] + an[n]*vm3e1n[i]);
  1117. }
  1118. }
  1119. // incident E field: BH p.89 (4.21); cf. p.92 (4.37), p.93 (4.38)
  1120. // basis unit vectors = er, etheta, ephi
  1121. std::complex<double> eifac = std::exp(std::complex<double>(0.0, 1.0)*Rho*std::cos(Theta));
  1122. Ei[0] = eifac*std::sin(Theta)*std::cos(Phi);
  1123. Ei[1] = eifac*std::cos(Theta)*std::cos(Phi);
  1124. Ei[2] = -(eifac*std::sin(Phi));
  1125. // magnetic field
  1126. double hffact = 1.0/(cc*mu);
  1127. for (int i = 0; i < 3; i++) {
  1128. Hs[i] = hffact*Hs[i];
  1129. }
  1130. // incident H field: BH p.26 (2.43), p.89 (4.21)
  1131. std::complex<double> hffacta = hffact;
  1132. std::complex<double> hifac = eifac*hffacta;
  1133. Hi[0] = hifac*std::sin(Theta)*std::sin(Phi);
  1134. Hi[1] = hifac*std::cos(Theta)*std::sin(Phi);
  1135. Hi[2] = hifac*std::cos(Phi);
  1136. for (int i = 0; i < 3; i++) {
  1137. // electric field E [V m-1] = EF*E0
  1138. E[i] = Ei[i] + Es[i];
  1139. H[i] = Hi[i] + Hs[i];
  1140. }
  1141. }
  1142. // ********************************************************************** //
  1143. // ********************************************************************** //
  1144. // ********************************************************************** //
  1145. //**********************************************************************************//
  1146. // This function calculates complex electric and magnetic field in the surroundings //
  1147. // and inside (TODO) the particle. //
  1148. // //
  1149. // Input parameters: //
  1150. // L: Number of layers //
  1151. // pl: Index of PEC layer. If there is none just send 0 (zero) //
  1152. // x: Array containing the size parameters of the layers [0..L-1] //
  1153. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  1154. // nmax: Maximum number of multipolar expansion terms to be used for the //
  1155. // calculations. Only use it if you know what you are doing, otherwise //
  1156. // set this parameter to 0 (zero) and the function will calculate it. //
  1157. // ncoord: Number of coordinate points //
  1158. // Coords: Array containing all coordinates where the complex electric and //
  1159. // magnetic fields will be calculated //
  1160. // //
  1161. // Output parameters: //
  1162. // E, H: Complex electric and magnetic field at the provided coordinates //
  1163. // //
  1164. // Return value: //
  1165. // Number of multipolar expansion terms used for the calculations //
  1166. //**********************************************************************************//
  1167. // int MultiLayerMie::nField(int L, int pl, std::vector<double> x, std::vector<std::complex<double> > m, int nmax,
  1168. // int ncoord, std::vector<double> Xp, std::vector<double> Yp, std::vector<double> Zp,
  1169. // std::vector<std::vector<std::complex<double> > >& E, std::vector<std::vector<std::complex<double> > >& H) {
  1170. // double Rho, Phi, Theta;
  1171. // std::vector<std::complex<double> > an, bn;
  1172. // // This array contains the fields in spherical coordinates
  1173. // std::vector<std::complex<double> > Es, Hs;
  1174. // Es.resize(3);
  1175. // Hs.resize(3);
  1176. // // Calculate scattering coefficients
  1177. // ScattCoeffs(L, pl, an, bn);
  1178. // std::vector<double> Pi, Tau;
  1179. // Pi.resize(nmax_);
  1180. // Tau.resize(nmax_);
  1181. // for (int c = 0; c < ncoord; c++) {
  1182. // // Convert to spherical coordinates
  1183. // Rho = sqrt(Xp[c]*Xp[c] + Yp[c]*Yp[c] + Zp[c]*Zp[c]);
  1184. // if (Rho < 1e-3) {
  1185. // // Avoid convergence problems
  1186. // Rho = 1e-3;
  1187. // }
  1188. // Phi = acos(Xp[c]/sqrt(Xp[c]*Xp[c] + Yp[c]*Yp[c]));
  1189. // Theta = acos(Xp[c]/Rho);
  1190. // calcPiTau(Theta, Pi, Tau);
  1191. // //*******************************************************//
  1192. // // external scattering field = incident + scattered //
  1193. // // BH p.92 (4.37), 94 (4.45), 95 (4.50) //
  1194. // // assume: medium is non-absorbing; refim = 0; Uabs = 0 //
  1195. // //*******************************************************//
  1196. // // Firstly the easiest case: the field outside the particle
  1197. // if (Rho >= x[L - 1]) {
  1198. // fieldExt(Rho, Phi, Theta, Pi, Tau, an, bn, Es, Hs);
  1199. // } else {
  1200. // // TODO, for now just set all the fields to zero
  1201. // for (int i = 0; i < 3; i++) {
  1202. // Es[i] = std::complex<double>(0.0, 0.0);
  1203. // Hs[i] = std::complex<double>(0.0, 0.0);
  1204. // }
  1205. // }
  1206. // //Now, convert the fields back to cartesian coordinates
  1207. // E[c][0] = std::sin(Theta)*std::cos(Phi)*Es[0] + std::cos(Theta)*std::cos(Phi)*Es[1] - std::sin(Phi)*Es[2];
  1208. // E[c][1] = std::sin(Theta)*std::sin(Phi)*Es[0] + std::cos(Theta)*std::sin(Phi)*Es[1] + std::cos(Phi)*Es[2];
  1209. // E[c][2] = std::cos(Theta)*Es[0] - std::sin(Theta)*Es[1];
  1210. // H[c][0] = std::sin(Theta)*std::cos(Phi)*Hs[0] + std::cos(Theta)*std::cos(Phi)*Hs[1] - std::sin(Phi)*Hs[2];
  1211. // H[c][1] = std::sin(Theta)*std::sin(Phi)*Hs[0] + std::cos(Theta)*std::sin(Phi)*Hs[1] + std::cos(Phi)*Hs[2];
  1212. // H[c][2] = std::cos(Theta)*Hs[0] - std::sin(Theta)*Hs[1];
  1213. // }
  1214. // return nmax;
  1215. // } // end of int nField()
  1216. } // end of namespace nmie