nmie-wrapper.cc 85 KB

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