nmie-wrapper.cc 82 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  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,2014,2015 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-wrapper.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, int nTheta, const std::vector<double>& Theta, double *Qext, double *Qsca, double *Qabs, double *Qbk, double *Qpr, double *g, double *Albedo, std::vector<std::complex<double> >& S1, std::vector<std::complex<double> >& S2) {
  51. if (x.size() != L || m.size() != L)
  52. throw std::invalid_argument("Declared number of layers do not fit x and m!");
  53. if (Theta.size() != nTheta)
  54. throw std::invalid_argument("Declared number of sample for Theta is not correct!");
  55. try {
  56. MultiLayerMie multi_layer_mie;
  57. multi_layer_mie.SetWidthSP(x);
  58. multi_layer_mie.SetIndexSP(m);
  59. multi_layer_mie.SetAngles(Theta);
  60. multi_layer_mie.RunMieCalculations();
  61. *Qext = multi_layer_mie.GetQext();
  62. *Qsca = multi_layer_mie.GetQsca();
  63. *Qabs = multi_layer_mie.GetQabs();
  64. *Qbk = multi_layer_mie.GetQbk();
  65. *Qpr = multi_layer_mie.GetQpr();
  66. *g = multi_layer_mie.GetAsymmetryFactor();
  67. *Albedo = multi_layer_mie.GetAlbedo();
  68. S1 = multi_layer_mie.GetS1();
  69. S2 = multi_layer_mie.GetS2();
  70. //multi_layer_mie.GetFailed();
  71. } catch( const std::invalid_argument& ia ) {
  72. // Will catch if multi_layer_mie fails or other errors.
  73. std::cerr << "Invalid argument: " << ia.what() << std::endl;
  74. throw std::invalid_argument(ia);
  75. return -1;
  76. }
  77. return 0;
  78. }
  79. // ********************************************************************** //
  80. // ********************************************************************** //
  81. // ********************************************************************** //
  82. int nField(const int L, const int pl, const std::vector<double>& x, const std::vector<std::complex<double> >& m, const int nmax, const int ncoord, const std::vector<double>& Xp_vec, const std::vector<double>& Yp_vec, const std::vector<double>& Zp_vec, std::vector<std::vector<std::complex<double> > >& E, std::vector<std::vector<std::complex<double> > >& H) {
  83. if (x.size() != L || m.size() != L)
  84. throw std::invalid_argument("Declared number of layers do not fit x and m!");
  85. if (Xp_vec.size() != ncoord || Yp_vec.size() != ncoord || Zp_vec.size() != ncoord
  86. || E.size() != ncoord || H.size() != ncoord )
  87. throw std::invalid_argument("Declared number of coords do not fit Xp, Yp, Zp, E, or H!");
  88. for (auto f:E)
  89. if ( f.size() != 3)
  90. throw std::invalid_argument("Field E is not 3D!");
  91. for (auto f:H)
  92. if ( f.size() != 3)
  93. throw std::invalid_argument("Field H is not 3D!");
  94. try {
  95. MultiLayerMie multi_layer_mie;
  96. //multi_layer_mie.SetPEC(pl);
  97. multi_layer_mie.SetWidthSP(x);
  98. multi_layer_mie.SetIndexSP(m);
  99. multi_layer_mie.SetFieldPointsSP({Xp_vec, Yp_vec, Zp_vec});
  100. multi_layer_mie.RunFieldCalculations();
  101. E = multi_layer_mie.GetFieldE();
  102. H = multi_layer_mie.GetFieldH();
  103. //multi_layer_mie.GetFailed();
  104. } catch( const std::invalid_argument& ia ) {
  105. // Will catch if multi_layer_mie fails or other errors.
  106. std::cerr << "Invalid argument: " << ia.what() << std::endl;
  107. throw std::invalid_argument(ia);
  108. return -1;
  109. }
  110. return 0;
  111. }
  112. // ********************************************************************** //
  113. // ********************************************************************** //
  114. // ********************************************************************** //
  115. void MultiLayerMie::GetFailed() {
  116. double faild_x = 9.42477796076938;
  117. //double faild_x = 9.42477796076937;
  118. std::complex<double> z(faild_x, 0.0);
  119. std::vector<int> nmax_local_array = {20, 100, 500, 2500};
  120. for (auto nmax_local : nmax_local_array) {
  121. std::vector<std::complex<double> > D1_failed(nmax_local +1);
  122. // Downward recurrence for D1 - equations (16a) and (16b)
  123. D1_failed[nmax_local] = std::complex<double>(0.0, 0.0);
  124. const std::complex<double> zinv = std::complex<double>(1.0, 0.0)/z;
  125. for (int n = nmax_local; n > 0; n--) {
  126. D1_failed[n - 1] = double(n)*zinv - 1.0/(D1_failed[n] + double(n)*zinv);
  127. }
  128. printf("Faild D1[0] from reccurence (z = %16.14f, nmax = %d): %g\n",
  129. faild_x, nmax_local, D1_failed[0].real());
  130. }
  131. printf("Faild D1[0] from continued fraction (z = %16.14f): %g\n", faild_x,
  132. calcD1confra(0,z).real());
  133. //D1[nmax_] = calcD1confra(nmax_, z);
  134. }
  135. // ********************************************************************** //
  136. // ********************************************************************** //
  137. // ********************************************************************** //
  138. double MultiLayerMie::GetQext() {
  139. if (!isMieCalculated_)
  140. throw std::invalid_argument("You should run calculations before result request!");
  141. return Qext_;
  142. }
  143. // ********************************************************************** //
  144. // ********************************************************************** //
  145. // ********************************************************************** //
  146. double MultiLayerMie::GetQabs() {
  147. if (!isMieCalculated_)
  148. throw std::invalid_argument("You should run calculations before result request!");
  149. return Qabs_;
  150. }
  151. // ********************************************************************** //
  152. // ********************************************************************** //
  153. // ********************************************************************** //
  154. std::vector<double> MultiLayerMie::GetQabs_channel() {
  155. if (!isMieCalculated_)
  156. throw std::invalid_argument("You should run calculations before result request!");
  157. return Qabs_ch_;
  158. }
  159. // ********************************************************************** //
  160. // ********************************************************************** //
  161. // ********************************************************************** //
  162. std::vector<double> MultiLayerMie::GetQabs_channel_normalized() {
  163. if (!isMieCalculated_)
  164. throw std::invalid_argument("You should run calculations before result request!");
  165. // std::vector<double> NACS(nmax_-1, 0.0);
  166. // double x2 = pow2(size_parameter_.back());
  167. // for (int i = 0; i < nmax_ - 1; ++i) {
  168. // const int n = i+1;
  169. // NACS[i] = Qabs_ch_[i]*x2/(2.0*(2.0*static_cast<double>(n)+1));
  170. // // if (NACS[i] > 0.250000001)
  171. // // throw std::invalid_argument("Unexpected normalized absorption cross-section value!");
  172. // }
  173. //return NACS;
  174. return Qabs_ch_norm_;
  175. }
  176. // ********************************************************************** //
  177. // ********************************************************************** //
  178. // ********************************************************************** //
  179. double MultiLayerMie::GetQsca() {
  180. if (!isMieCalculated_)
  181. throw std::invalid_argument("You should run calculations before result request!");
  182. return Qsca_;
  183. }
  184. // ********************************************************************** //
  185. // ********************************************************************** //
  186. // ********************************************************************** //
  187. std::vector<double> MultiLayerMie::GetQsca_channel() {
  188. if (!isMieCalculated_)
  189. throw std::invalid_argument("You should run calculations before result request!");
  190. return Qsca_ch_;
  191. }
  192. // ********************************************************************** //
  193. // ********************************************************************** //
  194. // ********************************************************************** //
  195. std::vector<double> MultiLayerMie::GetQsca_channel_normalized() {
  196. if (!isMieCalculated_)
  197. throw std::invalid_argument("You should run calculations before result request!");
  198. // std::vector<double> NACS(nmax_-1, 0.0);
  199. // double x2 = pow2(size_parameter_.back());
  200. // for (int i = 0; i < nmax_ - 1; ++i) {
  201. // const int n = i+1;
  202. // NACS[i] = Qsca_ch_[i]*x2/(2.0*(2.0*static_cast<double>(n)+1.0));
  203. // }
  204. // return NACS;
  205. return Qsca_ch_norm_;
  206. }
  207. // ********************************************************************** //
  208. // ********************************************************************** //
  209. // ********************************************************************** //
  210. double MultiLayerMie::GetQbk() {
  211. if (!isMieCalculated_)
  212. throw std::invalid_argument("You should run calculations before result request!");
  213. return Qbk_;
  214. }
  215. // ********************************************************************** //
  216. // ********************************************************************** //
  217. // ********************************************************************** //
  218. double MultiLayerMie::GetQpr() {
  219. if (!isMieCalculated_)
  220. throw std::invalid_argument("You should run calculations before result request!");
  221. return Qpr_;
  222. }
  223. // ********************************************************************** //
  224. // ********************************************************************** //
  225. // ********************************************************************** //
  226. double MultiLayerMie::GetAsymmetryFactor() {
  227. if (!isMieCalculated_)
  228. throw std::invalid_argument("You should run calculations before result request!");
  229. return asymmetry_factor_;
  230. }
  231. // ********************************************************************** //
  232. // ********************************************************************** //
  233. // ********************************************************************** //
  234. double MultiLayerMie::GetAlbedo() {
  235. if (!isMieCalculated_)
  236. throw std::invalid_argument("You should run calculations before result request!");
  237. return albedo_;
  238. }
  239. // ********************************************************************** //
  240. // ********************************************************************** //
  241. // ********************************************************************** //
  242. std::vector<std::complex<double> > MultiLayerMie::GetS1() {
  243. if (!isMieCalculated_)
  244. throw std::invalid_argument("You should run calculations before result request!");
  245. return S1_;
  246. }
  247. // ********************************************************************** //
  248. // ********************************************************************** //
  249. // ********************************************************************** //
  250. std::vector<std::complex<double> > MultiLayerMie::GetS2() {
  251. if (!isMieCalculated_)
  252. throw std::invalid_argument("You should run calculations before result request!");
  253. return S2_;
  254. }
  255. // ********************************************************************** //
  256. // ********************************************************************** //
  257. // ********************************************************************** //
  258. void MultiLayerMie::AddTargetLayer(double width, std::complex<double> layer_index) {
  259. isMieCalculated_ = false;
  260. if (width <= 0)
  261. throw std::invalid_argument("Layer width should be positive!");
  262. target_width_.push_back(width);
  263. target_index_.push_back(layer_index);
  264. } // end of void MultiLayerMie::AddTargetLayer(...)
  265. // ********************************************************************** //
  266. // ********************************************************************** //
  267. // ********************************************************************** //
  268. void MultiLayerMie::SetTargetPEC(double radius) {
  269. isMieCalculated_ = false;
  270. if (target_width_.size() != 0 || target_index_.size() != 0)
  271. throw std::invalid_argument("Error! Define PEC target radius before any other layers!");
  272. // Add layer of any index...
  273. AddTargetLayer(radius, std::complex<double>(0.0, 0.0));
  274. // ... and mark it as PEC
  275. SetPEC(0.0);
  276. }
  277. // ********************************************************************** //
  278. // ********************************************************************** //
  279. // ********************************************************************** //
  280. void MultiLayerMie::SetCoatingIndex(std::vector<std::complex<double> > index) {
  281. isMieCalculated_ = false;
  282. coating_index_.clear();
  283. for (auto value : index) coating_index_.push_back(value);
  284. } // end of void MultiLayerMie::SetCoatingIndex(std::vector<complex> index);
  285. // ********************************************************************** //
  286. // ********************************************************************** //
  287. // ********************************************************************** //
  288. void MultiLayerMie::SetAngles(const std::vector<double>& angles) {
  289. isMieCalculated_ = false;
  290. theta_ = angles;
  291. // theta_.clear();
  292. // for (auto value : angles) theta_.push_back(value);
  293. } // end of SetAngles()
  294. // ********************************************************************** //
  295. // ********************************************************************** //
  296. // ********************************************************************** //
  297. void MultiLayerMie::SetCoatingWidth(std::vector<double> width) {
  298. isMieCalculated_ = false;
  299. coating_width_.clear();
  300. for (auto w : width)
  301. if (w <= 0)
  302. throw std::invalid_argument("Coating width should be positive!");
  303. else coating_width_.push_back(w);
  304. }
  305. // end of void MultiLayerMie::SetCoatingWidth(...);
  306. // ********************************************************************** //
  307. // ********************************************************************** //
  308. // ********************************************************************** //
  309. void MultiLayerMie::SetWidthSP(const std::vector<double>& size_parameter) {
  310. isMieCalculated_ = false;
  311. size_parameter_.clear();
  312. double prev_size_parameter = 0.0;
  313. for (auto layer_size_parameter : size_parameter) {
  314. if (layer_size_parameter <= 0.0)
  315. throw std::invalid_argument("Size parameter should be positive!");
  316. if (prev_size_parameter > layer_size_parameter)
  317. throw std::invalid_argument
  318. ("Size parameter for next layer should be larger than the previous one!");
  319. prev_size_parameter = layer_size_parameter;
  320. size_parameter_.push_back(layer_size_parameter);
  321. }
  322. }
  323. // end of void MultiLayerMie::SetWidthSP(...);
  324. // ********************************************************************** //
  325. // ********************************************************************** //
  326. // ********************************************************************** //
  327. void MultiLayerMie::SetIndexSP(const std::vector< std::complex<double> >& index) {
  328. isMieCalculated_ = false;
  329. //index_.clear();
  330. index_ = index;
  331. // for (auto value : index) index_.push_back(value);
  332. } // end of void MultiLayerMie::SetIndexSP(...);
  333. // ********************************************************************** //
  334. // ********************************************************************** //
  335. // ********************************************************************** //
  336. void MultiLayerMie::SetFieldPointsSP(const std::vector< std::vector<double> >& coords_sp) {
  337. if (coords_sp.size() != 3)
  338. throw std::invalid_argument("Error! Wrong dimension of field monitor points!");
  339. if (coords_sp[0].size() != coords_sp[1].size()
  340. || coords_sp[0].size() != coords_sp[2].size())
  341. throw std::invalid_argument("Error! Missing coordinates for field monitor points!");
  342. coords_sp_ = coords_sp;
  343. // for (int i = 0; i < coords_sp_[0].size(); ++i) {
  344. // printf("%g, %g, %g\n", coords_sp_[0][i], coords_sp_[1][i], coords_sp_[2][i]);
  345. // }
  346. } // end of void MultiLayerMie::SetFieldPointsSP(...)
  347. // ********************************************************************** //
  348. // ********************************************************************** //
  349. // ********************************************************************** //
  350. void MultiLayerMie::SetPEC(int layer_position) {
  351. isMieCalculated_ = false;
  352. if (layer_position < 0)
  353. throw std::invalid_argument("Error! Layers are numbered from 0!");
  354. PEC_layer_position_ = layer_position;
  355. }
  356. // ********************************************************************** //
  357. // ********************************************************************** //
  358. // ********************************************************************** //
  359. void MultiLayerMie::SetMaxTermsNumber(int nmax) {
  360. isMieCalculated_ = false;
  361. nmax_preset_ = nmax;
  362. //debug
  363. printf("Setting max terms: %d\n", nmax_preset_);
  364. }
  365. // ********************************************************************** //
  366. // ********************************************************************** //
  367. // ********************************************************************** //
  368. void MultiLayerMie::GenerateSizeParameter() {
  369. isMieCalculated_ = false;
  370. size_parameter_.clear();
  371. double radius = 0.0;
  372. for (auto width : target_width_) {
  373. radius += width;
  374. size_parameter_.push_back(2*PI_*radius / wavelength_);
  375. }
  376. for (auto width : coating_width_) {
  377. radius += width;
  378. size_parameter_.push_back(2*PI_*radius / wavelength_);
  379. }
  380. total_radius_ = radius;
  381. } // end of void MultiLayerMie::GenerateSizeParameter();
  382. // ********************************************************************** //
  383. // ********************************************************************** //
  384. // ********************************************************************** //
  385. void MultiLayerMie::GenerateIndex() {
  386. isMieCalculated_ = false;
  387. index_.clear();
  388. for (auto index : target_index_) index_.push_back(index);
  389. for (auto index : coating_index_) index_.push_back(index);
  390. } // end of void MultiLayerMie::GenerateIndex();
  391. // ********************************************************************** //
  392. // ********************************************************************** //
  393. // ********************************************************************** //
  394. double MultiLayerMie::GetTotalRadius() {
  395. if (!isMieCalculated_)
  396. throw std::invalid_argument("You should run calculations before result request!");
  397. if (total_radius_ == 0) GenerateSizeParameter();
  398. return total_radius_;
  399. } // end of double MultiLayerMie::GetTotalRadius();
  400. // ********************************************************************** //
  401. // ********************************************************************** //
  402. // ********************************************************************** //
  403. std::vector< std::vector<double> >
  404. MultiLayerMie::GetSpectra(double from_WL, double to_WL, int samples) {
  405. if (!isMieCalculated_)
  406. throw std::invalid_argument("You should run calculations before result request!");
  407. std::vector< std::vector<double> > spectra;
  408. double step_WL = (to_WL - from_WL)/ static_cast<double>(samples);
  409. double wavelength_backup = wavelength_;
  410. long fails = 0;
  411. for (double WL = from_WL; WL < to_WL; WL += step_WL) {
  412. wavelength_ = WL;
  413. try {
  414. RunMieCalculations();
  415. } catch( const std::invalid_argument& ia ) {
  416. fails++;
  417. continue;
  418. }
  419. //printf("%3.1f ",WL);
  420. spectra.push_back(std::vector<double>({wavelength_, Qext_, Qsca_, Qabs_, Qbk_}));
  421. } // end of for each WL in spectra
  422. printf("Spectrum has %li fails\n",fails);
  423. wavelength_ = wavelength_backup;
  424. return spectra;
  425. }
  426. // ********************************************************************** //
  427. // ********************************************************************** //
  428. // ********************************************************************** //
  429. void MultiLayerMie::ClearTarget() {
  430. isMieCalculated_ = false;
  431. target_width_.clear();
  432. target_index_.clear();
  433. }
  434. // ********************************************************************** //
  435. // ********************************************************************** //
  436. // ********************************************************************** //
  437. void MultiLayerMie::ClearCoating() {
  438. isMieCalculated_ = false;
  439. coating_width_.clear();
  440. coating_index_.clear();
  441. }
  442. // ********************************************************************** //
  443. // ********************************************************************** //
  444. // ********************************************************************** //
  445. void MultiLayerMie::ClearLayers() {
  446. isMieCalculated_ = false;
  447. ClearTarget();
  448. ClearCoating();
  449. }
  450. // ********************************************************************** //
  451. // ********************************************************************** //
  452. // ********************************************************************** //
  453. void MultiLayerMie::ClearAllDesign() {
  454. isMieCalculated_ = false;
  455. ClearLayers();
  456. size_parameter_.clear();
  457. index_.clear();
  458. }
  459. // ********************************************************************** //
  460. // ********************************************************************** //
  461. // ********************************************************************** //
  462. // Computational core
  463. // ********************************************************************** //
  464. // ********************************************************************** //
  465. // ********************************************************************** //
  466. // Calculate Nstop - equation (17)
  467. //
  468. void MultiLayerMie::Nstop() {
  469. const double& xL = size_parameter_.back();
  470. if (xL <= 8) {
  471. nmax_ = round(xL + 4.0*pow(xL, 1.0/3.0) + 1);
  472. } else if (xL <= 4200) {
  473. nmax_ = round(xL + 4.05*pow(xL, 1.0/3.0) + 2);
  474. } else {
  475. nmax_ = round(xL + 4.0*pow(xL, 1.0/3.0) + 2);
  476. }
  477. }
  478. // ********************************************************************** //
  479. // ********************************************************************** //
  480. // ********************************************************************** //
  481. void MultiLayerMie::Nmax(int first_layer) {
  482. int ri, riM1;
  483. const std::vector<double>& x = size_parameter_;
  484. const std::vector<std::complex<double> >& m = index_;
  485. Nstop(); // Set initial nmax_ value
  486. for (int i = first_layer; i < x.size(); i++) {
  487. if (i > PEC_layer_position_)
  488. ri = round(std::abs(x[i]*m[i]));
  489. else
  490. ri = 0;
  491. nmax_ = std::max(nmax_, ri);
  492. // first layer is pec, if pec is present
  493. if ((i > first_layer) && ((i - 1) > PEC_layer_position_))
  494. riM1 = round(std::abs(x[i - 1]* m[i]));
  495. else
  496. riM1 = 0;
  497. nmax_ = std::max(nmax_, riM1);
  498. }
  499. nmax_ += 15; // Final nmax_ value
  500. }
  501. //**********************************************************************************//
  502. // This function calculates the spherical Bessel (jn) and Hankel (h1n) functions //
  503. // and their derivatives for a given complex value z. See pag. 87 B&H. //
  504. // //
  505. // Input parameters: //
  506. // z: Real argument to evaluate jn and h1n //
  507. // nmax_: Maximum number of terms to calculate jn and h1n //
  508. // //
  509. // Output parameters: //
  510. // jn, h1n: Spherical Bessel and Hankel functions //
  511. // jnp, h1np: Derivatives of the spherical Bessel and Hankel functions //
  512. // //
  513. // The implementation follows the algorithm by I.J. Thompson and A.R. Barnett, //
  514. // Comp. Phys. Comm. 47 (1987) 245-257. //
  515. // //
  516. // Complex spherical Bessel functions from n=0..nmax_-1 for z in the upper half //
  517. // plane (Im(z) > -3). //
  518. // //
  519. // j[n] = j/n(z) Regular solution: j[0]=sin(z)/z //
  520. // j'[n] = d[j/n(z)]/dz //
  521. // h1[n] = h[0]/n(z) Irregular Hankel function: //
  522. // h1'[n] = d[h[0]/n(z)]/dz h1[0] = j0(z) + i*y0(z) //
  523. // = (sin(z)-i*cos(z))/z //
  524. // = -i*exp(i*z)/z //
  525. // Using complex CF1, and trigonometric forms for n=0 solutions. //
  526. //**********************************************************************************//
  527. void MultiLayerMie::sbesjh(std::complex<double> z,
  528. std::vector<std::complex<double> >& jn,
  529. std::vector<std::complex<double> >& jnp,
  530. std::vector<std::complex<double> >& h1n,
  531. std::vector<std::complex<double> >& h1np) {
  532. const int limit = 20000;
  533. const double accur = 1.0e-12;
  534. const double tm30 = 1e-30;
  535. double absc;
  536. std::complex<double> zi, w;
  537. std::complex<double> pl, f, b, d, c, del, jn0, jndb, h1nldb, h1nbdb;
  538. absc = std::abs(std::real(z)) + std::abs(std::imag(z));
  539. if ((absc < accur) || (std::imag(z) < -3.0)) {
  540. throw std::invalid_argument("TODO add error description for condition if ((absc < accur) || (std::imag(z) < -3.0))");
  541. }
  542. zi = 1.0/z;
  543. w = zi + zi;
  544. pl = double(nmax_)*zi;
  545. f = pl + zi;
  546. b = f + f + zi;
  547. d = 0.0;
  548. c = f;
  549. for (int n = 0; n < limit; n++) {
  550. d = b - d;
  551. c = b - 1.0/c;
  552. absc = std::abs(std::real(d)) + std::abs(std::imag(d));
  553. if (absc < tm30) {
  554. d = tm30;
  555. }
  556. absc = std::abs(std::real(c)) + std::abs(std::imag(c));
  557. if (absc < tm30) {
  558. c = tm30;
  559. }
  560. d = 1.0/d;
  561. del = d*c;
  562. f = f*del;
  563. b += w;
  564. absc = std::abs(std::real(del - 1.0)) + std::abs(std::imag(del - 1.0));
  565. if (absc < accur) {
  566. // We have obtained the desired accuracy
  567. break;
  568. }
  569. }
  570. if (absc > accur) {
  571. throw std::invalid_argument("We were not able to obtain the desired accuracy");
  572. }
  573. jn[nmax_ - 1] = tm30;
  574. jnp[nmax_ - 1] = f*jn[nmax_ - 1];
  575. // Downward recursion to n=0 (N.B. Coulomb Functions)
  576. for (int n = nmax_ - 2; n >= 0; n--) {
  577. jn[n] = pl*jn[n + 1] + jnp[n + 1];
  578. jnp[n] = pl*jn[n] - jn[n + 1];
  579. pl = pl - zi;
  580. }
  581. // Calculate the n=0 Bessel Functions
  582. jn0 = zi*std::sin(z);
  583. h1n[0] = std::exp(std::complex<double>(0.0, 1.0)*z)*zi*(-std::complex<double>(0.0, 1.0));
  584. h1np[0] = h1n[0]*(std::complex<double>(0.0, 1.0) - zi);
  585. // Rescale j[n], j'[n], converting to spherical Bessel functions.
  586. // Recur h1[n], h1'[n] as spherical Bessel functions.
  587. w = 1.0/jn[0];
  588. pl = zi;
  589. for (int n = 0; n < nmax_; n++) {
  590. jn[n] = jn0*(w*jn[n]);
  591. jnp[n] = jn0*(w*jnp[n]) - zi*jn[n];
  592. if (n != 0) {
  593. h1n[n] = (pl - zi)*h1n[n - 1] - h1np[n - 1];
  594. // check if hankel is increasing (upward stable)
  595. if (std::abs(h1n[n]) < std::abs(h1n[n - 1])) {
  596. jndb = z;
  597. h1nldb = h1n[n];
  598. h1nbdb = h1n[n - 1];
  599. }
  600. pl += zi;
  601. h1np[n] = -(pl*h1n[n]) + h1n[n - 1];
  602. }
  603. }
  604. }
  605. //**********************************************************************************//
  606. // This function calculates the spherical Bessel functions (bj and by) and the //
  607. // logarithmic derivative (bd) for a given complex value z. See pag. 87 B&H. //
  608. // //
  609. // Input parameters: //
  610. // z: Complex argument to evaluate bj, by and bd //
  611. // nmax_: Maximum number of terms to calculate bj, by and bd //
  612. // //
  613. // Output parameters: //
  614. // bj, by: Spherical Bessel functions //
  615. // bd: Logarithmic derivative //
  616. //**********************************************************************************//
  617. void MultiLayerMie::sphericalBessel(std::complex<double> z,
  618. std::vector<std::complex<double> >& bj,
  619. std::vector<std::complex<double> >& by,
  620. std::vector<std::complex<double> >& bd) {
  621. std::vector<std::complex<double> > jn(nmax_), jnp(nmax_), h1n(nmax_), h1np(nmax_);
  622. sbesjh(z, jn, jnp, h1n, h1np);
  623. for (int n = 0; n < nmax_; n++) {
  624. bj[n] = jn[n];
  625. by[n] = (h1n[n] - jn[n])/std::complex<double>(0.0, 1.0);
  626. bd[n] = jnp[n]/jn[n] + 1.0/z;
  627. }
  628. // std::complex<double> besselj_0 = std::sin(z)/z;
  629. // std::complex<double> bessely_0 = -std::cos(z)/z;
  630. // if (nmax_>0) {
  631. // bj[0] = std::sin(z)/pow2(z)-std::cos(z)/z; //bj1
  632. // by[0] = std::cos(z)/pow2(z)-std::sin(z)/z; //by1
  633. // }
  634. // if (nmax_>1) {
  635. // bj[1] = bj[0]*3.0/z-besselj_0;//bj2
  636. // by[1] = by[0]*3.0/z-bessely_0;//bj2
  637. // }
  638. // for (int n = 2; n < nmax_; n++) {
  639. // bj[n] = (2.0*n-1.0)/z*bj[n-1] - bj[n];
  640. // by[n] = (2.0*n-1.0)/z*by[n-1] - by[n];
  641. // }
  642. }
  643. // ********************************************************************** //
  644. // ********************************************************************** //
  645. // ********************************************************************** //
  646. // Calculate an - equation (5)
  647. std::complex<double> MultiLayerMie::calc_an(int n, double XL, std::complex<double> Ha, std::complex<double> mL,
  648. std::complex<double> PsiXL, std::complex<double> ZetaXL,
  649. std::complex<double> PsiXLM1, std::complex<double> ZetaXLM1) {
  650. std::complex<double> Num = (Ha/mL + n/XL)*PsiXL - PsiXLM1;
  651. std::complex<double> Denom = (Ha/mL + n/XL)*ZetaXL - ZetaXLM1;
  652. return Num/Denom;
  653. }
  654. // ********************************************************************** //
  655. // ********************************************************************** //
  656. // ********************************************************************** //
  657. // Calculate bn - equation (6)
  658. std::complex<double> MultiLayerMie::calc_bn(int n, double XL, std::complex<double> Hb, std::complex<double> mL,
  659. std::complex<double> PsiXL, std::complex<double> ZetaXL,
  660. std::complex<double> PsiXLM1, std::complex<double> ZetaXLM1) {
  661. std::complex<double> Num = (mL*Hb + n/XL)*PsiXL - PsiXLM1;
  662. std::complex<double> Denom = (mL*Hb + n/XL)*ZetaXL - ZetaXLM1;
  663. return Num/Denom;
  664. }
  665. // ********************************************************************** //
  666. // ********************************************************************** //
  667. // ********************************************************************** //
  668. // Calculates S1 - equation (25a)
  669. std::complex<double> MultiLayerMie::calc_S1(int n, std::complex<double> an, std::complex<double> bn,
  670. double Pi, double Tau) {
  671. return double(n + n + 1)*(Pi*an + Tau*bn)/double(n*n + n);
  672. }
  673. // ********************************************************************** //
  674. // ********************************************************************** //
  675. // ********************************************************************** //
  676. // Calculates S2 - equation (25b) (it's the same as (25a), just switches Pi and Tau)
  677. std::complex<double> MultiLayerMie::calc_S2(int n, std::complex<double> an, std::complex<double> bn,
  678. double Pi, double Tau) {
  679. return calc_S1(n, an, bn, Tau, Pi);
  680. }
  681. //**********************************************************************************//
  682. // This function calculates the Riccati-Bessel functions (Psi and Zeta) for a //
  683. // real argument (x). //
  684. // Equations (20a) - (21b) //
  685. // //
  686. // Input parameters: //
  687. // x: Real argument to evaluate Psi and Zeta //
  688. // nmax: Maximum number of terms to calculate Psi and Zeta //
  689. // //
  690. // Output parameters: //
  691. // Psi, Zeta: Riccati-Bessel functions //
  692. //**********************************************************************************//
  693. void MultiLayerMie::calcPsiZeta(std::complex<double> z,
  694. std::vector<std::complex<double> > D1,
  695. std::vector<std::complex<double> > D3,
  696. std::vector<std::complex<double> >& Psi,
  697. std::vector<std::complex<double> >& Zeta) {
  698. //Upward recurrence for Psi and Zeta - equations (20a) - (21b)
  699. //Psi[0] = std::complex<double>(std::sin(x), 0);
  700. std::complex<double> c_i(0.0, 1.0);
  701. Psi[0] = std::sin(z);
  702. //Zeta[0] = std::complex<double>(std::sin(x), -std::cos(x));
  703. Zeta[0] = std::sin(z) - c_i*std::cos(z);
  704. for (int n = 1; n <= nmax_; n++) {
  705. Psi[n] = Psi[n - 1]*(static_cast<double>(n)/z - D1[n - 1]);
  706. Zeta[n] = Zeta[n - 1]*(static_cast<double>(n)/z - D3[n - 1]);
  707. }
  708. }
  709. //**********************************************************************************//
  710. // Function CONFRA ported from MIEV0.f (Wiscombe,1979)
  711. // Ref. to NCAR Technical Notes, Wiscombe, 1979
  712. /*
  713. c Compute Bessel function ratio A-sub-N from its
  714. c continued fraction using Lentz method
  715. c ZINV = Reciprocal of argument of A
  716. c I N T E R N A L V A R I A B L E S
  717. c ------------------------------------
  718. c CAK Term in continued fraction expansion of A (Eq. R25)
  719. c a_k
  720. c CAPT Factor used in Lentz iteration for A (Eq. R27)
  721. c T_k
  722. c CNUMER Numerator in capT ( Eq. R28A )
  723. c N_k
  724. c CDENOM Denominator in capT ( Eq. R28B )
  725. c D_k
  726. c CDTD Product of two successive denominators of capT factors
  727. c ( Eq. R34C )
  728. c xi_1
  729. c CNTN Product of two successive numerators of capT factors
  730. c ( Eq. R34B )
  731. c xi_2
  732. c EPS1 Ill-conditioning criterion
  733. c EPS2 Convergence criterion
  734. c KK Subscript k of cAk ( Eq. R25B )
  735. c k
  736. c KOUNT Iteration counter ( used to prevent infinite looping )
  737. c MAXIT Max. allowed no. of iterations
  738. c MM + 1 and - 1, alternately
  739. */
  740. std::complex<double> MultiLayerMie::calcD1confra(const int N, const std::complex<double> z) {
  741. // NTMR -> nmax_ -1 \\TODO nmax_ ?
  742. //int N = nmax_ - 1;
  743. int KK, KOUNT, MAXIT = 10000, MM;
  744. // double EPS1=1.0e-2;
  745. double EPS2=1.0e-8;
  746. std::complex<double> CAK, CAPT, CDENOM, CDTD, CNTN, CNUMER;
  747. std::complex<double> one = std::complex<double>(1.0,0.0);
  748. std::complex<double> ZINV = one/z;
  749. // c ** Eq. R25a
  750. std::complex<double> CONFRA = static_cast<std::complex<double> >(N+1)*ZINV; //debug ZINV
  751. MM = -1;
  752. KK = 2*N +3; //debug 3
  753. // c ** Eq. R25b, k=2
  754. CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; //debug -3 ZINV
  755. CDENOM = CAK;
  756. CNUMER = CDENOM + one / CONFRA; //-3zinv+z
  757. KOUNT = 1;
  758. //10 CONTINUE
  759. do { ++KOUNT;
  760. if (KOUNT > MAXIT) {
  761. printf("re(%g):im(%g)\t\n", CONFRA.real(), CONFRA.imag());
  762. throw std::invalid_argument("ConFra--Iteration failed to converge!\n");
  763. }
  764. MM *= -1; KK += 2; //debug mm=1 kk=5
  765. CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; // ** Eq. R25b //debug 5zinv
  766. // //c ** Eq. R32 Ill-conditioned case -- stride two terms instead of one
  767. // if (std::abs( CNUMER / CAK ) >= EPS1 || std::abs( CDENOM / CAK ) >= EPS1) {
  768. // //c ** Eq. R34
  769. // CNTN = CAK * CNUMER + 1.0;
  770. // CDTD = CAK * CDENOM + 1.0;
  771. // CONFRA = ( CNTN / CDTD ) * CONFRA; // ** Eq. R33
  772. // MM *= -1; KK += 2;
  773. // CAK = static_cast<std::complex<double> >(MM*KK) * ZINV; // ** Eq. R25b
  774. // //c ** Eq. R35
  775. // CNUMER = CAK + CNUMER / CNTN;
  776. // CDENOM = CAK + CDENOM / CDTD;
  777. // ++KOUNT;
  778. // //GO TO 10
  779. // continue;
  780. // } else { //c *** Well-conditioned case
  781. {
  782. CAPT = CNUMER / CDENOM; // ** Eq. R27 //debug (-3zinv + z)/(-3zinv)
  783. // printf("re(%g):im(%g)**\t", CAPT.real(), CAPT.imag());
  784. CONFRA = CAPT * CONFRA; // ** Eq. R26
  785. //if (N == 0) {output=true;printf(" re:");prn(CONFRA.real());printf(" im:"); prn(CONFRA.imag());output=false;};
  786. //c ** Check for convergence; Eq. R31
  787. if ( std::abs(CAPT.real() - 1.0) >= EPS2 || std::abs(CAPT.imag()) >= EPS2 ) {
  788. //c ** Eq. R30
  789. CNUMER = CAK + one/CNUMER;
  790. CDENOM = CAK + one/CDENOM;
  791. continue;
  792. //GO TO 10
  793. } // end of if < eps2
  794. }
  795. break;
  796. } while(1);
  797. //if (N == 0) printf(" return confra for z=(%g,%g)\n", ZINV.real(), ZINV.imag());
  798. return CONFRA;
  799. }
  800. //**********************************************************************************//
  801. // This function calculates the logarithmic derivatives of the Riccati-Bessel //
  802. // functions (D1 and D3) for a complex argument (z). //
  803. // Equations (16a), (16b) and (18a) - (18d) //
  804. // //
  805. // Input parameters: //
  806. // z: Complex argument to evaluate D1 and D3 //
  807. // nmax_: Maximum number of terms to calculate D1 and D3 //
  808. // //
  809. // Output parameters: //
  810. // D1, D3: Logarithmic derivatives of the Riccati-Bessel functions //
  811. //**********************************************************************************//
  812. void MultiLayerMie::calcD1D3(const std::complex<double> z,
  813. std::vector<std::complex<double> >& D1,
  814. std::vector<std::complex<double> >& D3) {
  815. // Downward recurrence for D1 - equations (16a) and (16b)
  816. D1[nmax_] = std::complex<double>(0.0, 0.0);
  817. //D1[nmax_] = calcD1confra(nmax_, z);
  818. const std::complex<double> zinv = std::complex<double>(1.0, 0.0)/z;
  819. // printf(" D:");prn((D1[nmax_]).real()); printf("\t diff:");
  820. // prn((D1[nmax_] + double(nmax_)*zinv).real());
  821. for (int n = nmax_; n > 0; n--) {
  822. D1[n - 1] = double(n)*zinv - 1.0/(D1[n] + double(n)*zinv);
  823. //D1[n-1] = calcD1confra(n-1, z);
  824. // printf(" D:");prn((D1[n-1]).real()); printf("\t diff:");
  825. // prn((D1[n] + double(n)*zinv).real());
  826. }
  827. // printf("\n\n"); iformat=0;
  828. if (std::abs(D1[0]) > 100000.0 )
  829. throw std::invalid_argument
  830. ("Unstable D1! Please, try to change input parameters!\n");
  831. // Upward recurrence for PsiZeta and D3 - equations (18a) - (18d)
  832. PsiZeta_[0] = 0.5*(1.0 - std::complex<double>(std::cos(2.0*z.real()), std::sin(2.0*z.real()))
  833. *std::exp(-2.0*z.imag()));
  834. D3[0] = std::complex<double>(0.0, 1.0);
  835. for (int n = 1; n <= nmax_; n++) {
  836. PsiZeta_[n] = PsiZeta_[n - 1]*(static_cast<double>(n)*zinv - D1[n - 1])
  837. *(static_cast<double>(n)*zinv- D3[n - 1]);
  838. D3[n] = D1[n] + std::complex<double>(0.0, 1.0)/PsiZeta_[n];
  839. }
  840. }
  841. //**********************************************************************************//
  842. // This function calculates Pi and Tau for all values of Theta. //
  843. // Equations (26a) - (26c) //
  844. // //
  845. // Input parameters: //
  846. // nmax_: Maximum number of terms to calculate Pi and Tau //
  847. // nTheta: Number of scattering angles //
  848. // Theta: Array containing all the scattering angles where the scattering //
  849. // amplitudes will be calculated //
  850. // //
  851. // Output parameters: //
  852. // Pi, Tau: Angular functions Pi and Tau, as defined in equations (26a) - (26c) //
  853. //**********************************************************************************//
  854. void MultiLayerMie::calcSinglePiTau(const double& costheta, std::vector<double>& Pi,
  855. std::vector<double>& Tau) {
  856. //****************************************************//
  857. // Equations (26a) - (26c) //
  858. //****************************************************//
  859. for (int n = 0; n < nmax_; n++) {
  860. if (n == 0) {
  861. // Initialize Pi and Tau
  862. Pi[n] = 1.0;
  863. Tau[n] = (n + 1)*costheta;
  864. } else {
  865. // Calculate the actual values
  866. Pi[n] = ((n == 1) ? ((n + n + 1)*costheta*Pi[n - 1]/n)
  867. : (((n + n + 1)*costheta*Pi[n - 1]
  868. - (n + 1)*Pi[n - 2])/n));
  869. Tau[n] = (n + 1)*costheta*Pi[n] - (n + 2)*Pi[n - 1];
  870. }
  871. }
  872. } // end of void MultiLayerMie::calcPiTau(...)
  873. void MultiLayerMie::calcAllPiTau(std::vector< std::vector<double> >& Pi,
  874. std::vector< std::vector<double> >& Tau) {
  875. std::vector<double> costheta(theta_.size(), 0.0);
  876. for (int t = 0; t < theta_.size(); t++) {
  877. costheta[t] = std::cos(theta_[t]);
  878. }
  879. // Do not join upper and lower 'for' to a single one! It will slow
  880. // down the code!!! (For about 0.5-2.0% of runtime, it is probably
  881. // due to increased cache missing rate originated from the
  882. // recurrence in calcPiTau...)
  883. for (int t = 0; t < theta_.size(); t++) {
  884. calcSinglePiTau(costheta[t], Pi[t], Tau[t]);
  885. //calcSinglePiTau(std::cos(theta_[t]), Pi[t], Tau[t]); // It is slow!!
  886. }
  887. } // end of void MultiLayerMie::calcAllPiTau(...)
  888. //**********************************************************************************//
  889. // This function calculates the scattering coefficients required to calculate //
  890. // both the near- and far-field parameters. //
  891. // //
  892. // Input parameters: //
  893. // L: Number of layers //
  894. // pl: Index of PEC layer. If there is none just send -1 //
  895. // x: Array containing the size parameters of the layers [0..L-1] //
  896. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  897. // nmax: Maximum number of multipolar expansion terms to be used for the //
  898. // calculations. Only use it if you know what you are doing, otherwise //
  899. // set this parameter to -1 and the function will calculate it. //
  900. // //
  901. // Output parameters: //
  902. // an, bn: Complex scattering amplitudes //
  903. // //
  904. // Return value: //
  905. // Number of multipolar expansion terms used for the calculations //
  906. //**********************************************************************************//
  907. void MultiLayerMie::ScattCoeffs(std::vector<std::complex<double> >& an,
  908. std::vector<std::complex<double> >& bn) {
  909. const std::vector<double>& x = size_parameter_;
  910. const std::vector<std::complex<double> >& m = index_;
  911. const int& pl = PEC_layer_position_;
  912. const int L = index_.size();
  913. //************************************************************************//
  914. // Calculate the index of the first layer. It can be either 0
  915. // (default) // or the index of the outermost PEC layer. In the
  916. // latter case all layers // below the PEC are discarded. //
  917. // ************************************************************************//
  918. // TODO, is it possible for PEC to have a zero index? If yes than
  919. // is should be:
  920. // int fl = (pl > -1) ? pl : 0;
  921. // This will give the same result, however, it corresponds the
  922. // logic - if there is PEC, than first layer is PEC.
  923. int fl = (pl > 0) ? pl : 0;
  924. if (nmax_ <= 0) Nmax(fl);
  925. std::complex<double> z1, z2;
  926. //**************************************************************************//
  927. // Note that since Fri, Nov 14, 2014 all arrays start from 0 (zero), which //
  928. // means that index = layer number - 1 or index = n - 1. The only exception //
  929. // are the arrays for representing D1, D3 and Q because they need a value //
  930. // for the index 0 (zero), hence it is important to consider this shift //
  931. // between different arrays. The change was done to optimize memory usage. //
  932. //**************************************************************************//
  933. // Allocate memory to the arrays
  934. std::vector<std::complex<double> > D1_mlxl(nmax_ + 1), D1_mlxlM1(nmax_ + 1),
  935. D3_mlxl(nmax_ + 1), D3_mlxlM1(nmax_ + 1);
  936. std::vector<std::vector<std::complex<double> > > Q(L), Ha(L), Hb(L);
  937. for (int l = 0; l < L; l++) {
  938. // D1_mlxl[l].resize(nmax_ + 1);
  939. // D1_mlxlM1[l].resize(nmax_ + 1);
  940. // D3_mlxl[l].resize(nmax_ + 1);
  941. // D3_mlxlM1[l].resize(nmax_ + 1);
  942. Q[l].resize(nmax_ + 1);
  943. Ha[l].resize(nmax_);
  944. Hb[l].resize(nmax_);
  945. }
  946. an.resize(nmax_);
  947. bn.resize(nmax_);
  948. PsiZeta_.resize(nmax_ + 1);
  949. std::vector<std::complex<double> > D1XL(nmax_ + 1), D3XL(nmax_ + 1),
  950. PsiXL(nmax_ + 1), ZetaXL(nmax_ + 1);
  951. //*************************************************//
  952. // Calculate D1 and D3 for z1 in the first layer //
  953. //*************************************************//
  954. if (fl == pl) { // PEC layer
  955. for (int n = 0; n <= nmax_; n++) {
  956. D1_mlxl[n] = std::complex<double>(0.0, -1.0);
  957. D3_mlxl[n] = std::complex<double>(0.0, 1.0);
  958. }
  959. } else { // Regular layer
  960. z1 = x[fl]* m[fl];
  961. // Calculate D1 and D3
  962. calcD1D3(z1, D1_mlxl, D3_mlxl);
  963. }
  964. // do { \
  965. // ++iformat;\
  966. // if (iformat%5 == 0) printf("%24.16e",z1.real()); \
  967. // } while (false);
  968. //******************************************************************//
  969. // Calculate Ha and Hb in the first layer - equations (7a) and (8a) //
  970. //******************************************************************//
  971. for (int n = 0; n < nmax_; n++) {
  972. Ha[fl][n] = D1_mlxl[n + 1];
  973. Hb[fl][n] = D1_mlxl[n + 1];
  974. }
  975. //*****************************************************//
  976. // Iteration from the second layer to the last one (L) //
  977. //*****************************************************//
  978. std::complex<double> Temp, Num, Denom;
  979. std::complex<double> G1, G2;
  980. for (int l = fl + 1; l < L; l++) {
  981. //************************************************************//
  982. //Calculate D1 and D3 for z1 and z2 in the layers fl+1..L //
  983. //************************************************************//
  984. z1 = x[l]*m[l];
  985. z2 = x[l - 1]*m[l];
  986. //Calculate D1 and D3 for z1
  987. calcD1D3(z1, D1_mlxl, D3_mlxl);
  988. //Calculate D1 and D3 for z2
  989. calcD1D3(z2, D1_mlxlM1, D3_mlxlM1);
  990. // prn(z1.real());
  991. // for ( auto i : D1_mlxl) { prn(i.real());
  992. // // prn(i.imag());
  993. // } printf("\n");
  994. //*********************************************//
  995. //Calculate Q, Ha and Hb in the layers fl+1..L //
  996. //*********************************************//
  997. // Upward recurrence for Q - equations (19a) and (19b)
  998. Num = std::exp(-2.0*(z1.imag() - z2.imag()))
  999. * std::complex<double>(std::cos(-2.0*z2.real()) - std::exp(-2.0*z2.imag()), std::sin(-2.0*z2.real()));
  1000. Denom = std::complex<double>(std::cos(-2.0*z1.real()) - std::exp(-2.0*z1.imag()), std::sin(-2.0*z1.real()));
  1001. Q[l][0] = Num/Denom;
  1002. for (int n = 1; n <= nmax_; n++) {
  1003. Num = (z1*D1_mlxl[n] + double(n))*(double(n) - z1*D3_mlxl[n - 1]);
  1004. Denom = (z2*D1_mlxlM1[n] + double(n))*(double(n) - z2*D3_mlxlM1[n - 1]);
  1005. Q[l][n] = ((pow2(x[l - 1]/x[l])* Q[l][n - 1])*Num)/Denom;
  1006. }
  1007. // Upward recurrence for Ha and Hb - equations (7b), (8b) and (12) - (15)
  1008. for (int n = 1; n <= nmax_; n++) {
  1009. //Ha
  1010. if ((l - 1) == pl) { // The layer below the current one is a PEC layer
  1011. G1 = -D1_mlxlM1[n];
  1012. G2 = -D3_mlxlM1[n];
  1013. } else {
  1014. G1 = (m[l]*Ha[l - 1][n - 1]) - (m[l - 1]*D1_mlxlM1[n]);
  1015. G2 = (m[l]*Ha[l - 1][n - 1]) - (m[l - 1]*D3_mlxlM1[n]);
  1016. } // end of if PEC
  1017. Temp = Q[l][n]*G1;
  1018. Num = (G2*D1_mlxl[n]) - (Temp*D3_mlxl[n]);
  1019. Denom = G2 - Temp;
  1020. Ha[l][n - 1] = Num/Denom;
  1021. //Hb
  1022. if ((l - 1) == pl) { // The layer below the current one is a PEC layer
  1023. G1 = Hb[l - 1][n - 1];
  1024. G2 = Hb[l - 1][n - 1];
  1025. } else {
  1026. G1 = (m[l - 1]*Hb[l - 1][n - 1]) - (m[l]*D1_mlxlM1[n]);
  1027. G2 = (m[l - 1]*Hb[l - 1][n - 1]) - (m[l]*D3_mlxlM1[n]);
  1028. } // end of if PEC
  1029. Temp = Q[l][n]*G1;
  1030. Num = (G2*D1_mlxl[n]) - (Temp* D3_mlxl[n]);
  1031. Denom = (G2- Temp);
  1032. Hb[l][n - 1] = (Num/ Denom);
  1033. } // end of for Ha and Hb terms
  1034. } // end of for layers iteration
  1035. //**************************************//
  1036. //Calculate D1, D3, Psi and Zeta for XL //
  1037. //**************************************//
  1038. // Calculate D1XL and D3XL
  1039. calcD1D3(x[L - 1], D1XL, D3XL);
  1040. //printf("%5.20f\n",Ha[L-1][0].real());
  1041. // Calculate PsiXL and ZetaXL
  1042. calcPsiZeta(x[L - 1], D1XL, D3XL, PsiXL, ZetaXL);
  1043. //*********************************************************************//
  1044. // Finally, we calculate the scattering coefficients (an and bn) and //
  1045. // the angular functions (Pi and Tau). Note that for these arrays the //
  1046. // first layer is 0 (zero), in future versions all arrays will follow //
  1047. // this convention to save memory. (13 Nov, 2014) //
  1048. //*********************************************************************//
  1049. for (int n = 0; n < nmax_; n++) {
  1050. //********************************************************************//
  1051. //Expressions for calculating an and bn coefficients are not valid if //
  1052. //there is only one PEC layer (ie, for a simple PEC sphere). //
  1053. //********************************************************************//
  1054. if (pl < (L - 1)) {
  1055. 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]);
  1056. 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]);
  1057. } else {
  1058. 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]);
  1059. bn[n] = PsiXL[n + 1]/ZetaXL[n + 1];
  1060. }
  1061. } // end of for an and bn terms
  1062. } // end of void MultiLayerMie::ScattCoeffs(...)
  1063. // ********************************************************************** //
  1064. // ********************************************************************** //
  1065. // ********************************************************************** //
  1066. void MultiLayerMie::InitMieCalculations() {
  1067. isMieCalculated_ = false;
  1068. // Initialize the scattering parameters
  1069. Qext_ = 0;
  1070. Qsca_ = 0;
  1071. Qabs_ = 0;
  1072. Qbk_ = 0;
  1073. Qpr_ = 0;
  1074. asymmetry_factor_ = 0;
  1075. albedo_ = 0;
  1076. Qsca_ch_.clear();
  1077. Qext_ch_.clear();
  1078. Qabs_ch_.clear();
  1079. Qbk_ch_.clear();
  1080. Qpr_ch_.clear();
  1081. Qsca_ch_.resize(nmax_-1);
  1082. Qext_ch_.resize(nmax_-1);
  1083. Qabs_ch_.resize(nmax_-1);
  1084. Qbk_ch_.resize(nmax_-1);
  1085. Qpr_ch_.resize(nmax_-1);
  1086. Qsca_ch_norm_.resize(nmax_-1);
  1087. Qext_ch_norm_.resize(nmax_-1);
  1088. Qabs_ch_norm_.resize(nmax_-1);
  1089. Qbk_ch_norm_.resize(nmax_-1);
  1090. Qpr_ch_norm_.resize(nmax_-1);
  1091. // Initialize the scattering amplitudes
  1092. std::vector<std::complex<double> > tmp1(theta_.size(),std::complex<double>(0.0, 0.0));
  1093. S1_.swap(tmp1);
  1094. S2_ = S1_;
  1095. }
  1096. // ********************************************************************** //
  1097. // ********************************************************************** //
  1098. // ********************************************************************** //
  1099. void MultiLayerMie::ConvertToSP() {
  1100. isMieCalculated_ = false;
  1101. if (target_width_.size() + coating_width_.size() == 0)
  1102. return; // Nothing to convert, we suppose that SP was set directly
  1103. GenerateSizeParameter();
  1104. GenerateIndex();
  1105. if (size_parameter_.size() != index_.size())
  1106. throw std::invalid_argument("Ivalid conversion of width to size parameter units!/n");
  1107. }
  1108. // ********************************************************************** //
  1109. // ********************************************************************** //
  1110. // ********************************************************************** //
  1111. //**********************************************************************************//
  1112. // This function calculates the actual scattering parameters and amplitudes //
  1113. // //
  1114. // Input parameters: //
  1115. // L: Number of layers //
  1116. // pl: Index of PEC layer. If there is none just send -1 //
  1117. // x: Array containing the size parameters of the layers [0..L-1] //
  1118. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  1119. // nTheta: Number of scattering angles //
  1120. // Theta: Array containing all the scattering angles where the scattering //
  1121. // amplitudes will be calculated //
  1122. // nmax_: Maximum number of multipolar expansion terms to be used for the //
  1123. // calculations. Only use it if you know what you are doing, otherwise //
  1124. // set this parameter to -1 and the function will calculate it //
  1125. // //
  1126. // Output parameters: //
  1127. // Qext: Efficiency factor for extinction //
  1128. // Qsca: Efficiency factor for scattering //
  1129. // Qabs: Efficiency factor for absorption (Qabs = Qext - Qsca) //
  1130. // Qbk: Efficiency factor for backscattering //
  1131. // Qpr: Efficiency factor for the radiation pressure //
  1132. // g: Asymmetry factor (g = (Qext-Qpr)/Qsca) //
  1133. // Albedo: Single scattering albedo (Albedo = Qsca/Qext) //
  1134. // S1, S2: Complex scattering amplitudes //
  1135. // //
  1136. // Return value: //
  1137. // Number of multipolar expansion terms used for the calculations //
  1138. //**********************************************************************************//
  1139. void MultiLayerMie::RunMieCalculations() {
  1140. isMieCalculated_ = false;
  1141. ConvertToSP();
  1142. nmax_ = nmax_preset_;
  1143. if (size_parameter_.size() != index_.size())
  1144. throw std::invalid_argument("Each size parameter should have only one index!");
  1145. if (size_parameter_.size() == 0)
  1146. throw std::invalid_argument("Initialize model first!");
  1147. const std::vector<double>& x = size_parameter_;
  1148. // Calculate scattering coefficients
  1149. ScattCoeffs(an_, bn_);
  1150. // std::vector< std::vector<double> > Pi(nmax_), Tau(nmax_);
  1151. std::vector< std::vector<double> > Pi, Tau;
  1152. Pi.resize(theta_.size());
  1153. Tau.resize(theta_.size());
  1154. for (int i =0; i< theta_.size(); ++i) {
  1155. Pi[i].resize(nmax_);
  1156. Tau[i].resize(nmax_);
  1157. }
  1158. calcAllPiTau(Pi, Tau);
  1159. InitMieCalculations(); //
  1160. std::complex<double> Qbktmp(0.0, 0.0);
  1161. std::vector< std::complex<double> > Qbktmp_ch(nmax_ - 1, Qbktmp);
  1162. // By using downward recurrence we avoid loss of precision due to float rounding errors
  1163. // See: https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
  1164. // http://en.wikipedia.org/wiki/Loss_of_significance
  1165. for (int i = nmax_ - 2; i >= 0; i--) {
  1166. const int n = i + 1;
  1167. // Equation (27)
  1168. Qext_ch_norm_[i] = (an_[i].real() + bn_[i].real());
  1169. Qext_ch_[i] = (n + n + 1.0)*Qext_ch_norm_[i];
  1170. //Qext_ch_[i] = (n + n + 1)*(an_[i].real() + bn_[i].real());
  1171. Qext_ += Qext_ch_[i];
  1172. // Equation (28)
  1173. Qsca_ch_norm_[i] = (an_[i].real()*an_[i].real() + an_[i].imag()*an_[i].imag()
  1174. + bn_[i].real()*bn_[i].real() + bn_[i].imag()*bn_[i].imag());
  1175. Qsca_ch_[i] = (n + n + 1.0)*Qsca_ch_norm_[i];
  1176. Qsca_ += Qsca_ch_[i];
  1177. // Qsca_ch_[i] += (n + n + 1)*(an_[i].real()*an_[i].real() + an_[i].imag()*an_[i].imag()
  1178. // + bn_[i].real()*bn_[i].real() + bn_[i].imag()*bn_[i].imag());
  1179. // Equation (29) TODO We must check carefully this equation. If we
  1180. // remove the typecast to double then the result changes. Which is
  1181. // the correct one??? Ovidio (2014/12/10) With cast ratio will
  1182. // give double, without cast (n + n + 1)/(n*(n + 1)) will be
  1183. // rounded to integer. Tig (2015/02/24)
  1184. Qpr_ch_[i]=((n*(n + 2)/(n + 1))*((an_[i]*std::conj(an_[n]) + bn_[i]*std::conj(bn_[n])).real())
  1185. + ((double)(n + n + 1)/(n*(n + 1)))*(an_[i]*std::conj(bn_[i])).real());
  1186. Qpr_ += Qpr_ch_[i];
  1187. // Equation (33)
  1188. Qbktmp_ch[i] = (double)(n + n + 1)*(1 - 2*(n % 2))*(an_[i]- bn_[i]);
  1189. Qbktmp += Qbktmp_ch[i];
  1190. // Calculate the scattering amplitudes (S1 and S2) //
  1191. // Equations (25a) - (25b) //
  1192. for (int t = 0; t < theta_.size(); t++) {
  1193. S1_[t] += calc_S1(n, an_[i], bn_[i], Pi[t][i], Tau[t][i]);
  1194. S2_[t] += calc_S2(n, an_[i], bn_[i], Pi[t][i], Tau[t][i]);
  1195. }
  1196. }
  1197. double x2 = pow2(x.back());
  1198. Qext_ = 2.0*(Qext_)/x2; // Equation (27)
  1199. for (double& Q : Qext_ch_) Q = 2.0*Q/x2;
  1200. Qsca_ = 2.0*(Qsca_)/x2; // Equation (28)
  1201. for (double& Q : Qsca_ch_) Q = 2.0*Q/x2;
  1202. //for (double& Q : Qsca_ch_norm_) Q = 2.0*Q/x2;
  1203. Qpr_ = Qext_ - 4.0*(Qpr_)/x2; // Equation (29)
  1204. for (int i = 0; i < nmax_ - 1; ++i) Qpr_ch_[i] = Qext_ch_[i] - 4.0*Qpr_ch_[i]/x2;
  1205. Qabs_ = Qext_ - Qsca_; // Equation (30)
  1206. for (int i = 0; i < nmax_ - 1; ++i) {
  1207. Qabs_ch_[i] = Qext_ch_[i] - Qsca_ch_[i];
  1208. Qabs_ch_norm_[i] = Qext_ch_norm_[i] - Qsca_ch_norm_[i];
  1209. }
  1210. albedo_ = Qsca_ / Qext_; // Equation (31)
  1211. asymmetry_factor_ = (Qext_ - Qpr_) / Qsca_; // Equation (32)
  1212. Qbk_ = (Qbktmp.real()*Qbktmp.real() + Qbktmp.imag()*Qbktmp.imag())/x2; // Equation (33)
  1213. isMieCalculated_ = true;
  1214. nmax_used_ = nmax_;
  1215. printf("Run Mie result: Qext = %g, Qsca = %g, Qabs = %g, Qbk = %g \n",
  1216. GetQext(), GetQsca(), GetQabs(), GetQbk() );
  1217. //return nmax;
  1218. }
  1219. // ********************************************************************** //
  1220. // ********************************************************************** //
  1221. // ********************************************************************** //
  1222. void MultiLayerMie::ScattCoeffsLayerdInit() {
  1223. const int L = index_.size();
  1224. // we need to fill
  1225. // std::vector< std::vector<std::complex<double> > > al_n_, bl_n_, cl_n_, dl_n_;
  1226. // for n = [0..nmax_) and for l=[L..0)
  1227. // TODO: to decrease cache miss outer loop is with n and inner with reversed l
  1228. // at the moment outer is forward l and inner in n
  1229. al_n_.resize(L+1);
  1230. bl_n_.resize(L+1);
  1231. cl_n_.resize(L+1);
  1232. dl_n_.resize(L+1);
  1233. for (auto& element:al_n_) element.resize(nmax_);
  1234. for (auto& element:bl_n_) element.resize(nmax_);
  1235. for (auto& element:cl_n_) element.resize(nmax_);
  1236. for (auto& element:dl_n_) element.resize(nmax_);
  1237. std::complex<double> c_one(1.0, 0.0);
  1238. std::complex<double> c_zero(0.0, 0.0);
  1239. // Yang, paragraph under eq. A3
  1240. // a^(L+1)_n = a_n, d^(L+1) = 1 ...
  1241. for (int i = 0; i < nmax_; ++i) {
  1242. al_n_[L][i] = an_[i];
  1243. bl_n_[L][i] = bn_[i];
  1244. cl_n_[L][i] = c_one;
  1245. dl_n_[L][i] = c_one;
  1246. if (i<3) printf(" (%g) ", std::abs(an_[i]));
  1247. }
  1248. }
  1249. // ********************************************************************** //
  1250. // ********************************************************************** //
  1251. // ********************************************************************** //
  1252. void MultiLayerMie::ScattCoeffsLayerd() {
  1253. if (!isMieCalculated_)
  1254. throw std::invalid_argument("(ScattCoeffsLayerd) You should run calculations first!");
  1255. ScattCoeffsLayerdInit();
  1256. const int L = index_.size();
  1257. std::vector<std::complex<double> > z(L), z1(L);
  1258. for (int i = 0; i<L-1; ++i) {
  1259. z[i] =size_parameter_[i]*index_[i];
  1260. z1[i]=size_parameter_[i]*index_[i+1];
  1261. }
  1262. z[L-1] =size_parameter_[L-1]*index_[L-1];
  1263. z1[L-1] =size_parameter_[L-1];
  1264. std::vector< std::vector<std::complex<double> > > D1z(L), D1z1(L), D3z(L), D3z1(L);
  1265. std::vector< std::vector<std::complex<double> > > Psiz(L), Psiz1(L), Zetaz(L), Zetaz1(L);
  1266. for (int l = 0; l < L; ++l) {
  1267. D1z[l].resize(nmax_ +1);
  1268. D1z1[l].resize(nmax_ +1);
  1269. D3z[l].resize(nmax_ +1);
  1270. D3z1[l].resize(nmax_ +1);
  1271. Psiz[l].resize(nmax_ +1);
  1272. Psiz1[l].resize(nmax_ +1);
  1273. Zetaz[l].resize(nmax_ +1);
  1274. Zetaz1[l].resize(nmax_ +1);
  1275. }
  1276. for (int l = 0; l < L; ++l) {
  1277. calcD1D3(z[l],D1z[l],D3z[l]);
  1278. calcD1D3(z1[l],D1z1[l],D3z1[l]);
  1279. calcPsiZeta(z[l],D1z[l],D3z[l], Psiz[l],Zetaz[l]);
  1280. calcPsiZeta(z1[l],D1z1[l],D3z1[l], Psiz1[l],Zetaz1[l]);
  1281. }
  1282. auto& m = index_;
  1283. std::vector< std::complex<double> > m1(L);
  1284. for (int l = 0; l < L-1; ++l) m1[l] = m[l+1];
  1285. m1[L-1] = std::complex<double> (1.0, 0.0);
  1286. // for (auto zz : m) printf ("m[i]=%g \n\n ", zz.real());
  1287. for (int l = L-1; l >= 0; --l) {
  1288. for (int n = 0; n < nmax_; ++n) {
  1289. // al_n
  1290. auto denom = m1[l]*Zetaz[l][n+1] * ( D1z[l][n+1] - D3z[l][n+1] );
  1291. al_n_[l][n] = D1z[l][n+1]* m1[l]
  1292. *(al_n_[l+1][n]*Zetaz1[l][n+1] - dl_n_[l+1][n]*Psiz1[l][n+1])
  1293. - m[l]*(-D1z1[l][n+1]*dl_n_[l+1][n]*Psiz1[l][n+1]
  1294. +D3z1[l][n+1]*al_n_[l+1][n]*Zetaz1[l][n+1]);
  1295. al_n_[l][n] /= denom;
  1296. // if (n<2) printf( "denom[%d][%d]:%g \n", l, n,
  1297. // std::abs(Psiz[l][n+1]));
  1298. // dl_n
  1299. denom = m1[l]*Psiz[l][n+1] * ( D1z[l][n+1] - D3z[l][n+1] );
  1300. dl_n_[l][n] = D3z[l][n+1]*m1[l]
  1301. *(al_n_[l+1][n]*Zetaz1[l][n+1] - dl_n_[l+1][n]*Psiz1[l][n+1])
  1302. - m[l]*(-D1z1[l][n+1]*dl_n_[l+1][n]*Psiz1[l][n+1]
  1303. +D3z1[l][n+1]*al_n_[l+1][n]*Zetaz1[l][n+1]);
  1304. dl_n_[l][n] /= denom;
  1305. // bl_n
  1306. denom = m1[l]*Zetaz[l][n+1] * ( D1z[l][n+1] - D3z[l][n+1] );
  1307. bl_n_[l][n] = D1z[l][n+1]* m[l]
  1308. *(bl_n_[l+1][n]*Zetaz1[l][n+1] - cl_n_[l+1][n]*Psiz1[l][n+1])
  1309. - m1[l]*(-D1z1[l][n+1]*cl_n_[l+1][n]*Psiz1[l][n+1]
  1310. +D3z1[l][n+1]*bl_n_[l+1][n]*Zetaz1[l][n+1]);
  1311. bl_n_[l][n] /= denom;
  1312. // cl_n
  1313. denom = m1[l]*Psiz[l][n+1] * ( D1z[l][n+1] - D3z[l][n+1] );
  1314. cl_n_[l][n] = D3z[l][n+1]*m[l]
  1315. *(bl_n_[l+1][n]*Zetaz1[l][n+1] - cl_n_[l+1][n]*Psiz1[l][n+1])
  1316. - m1[l]*(-D1z1[l][n+1]*cl_n_[l+1][n]*Psiz1[l][n+1]
  1317. +D3z1[l][n+1]*bl_n_[l+1][n]*Zetaz1[l][n+1]);
  1318. cl_n_[l][n] /= denom;
  1319. } // end of all n
  1320. } // end of for all l
  1321. // Check the result and change an__0 and bn__0 for exact zero
  1322. for (int n = 0; n < nmax_; ++n) {
  1323. if (std::abs(al_n_[0][n]) < 1e-10) al_n_[0][n] = 0.0;
  1324. else throw std::invalid_argument("Unstable calculation of a__0_n!");
  1325. if (std::abs(bl_n_[0][n]) < 1e-10) bl_n_[0][n] = 0.0;
  1326. else throw std::invalid_argument("Unstable calculation of b__0_n!");
  1327. }
  1328. // for (int l = 0; l < L; ++l) {
  1329. // printf("l=%d --> ", l);
  1330. // for (int n = 0; n < nmax_ + 1; ++n) {
  1331. // if (n < 20) continue;
  1332. // printf("n=%d --> D1zn=%g, D3zn=%g, D1zn=%g, D3zn=%g || ",
  1333. // n,
  1334. // D1z[l][n].real(), D3z[l][n].real(),
  1335. // D1z1[l][n].real(), D3z1[l][n].real());
  1336. // }
  1337. // printf("\n\n");
  1338. // }
  1339. // for (int l = 0; l < L; ++l) {
  1340. // printf("l=%d --> ", l);
  1341. // for (int n = 0; n < nmax_ + 1; ++n) {
  1342. // printf("n=%d --> D1zn=%g, D3zn=%g, D1zn=%g, D3zn=%g || ",
  1343. // n,
  1344. // D1z[l][n].real(), D3z[l][n].real(),
  1345. // D1z1[l][n].real(), D3z1[l][n].real());
  1346. // }
  1347. // printf("\n\n");
  1348. // }
  1349. for (int i = 0; i < L+1; ++i) {
  1350. printf("Layer =%d ---> ", i);
  1351. for (int n = 0; n < nmax_; ++n) {
  1352. // if (n < 20) continue;
  1353. printf(" || n=%d --> a=%g,%g b=%g,%g c=%g,%g d=%g,%g",
  1354. n,
  1355. al_n_[i][n].real(), al_n_[i][n].imag(),
  1356. bl_n_[i][n].real(), bl_n_[i][n].imag(),
  1357. cl_n_[i][n].real(), cl_n_[i][n].imag(),
  1358. dl_n_[i][n].real(), dl_n_[i][n].imag());
  1359. }
  1360. printf("\n\n");
  1361. }
  1362. }
  1363. // ********************************************************************** //
  1364. // ********************************************************************** //
  1365. // ********************************************************************** //
  1366. // external scattering field = incident + scattered
  1367. // BH p.92 (4.37), 94 (4.45), 95 (4.50)
  1368. // assume: medium is non-absorbing; refim = 0; Uabs = 0
  1369. void MultiLayerMie::fieldExt(const double Rho, const double Phi, const double Theta, const std::vector<double>& Pi, const std::vector<double>& Tau, std::vector<std::complex<double> >& E, std::vector<std::complex<double> >& H) {
  1370. std::complex<double> c_zero(0.0, 0.0), c_i(0.0, 1.0);
  1371. std::vector<std::complex<double> > vm3o1n(3), vm3e1n(3), vn3o1n(3), vn3e1n(3);
  1372. std::vector<std::complex<double> > Ei(3,c_zero), Hi(3,c_zero),
  1373. Es(3,c_zero), Hs(3,c_zero);
  1374. std::vector<std::complex<double> > bj(nmax_+1), by(nmax_+1), bd(nmax_+1);
  1375. // Calculate spherical Bessel and Hankel functions
  1376. printf("########## layer OUT ############\n");
  1377. sphericalBessel(Rho,bj, by, bd);
  1378. for (int n = 0; n < nmax_; n++) {
  1379. double rn = static_cast<double>(n + 1);
  1380. std::complex<double> zn = bj[n+1] + c_i*by[n+1];
  1381. // using BH 4.12 and 4.50
  1382. std::complex<double> xxip = Rho*(bj[n] + c_i*by[n]) - rn*zn;
  1383. using std::sin;
  1384. using std::cos;
  1385. vm3o1n[0] = c_zero;
  1386. vm3o1n[1] = cos(Phi)*Pi[n]*zn;
  1387. vm3o1n[2] = -sin(Phi)*Tau[n]*zn;
  1388. vm3e1n[0] = c_zero;
  1389. vm3e1n[1] = -sin(Phi)*Pi[n]*zn;
  1390. vm3e1n[2] = -cos(Phi)*Tau[n]*zn;
  1391. vn3o1n[0] = sin(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1392. vn3o1n[1] = sin(Phi)*Tau[n]*xxip/Rho;
  1393. vn3o1n[2] = cos(Phi)*Pi[n]*xxip/Rho;
  1394. vn3e1n[0] = cos(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1395. vn3e1n[1] = cos(Phi)*Tau[n]*xxip/Rho;
  1396. vn3e1n[2] = -sin(Phi)*Pi[n]*xxip/Rho;
  1397. // scattered field: BH p.94 (4.45)
  1398. std::complex<double> encap = std::pow(c_i, rn)*(2.0*rn + 1.0)/(rn*rn + rn);
  1399. for (int i = 0; i < 3; i++) {
  1400. Es[i] = Es[i] + encap*(c_i*an_[n]*vn3e1n[i] - bn_[n]*vm3o1n[i]);
  1401. Hs[i] = Hs[i] + encap*(c_i*bn_[n]*vn3o1n[i] + an_[n]*vm3e1n[i]);
  1402. //if (n<3) printf(" E[%d]=%g ", i,std::abs(Es[i]));
  1403. if (n<3) printf(" !!=%d=== %g ", i,std::abs(Es[i]));
  1404. }
  1405. }
  1406. // incident E field: BH p.89 (4.21); cf. p.92 (4.37), p.93 (4.38)
  1407. // basis unit vectors = er, etheta, ephi
  1408. std::complex<double> eifac = std::exp(std::complex<double>(0.0, Rho*std::cos(Theta)));
  1409. {
  1410. using std::sin;
  1411. using std::cos;
  1412. Ei[0] = eifac*sin(Theta)*cos(Phi);
  1413. Ei[1] = eifac*cos(Theta)*cos(Phi);
  1414. Ei[2] = -eifac*sin(Phi);
  1415. }
  1416. // magnetic field
  1417. double hffact = 1.0/(cc_*mu_);
  1418. for (int i = 0; i < 3; i++) {
  1419. Hs[i] = hffact*Hs[i];
  1420. }
  1421. // incident H field: BH p.26 (2.43), p.89 (4.21)
  1422. std::complex<double> hffacta = hffact;
  1423. std::complex<double> hifac = eifac*hffacta;
  1424. {
  1425. using std::sin;
  1426. using std::cos;
  1427. Hi[0] = hifac*sin(Theta)*sin(Phi);
  1428. Hi[1] = hifac*cos(Theta)*sin(Phi);
  1429. Hi[2] = hifac*cos(Phi);
  1430. }
  1431. for (int i = 0; i < 3; i++) {
  1432. // electric field E [V m-1] = EF*E0
  1433. E[i] = Ei[i] + Es[i];
  1434. H[i] = Hi[i] + Hs[i];
  1435. // printf("ext E[%d]=%g",i,std::abs(E[i]));
  1436. }
  1437. } // end of void fieldExt(...)
  1438. // ********************************************************************** //
  1439. // ********************************************************************** //
  1440. // ********************************************************************** //
  1441. void MultiLayerMie::fieldInt(const double Rho, const double Phi, const double Theta, const std::vector<double>& Pi, const std::vector<double>& Tau, std::vector<std::complex<double> >& E, std::vector<std::complex<double> >& H) {
  1442. // printf("field int Qext = %g, Qsca = %g, Qabs = %g, Qbk = %g, \n",
  1443. // GetQext(), GetQsca(), GetQabs(), GetQbk() );
  1444. std::complex<double> c_zero(0.0, 0.0), c_i(0.0, 1.0), c_one(1.0, 0.0);
  1445. std::vector<std::complex<double> > vm3o1n(3), vm3e1n(3), vn3o1n(3), vn3e1n(3);
  1446. std::vector<std::complex<double> > vm1o1n(3), vm1e1n(3), vn1o1n(3), vn1e1n(3);
  1447. std::vector<std::complex<double> > El(3,c_zero),Ei(3,c_zero), Hl(3,c_zero);
  1448. std::vector<std::complex<double> > bj(nmax_+1), by(nmax_+1), bd(nmax_+1);
  1449. int layer=0; // layer number
  1450. std::complex<double> index_l;
  1451. for (int i = 0; i < size_parameter_.size()-1; ++i) {
  1452. if (size_parameter_[i] < Rho && Rho <= size_parameter_[i+1]) {
  1453. layer=i;
  1454. }
  1455. }
  1456. if (Rho > size_parameter_.back()) {
  1457. layer = size_parameter_.size();
  1458. index_l = c_one;
  1459. } else {
  1460. index_l = index_[layer];
  1461. }
  1462. std::complex<double> bessel_arg = Rho*index_l;
  1463. std::complex<double>& rh = bessel_arg;
  1464. std::complex<double> besselj_1 = std::sin(rh)/pow2(rh)-std::cos(rh)/rh;
  1465. printf("bessel arg = %g,%g index=%g,%g besselj[1]=%g,%g\n", bessel_arg.real(), bessel_arg.imag(), index_l.real(), index_l.imag(), besselj_1.real(), besselj_1.imag());
  1466. const int& l = layer;
  1467. printf("########## layer %d ############\n",l);
  1468. // Calculate spherical Bessel and Hankel functions
  1469. sphericalBessel(bessel_arg,bj, by, bd);
  1470. printf("besselj[1]=%g,%g\n", bj[1].real(), bj[1].imag());
  1471. printf("bessely[1]=%g,%g\n", by[1].real(), by[1].imag());
  1472. for (int n = 0; n < nmax_; n++) {
  1473. double rn = static_cast<double>(n + 1);
  1474. std::complex<double> znm1 = bj[n] + c_i*by[n];
  1475. std::complex<double> zn = bj[n+1] + c_i*by[n+1];
  1476. //if (n<3) printf("\nbesselh = %g,%g", zn.real(), zn.imag()); //!
  1477. // using BH 4.12 and 4.50
  1478. std::complex<double> xxip = Rho*(bj[n] + c_i*by[n]) - rn*zn;
  1479. //if (n<3) printf("\nxxip = %g,%g", xxip.real(), xxip.imag()); //!
  1480. using std::sin;
  1481. using std::cos;
  1482. vm3o1n[0] = c_zero;
  1483. vm3o1n[1] = cos(Phi)*Pi[n]*zn;
  1484. vm3o1n[2] = -sin(Phi)*Tau[n]*zn;
  1485. // if (n<3) printf("\nRE vm3o1n[0]%g vm3o1n[1]%g vm3o1n[2]%g \nIM vm3o1n[0]%g vm3o1n[1]%g vm3o1n[2]%g",
  1486. // vm3o1n[0].real(), vm3o1n[1].real(), vm3o1n[2].real(),
  1487. // vm3o1n[0].imag(), vm3o1n[1].imag(), vm3o1n[2].imag());
  1488. vm3e1n[0] = c_zero;
  1489. vm3e1n[1] = -sin(Phi)*Pi[n]*zn;
  1490. vm3e1n[2] = -cos(Phi)*Tau[n]*zn;
  1491. vn3o1n[0] = sin(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1492. vn3o1n[1] = sin(Phi)*Tau[n]*xxip/Rho;
  1493. vn3o1n[2] = cos(Phi)*Pi[n]*xxip/Rho;
  1494. vn3e1n[0] = cos(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1495. vn3e1n[1] = cos(Phi)*Tau[n]*xxip/Rho;
  1496. vn3e1n[2] = -sin(Phi)*Pi[n]*xxip/Rho;
  1497. // if (n<3) printf("\nRE vn3e1n[0]%g vn3e1n[1]%g vn3e1n[2]%g \nIM vn3e1n[0]%g vn3e1n[1]%g vn3e1n[2]%g",
  1498. // vn3e1n[0].real(), vn3e1n[1].real(), vn3e1n[2].real(),
  1499. // vn3e1n[0].imag(), vn3e1n[1].imag(), vn3e1n[2].imag());
  1500. znm1 = bj[n];
  1501. zn = bj[n+1];
  1502. // znm1 = (bj[n] + c_i*by[n]).real();
  1503. // zn = (bj[n+1] + c_i*by[n+1]).real();
  1504. xxip = Rho*(bj[n]) - rn*zn;
  1505. if (n<3)printf("\nbesselj = %g,%g", zn.real(), zn.imag()); //!
  1506. vm1o1n[0] = c_zero;
  1507. vm1o1n[1] = cos(Phi)*Pi[n]*zn;
  1508. vm1o1n[2] = -sin(Phi)*Tau[n]*zn;
  1509. vm1e1n[0] = c_zero;
  1510. vm1e1n[1] = -sin(Phi)*Pi[n]*zn;
  1511. vm1e1n[2] = -cos(Phi)*Tau[n]*zn;
  1512. vn1o1n[0] = sin(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1513. vn1o1n[1] = sin(Phi)*Tau[n]*xxip/Rho;
  1514. vn1o1n[2] = cos(Phi)*Pi[n]*xxip/Rho;
  1515. // if (n<3) printf("\nvn1o1n[2](%g) = cos(Phi)(%g)*Pi[n](%g)*xxip(%g)/Rho(%g)",
  1516. // std::abs(vn1o1n[2]), cos(Phi),Pi[n],std::abs(xxip),Rho);
  1517. vn1e1n[0] = cos(Phi)*rn*(rn + 1.0)*sin(Theta)*Pi[n]*zn/Rho;
  1518. vn1e1n[1] = cos(Phi)*Tau[n]*xxip/Rho;
  1519. vn1e1n[2] = -sin(Phi)*Pi[n]*xxip/Rho;
  1520. // if (n<3) printf("\nRE vm3o1n[0]%g vm3o1n[1]%g vm3o1n[2]%g \nIM vm3o1n[0]%g vm3o1n[1]%g vm3o1n[2]%g",
  1521. // vm3o1n[0].real(), vm3o1n[1].real(), vm3o1n[2].real(),
  1522. // vm3o1n[0].imag(), vm3o1n[1].imag(), vm3o1n[2].imag());
  1523. // scattered field: BH p.94 (4.45)
  1524. std::complex<double> encap = std::pow(c_i, rn)*(2.0*rn + 1.0)/(rn*rn + rn);
  1525. // if (n<3) printf("\n===== n=%d ======\n",n);
  1526. for (int i = 0; i < 3; i++) {
  1527. // if (n<3 && i==0) printf("\nn=%d",n);
  1528. // if (n<3) printf("\nbefore !El[%d]=%g,%g! ", i, El[i].real(), El[i].imag());
  1529. Ei[i] = encap*(
  1530. cl_n_[l][n]*vm1o1n[i] - c_i*dl_n_[l][n]*vn1e1n[i]
  1531. + c_i*al_n_[l][n]*vn3e1n[i] - bl_n_[l][n]*vm3o1n[i]
  1532. );
  1533. El[i] = El[i] + encap*(cl_n_[l][n]*vm1o1n[i] - c_i*dl_n_[l][n]*vn1e1n[i]
  1534. + c_i*al_n_[l][n]*vn3e1n[i] - bl_n_[l][n]*vm3o1n[i]);
  1535. Hl[i] = Hl[i] + encap*(-dl_n_[l][n]*vm1e1n[i] - c_i*cl_n_[l][n]*vn1o1n[i]
  1536. + c_i*bl_n_[l][n]*vn3o1n[i] + al_n_[l][n]*vm3e1n[i]);
  1537. // printf("\n !Ei[%d]=%g,%g! ", i, Ei[i].real(), Ei[i].imag());
  1538. // if (n<3) printf("\n !El[%d]=%g,%g! ", i, El[i].real(), El[i].imag());
  1539. // //printf(" ===%d=== %g ", i,std::abs(cl_n_[l][n]*vm1o1n[i] - c_i*dl_n_[l][n]*vn1e1n[i]));
  1540. // if (n<3) printf(" ===%d=== %g ", i,std::abs(//-dl_n_[l][n]*vm1e1n[i]
  1541. // //- c_i*cl_n_[l][n]*
  1542. // vn1o1n[i]
  1543. // // + c_i*bl_n_[l][n]*vn3o1n[i]
  1544. // // + al_n_[l][n]*vm3e1n[i]
  1545. // ));
  1546. // if (n<3) printf(" --- Ei[%d]=%g! ", i,std::abs(encap*(vm1o1n[i] - c_i*vn1e1n[i])));
  1547. }
  1548. //if (n<3) printf(" bj=%g \n", std::abs(bj[n]));
  1549. } // end of for all n
  1550. // magnetic field
  1551. double hffact = 1.0/(cc_*mu_);
  1552. for (int i = 0; i < 3; i++) {
  1553. Hl[i] = hffact*Hl[i];
  1554. }
  1555. for (int i = 0; i < 3; i++) {
  1556. // electric field E [V m-1] = EF*E0
  1557. E[i] = El[i];
  1558. H[i] = Hl[i];
  1559. printf("\n !El[%d]=%g,%g! ", i, El[i].real(), El[i].imag());
  1560. //printf(" E[%d]=%g",i,std::abs(El[i]));
  1561. }
  1562. } // end of void fieldExt(...)
  1563. // ********************************************************************** //
  1564. // ********************************************************************** //
  1565. // ********************************************************************** //
  1566. //**********************************************************************************//
  1567. // This function calculates complex electric and magnetic field in the surroundings //
  1568. // and inside (TODO) the particle. //
  1569. // //
  1570. // Input parameters: //
  1571. // L: Number of layers //
  1572. // pl: Index of PEC layer. If there is none just send 0 (zero) //
  1573. // x: Array containing the size parameters of the layers [0..L-1] //
  1574. // m: Array containing the relative refractive indexes of the layers [0..L-1] //
  1575. // nmax: Maximum number of multipolar expansion terms to be used for the //
  1576. // calculations. Only use it if you know what you are doing, otherwise //
  1577. // set this parameter to 0 (zero) and the function will calculate it. //
  1578. // ncoord: Number of coordinate points //
  1579. // Coords: Array containing all coordinates where the complex electric and //
  1580. // magnetic fields will be calculated //
  1581. // //
  1582. // Output parameters: //
  1583. // E, H: Complex electric and magnetic field at the provided coordinates //
  1584. // //
  1585. // Return value: //
  1586. // Number of multipolar expansion terms used for the calculations //
  1587. //**********************************************************************************//
  1588. void MultiLayerMie::RunFieldCalculations() {
  1589. // Calculate scattering coefficients an_ and bn_
  1590. RunMieCalculations();
  1591. //nmax_=10;
  1592. ScattCoeffsLayerd();
  1593. std::vector<double> Pi(nmax_), Tau(nmax_);
  1594. long total_points = coords_sp_[0].size();
  1595. E_field_.resize(total_points);
  1596. H_field_.resize(total_points);
  1597. for (auto& f:E_field_) f.resize(3);
  1598. for (auto& f:H_field_) f.resize(3);
  1599. for (int point = 0; point < total_points; ++point) {
  1600. const double& Xp = coords_sp_[0][point];
  1601. const double& Yp = coords_sp_[1][point];
  1602. const double& Zp = coords_sp_[2][point];
  1603. printf("X=%g, Y=%g, Z=%g\n", Xp, Yp, Zp);
  1604. // Convert to spherical coordinates
  1605. double Rho, Phi, Theta;
  1606. Rho = std::sqrt(pow2(Xp) + pow2(Yp) + pow2(Zp));
  1607. // printf("Rho=%g\n", Rho);
  1608. // Avoid convergence problems due to Rho too small
  1609. if (Rho < 1e-5) Rho = 1e-10;
  1610. // If Rho=0 then Theta is undefined. Just set it to zero to avoid problems
  1611. if (Rho == 0.0) Theta = 0.0;
  1612. else Theta = std::acos(Zp/Rho);
  1613. // printf("Theta=%g\n", Theta);
  1614. // If Xp=Yp=0 then Phi is undefined. Just set it to zero to zero to avoid problems
  1615. if (Xp == 0.0 && Yp == 0.0) Phi = 0.0;
  1616. else Phi = std::acos(Xp/std::sqrt(pow2(Xp) + pow2(Yp)));
  1617. // printf("Phi=%g\n", Phi);
  1618. calcSinglePiTau(std::cos(Theta), Pi, Tau);
  1619. //*******************************************************//
  1620. // external scattering field = incident + scattered //
  1621. // BH p.92 (4.37), 94 (4.45), 95 (4.50) //
  1622. // assume: medium is non-absorbing; refim = 0; Uabs = 0 //
  1623. //*******************************************************//
  1624. // This array contains the fields in spherical coordinates
  1625. std::vector<std::complex<double> > Es(3), Hs(3);
  1626. const double outer_size = size_parameter_.back();
  1627. // Firstly the easiest case: the field outside the particle
  1628. printf("rho=%g, outer=%g ", Rho, outer_size);
  1629. if (Rho >= outer_size) {
  1630. fieldExt(Rho, Phi, Theta, Pi, Tau, Es, Hs);
  1631. printf("\nFin E ext: %g,%g,%g Rho=%g\n", std::abs(Es[0]), std::abs(Es[1]),std::abs(Es[2]), Rho);
  1632. } else {
  1633. fieldInt(Rho, Phi, Theta, Pi, Tau, Es, Hs);
  1634. printf("\nFin E int: %g,%g,%g Rho=%g\n", std::abs(Es[0]), std::abs(Es[1]),std::abs(Es[2]), Rho);
  1635. }
  1636. std::complex<double>& Ex = E_field_[point][0];
  1637. std::complex<double>& Ey = E_field_[point][1];
  1638. std::complex<double>& Ez = E_field_[point][2];
  1639. std::complex<double>& Hx = H_field_[point][0];
  1640. std::complex<double>& Hy = H_field_[point][1];
  1641. std::complex<double>& Hz = H_field_[point][2];
  1642. //Now, convert the fields back to cartesian coordinates
  1643. {
  1644. using std::sin;
  1645. using std::cos;
  1646. Ex = sin(Theta)*cos(Phi)*Es[0] + cos(Theta)*cos(Phi)*Es[1] - sin(Phi)*Es[2];
  1647. Ey = sin(Theta)*sin(Phi)*Es[0] + cos(Theta)*sin(Phi)*Es[1] + cos(Phi)*Es[2];
  1648. Ez = cos(Theta)*Es[0] - sin(Theta)*Es[1];
  1649. Hx = sin(Theta)*cos(Phi)*Hs[0] + cos(Theta)*cos(Phi)*Hs[1] - sin(Phi)*Hs[2];
  1650. Hy = sin(Theta)*sin(Phi)*Hs[0] + cos(Theta)*sin(Phi)*Hs[1] + cos(Phi)*Hs[2];
  1651. Hz = cos(Theta)*Hs[0] - sin(Theta)*Hs[1];
  1652. }
  1653. printf("Cart E: %g,%g,%g Rho=%g\n", std::abs(Ex), std::abs(Ey),std::abs(Ez),
  1654. Rho);
  1655. } // end of for all field coordinates
  1656. } // end of void MultiLayerMie::RunFieldCalculations()
  1657. } // end of namespace nmie