nmie-applied-impl.hpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #ifndef SRC_NMIE_APPLIED_IMPL_HPP_
  2. #define SRC_NMIE_APPLIED_IMPL_HPP_
  3. //**********************************************************************************//
  4. // Copyright (C) 2009-2018 Ovidio Pena <ovidio@bytesfall.com> //
  5. // Copyright (C) 2013-2018 Konstantin Ladutenko <kostyfisik@gmail.com> //
  6. // //
  7. // This file is part of scattnlay //
  8. // //
  9. // This program is free software: you can redistribute it and/or modify //
  10. // it under the terms of the GNU General Public License as published by //
  11. // the Free Software Foundation, either version 3 of the License, or //
  12. // (at your option) any later version. //
  13. // //
  14. // This program is distributed in the hope that it will be useful, //
  15. // but WITHOUT ANY WARRANTY; without even the implied warranty of //
  16. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
  17. // GNU General Public License for more details. //
  18. // //
  19. // The only additional remark is that we expect that all publications //
  20. // describing work using this software, or all commercial products //
  21. // using it, cite at least one of the following references: //
  22. // [1] O. Pena and U. Pal, "Scattering of electromagnetic radiation by //
  23. // a multilayered sphere," Computer Physics Communications, //
  24. // vol. 180, Nov. 2009, pp. 2348-2354. //
  25. // [2] K. Ladutenko, U. Pal, A. Rivera, and O. Pena-Rodriguez, "Mie //
  26. // calculation of electromagnetic near-field for a multilayered //
  27. // sphere," Computer Physics Communications, vol. 214, May 2017, //
  28. // pp. 225-230. //
  29. // //
  30. // You should have received a copy of the GNU General Public License //
  31. // along with this program. If not, see <http://www.gnu.org/licenses/>. //
  32. // //
  33. // @brief Wrapper class around nMie function for ease of use //
  34. // //
  35. //**********************************************************************************//
  36. #include <array>
  37. #include <algorithm>
  38. #include <cstdio>
  39. #include <cstdlib>
  40. #include <stdexcept>
  41. #include <vector>
  42. namespace nmie {
  43. // ********************************************************************** //
  44. // ********************************************************************** //
  45. // ********************************************************************** //
  46. template <typename FloatType>
  47. void MultiLayerMieApplied<FloatType>::GetFailed() {
  48. FloatType faild_x = 9.42477796076938;
  49. //FloatType faild_x = 9.42477796076937;
  50. std::complex<FloatType> z(faild_x, 0.0);
  51. std::vector<int> nmax_local_array = {20, 100, 500, 2500};
  52. for (auto nmax_local : nmax_local_array) {
  53. std::vector<std::complex<FloatType> > D1_failed(nmax_local + 1);
  54. // Downward recurrence for D1 - equations (16a) and (16b)
  55. D1_failed[nmax_local] = std::complex<FloatType>(0.0, 0.0);
  56. const std::complex<FloatType> zinv = std::complex<FloatType>(1.0, 0.0)/z;
  57. for (int n = nmax_local; n > 0; n--) {
  58. D1_failed[n - 1] = FloatType(n)*zinv - 1.0/(D1_failed[n] + FloatType(n)*zinv);
  59. }
  60. printf("Faild D1[0] from reccurence (z = %16.14f, nmax = %d): %g\n",
  61. faild_x, nmax_local, D1_failed[0].real());
  62. }
  63. printf("Faild D1[0] from continued fraction (z = %16.14f): %g\n", faild_x,
  64. calcD1confra(0,z).real());
  65. //D1[nmax_] = calcD1confra(nmax_, z);
  66. }
  67. // ********************************************************************** //
  68. // ********************************************************************** //
  69. // ********************************************************************** //
  70. template <typename FloatType>
  71. void MultiLayerMieApplied<FloatType>::AddTargetLayer(FloatType width, std::complex<FloatType> layer_index) {
  72. this->MarkUncalculated();
  73. if (width <= 0)
  74. throw std::invalid_argument("Layer width should be positive!");
  75. target_width_.push_back(width);
  76. target_index_.push_back(layer_index);
  77. } // end of void MultiLayerMieApplied<FloatType>::AddTargetLayer(...)
  78. // ********************************************************************** //
  79. // ********************************************************************** //
  80. // ********************************************************************** //
  81. template <typename FloatType>
  82. void MultiLayerMieApplied<FloatType>::AddTargetLayerReIm(FloatType width,
  83. FloatType re_layer_index, FloatType im_layer_index) {
  84. this->MarkUncalculated();
  85. if (width <= 0)
  86. throw std::invalid_argument("Layer width should be positive!");
  87. target_width_.push_back(width);
  88. target_index_.push_back(std::complex<FloatType>(re_layer_index,im_layer_index));
  89. } // end of void MultiLayerMieApplied<FloatType>::AddTargetLayer(...)
  90. // ********************************************************************** //
  91. // ********************************************************************** //
  92. // ********************************************************************** //
  93. template <typename FloatType>
  94. void MultiLayerMieApplied<FloatType>::SetTargetPEC(FloatType radius) {
  95. this->MarkUncalculated();
  96. if (target_width_.size() != 0 || target_index_.size() != 0)
  97. throw std::invalid_argument("Error! Define PEC target radius before any other layers!");
  98. // Add layer of any index...
  99. AddTargetLayer(radius, std::complex<FloatType>(0.0, 0.0));
  100. // ... and mark it as PEC
  101. this->SetPECLayer(0);
  102. }
  103. // ********************************************************************** //
  104. // ********************************************************************** //
  105. // ********************************************************************** //
  106. template <typename FloatType>
  107. void MultiLayerMieApplied<FloatType>::SetCoatingIndex(std::vector<std::complex<FloatType> > index) {
  108. this->MarkUncalculated();
  109. coating_index_.clear();
  110. for (auto value : index) coating_index_.push_back(value);
  111. } // end of void MultiLayerMieApplied<FloatType>::SetCoatingIndex(std::vector<complex> index);
  112. // ********************************************************************** //
  113. // ********************************************************************** //
  114. // ********************************************************************** //
  115. template <typename FloatType>
  116. void MultiLayerMieApplied<FloatType>::SetCoatingWidth(std::vector<FloatType> width) {
  117. this->MarkUncalculated();
  118. coating_width_.clear();
  119. for (auto w : width)
  120. if (w <= 0)
  121. throw std::invalid_argument("Coating width should be positive!");
  122. else coating_width_.push_back(w);
  123. }
  124. // end of void MultiLayerMieApplied<FloatType>::SetCoatingWidth(...);
  125. // ********************************************************************** //
  126. // ********************************************************************** //
  127. // ********************************************************************** //
  128. template <typename FloatType>
  129. void MultiLayerMieApplied<FloatType>::SetWidthSP(const std::vector<FloatType>& size_parameter) {
  130. this->MarkUncalculated();
  131. this->size_param_.clear();
  132. FloatType prev_size_parameter = 0.0;
  133. for (auto layer_size_parameter : size_parameter) {
  134. if (layer_size_parameter <= 0.0)
  135. throw std::invalid_argument("Size parameter should be positive!");
  136. if (prev_size_parameter > layer_size_parameter)
  137. throw std::invalid_argument
  138. ("Size parameter for next layer should be larger than the previous one!");
  139. prev_size_parameter = layer_size_parameter;
  140. this->size_param_.push_back(layer_size_parameter);
  141. }
  142. }
  143. // end of void MultiLayerMieApplied<FloatType>::SetWidthSP(...);
  144. // ********************************************************************** //
  145. // ********************************************************************** //
  146. // ********************************************************************** //
  147. template <typename FloatType>
  148. void MultiLayerMieApplied<FloatType>::SetIndexSP(const std::vector< std::complex<FloatType> >& index) {
  149. this->MarkUncalculated();
  150. //refractive_index_.clear();
  151. this->refractive_index_ = index;
  152. // for (auto value : index) refractive_index_.push_back(value);
  153. } // end of void MultiLayerMieApplied<FloatType>::SetIndexSP(...);
  154. // ********************************************************************** //
  155. // ********************************************************************** //
  156. // ********************************************************************** //
  157. template <typename FloatType>
  158. void MultiLayerMieApplied<FloatType>::SetFieldPointsSP(const std::vector< std::vector<FloatType> >& coords_sp) {
  159. if (coords_sp.size() != 3)
  160. throw std::invalid_argument("Error! Wrong dimension of field monitor points!");
  161. if (coords_sp[0].size() != coords_sp[1].size() || coords_sp[0].size() != coords_sp[2].size())
  162. throw std::invalid_argument("Error! Missing coordinates for field monitor points!");
  163. this->coords_ = coords_sp;
  164. // for (int i = 0; i < coords_sp_[0].size(); ++i) {
  165. // printf("%g, %g, %g\n", coords_sp_[0][i], coords_sp_[1][i], coords_sp_[2][i]);
  166. // }
  167. } // end of void MultiLayerMieApplied<FloatType>::SetFieldPointsSP(...)
  168. // ********************************************************************** //
  169. // ********************************************************************** //
  170. // ********************************************************************** //
  171. template <typename FloatType>
  172. void MultiLayerMieApplied<FloatType>::GenerateSizeParameter() {
  173. this->MarkUncalculated();
  174. this->size_param_.clear();
  175. FloatType radius = 0.0;
  176. for (auto width : target_width_) {
  177. radius += width;
  178. this->size_param_.push_back(2*this->PI_*radius/wavelength_);
  179. }
  180. for (auto width : coating_width_) {
  181. radius += width;
  182. this->size_param_.push_back(2*this->PI_*radius/wavelength_);
  183. }
  184. this->total_radius_ = radius;
  185. } // end of void MultiLayerMieApplied<FloatType>::GenerateSizeParameter();
  186. // ********************************************************************** //
  187. // ********************************************************************** //
  188. // ********************************************************************** //
  189. template <typename FloatType>
  190. void MultiLayerMieApplied<FloatType>::GenerateIndex() {
  191. this->MarkUncalculated();
  192. this->refractive_index_.clear();
  193. for (auto index : this->target_index_)
  194. this->refractive_index_.push_back(index);
  195. for (auto index : this->coating_index_)
  196. this->refractive_index_.push_back(index);
  197. } // end of void MultiLayerMieApplied<FloatType>::GenerateIndex();
  198. // ********************************************************************** //
  199. // ********************************************************************** //
  200. // ********************************************************************** //
  201. template <typename FloatType>
  202. FloatType MultiLayerMieApplied<FloatType>::GetTotalRadius() {
  203. if (!this->isMieCalculated()) GenerateSizeParameter();
  204. return this->total_radius_;
  205. } // end of FloatType MultiLayerMieApplied<FloatType>::GetTotalRadius();
  206. // ********************************************************************** //
  207. // ********************************************************************** //
  208. // ********************************************************************** //
  209. template <typename FloatType>
  210. std::vector< std::vector<FloatType> >
  211. MultiLayerMieApplied<FloatType>::GetSpectra(FloatType from_WL, FloatType to_WL, int samples) {
  212. if (!this->isMieCalculated())
  213. throw std::invalid_argument("You should run calculations before result request!");
  214. std::vector< std::vector<FloatType> > spectra;
  215. FloatType step_WL = (to_WL - from_WL)/static_cast<FloatType>(samples);
  216. FloatType wavelength_backup = wavelength_;
  217. long fails = 0;
  218. for (FloatType WL = from_WL; WL < to_WL; WL += step_WL) {
  219. wavelength_ = WL;
  220. try {
  221. RunMieCalculation();
  222. } catch(const std::invalid_argument& ia) {
  223. fails++;
  224. continue;
  225. }
  226. //printf("%3.1f ",WL);
  227. spectra.push_back(std::vector<FloatType>({wavelength_, this->GetQext(),
  228. this->GetQsca(), this->GetQabs(), this->GetQbk()}));
  229. } // end of for each WL in spectra
  230. printf("Spectrum has %li fails\n",fails);
  231. wavelength_ = wavelength_backup;
  232. return spectra;
  233. }
  234. // ********************************************************************** //
  235. // ********************************************************************** //
  236. // ********************************************************************** //
  237. template <typename FloatType>
  238. void MultiLayerMieApplied<FloatType>::ClearTarget() {
  239. this->MarkUncalculated();
  240. this->target_width_.clear();
  241. this->target_index_.clear();
  242. }
  243. // ********************************************************************** //
  244. // ********************************************************************** //
  245. // ********************************************************************** //
  246. template <typename FloatType>
  247. void MultiLayerMieApplied<FloatType>::ClearCoating() {
  248. this->MarkUncalculated();
  249. this->coating_width_.clear();
  250. this->coating_index_.clear();
  251. }
  252. // ********************************************************************** //
  253. // ********************************************************************** //
  254. // ********************************************************************** //
  255. template <typename FloatType>
  256. void MultiLayerMieApplied<FloatType>::ClearLayers() {
  257. this->MarkUncalculated();
  258. this->ClearTarget();
  259. this->ClearCoating();
  260. }
  261. // ********************************************************************** //
  262. // ********************************************************************** //
  263. // ********************************************************************** //
  264. template <typename FloatType>
  265. void MultiLayerMieApplied<FloatType>::ClearAllDesign() {
  266. this->MarkUncalculated();
  267. this->ClearLayers();
  268. this->size_param_.clear();
  269. this->refractive_index_.clear();
  270. }
  271. // ********************************************************************** //
  272. // ********************************************************************** //
  273. // ********************************************************************** //
  274. // Computational core
  275. // ********************************************************************** //
  276. // ********************************************************************** //
  277. // ********************************************************************** //
  278. //**********************************************************************************//
  279. // Function CONFRA ported from MIEV0.f (Wiscombe,1979)
  280. // Ref. to NCAR Technical Notes, Wiscombe, 1979
  281. /*
  282. c Compute Bessel function ratio A-sub-N from its
  283. c continued fraction using Lentz method
  284. c ZINV = Reciprocal of argument of A
  285. c I N T E R N A L V A R I A B L E S
  286. c ------------------------------------
  287. c CAK Term in continued fraction expansion of A (Eq. R25)
  288. c a_k
  289. c CAPT Factor used in Lentz iteration for A (Eq. R27)
  290. c T_k
  291. c CNUMER Numerator in capT (Eq. R28A)
  292. c N_k
  293. c CDENOM Denominator in capT (Eq. R28B)
  294. c D_k
  295. c CDTD Product of two successive denominators of capT factors
  296. c (Eq. R34C)
  297. c xi_1
  298. c CNTN Product of two successive numerators of capT factors
  299. c (Eq. R34B)
  300. c xi_2
  301. c EPS1 Ill-conditioning criterion
  302. c EPS2 Convergence criterion
  303. c KK Subscript k of cAk (Eq. R25B)
  304. c k
  305. c KOUNT Iteration counter (used to prevent infinite looping)
  306. c MAXIT Max. allowed no. of iterations
  307. c MM + 1 and - 1, alternately
  308. */
  309. template <typename FloatType>
  310. std::complex<FloatType> MultiLayerMieApplied<FloatType>::calcD1confra(const int N, const std::complex<FloatType> z) {
  311. // NTMR -> nmax_ - 1 \\TODO nmax_ ?
  312. //int N = nmax_ - 1;
  313. int KK, KOUNT, MAXIT = 10000, MM;
  314. // FloatType EPS1=1.0e-2;
  315. FloatType EPS2=1.0e-8;
  316. std::complex<FloatType> CAK, CAPT, CDENOM, CDTD, CNTN, CNUMER;
  317. std::complex<FloatType> one = std::complex<FloatType>(1.0,0.0);
  318. std::complex<FloatType> ZINV = one/z;
  319. // c ** Eq. R25a
  320. std::complex<FloatType> CONFRA = static_cast<std::complex<FloatType> >(N + 1)*ZINV; //debug ZINV
  321. MM = - 1;
  322. KK = 2*N +3; //debug 3
  323. // c ** Eq. R25b, k=2
  324. CAK = static_cast<std::complex<FloatType> >(MM*KK)*ZINV; //debug -3 ZINV
  325. CDENOM = CAK;
  326. CNUMER = CDENOM + one/CONFRA; //-3zinv+z
  327. KOUNT = 1;
  328. //10 CONTINUE
  329. do { ++KOUNT;
  330. if (KOUNT > MAXIT) {
  331. printf("re(%g):im(%g)\t\n", CONFRA.real(), CONFRA.imag());
  332. throw std::invalid_argument("ConFra--Iteration failed to converge!\n");
  333. }
  334. MM *= - 1; KK += 2; //debug mm=1 kk=5
  335. CAK = static_cast<std::complex<FloatType> >(MM*KK)*ZINV; // ** Eq. R25b //debug 5zinv
  336. // //c ** Eq. R32 Ill-conditioned case -- stride two terms instead of one
  337. // if (std::abs(CNUMER/CAK) >= EPS1 || std::abs(CDENOM/CAK) >= EPS1) {
  338. // //c ** Eq. R34
  339. // CNTN = CAK*CNUMER + 1.0;
  340. // CDTD = CAK*CDENOM + 1.0;
  341. // CONFRA = (CNTN/CDTD)*CONFRA; // ** Eq. R33
  342. // MM *= - 1; KK += 2;
  343. // CAK = static_cast<std::complex<FloatType> >(MM*KK)*ZINV; // ** Eq. R25b
  344. // //c ** Eq. R35
  345. // CNUMER = CAK + CNUMER/CNTN;
  346. // CDENOM = CAK + CDENOM/CDTD;
  347. // ++KOUNT;
  348. // //GO TO 10
  349. // continue;
  350. // } else { //c *** Well-conditioned case
  351. {
  352. CAPT = CNUMER/CDENOM; // ** Eq. R27 //debug (-3zinv + z)/(-3zinv)
  353. // printf("re(%g):im(%g)**\t", CAPT.real(), CAPT.imag());
  354. CONFRA = CAPT*CONFRA; // ** Eq. R26
  355. //if (N == 0) {output=true;printf(" re:");prn(CONFRA.real());printf(" im:"); prn(CONFRA.imag());output=false;};
  356. //c ** Check for convergence; Eq. R31
  357. if (std::abs(CAPT.real() - 1.0) >= EPS2 || std::abs(CAPT.imag()) >= EPS2) {
  358. //c ** Eq. R30
  359. CNUMER = CAK + one/CNUMER;
  360. CDENOM = CAK + one/CDENOM;
  361. continue;
  362. //GO TO 10
  363. } // end of if < eps2
  364. }
  365. break;
  366. } while(1);
  367. //if (N == 0) printf(" return confra for z=(%g,%g)\n", ZINV.real(), ZINV.imag());
  368. return CONFRA;
  369. }
  370. // ********************************************************************** //
  371. // ********************************************************************** //
  372. // ********************************************************************** //
  373. template <typename FloatType>
  374. void MultiLayerMieApplied<FloatType>::ConvertToSP() {
  375. this->MarkUncalculated();
  376. if (target_width_.size() + coating_width_.size() == 0)
  377. return; // Nothing to convert, we suppose that SP was set directly
  378. GenerateSizeParameter();
  379. GenerateIndex();
  380. if (this->size_param_.size() != this->refractive_index_.size())
  381. throw std::invalid_argument("Ivalid conversion of width to size parameter units!/n");
  382. }
  383. // ********************************************************************** //
  384. // ********************************************************************** //
  385. // ********************************************************************** //
  386. template <typename FloatType>
  387. void MultiLayerMieApplied<FloatType>::RunMieCalculation() {
  388. ConvertToSP();
  389. this->MultiLayerMie<FloatType>::RunMieCalculation();
  390. }
  391. template <typename FloatType>
  392. void MultiLayerMieApplied<FloatType>::RunFieldCalculationPolar(const int outer_arc_points,
  393. const int radius_points,
  394. const double from_Rho, const double to_Rho,
  395. const double from_Theta, const double to_Theta,
  396. const double from_Phi, const double to_Phi,
  397. const int isIgnoreAvailableNmax) {
  398. // ConvertToSP();
  399. this->MultiLayerMie<FloatType>::RunFieldCalculationPolar(outer_arc_points, radius_points, from_Rho, to_Rho,
  400. from_Theta, to_Theta, from_Phi, to_Phi,
  401. isIgnoreAvailableNmax == 0 ? false : true);
  402. }
  403. //from https://toughengineer.github.io/demo/dsp/fft-perf/
  404. template <typename FloatType=double>
  405. emscripten::val toJSFloat64Array(const std::vector<double> &v) {
  406. emscripten::val view{ emscripten::typed_memory_view(v.size(), v.data()) }; // make a view of local object
  407. auto result = emscripten::val::global("Float64Array").new_(v.size()); // make a JS typed array
  408. result.call<void>("set", view); // set typed array values "on the JS side" using the memory view
  409. return result;
  410. }
  411. template <typename FloatType>
  412. emscripten::val MultiLayerMieApplied<FloatType>::GetFieldEabs() {
  413. auto Eabs = this->MultiLayerMie<FloatType>::GetFieldEabs();
  414. return toJSFloat64Array(Eabs);
  415. }
  416. // ********************************************************************** //
  417. // ********************************************************************** //
  418. // ********************************************************************** //
  419. template <typename FloatType>
  420. void MultiLayerMieApplied<FloatType>::GetExpanCoeffs( std::vector< std::vector<std::complex<FloatType> > >& aln, std::vector< std::vector<std::complex<FloatType> > >& bln, std::vector< std::vector<std::complex<FloatType> > >& cln, std::vector< std::vector<std::complex<FloatType> > >& dln) {
  421. ConvertToSP(); // Case of call before running full Mie calculation.
  422. // Calculate scattering coefficients an_ and bn_
  423. this->calcScattCoeffs();
  424. // Calculate expansion coefficients aln_, bln_, cln_, and dln_
  425. this->calcExpanCoeffs();
  426. aln = this->aln_;
  427. bln = this->bln_;
  428. cln = this->cln_;
  429. dln = this->dln_;
  430. } // end of void MultiLayerMieApplied<FloatType>::GetExpanCoeffs( ...)
  431. // ********************************************************************** //
  432. // ********************************************************************** //
  433. // ********************************************************************** //
  434. } // end of namespace nmie
  435. #endif // SRC_NMIE_APPLIED_IMPL_HPP_